1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
|
<?php namespace WpAssetCleanUp\OptimiseAssets;
use WpAssetCleanUp\CleanUp; use WpAssetCleanUp\Main; use WpAssetCleanUp\Menu; use WpAssetCleanUp\MetaBoxes;
/** * Class MinifyCss * @package WpAssetCleanUp\OptimiseAssets */ class MinifyCss { /** * @param $cssContent * @param bool $forInlineStyle * * @return string */ public static function applyMinification($cssContent, $forInlineStyle = false) { if (class_exists('\MatthiasMullie\Minify\CSS')) { $sha1OriginalContent = sha1($cssContent); $checkForAlreadyMinifiedShaOne = mb_strlen($cssContent) > 40000;
// Let's check if the content is already minified // Save resources as the minify process can take time if the content is very large // Limit the total number of entries tp 100: if it's more than that, it's likely because there's dynamic JS altering on every page load if ($checkForAlreadyMinifiedShaOne && OptimizeCommon::originalContentIsAlreadyMarkedAsMinified($sha1OriginalContent, 'styles')) { return $cssContent; }
// [CUSTOM BUG FIX] // Encode the special matched content to avoid any wrong minification from the minifier $hasVarWithZeroUnit = false;
preg_match_all('#--([a-zA-Z0-9_-]+):(\s+)0(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)#', $cssContent, $cssVariablesMatches);
if (isset($cssVariablesMatches[0]) && ! empty($cssVariablesMatches[0])) { $hasVarWithZeroUnit = true;
foreach ($cssVariablesMatches[0] as $zeroUnitMatch) { $cssContent = str_replace( $zeroUnitMatch, '[wpacu]' . base64_encode( $zeroUnitMatch ) . '[/wpacu]', $cssContent ); } } // [/CUSTOM BUG FIX]
$minifier = new \MatthiasMullie\Minify\CSS( $cssContent );
if ( $forInlineStyle ) { // If the minification is applied for inlined CSS (within STYLE) // Leave the background URLs unchanged as it sometimes lead to issues $minifier->setImportExtensions( array() ); }
$minifiedContent = trim( $minifier->minify() );
// [CUSTOM BUG FIX] // Restore the original content if ($hasVarWithZeroUnit) { foreach ( $cssVariablesMatches[0] as $zeroUnitMatch ) { $zeroUnitMatchAlt = str_replace(': 0', ':0', $zeroUnitMatch); // remove the space $minifiedContent = str_replace( '[wpacu]' . base64_encode( $zeroUnitMatch ) . '[/wpacu]', $zeroUnitMatchAlt, $minifiedContent ); } } // [/CUSTOM BUG FIX]
if ($checkForAlreadyMinifiedShaOne && $minifiedContent === $cssContent) { // If the resulting content is the same, mark it as minified to avoid the minify process next time OptimizeCommon::originalContentMarkAsAlreadyMinified( $sha1OriginalContent, 'styles' ); }
return $minifiedContent; }
return $cssContent;
}
/** * @param $href * @param string $handle * * @return bool */ public static function skipMinify($href, $handle = '') { // Things like WP Fastest Cache Toolbar CSS shouldn't be minified and take up space on the server if ($handle !== '' && in_array($handle, Main::instance()->skipAssets['styles'])) { return true; }
// Some of these files (e.g. from Oxygen, WooCommerce) are already minified $regExps = array( '#/wp-content/plugins/wp-asset-clean-up(.*?).min.css#',
// Formidable Forms '#/wp-content/plugins/formidable/css/formidableforms.css#',
// Oxygen //'#/wp-content/plugins/oxygen/component-framework/oxygen.css#',
// WooCommerce '#/wp-content/plugins/woocommerce/assets/css/woocommerce-layout.css#', '#/wp-content/plugins/woocommerce/assets/css/woocommerce.css#', '#/wp-content/plugins/woocommerce/assets/css/woocommerce-smallscreen.css#', '#/wp-content/plugins/woocommerce/assets/css/blocks/style.css#', '#/wp-content/plugins/woocommerce/packages/woocommerce-blocks/build/style.css#',
// Other libraries from the core that end in .min.css '#/wp-includes/css/(.*?).min.css#',
// Files within /wp-content/uploads/ or /wp-content/cache/ // Could belong to plugins such as "Elementor, "Oxygen" etc. '#/wp-content/uploads/elementor/(.*?).css#', '#/wp-content/uploads/oxygen/css/(.*?)-(.*?).css#', '#/wp-content/cache/(.*?).css#',
// Already minified and it also has a random name making the cache folder make bigger '#/wp-content/bs-booster-cache/#',
);
if (Main::instance()->settings['minify_loaded_css_exceptions'] !== '') { $loadedCssExceptionsPatterns = trim(Main::instance()->settings['minify_loaded_css_exceptions']);
if (strpos($loadedCssExceptionsPatterns, "\n")) { // Multiple values (one per line) foreach (explode("\n", $loadedCssExceptionsPatterns) as $loadedCssExceptionPattern) { $regExps[] = '#'.trim($loadedCssExceptionPattern).'#'; } } else { // Only one value? $regExps[] = '#'.trim($loadedCssExceptionsPatterns).'#'; } }
foreach ($regExps as $regExp) { if ( preg_match( $regExp, $href ) || ( strpos($href, $regExp) !== false ) ) { return true; } }
return false; }
/** * @param $htmlSource * * @return mixed|string */ public static function minifyInlineStyleTags($htmlSource) { if (stripos($htmlSource, '<style') === false) { return $htmlSource; // no STYLE tags }
$skipTagsContaining = array( 'data-wpacu-skip', 'astra-theme-css-inline-css', 'astra-edd-inline-css', 'et-builder-module-design-cached-inline-styles', 'fusion-stylesheet-inline-css', 'woocommerce-general-inline-css', 'woocommerce-inline-inline-css', 'data-wpacu-own-inline-style', // Only shown to the admin, irrelevant for any optimization (save resources) 'data-wpacu-inline-css-file' // already minified/optimized since the INLINE was generated from the cached file );
$fetchType = 'regex';
if ($fetchType === 'dom') { // DOMDocument extension has to be enabled, otherwise return the HTML source as was (no changes) if (! (function_exists('libxml_use_internal_errors') && function_exists('libxml_clear_errors') && class_exists('\DOMDocument'))) { return $htmlSource; }
$domTag = OptimizeCommon::getDomLoadedTag($htmlSource, 'minifyInlineStyleTags');
$styleTagsObj = $domTag->getElementsByTagName( 'style' );
if ( $styleTagsObj === null ) { return $htmlSource; }
foreach ( $styleTagsObj as $styleTagObj ) { $originalTag = CleanUp::getOuterHTML( $styleTagObj );
// No need to use extra resources as the tag is already minified if ( preg_match( '(' . implode( '|', $skipTagsContaining ) . ')', $originalTag ) ) { continue; }
$originalTagContents = ( isset( $styleTagObj->nodeValue ) && trim( $styleTagObj->nodeValue ) !== '' ) ? $styleTagObj->nodeValue : false;
if ( $originalTagContents ) { $newTagContents = OptimizeCss::maybeAlterContentForInlineStyleTag( $originalTagContents, true, array( 'just_minify' ) );
// Only comments or no content added to the inline STYLE tag? Strip it completely to reduce the number of DOM elements if ( $newTagContents === '/**/' || ! $newTagContents ) { $htmlSource = str_ireplace( '>' . $originalTagContents . '</style', '></style', $htmlSource );
preg_match( '#<style.*?>#si', $originalTag, $matchFromStyle );
if ( isset( $matchFromStyle[0] ) && $styleTagWithoutContent = $matchFromStyle[0] ) { $styleTagWithoutContentAlt = str_replace( '"', '\'', $styleTagWithoutContent ); $htmlSource = str_ireplace( array( $styleTagWithoutContent . '</style>', $styleTagWithoutContentAlt . '</style>' ), '', $htmlSource ); } } else { // It has content; do the replacement $htmlSource = str_ireplace( '>' . $originalTagContents . '</style>', '>' . $newTagContents . '</style>', $htmlSource ); } libxml_clear_errors(); } } } elseif ($fetchType === 'regex') { preg_match_all( '@(<style[^>]*?>).*?</style>@si', $htmlSource, $matchesStyleTags, PREG_SET_ORDER );
if ( $matchesStyleTags === null ) { return $htmlSource; }
foreach ($matchesStyleTags as $matchedStyle) { if ( ! (isset($matchedStyle[0]) && $matchedStyle[0]) ) { continue; }
$originalTag = $matchedStyle[0];
if (substr($originalTag, -strlen('></style>')) === strtolower('></style>')) { // No empty STYLE tags continue; }
// No need to use extra resources as the tag is already minified if ( preg_match( '(' . implode( '|', $skipTagsContaining ) . ')', $originalTag ) ) { continue; }
$tagOpen = $matchedStyle[1];
$withTagOpenStripped = substr($originalTag, strlen($tagOpen)); $originalTagContents = substr($withTagOpenStripped, 0, -strlen('</style>'));
if ( $originalTagContents ) { $newTagContents = OptimizeCss::maybeAlterContentForInlineStyleTag( $originalTagContents, true, array( 'just_minify' ) );
// Only comments or no content added to the inline STYLE tag? Strip it completely to reduce the number of DOM elements if ( $newTagContents === '/**/' || ! $newTagContents ) { $htmlSource = str_replace( '>' . $originalTagContents . '</', '></', $htmlSource );
preg_match( '#<style.*?>#si', $originalTag, $matchFromStyle );
if ( isset( $matchFromStyle[0] ) && $styleTagWithoutContent = $matchFromStyle[0] ) { $styleTagWithoutContentAlt = str_ireplace( '"', '\'', $styleTagWithoutContent ); $htmlSource = str_ireplace( array( $styleTagWithoutContent . '</style>', $styleTagWithoutContentAlt . '</style>' ), '', $htmlSource ); } } else { // It has content; do the replacement $htmlSource = str_replace( '>' . $originalTagContents . '</style>', '>' . $newTagContents . '</style>', $htmlSource ); } } } }
return $htmlSource; }
/** * @return bool */ public static function isMinifyCssEnabled() { if (defined('WPACU_IS_MINIFY_CSS_ENABLED')) { return WPACU_IS_MINIFY_CSS_ENABLED; }
// Request Minify On The Fly // It will preview the page with CSS minified // Only if the admin is logged-in as it uses more resources (CPU / Memory) if (array_key_exists('wpacu_css_minify', $_GET) && Menu::userCanManageAssets()) { self::isMinifyCssEnabledChecked('true'); return true; }
if ( array_key_exists('wpacu_no_css_minify', $_GET) || // not on query string request (debugging purposes) is_admin() || // not for Dashboard view (! Main::instance()->settings['minify_loaded_css']) || // Minify CSS has to be Enabled (Main::instance()->settings['test_mode'] && ! Menu::userCanManageAssets()) ) { // Does not trigger if "Test Mode" is Enabled self::isMinifyCssEnabledChecked('false'); return false; }
if (defined('WPACU_CURRENT_PAGE_ID') && WPACU_CURRENT_PAGE_ID > 0 && is_singular()) { // If "Do not minify CSS on this page" is checked in "Asset CleanUp: Options" side meta box $pageOptions = MetaBoxes::getPageOptions( WPACU_CURRENT_PAGE_ID );
if ( isset( $pageOptions['no_css_minify'] ) && $pageOptions['no_css_minify'] ) { self::isMinifyCssEnabledChecked('false'); return false; } }
if (OptimizeCss::isOptimizeCssEnabledByOtherParty('if_enabled')) { self::isMinifyCssEnabledChecked('false'); return false; }
return true; }
/** * @param $value */ public static function isMinifyCssEnabledChecked($value) { if (! defined('WPACU_IS_MINIFY_CSS_ENABLED')) { if ($value === 'true') { define( 'WPACU_IS_MINIFY_CSS_ENABLED', true ); } elseif ($value === 'false') { define( 'WPACU_IS_MINIFY_CSS_ENABLED', false ); } } } }
|