C:\xampp\htdocs\landing\wp-content\plugins\wp-asset-clean-up\classes\OptimiseAssets\OptimizeCss.php


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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
<?php
namespace WpAssetCleanUp\OptimiseAssets;

use 
WpAssetCleanUp\ObjectCache;
use 
WpAssetCleanUp\Plugin;
use 
WpAssetCleanUp\Preloads;
use 
WpAssetCleanUp\FileSystem;
use 
WpAssetCleanUp\CleanUp;
use 
WpAssetCleanUp\Main;
use 
WpAssetCleanUp\MetaBoxes;
use 
WpAssetCleanUp\Misc;

/**
 * Class OptimizeCss
 * @package WpAssetCleanUp
 */
class OptimizeCss
{
    
/**
     *
     */
    
const MOVE_NOSCRIPT_TO_BODY_FOR_CERTAIN_LINK_TAGS '<span style="display: none;" data-name=wpacu-delimiter data-content="ASSET CLEANUP NOSCRIPT FOR ASYNC PRELOADS"></span>';

    
/**
     *
     */
    
public function init()
    {
        
add_action('init', array($this'triggersAfterInit'));
        
add_action('wp_footer', static function() {
            if ( 
Plugin::preventAnyFrontendOptimization() || Main::isTestModeActive() ) { return; }

            
/* [wpacu_timing] */ Misc::scriptExecTimer'prepare_optimize_files_css' ); /* [/wpacu_timing] */
            
self::prepareOptimizeList();
            
/* [wpacu_timing] */ Misc::scriptExecTimer'prepare_optimize_files_css''end' ); /* [/wpacu_timing] */

            
echo self::MOVE_NOSCRIPT_TO_BODY_FOR_CERTAIN_LINK_TAGS;
        }, 
PHP_INT_MAX);

        
add_filter('wpacu_html_source_after_optimization', static function($htmlSource) {
            
// Are any the marks still there & weren't replaced? Strip them to have a clean HTML output!
            
return str_replace(self::MOVE_NOSCRIPT_TO_BODY_FOR_CERTAIN_LINK_TAGS''$htmlSource);
        });

        
add_filter('wpacu_add_noscript_certain_link_tags', array($this'appendNoScriptCertainLinkTags'));
    }

    
/**
     *
     */
    
public function triggersAfterInit()
    {
        if (
self::isInlineCssEnabled()) {
            
$allPatterns self::getAllInlineChosenPatterns();

            if (! empty(
$allPatterns)) {
                
// Make "Inline CSS Files" compatible with "Optimize CSS Delivery" from WP Rocket
                
add_filter('rocket_async_css_regex_pattern', static function($regex) {
                    return 
'/(?=<link(?!.*wpacu-to-be-inlined.*)[^>]*\s(rel\s*=\s*[\'"]stylesheet["\']))<link(?!.*wpacu-to-be-inlined.*)[^>]*\shref\s*=\s*[\'"]([^\'"]+)[\'"](.*)>/iU';
                });

                
add_filter('style_loader_tag', static function($styleTag) use ($allPatterns) {
                    foreach (
$allPatterns as $patternToCheck) {
                        
preg_match_all'#<link[^>]*stylesheet[^>]*('.$patternToCheck.').*(>)#Usmi'$styleTag$matchesSourcesFromTagsPREG_SET_ORDER );

                        if ( ! empty( 
$matchesSourcesFromTags ) ) {
                            return 
str_replace'<link ''<link wpacu-to-be-inlined=\'1\' '$styleTag );
                        }
                    }

                    return 
$styleTag;
                }, 
101);
            }
        }
    }

    
/**
     * @return array
     */
    
public static function getAllInlineChosenPatterns()
    {
        
$inlineCssFilesPatterns trim(Main::instance()->settings['inline_css_files_list']);

        
$allPatterns = array();

        if (
strpos($inlineCssFilesPatterns"\n")) {
            
// Multiple values (one per line)
            
foreach (explode("\n"$inlineCssFilesPatterns) as $inlinePattern) {
                
$allPatterns[] = trim($inlinePattern);
            }
        } else {
            
// Only one value?
            
$allPatterns[] = trim($inlineCssFilesPatterns);
        }

        
// Strip any empty values
        
return array_filter($allPatterns);
    }

    
/**
     *
     */
    
public static function prepareOptimizeList()
    {
        if ( ! 
self::isWorthCheckingForOptimization() || Plugin::preventAnyFrontendOptimization() ) {
            return;
        }

        global 
$wp_styles;

        
$allStylesHandles ObjectCache::wpacu_cache_get('wpacu_all_styles_handles');
        if (empty(
$allStylesHandles)) {
            return;
        }

        
// [Start] Collect for caching
        
$wpStylesDone       = isset($wp_styles->done)       && is_array($wp_styles->done)       ? $wp_styles->done       : array();
        
$wpStylesRegistered = isset($wp_styles->registered) && is_array($wp_styles->registered) ? $wp_styles->registered : array();

        
// Collect all enqueued clean (no query strings) HREFs to later compare them against any hardcoded CSS
        
$allEnqueuedCleanLinkHrefs = array();

        if (! empty(
$wpStylesDone) && ! empty($wpStylesRegistered)) {
            foreach ( 
$wpStylesDone as $index => $styleHandle ) {
                if ( isset( 
Main::instance()->wpAllStyles['registered'][ $styleHandle ]->src ) && ( $src Main::instance()->wpAllStyles['registered'][ $styleHandle ]->src ) ) {
                    
$localAssetPath OptimizeCommon::getLocalAssetPath$src'css' );

                    if ( ! 
$localAssetPath || ! is_file$localAssetPath ) ) {
                        continue; 
// not a local file
                    
}

                    
ob_start();
                    
$wp_styles->do_item$styleHandle );
                    
$linkSourceTag trimob_get_clean() );

                    
// Check if the CSS has any 'data-wpacu-skip' attribute; if it does, do not alter it
                    
if ( preg_match'#data-wpacu-skip([=>/ ])#i'$linkSourceTag ) ) {
                        unset( 
$wpStylesDone$index ] );
                        continue;
                    }

                    
$cleanLinkHrefFromTagArray OptimizeCommon::getLocalCleanSourceFromTag$linkSourceTag'href' );

                    if ( isset( 
$cleanLinkHrefFromTagArray['source'] ) && $cleanLinkHrefFromTagArray['source'] ) {
                        
$allEnqueuedCleanLinkHrefs[] = $cleanLinkHrefFromTagArray['source'];
                    }
                }
            }
        }

        
$cssOptimizeList = array();

        if (! empty(
$wpStylesDone) && ! empty($wpStylesRegistered)) {
            foreach ( 
$wpStylesDone as $handle ) {
                if ( ! isset( 
$wpStylesRegistered$handle ]->src ) ) {
                    continue;
                }

                
$value $wpStylesRegistered$handle ];

                
$localAssetPath OptimizeCommon::getLocalAssetPath$value->src'css' );
                if ( ! 
$localAssetPath || ! is_file$localAssetPath ) ) {
                    continue; 
// not a local file
                
}

                
$optimizeValues self::maybeOptimizeIt$value );
                
ObjectCache::wpacu_cache_set'wpacu_maybe_optimize_it_css_' $handle$optimizeValues );

                if ( ! empty( 
$optimizeValues ) ) {
                    
$cssOptimizeList[] = $optimizeValues;
                }
            }
        }

        if (empty(
$cssOptimizeList)) {
            return;
        }

        
ObjectCache::wpacu_cache_add('wpacu_css_enqueued_hrefs'$allEnqueuedCleanLinkHrefs);
        
ObjectCache::wpacu_cache_add('wpacu_css_optimize_list'$cssOptimizeList);
        
// [End] Collect for caching
    
}

    
/**
     * @param $value
     *
     * @return mixed
     */
    
public static function maybeOptimizeIt($value)
    {
        if (
$optimizeValues ObjectCache::wpacu_cache_get('wpacu_maybe_optimize_it_css_'.$value->handle)) {
            return 
$optimizeValues;
        }

        global 
$wp_version;

        
$src = isset($value->src) ? $value->src false;

        if (! 
$src) {
            return array();
        }

        
$doFileMinify true;

        if (! 
MinifyCss::isMinifyCssEnabled()) {
            
$doFileMinify false;
        } elseif (
MinifyCss::skipMinify($src$value->handle)) {
            
$doFileMinify false;
        }

        
// Default (it will be later replaced with the last time the file was modified, which is more accurate)
        
$dbVer = (isset($value->ver) && $value->ver) ? $value->ver $wp_version;

        
$isCssFile false;

        
$localAssetPath OptimizeCommon::getLocalAssetPath($src'css');
        if (
$localAssetPath && is_file($localAssetPath)) {
            if (
$fileMTime = @filemtime($localAssetPath)) {
                
$dbVer $fileMTime;
            }
            
$isCssFile true;
        }

        
$handleDbStr md5($value->handle);

        
$transientName 'wpacu_css_optimize_'.$handleDbStr;

        
$skipCache false;

        if (isset(
$_GET['wpacu_no_cache']) || (defined('WPACU_NO_CACHE') && WPACU_NO_CACHE === true)) {
            
$skipCache true;
        }

        if (! 
$skipCache) {
            if (
Main::instance()->settings['fetch_cached_files_details_from'] === 'db_disk') {
                    if ( ! isset( 
$GLOBALS['wpacu_from_location_inc'] ) ) {
                        
$GLOBALS['wpacu_from_location_inc'] = 1;
                    }
                    
$fromLocation = ( $GLOBALS['wpacu_from_location_inc'] % ) ? 'db' 'disk';
                } else {
                    
$fromLocation Main::instance()->settings['fetch_cached_files_details_from'];
                }

            
$savedValues OptimizeCommon::getTransient($transientName$fromLocation);

            if ( 
$savedValues ) {
                
$savedValuesArray json_decode$savedValuesARRAY_A );

                if ( 
$savedValuesArray['ver'] !== $dbVer ) {
                    
// New File Version? Delete transient as it will be re-created with the new version
                    
OptimizeCommon::deleteTransient($transientName);
                } else {
                    
$localPathToCssOptimized str_replace'//''/'ABSPATH $savedValuesArray['optimize_uri'] );

                    
// Read the file from its caching (that makes the processing faster)
                    
if ( isset( $savedValuesArray['source_uri'] ) && is_file$localPathToCssOptimized ) ) {
                        if (
Main::instance()->settings['fetch_cached_files_details_from'] === 'db_disk') {
                            
$GLOBALS['wpacu_from_location_inc']++;
                        }
                        return array(
                            
$savedValuesArray['source_uri'],
                            
$savedValuesArray['optimize_uri'],
                            
$value->src,
                            
$value->handle
                        
);
                    }

                    
// If nothing valid gets returned above, make sure the transient gets deleted as it's re-added later on
                    
OptimizeCommon::deleteTransient($transientName);
                }
            }
        }

        
// Check if it starts without "/" or a protocol; e.g. "wp-content/theme/style.css"
        
if (strpos($src'/') !== &&
            
strpos($src'//') !== &&
            
stripos($src'http://') !== &&
            
stripos($src'https://') !== 0
        
) {
            
$src '/'.$src// append the forward slash to be processed as relative later on
        
}

        
// Starts with '/', but not with '//'
        
if (strpos($src'/') === && strpos($src'//') !== 0) {
            
$src site_url() . $src;
        }

        if (
Main::instance()->settings['cache_dynamic_loaded_css'] &&
            
$value->handle === 'sccss_style' &&
            
in_array('simple-custom-css/simple-custom-css.php'apply_filters('active_plugins'get_option('active_plugins', array())))
        ) {
            
$pathToAssetDir '';
            
$sourceBeforeOptimization $value->src;

            if (! (
$cssContent DynamicLoadedAssets::getAssetContentFrom('simple-custom-css'$value))) {
                return array();
            }
        } elseif (
Main::instance()->settings['cache_dynamic_loaded_css'] &&
                  ((
strpos($src'/?') !== false) || (strpos($srcrtrim(site_url(),'/').'?') !== false) || (strpos($src'.php?') !== false) || Misc::endsWith($src'.php')) &&
                  (
strpos($srcrtrim(site_url(), '/')) !== false)
        ) {
            
$pathToAssetDir '';
            
$sourceBeforeOptimization str_replace('&#038;''&'$value->src);

            if (! (
$cssContent DynamicLoadedAssets::getAssetContentFrom('dynamic'$value))) {
                return array();
            }
        } else {
            if (! 
$isCssFile) {
                return array();
            }

            
/*
             * This is a local .CSS file
             */
            
$pathToAssetDir OptimizeCommon::getPathToAssetDir($src);

            
$cssContent FileSystem::file_get_contents($localAssetPath'combine_css_imports');

            
$sourceBeforeOptimization str_replace(ABSPATH'/'$localAssetPath);
        }

        
$cssContent trim($cssContent);

        
/*
         * [START] CSS Content Optimization
        */
        // If there are no changes from this point, do not optimize (keep the file where it is)
        
$cssContentBefore $cssContent;

        if (
$cssContent) { // only proceed with extra alterations if there is some content there (save resources)
            
if ( Main::instance()->settings['google_fonts_display'] ) {
                
// Any "font-display" enabled in "Settings" - "Google Fonts"?
                
$cssContent FontsGoogle::alterGoogleFontUrlFromCssContent$cssContent );
            }

            
// Move any @imports to top; This also strips any @imports to Google Fonts if the option is chosen
            
$cssContent self::importsUpdate$cssContent );
        }

        
// If it stays like this, it means there is content there, even if only comments
        
$cssContentBecomesEmptyAfterMin false;

        if (
$doFileMinify && $cssContent) { // only bother to minify it if it has any content, save resources
            // Minify this file?
            
$cssContentBeforeMin trim($cssContent);
            
$cssContentAfterMin  MinifyCss::applyMinification($cssContent);

            
$cssContent $cssContentAfterMin;

            if (
$cssContentBeforeMin && $cssContentAfterMin === '') {
                
// It had content, but became empty after minification, most likely it had only comments (e.g. a default child theme's style)
                
$cssContentBecomesEmptyAfterMin true;
            }
        }

        if (
$cssContentBecomesEmptyAfterMin || $cssContent === '') {
            
$cssContent '/**/';
        } else {
            if ( 
Main::instance()->settings['google_fonts_remove'] ) {
                
$cssContent FontsGoogleRemove::cleanFontFaceReferences$cssContent );
            }

            
// No changes were made, thus, there's no point in changing the original file location
            
if ( $isCssFile && ! $cssContentBecomesEmptyAfterMin && trim$cssContentBefore ) === trim$cssContent ) ) {
                
// There's no point in changing the original CSS (static) file location
                
return false;
            }

            
// Continue, as changes are to be made
            // Does it have a source map? Strip it
            
if (strpos($cssContent'/*# sourceMappingURL=') !== false) {
                
$cssContent OptimizeCommon::stripSourceMap($cssContent'css');
            }

            
$cssContent self::maybeFixCssContent$cssContent$pathToAssetDir '/' ); // Path
        
}
        
/*
         * [END] CSS Content Optimization
        */

        // Relative path to the new file
        // Save it to /wp-content/cache/css/{OptimizeCommon::$optimizedSingleFilesDir}/
        /*
        if ($fileVer !== $wp_version) {
            if (is_array($fileVer)) {
                // Convert to string if it's an array (rare cases)
                $fileVer = implode('-', $fileVer);
            }
            $fileVer = trim(str_replace(' ', '_', preg_replace('/\s+/', ' ', $fileVer)));
            $fileVer = (strlen($fileVer) > 50) ? substr(md5($fileVer), 0, 20) : $fileVer; // don't end up with too long filenames
        }
        */
        
$fileVer sha1($cssContent);

        
$newFilePathUri  self::getRelPathCssCacheDir() . OptimizeCommon::$optimizedSingleFilesDir '/' sanitize_title($value->handle) . '-v' $fileVer;
        
$newFilePathUri .= '.css';

        if (
$cssContent === '') {
            
$cssContent '/**/';
        }

        if (
$cssContent === '/**/') {
            
// Leave a signature that the file is empty, thus it would be faster to take further actions upon it later on, saving resources)
            
$newFilePathUri str_replace('.css''-wpacu-empty-file.css'$newFilePathUri);
        }

        
$newLocalPath    WP_CONTENT_DIR $newFilePathUri// Ful Local path
        
$newLocalPathUrl WP_CONTENT_URL $newFilePathUri// Full URL path

        
if ($cssContent && $cssContent !== '/**/') {
            
$cssContent '/*!' $sourceBeforeOptimization '*/' $cssContent;
        }

        
$saveFile FileSystem::file_put_contents($newLocalPath$cssContent);

        if (! 
$saveFile && ! $cssContent) {
            
// Fallback to the original CSS if the optimized version can't be created or updated
            
return array();
        }

        
$saveValues = array(
            
'source_uri'   => OptimizeCommon::getSourceRelPath($src),
            
'optimize_uri' => OptimizeCommon::getSourceRelPath($newLocalPathUrl),
            
'ver'          => $dbVer
        
);

        
// Re-add transient
        
OptimizeCommon::setTransient($transientNamejson_encode($saveValues));

        return array(
            
OptimizeCommon::getSourceRelPath($src), // Original SRC (Relative path)
            
OptimizeCommon::getSourceRelPath($newLocalPathUrl), // New SRC (Relative path)
            
$value->src// SRC (as it is)
            
$value->handle
        
);
    }

    
/**
     * @param $htmlSource
     *
     * @return mixed|void
     */
    
public static function alterHtmlSource($htmlSource)
    {
        
// There has to be at least one "<link" or "<style", otherwise, it could be a feed request or something similar (not page, post, homepage etc.)
        
if ( (stripos($htmlSource'<link') === false && stripos($htmlSource'<style') === false) || array_key_exists('wpacu_no_optimize_css'$_GET) ) {
            return 
$htmlSource;
        }

        
/* [wpacu_timing] */ Misc::scriptExecTimer('alter_html_source_for_optimize_css'); /* [/wpacu_timing] */

        // Are there any assets unloaded where their "children" are ignored?
        // Since they weren't dequeued the WP way (to avoid unloading the "children"), they will be stripped here
        
if (! Main::instance()->preventAssetsSettings()) {
            
/* [wpacu_timing] */ $wpacuTimingName 'alter_html_source_unload_ignore_deps_css'Misc::scriptExecTimer($wpacuTimingName); /* [/wpacu_timing] */
            
$htmlSource self::ignoreDependencyRuleAndKeepChildrenLoaded($htmlSource);
            
/* [wpacu_timing] */ Misc::scriptExecTimer($wpacuTimingName'end'); /* [/wpacu_timing] */
        
}

        if (
self::isWorthCheckingForOptimization()) {
            
/* [wpacu_timing] */ $wpacuTimingName 'alter_html_source_original_to_optimized_css'Misc::scriptExecTimer($wpacuTimingName); /* [/wpacu_timing] */
            // 'wpacu_css_optimize_list' caching list is also checked; if it's empty, no optimization is made
            
$htmlSource self::updateHtmlSourceOriginalToOptimizedCss($htmlSource);
            
/* [wpacu_timing] */ Misc::scriptExecTimer($wpacuTimingName'end'); /* [/wpacu_timing] */
        
}

        if (! 
Main::instance()->preventAssetsSettings()) {
            
/* [wpacu_timing] */ $wpacuTimingName 'alter_html_source_for_preload_css'Misc::scriptExecTimer($wpacuTimingName); /* [/wpacu_timing] */
            
$htmlSource Preloads::instance()->doChanges($htmlSource);
            
/* [wpacu_timing] */ Misc::scriptExecTimer($wpacuTimingName'end'); /* [/wpacu_timing] */
        
}

        if (
self::isInlineCssEnabled()) {
            
/* [wpacu_timing] */ $wpacuTimingName 'alter_html_source_for_inline_css'Misc::scriptExecTimer($wpacuTimingName); /* [/wpacu_timing] */
            
$htmlSource self::doInline($htmlSource);
            
/* [wpacu_timing] */ Misc::scriptExecTimer($wpacuTimingName'end'); /* [/wpacu_timing] */
        
}

        
$proceedWithCombineOnThisPage true;

        
// If "Do not combine CSS on this page" is checked in "Asset CleanUp: Options" side meta box
        // Works for posts, pages and custom post types
        
if (defined('WPACU_CURRENT_PAGE_ID') && WPACU_CURRENT_PAGE_ID 0) {
            
$pageOptions MetaBoxes::getPageOptions(WPACU_CURRENT_PAGE_ID);

            
// 'no_css_optimize' refers to avoid the combination of CSS files
            
if ( isset( $pageOptions['no_css_optimize'] ) && $pageOptions['no_css_optimize'] ) {
                
$proceedWithCombineOnThisPage false;
            }
        }

        if (
$proceedWithCombineOnThisPage) {
            
/* [wpacu_timing] */ $wpacuTimingName 'alter_html_source_for_combine_css'Misc::scriptExecTimer($wpacuTimingName); /* [/wpacu_timing] */
            
$htmlSource CombineCss::doCombine($htmlSource);
            
/* [wpacu_timing] */ Misc::scriptExecTimer($wpacuTimingName'end'); /* [/wpacu_timing] */
        
}

        if (! 
Main::instance()->preventAssetsSettings() && Main::instance()->settings['minify_loaded_css'] && Main::instance()->settings['minify_loaded_css_inline']) {
            
/* [wpacu_timing] */ $wpacuTimingName 'alter_html_source_for_minify_inline_style_tags'Misc::scriptExecTimer($wpacuTimingName); /* [/wpacu_timing] */
            
$htmlSource MinifyCss::minifyInlineStyleTags($htmlSource);
            
/* [wpacu_timing] */ Misc::scriptExecTimer($wpacuTimingName'end'); /* [/wpacu_timing] */
        
}

        
// Final cleanups
        
$htmlSource preg_replace('#<link(\s+|)data-wpacu-link-rel-href-before=(["\'])' '(.*)' '(\1)#Usmi''<link '$htmlSource);
        
//$htmlSource = preg_replace('#<link(.*)data-wpacu-style-handle=\'(.*)\'#Umi', '<link \\1', $htmlSource);

        /* [wpacu_timing] */ 
$wpacuTimingName 'alter_html_source_for_google_fonts_optimization_removal'Misc::scriptExecTimer($wpacuTimingName); /* [/wpacu_timing] */
        // Alter HTML Source for Google Fonts Optimization / Removal
        
$htmlSource FontsGoogle::alterHtmlSource($htmlSource);
        
/* [wpacu_timing] */ Misc::scriptExecTimer($wpacuTimingName'end'); /* [/wpacu_timing] */

        // NOSCRIPT fallback: Applies for Google Fonts (async) (Lite and Pro) /  Preloads (Async in Pro version) / Critical CSS (as as LINK "stylesheet" tags will be async preloaded)
        /* [wpacu_timing] */ 
$wpacuTimingName 'alter_html_source_for_add_async_preloads_noscript'Misc::scriptExecTimer($wpacuTimingName); /* [/wpacu_timing] */
        
$htmlSource apply_filters('wpacu_add_noscript_certain_link_tags'$htmlSource);
        
/* [wpacu_timing] */ Misc::scriptExecTimer($wpacuTimingName'end'); /* [/wpacu_timing] */

        /* [wpacu_timing] */ 
Misc::scriptExecTimer('alter_html_source_for_optimize_css''end'); /* [/wpacu_timing] */

        
return $htmlSource;
    }

    
/**
     * @return string
     */
    
public static function getRelPathCssCacheDir()
    {
        return 
OptimizeCommon::getRelPathPluginCacheDir().'css/'// keep trailing slash at the end
    
}

    
/**
     * @param $firstLinkHref
     * @param $htmlSource
     *
     * @return string
     */
    
public static function getFirstLinkTag($firstLinkHref$htmlSource)
    {
        
preg_match_all('#<link[^>]*stylesheet[^>]*(>)#Umi'$htmlSource$matches);
        foreach (
$matches[0] as $matchTag) {
            if (
strpos($matchTag$firstLinkHref) !== false) {
                return 
trim($matchTag);
            }
        }

        return 
'';
    }

    
/**
     *
     * @param $cssContent
     * @param $appendBefore
     * @param $fix
     *
     * @return mixed
     */
    
public static function maybeFixCssContent($cssContent$appendBefore$fix 'path')
    {
        
// Updates (background | font etc.) URLs to the right path and others
        
if ($fix === 'path') {
            
// Clear any extra spaces between @import and the single/double quotes
            
$cssContent preg_replace('/@import(\s+|)([\'"])/i''@import \\2'$cssContent);

            
$cssContentPathReps = array(
                
// @import with url(), background-image etc.
                
'url("../' => 'url("'.$appendBefore.'../',
                
"url('../" => "url('".$appendBefore.'../',
                
'url(../'  => 'url('.$appendBefore.'../',

                
'url("./'  => 'url("'.$appendBefore.'./',
                
"url('./"  => "url('".$appendBefore.'./',
                
'url(./'   => 'url('.$appendBefore.'./',

                
// @import without URL
                
'@import "../' => '@import "'.$appendBefore.'../',
                
"@import '../" => "@import '".$appendBefore.'../',

                
'@import "./'  => '@import "'.$appendBefore.'./',
                
"@import './"  => "@import '".$appendBefore.'./'
            
);

            
$cssContent str_replace(array_keys($cssContentPathReps), array_values($cssContentPathReps), $cssContent);

            
// Rare cases
            
$cssContent preg_replace('/url\((\s+)http/i''url(http'$cssContent);

            
// Avoid Background URLs starting with "data", "http" or "https" as they do not need to have a path updated
            
preg_match_all('/url\((?![\'"]?(?:data|http|https):)[\'"]?([^\'")]*)[\'"]?\)/i'$cssContent$matches);

            
// If it start with forward slash (/), it doesn't need fix, just skip it
            // Also skip ../ types as they were already processed
            
$toSkipList = array("url('/"'url("/''url(/');

            foreach (
$matches[0] as $match) {
                
$fullUrlMatch trim($match);

                foreach (
$toSkipList as $toSkip) {
                    if (
substr($fullUrlMatch0strlen($toSkip)) === $toSkip) {
                        continue 
2// doesn't need any fix, go to the next match
                    
}
                }

                
// Go through all situations: with and without quotes, with traversal directory (e.g. ../../)
                
$alteredMatch str_replace(
                    array(
'url("'"url('"),
                    array(
'url("' $appendBefore"url('" $appendBefore),
                    
$fullUrlMatch
                
);

                
$alteredMatch trim($alteredMatch);

                if (! 
in_array($fullUrlMatch[4], array("'"'"''/''.'))) {
                    
$alteredMatch str_replace('url(''url(' $appendBefore$alteredMatch);
                    
$alteredMatch str_replace(array('")''\')'), ')'$alteredMatch);
                }

                
// Finally, apply the changes
                
$cssContent str_replace($fullUrlMatch$alteredMatch$cssContent);

                
// Bug fix
                
$cssContent str_replace(
                    array(
$appendBefore '"' $appendBefore$appendBefore "'" $appendBefore),
                    
$appendBefore,
                    
$cssContent
                
);

                
// Bug Fix 2
                
$cssContent str_replace($appendBefore 'http''http'$cssContent);
                
$cssContent str_replace($appendBefore '//''//'$cssContent);
            }
        }

        return 
$cssContent;
    }

    
/**
     * Next: Alter the HTML source by updating the original link URLs with the just cached ones
     *
     * @param $htmlSource
     *
     * @return mixed
     */
    
public static function updateHtmlSourceOriginalToOptimizedCss($htmlSource)
    {
        
$cssOptimizeList ObjectCache::wpacu_cache_get('wpacu_css_optimize_list') ?: array();

        if (empty(
$cssOptimizeList)) {
            return 
$htmlSource;
        }

        
$allEnqueuedCleanLinkHrefs ObjectCache::wpacu_cache_get('wpacu_css_enqueued_hrefs') ?: array();

        
$cdnUrls OptimizeCommon::getAnyCdnUrls();
        
$cdnUrlForCss = isset($cdnUrls['css']) ? $cdnUrls['css'] : false;

        
// Grabs both LINK "stylesheet" and those with as="style" which is for preloaded LINK tags
        
preg_match_all('#<link[^>]*(stylesheet|(as(\s+|)=(\s+|)(|"|\')style(|"|\')))[^>]*>#Umi'OptimizeCommon::cleanerHtmlSource$htmlSource, array( 'for_fetching_link_tags' ) ), $matchesSourcesFromTagsPREG_SET_ORDER);

        if (empty(
$matchesSourcesFromTags)) {
            return 
$htmlSource;
        }

        
$linkTagsToUpdate = array();

        foreach (
$matchesSourcesFromTags as $matches) {
            
$linkSourceTag $matches[0];

            if (
$linkSourceTag === '' || strip_tags($linkSourceTag) !== '') {
                
// Hmm? Not a valid tag... Skip it...
                
continue;
            }

            
// Check if the CSS has any 'data-wpacu-skip' attribute; if it does, do not alter it
            
if (preg_match('#data-wpacu-skip([=>/ ])#i'$linkSourceTag)) {
                continue;
            }

            
$cleanLinkHrefFromTagArray OptimizeCommon::getLocalCleanSourceFromTag($linkSourceTag'href');

            
// Skip external links, no point in carrying on
            
if (! $cleanLinkHrefFromTagArray || ! is_array($cleanLinkHrefFromTagArray)) {
                continue;
            }

            
// Is it a local CSS? Check if it's hardcoded (not enqueued the WordPress way)
            
$cleanLinkHrefFromTag $cleanLinkHrefFromTagArray['source'];
            
$afterQuestionMark $cleanLinkHrefFromTagArray['after_question_mark'];

            if (! 
in_array($cleanLinkHrefFromTag$allEnqueuedCleanLinkHrefs)) {
                
// Not in the final enqueued list? Most likely hardcoded (not added via wp_enqueue_scripts())
                // Emulate the object value (as the enqueued styles)
                
$generatedHandle md5($cleanLinkHrefFromTag);

                
$value = (object)array(
                    
'handle' => $generatedHandle,
                    
'src'    => $cleanLinkHrefFromTag,
                    
'ver'    => md5($afterQuestionMark)
                );

                
$optimizeValues self::maybeOptimizeIt($value);
                
ObjectCache::wpacu_cache_set('wpacu_maybe_optimize_it_css_'.$generatedHandle$optimizeValues);

                if (! empty(
$optimizeValues)) {
                    
$cssOptimizeList[] = $optimizeValues;
                }
            }

            foreach (
$cssOptimizeList as $cssItemIndex => $listValues) {
                
// Index 0: Source URL (relative)
                // Index 1: New Optimized URL (relative)
                // Index 2: Source URL (as it is)

                // The contents of the CSS file has been changed and thus, we will replace the source path from LINK with the cached (e.g. minified) one

                // If the minified files are deleted (e.g. /wp-content/cache/ is cleared)
                // do not replace the CSS file path to avoid breaking the website
                
$localPathOptimizedFile rtrim(ABSPATH'/') . $listValues[1];

                if (! 
is_file($localPathOptimizedFile)) {
                    continue;
                }

                
// Make sure the source URL gets updated even if it starts with // (some plugins/theme strip the protocol when enqueuing CSS files)
                
$siteUrlNoProtocol str_replace(array('http://''https://'), '//'site_url());

                
// If the first value fails to be replaced, the next one will be attempted for replacement
                // the order of the elements in the array is very important
                
$sourceUrlList = array(
                    
site_url() . $listValues[0], // with protocol
                    
$siteUrlNoProtocol $listValues[0// without protocol
                
);

                if (
$cdnUrlForCss) {
                    
// Does it have a CDN?
                    
$sourceUrlList[] = OptimizeCommon::cdnToUrlFormat($cdnUrlForCss'rel') . $listValues[0];
                }

                
// Any rel tag? You never know
                // e.g. <link src="/wp-content/themes/my-theme/style.css"></script>
                
if ( (strpos($listValues[2], '/') === && strpos($listValues[2], '//') !== 0)
                    || (
strpos($listValues[2], '/') !== &&
                        
strpos($listValues[2], '//') !== &&
                        
stripos($listValues[2], 'http://') !== &&
                        
stripos($listValues[2], 'https://') !== 0) ) {
                    
$sourceUrlList[] = $listValues[2];
                }

                
// If no CDN is set, it will return site_url() as a prefix
                
$optimizeUrl OptimizeCommon::cdnToUrlFormat($cdnUrlForCss'raw') . $listValues[1]; // string

                
if ($linkSourceTag !== str_replace($sourceUrlList$optimizeUrl$linkSourceTag)) {
                    
// Extra measure: Check the file size which should be 4 bytes, but add some margin error in case some environments will report less
                    
$isEmptyOptimizedFile = (strpos($localPathOptimizedFile'-wpacu-empty-file.css') !== false && filesize($localPathOptimizedFile) < 10);

                    
// Strip it as its content (after optimization, for instance) is empty; no point in having extra HTTP requests
                    
if ($isEmptyOptimizedFile) {
                        
// Note: As for September 3, 2020, the inline CSS associated with the handle is no longer removed if the main CSS file is empty
                        // There could be cases when the main CSS file is empty (e.g. theme's styling), but the inline STYLE tag associated with it has syntax that is needed

                        
$htmlSource       str_replace($linkSourceTag''$htmlSource);

                        } else {
                        
// Do the replacement
                        
$newLinkSourceTag self::updateOriginalToOptimizedTag$linkSourceTag$sourceUrlList$optimizeUrl );
                        
$linkTagsToUpdate[$linkSourceTag] = $newLinkSourceTag;
                        }

                    unset(
$cssOptimizeList[$cssItemIndex]); // item from the array is not needed anymore
                    
break; // there was a match, stop here
                
}
            }
        }

        
$htmlSource strtr($htmlSource$linkTagsToUpdate);

        return 
$htmlSource;
    }

    
/**
     * @param $linkSourceTag string
     * @param $sourceUrlList array
     * @param $optimizeUrl string
     *
     * @return mixed
     */
    
public static function updateOriginalToOptimizedTag($linkSourceTag$sourceUrlList$optimizeUrl)
    {
        
$newLinkSourceTag str_replace($sourceUrlList$optimizeUrl$linkSourceTag);

        
// Needed in case it's added to the Combine CSS exceptions list
        
if (CombineCss::proceedWithCssCombine()) {
            
$sourceUrlRel is_array($sourceUrlList) ? OptimizeCommon::getSourceRelPath($sourceUrlList[0]) : OptimizeCommon::getSourceRelPath($sourceUrlList);
            
$newLinkSourceTag str_ireplace('<link ''<link data-wpacu-link-rel-href-before="'.$sourceUrlRel.'" '$newLinkSourceTag);
        }

        
preg_match_all'#\shref=(["\'])(.*?)(["\'])#'$newLinkSourceTag$outputMatchesSrc );

        
// No space from the matching and ? should be there
        
if (isset( $outputMatchesSrc[2][0] ) && ( strpos$outputMatchesSrc[2][0], ' ' ) === false )) {
            if ( 
strpos$outputMatchesSrc[2][0], '?' ) !== false ) {
                
// Strip things like ?ver=
                
list( , $toStrip ) = explode'?'$outputMatchesSrc[2][0] );
                
$toStrip            '?' trim$toStrip );
                
$newLinkSourceTag str_replace$toStrip''$newLinkSourceTag );
            }

            if ( 
strpos$outputMatchesSrc[2][0], '&#038;ver' ) !== false ) {
                
// Replace any .js&#038;ver with .js
                
$toStrip strrchr($outputMatchesSrc[2][0], '&#038;ver');
                
$newLinkSourceTag str_replace$toStrip''$newLinkSourceTag );
            }
        }

        global 
$wp_version;
        
$newLinkSourceTag str_replace('.css&#038;ver='.$wp_version'.css'$newLinkSourceTag);
        
$newLinkSourceTag str_replace('.css&#038;ver=''.css'$newLinkSourceTag);

        
$newLinkSourceTag preg_replace('!\s+!'' '$newLinkSourceTag); // replace multiple spaces with only one space

        
return $newLinkSourceTag;
    }

    
/**
     * @return bool
     */
    
public static function isInlineCssEnabled()
    {
        
$isEnabledInSettingsWithListOrAuto = (Main::instance()->settings['inline_css_files'] &&
            (
trim(Main::instance()->settings['inline_css_files_list']) !== '' || self::isAutoInlineEnabled()));

        if (! 
$isEnabledInSettingsWithListOrAuto) {
            return 
false;
        }

        
// Deactivate it for debugging purposes via query string /?wpacu_no_inline_js
        
if (array_key_exists('wpacu_no_inline_css'$_GET)) {
            return 
false;
        }

        
// Finally, return true
        
return true;
    }

    
/**
     * From LINK to STYLE tag: it processes the contents of the LINK stylesheet and replaces the tag with a STYLE tag having the content inlined
     *
     * @param $htmlSource
     *
     * @return mixed
     */
    
public static function doInline($htmlSource)
    {
        
$allPatterns self::getAllInlineChosenPatterns();

        
// Skip any LINK tags within conditional comments (e.g. Internet Explorer ones)
        
preg_match_all(
            
'#<link[^>]*rel=([\'"])stylesheet([\'"])[^>]*\shref.*>#Usmi',
            
OptimizeCommon::cleanerHtmlSource$htmlSource, array( 'strip_content_between_conditional_comments''for_fetching_link_tags' ) ),
            
$matchesSourcesFromTags,
            
PREG_SET_ORDER
        
);

        
// In case automatic inlining is used
        
$belowSizeInput = (int)Main::instance()->settings['inline_css_files_below_size_input'];

        if (
$belowSizeInput === 0) {
            
$belowSizeInput 1// needs to have a minimum value
        
}

        if (! empty(
$matchesSourcesFromTags)) {
            
$cdnUrls OptimizeCommon::getAnyCdnUrls();
            
$cdnUrlForCss = isset($cdnUrls['css']) ? trim($cdnUrls['css']) : false;

            foreach (
$matchesSourcesFromTags as $matchList) {
                
$matchedTag $matchList[0];

                
// Do not inline the admin bar SCRIPT file, saving resources as it's shown for the logged-in user only
                
if (strpos($matchedTag'/wp-includes/css/admin-bar') !== false) {
                    continue;
                }

                
// They were preloaded for a reason, leave them
                
if (strpos($matchedTag'data-wpacu-preload-it-async=') !== false || strpos($matchedTag'data-wpacu-to-be-preloaded-basic=') !== false) {
                    continue;
                }

                if (
strip_tags($matchedTag) !== '') {
                    continue; 
// something is funny, don't mess with the HTML alteration, leave it as it was
                
}

                
$chosenInlineCssMatches false;

                
// Condition #1: Only chosen (via textarea) CSS get inlined
                
if ( false !== strpos$matchedTag' wpacu-to-be-inlined' ) ) {
                    
$chosenInlineCssMatches true;
                } elseif ( ! empty( 
$allPatterns ) ) {
                    
// Fallback, in case "wpacu-to-be-inlined" was not already added to the tag
                    
foreach ($allPatterns as $patternToCheck) {
                        if (
preg_match('#'.$patternToCheck.'#si'$matchedTag) || strpos($matchedTag$patternToCheck) !== false) {
                            
$chosenInlineCssMatches true;
                            break;
                        }
                    }
                }

                
// Is auto inline disabled and the chosen CSS does not match? Continue to the next LINK tag
                
if (! $chosenInlineCssMatches && ! self::isAutoInlineEnabled()) {
                    continue;
                }

                
preg_match_all('#href=(["\'])' '(.*)' '(["\'])#Usmi'$matchedTag$outputMatchesHref);
                
$linkHrefOriginal trim($outputMatchesHref[2][0], '"\'');
                
$localAssetPath OptimizeCommon::getLocalAssetPath($linkHrefOriginal'css');

                if (! 
$localAssetPath) {
                    continue; 
// Not on the same domain
                
}

                
// Condition #2: Auto inline is enabled and there's no match for any entry in the textarea
                
if (! $chosenInlineCssMatches && self::isAutoInlineEnabled()) {
                    
$fileSizeKb number_format(filesize($localAssetPath) / 10242);

                    
// If it's not smaller than the value from the input, do not continue with the inlining
                    
if ($fileSizeKb >= $belowSizeInput) {
                        continue;
                    }
                }

                
// Is there a media attribute? Make sure to add it to the STYLE tag
                
preg_match_all('#media=(["\'])' '(.*)' '(["\'])#Usmi'$matchedTag$outputMatchesMedia);
                
$mediaAttrValue = isset($outputMatchesMedia[2][0]) ? trim($outputMatchesMedia[2][0], '"\'') : '';
                
$mediaAttr = ($mediaAttrValue && $mediaAttrValue !== 'all') ? 'media=\''.$mediaAttrValue.'\'' '';

                
$appendBeforeAnyRelPath $cdnUrlForCss OptimizeCommon::cdnToUrlFormat($cdnUrlForCss'raw') : '';

                
$cssContent self::maybeFixCssContent(
                    
FileSystem::file_get_contents($localAssetPath'combine_css_imports'), // CSS content
                    
$appendBeforeAnyRelPath OptimizeCommon::getPathToAssetDir($linkHrefOriginal) . '/'
                
);

                
// The CSS file is read from its original plugin/theme/cache location
                // If minify was enabled, then it's already minified, no point in re-minify it to save resources
                // Changing paths (relative) to fonts, images, etc. are relevant in this case
                
$cssContent self::maybeAlterContentForCssFile($cssContentfalse);

                if (
$cssContent && $cssContent !== '/**/') {
                    
$htmlSource str_replace(
                        
$matchedTag,
                        
'<style type=\'text/css\' '.$mediaAttr.' data-wpacu-inline-css-file=\'1\'>'."\n".$cssContent."\n".'</style>',
                        
$htmlSource
                    
);
                } else {
                    
// After CSS alteration (e.g. minify), there's no content left, most likely the CSS file contained only comments, elements without any syntax or empty spaces
                    // Strip the tag completely as there's no reason to print an empty SCRIPT tag to further add to the total DOM elements
                    
$htmlSource str_replace($matchedTag''$htmlSource);
                }
            }
        }

        return 
$htmlSource;
    }

    
/**
     * This applies to both inline and static JS files contents
     *
     * @param $cssContent
     * @param bool $doCssMinify (false by default as it could be already minified or non-minify type)
     * @param array $extraParams
     *
     * @return mixed|string|string[]|null
     */
    
public static function maybeAlterContentForCssFile($cssContent$doCssMinify false$extraParams = array())
    {
        if (! 
trim($cssContent)) {
            return 
$cssContent;
        }

        
/* [START] Change CSS Content */
        // Move any @imports to top; This also strips any @imports to Google Fonts if the option is chosen
        
$cssContent self::importsUpdate$cssContent );

        if ( 
$doCssMinify ) {
            
$cssContent MinifyCss::applyMinification$cssContent$doCssMinify );
        }

        if ( 
Main::instance()->settings['google_fonts_remove'] ) {
            
$cssContent FontsGoogleRemove::cleanFontFaceReferences$cssContent );
        }

        
// Does it have a source map? Strip it
        
if (strpos($cssContent'/*# sourceMappingURL=') !== false) {
            
$cssContent OptimizeCommon::stripSourceMap($cssContent'css');
        }
        
/* [END] Change CSS Content */

        
return $cssContent;
    }

    
/**
     * @param $cssContent
     * @param bool $doCssMinify
     * @param array $extraParams
     *
     * @return mixed|string
     */
    
public static function maybeAlterContentForInlineStyleTag($cssContent$doCssMinify false$extraParams = array())
    {
        if (! 
trim($cssContent)) {
            return 
$cssContent;
        }

        
$useCacheForInlineStyle true;

        if (
mb_strlen($cssContent) > 500000) { // Bigger then ~500KB? Skip alteration
            
return $cssContent;
        }

        if (
mb_strlen($cssContent) < 40000) { // Smaller than than ~40KB? Do not cache it
            
$useCacheForInlineStyle false;
        }

        
// For debugging purposes
        
if (isset($_GET['wpacu_no_cache']) || (defined('WPACU_NO_CACHE') && WPACU_NO_CACHE === true)) { $useCacheForInlineStyle false; }

        if (
$useCacheForInlineStyle) {
            
// Anything in the cache? Take it from there and don't spend resources with the minification
            // (which in some environments uses the CPU, depending on the complexity of the JavaScript code) and any other alteration
            
$cssContentBeforeHash sha1$cssContent );

            
$pathToInlineCssOptimizedItem WP_CONTENT_DIR self::getRelPathCssCacheDir() . '/item/inline/' $cssContentBeforeHash '.css';

            
// Check if the file exists before moving forward
            
if ( is_file$pathToInlineCssOptimizedItem ) ) {
                
$cachedCssFileExpiresIn OptimizeCommon::$cachedAssetFileExpiresIn;

                if ( 
filemtime$pathToInlineCssOptimizedItem ) < ( time() - $cachedCssFileExpiresIn ) ) {
                    
// Has the caching period expired? Remove the file as a new one has to be generated
                    
@unlink$pathToInlineCssOptimizedItem );
                } else {
                    
// Not expired / Return its content from the cache in a faster way
                    
$inlineCssStorageItemJsonContent trimFileSystem::file_get_contents$pathToInlineCssOptimizedItem ) );

                    if ( 
$inlineCssStorageItemJsonContent !== '' ) {
                        return 
$inlineCssStorageItemJsonContent;
                    }
                }
            }
        }

        
/* [START] Change CSS Content */
        
if ( $doCssMinify && in_array('just_minify'$extraParams) ) {
            
$cssContent MinifyCss::applyMinification$cssContent$useCacheForInlineStyle );
        } else {
            
// Move any @imports to top; This also strips any @imports to Google Fonts if the option is chosen
            
$cssContent self::importsUpdate$cssContent );

            if ( 
$doCssMinify ) {
                
$cssContent MinifyCss::applyMinification$cssContent$useCacheForInlineStyle );
            }

            if ( 
Main::instance()->settings['google_fonts_remove'] ) {
                
$cssContent FontsGoogleRemove::cleanFontFaceReferences$cssContent );
            }
        }
        
/* [END] Change CSS Content */

        
if ($useCacheForInlineStyle && isset($pathToInlineCssOptimizedItem)) {
            
// Store the optimized content to the cached CSS file which would be read quicker
            
FileSystem::file_put_contents$pathToInlineCssOptimizedItem$cssContent );
        }

        return 
$cssContent;
    }

    
/**
     * @return bool
     */
    
public static function isAutoInlineEnabled()
    {
        return 
Main::instance()->settings['inline_css_files'] &&
               
Main::instance()->settings['inline_css_files_below_size'] &&
               (int)
Main::instance()->settings['inline_css_files_below_size_input'] > 0;
    }

    
/**
     * Source: https://www.minifier.org/ | https://github.com/matthiasmullie/minify
     *
     * @param $content
     *
     * @return string
     */
    
public static function importsUpdate($content)
    {
        if (
preg_match_all('/(;?)(@import (?<url>url\()?(?P<quotes>["\']?).+?(?P=quotes)(?(url)\)));?/'$content$matches)) {
            
// Remove from content (they will be appended to the top if they qualify)
            
foreach ($matches[0] as $import) {
                
$content str_replace($import''$content);
            }

            
// Strip any @imports to Google Fonts if it's the case
            
$importsAddToTop Main::instance()->settings['google_fonts_remove'] ? FontsGoogleRemove::stripGoogleApisImport($matches[2]) : $matches[2];

            
// Add to top if there are any imports left
            
if (! empty($importsAddToTop)) {
                
$content implode(';'$importsAddToTop) . ';' trim($content';');
            }
        }

        return 
$content;
    }

    
/**
     * @param string $returnType
     *
     * @return array|bool
     */
    
public static function isOptimizeCssEnabledByOtherParty($returnType 'list')
    {
        
$pluginsToCheck = array(
            
'autoptimize/autoptimize.php'            => 'Autoptimize',
            
'wp-rocket/wp-rocket.php'                => 'WP Rocket',
            
'wp-fastest-cache/wpFastestCache.php'    => 'WP Fastest Cache',
            
'w3-total-cache/w3-total-cache.php'      => 'W3 Total Cache',
            
'sg-cachepress/sg-cachepress.php'        => 'SG Optimizer',
            
'fast-velocity-minify/fvm.php'           => 'Fast Velocity Minify',
            
'litespeed-cache/litespeed-cache.php'    => 'LiteSpeed Cache',
            
'swift-performance-lite/performance.php' => 'Swift Performance Lite',
            
'breeze/breeze.php'                      => 'Breeze – WordPress Cache Plugin'
        
);

        
$cssOptimizeEnabledIn = array();

        foreach (
$pluginsToCheck as $plugin => $pluginTitle) {
            
// "Autoptimize" check
            
if ($plugin === 'autoptimize/autoptimize.php' && Misc::isPluginActive($plugin) && get_option('autoptimize_css')) {
                
$cssOptimizeEnabledIn[] = $pluginTitle;

                if (
$returnType === 'if_enabled') { return true; }
            }

            
// "WP Rocket" check
            
if ($plugin === 'wp-rocket/wp-rocket.php' && Misc::isPluginActive($plugin)) {
                if (
function_exists('get_rocket_option')) {
                    
$wpRocketMinifyCss trim(get_rocket_option('minify_css')) ?: false;
                    
$wpRocketMinifyConcatenateCss trim(get_rocket_option('minify_concatenate_css')) ?: false;
                } else {
                    
$wpRocketSettings  get_option('wp_rocket_settings');
                    
$wpRocketMinifyCss = isset($wpRocketSettings['minify_css']) && trim($wpRocketSettings['minify_css']);
                    
$wpRocketMinifyConcatenateCss = isset($wpRocketSettings['minify_concatenate_css']) && trim($wpRocketSettings['minify_concatenate_css']);
                }

                if (
$wpRocketMinifyCss || $wpRocketMinifyConcatenateCss) {
                    
$cssOptimizeEnabledIn[] = $pluginTitle;

                    if (
$returnType === 'if_enabled') { return true; }
                }
            }

            
// "WP Fastest Cache" check
            
if ($plugin === 'wp-fastest-cache/wpFastestCache.php' && Misc::isPluginActive($plugin)) {
                
$wpfcOptionsJson get_option('WpFastestCache');
                
$wpfcOptions = @json_decode($wpfcOptionsJsonARRAY_A);

                if (isset(
$wpfcOptions['wpFastestCacheMinifyCss']) || isset($wpfcOptions['wpFastestCacheCombineCss'])) {
                    
$cssOptimizeEnabledIn[] = $pluginTitle;

                    if (
$returnType === 'if_enabled') { return true; }
                }
            }

            
// "W3 Total Cache" check
            
if ($plugin === 'w3-total-cache/w3-total-cache.php' && Misc::isPluginActive($plugin)) {
                
$w3tcConfigMaster Misc::getW3tcMasterConfig();
                
$w3tcEnableCss = (int)trim(Misc::extractBetween($w3tcConfigMaster'"minify.css.enable":'','), '" ');

                if (
$w3tcEnableCss === 1) {
                    
$cssOptimizeEnabledIn[] = $pluginTitle;

                    if (
$returnType === 'if_enabled') { return true; }
                }
            }

            
// "SG Optimizer" check
            
if ($plugin === 'sg-cachepress/sg-cachepress.php' && Misc::isPluginActive($plugin)) {
                if (
class_exists('\SiteGround_Optimizer\Options\Options')
                    && 
method_exists('\SiteGround_Optimizer\Options\Options''is_enabled')
                    && @\
SiteGround_Optimizer\Options\Options::is_enabled('siteground_optimizer_combine_css')) {
                    
$cssOptimizeEnabledIn[] = $pluginTitle;
                    if (
$returnType === 'if_enabled') { return true; }
                }
            }

            
// "Fast Velocity Minify" check
            
if ($plugin === 'fast-velocity-minify/fvm.php' && Misc::isPluginActive($plugin)) {
                
// It's enough if it's active due to its configuration
                
$cssOptimizeEnabledIn[] = $pluginTitle;

                if (
$returnType === 'if_enabled') { return true; }
            }

            
// "LiteSpeed Cache" check
            
if ($plugin === 'litespeed-cache/litespeed-cache.php' && Misc::isPluginActive($plugin) && ($liteSpeedCacheConf apply_filters('litespeed_cache_get_options'get_option('litespeed-cache-conf')))) {
                if ( (isset(
$liteSpeedCacheConf['css_minify']) && $liteSpeedCacheConf['css_minify'])
                     || (isset(
$liteSpeedCacheConf['css_combine']) && $liteSpeedCacheConf['css_combine']) ) {
                    
$cssOptimizeEnabledIn[] = $pluginTitle;

                    if (
$returnType === 'if_enabled') { return true; }
                }
            }

            
// "Swift Performance Lite" check
            
if ($plugin === 'swift-performance-lite/performance.php' && Misc::isPluginActive($plugin)
                && 
class_exists('Swift_Performance_Lite') && method_exists('Swift_Performance_Lite''check_option')) {
                if ( @\
Swift_Performance_Lite::check_option('merge-styles'1) ) {
                    
$cssOptimizeEnabledIn[] = $pluginTitle;
                }

                if (
$returnType === 'if_enabled') { return true; }
            }

            
// "Breeze – WordPress Cache Plugin"
            
if ($plugin === 'breeze/breeze.php' && Misc::isPluginActive($plugin)) {
                
$breezeBasicSettings    get_option('breeze_basic_settings');
                
$breezeAdvancedSettings get_option('breeze_advanced_settings');

                if (isset(
$breezeBasicSettings['breeze-minify-css'], $breezeAdvancedSettings['breeze-group-css'])
                    && 
$breezeBasicSettings['breeze-minify-css'] && $breezeAdvancedSettings['breeze-group-css']) {
                    
$cssOptimizeEnabledIn[] = $pluginTitle;

                    if (
$returnType === 'if_enabled') { return true; }
                }
            }
        }

        if (
$returnType === 'if_enabled') { return false; }

        return 
$cssOptimizeEnabledIn;
    }

    
/**
     * @return bool
     */
    
public static function isWpRocketOptimizeCssDeliveryEnabled()
    {
        if (
Misc::isPluginActive('wp-rocket/wp-rocket.php')) {
            if (
function_exists('get_rocket_option')) {
                
$wpRocketAsyncCss trim(get_rocket_option('async_css')) ?: false;
            } else {
                
$wpRocketSettings  get_option('wp_rocket_settings');
                
$wpRocketAsyncCss = isset($wpRocketSettings['async_css']) && trim($wpRocketSettings['async_css']);
            }

            return 
$wpRocketAsyncCss;
        }

        return 
false;
    }

    
/**
     * @return bool
     */
    
public static function wpfcMinifyCssEnabledOnly()
    {
        if (
Misc::isPluginActive('wp-fastest-cache/wpFastestCache.php')) {
            
$wpfcOptionsJson get_option('WpFastestCache');
            
$wpfcOptions     = @json_decode($wpfcOptionsJsonARRAY_A);

            
// "Minify CSS" is enabled, "Combine CSS" is disabled
            
return isset($wpfcOptions['wpFastestCacheMinifyCss']) && ! isset($wpfcOptions['wpFastestCacheCombineCss']);
        }

        return 
false;
    }

    
/**
     * @return bool
     */
    
public static function isWorthCheckingForOptimization()
    {
        
// At least one of these options have to be enabled
        // Otherwise, we will not perform specific useless actions and save resources
        
return MinifyCss::isMinifyCssEnabled() ||
               
Main::instance()->settings['google_fonts_display'] ||
               
Main::instance()->settings['google_fonts_remove'];
    }

    
/**
     * @param $htmlSource
     *
     * @return mixed
     */
    
public static function ignoreDependencyRuleAndKeepChildrenLoaded($htmlSource)
    {
        
$ignoreChild Main::instance()->getIgnoreChildren();

        if (isset(
$ignoreChild['styles']) && ! empty($ignoreChild['styles'])) {
            foreach (
array_keys($ignoreChild['styles']) as $styleHandle) {
                
// Always load the Dashicons if the top admin bar (toolbar) is shown
                
if ($styleHandle === 'dashicons' && is_admin_bar_showing()) {
                    continue;
                }

                if (isset(
Main::instance()->wpAllStyles['registered'][$styleHandle]->srcMain::instance()->ignoreChildren['styles'][$styleHandle.'_has_unload_rule']) && Main::instance()->wpAllStyles['registered'][$styleHandle]->src && Main::instance()->ignoreChildren['styles'][$styleHandle.'_has_unload_rule']) {
                    if (
$scriptExtraAfterHtml self::generateInlineAssocHtmlForHandle($styleHandle)) {
                        
$htmlSource str_replace($scriptExtraAfterHtml''$htmlSource);
                    }

                    
$listWithMatches   = array();
                    
$listWithMatches[] = 'data-wpacu-style-handle=[\'"]'.$styleHandle.'[\'"]';

                    if (
$styleSrc Main::instance()->wpAllStyles['registered'][$styleHandle]->src) {
                        
$listWithMatches[] = preg_quote(OptimizeCommon::getSourceRelPath($styleSrc), '/');
                    }

                    
$htmlSource CleanUp::cleanLinkTagFromHtmlSource($listWithMatches$htmlSource);
                }
            }
        }

        return 
$htmlSource;
    }

    
/**
     * @param $styleTagOrHandle
     * @param $wpacuRegisteredStyles
     * @param $from
     * @param string $return ("value": CSS Inline Content / "html": CSS Inline Content surrounded by tags)
     *
     * @return array
     */
    
public static function getInlineAssociatedWithLinkHandle($styleTagOrHandle$wpacuRegisteredStyles$from 'tag'$return 'value')
    {
        
$styleExtraAfter '';

        if (
$from === 'tag') {
            
preg_match_all('#data-wpacu-style-handle=([\'])' '(.*)' '(\1)#Usmi'$styleTagOrHandle$outputMatches);
            
$styleHandle = (isset($outputMatches[2][0]) && $outputMatches[2][0]) ? trim($outputMatches[2][0], '"\'') : '';
        } else {
            
$styleHandle $styleTagOrHandle;
        }

        if (
$return === 'value' && $styleHandle && isset($wpacuRegisteredStyles[$styleHandle]->extra)) {
            
$styleExtraArray $wpacuRegisteredStyles[$styleHandle]->extra;

            if (isset(
$styleExtraArray['after']) && ! empty($styleExtraArray['after'])) {
                
$styleExtraAfter .= "<style id='".$styleHandle."-inline-css' type='text/css'>\n";

                foreach (
$styleExtraArray['after'] as $afterData) {
                    if (! 
is_bool($afterData)) {
                        
$styleExtraAfter .= $afterData."\n";
                    }
                }

                
$styleExtraAfter .= '</style>';
            }

            return array(
'after' => $styleExtraAfter);
        }

        if ( 
$return === 'html' && $styleHandle ) {
            
// 'after' is the only one for inline CSS; there's no 'data' or 'before' like in the inline JS
            
return array('after' => self::generateInlineAssocHtmlForHandle($styleHandle));
        }

        return array(
'after' => array());
    }

    
/**
     * @param $handle
     * @param $inlineStyleContent
     *
     * @return string
     */
    
public static function generateInlineAssocHtmlForHandle($handle$inlineStyleContent '')
    {
        global 
$wp_styles;

        
$typeAttr '';

        if ( 
function_exists'is_admin' ) && ! is_admin()
            &&
            
function_exists'current_theme_supports' ) && ! current_theme_supports'html5''style' )
        ) {
            
$typeAttr " type='text/css'";
        }

        
$output '';

        if ( 
$inlineStyleContent === '' ) {
            
$inlineStyleContent $wp_styles->print_inline_style$handlefalse );
        }

        if ( 
$inlineStyleContent ) {
            
$output sprintf(
                
"<style id='%s-inline-css'%s>\n%s\n</style>",
                
esc_attr$handle ),
                
$typeAttr,
                
$inlineStyleContent
            
);
        }

        return 
$output;
    }

    
/**
     * @param $htmlSource
     *
     * @return mixed
     */
    
public function appendNoScriptCertainLinkTags($htmlSource)
    {
        
preg_match_all('#<link[^>]*(data-wpacu-preload-it-async)[^>]*(>)#Umi'$htmlSource$matchesSourcesFromTagsPREG_SET_ORDER);

        
$noScripts '';

        if (! empty(
$matchesSourcesFromTags)) {
            foreach (
$matchesSourcesFromTags as $matchedValues) {
                
$matchedTag $matchedValues[0];

                
preg_match_all('#media=(["\'])' '(.*)' '(["\'])#Usmi'$matchedTag$outputMatchesMedia);
                
$mediaAttrValue = isset($outputMatchesMedia[2][0]) ? trim($outputMatchesMedia[2][0], '"\'') : '';

                
preg_match_all('#href=(["\'])' '(.*)' '(["\'])#Usmi'$matchedTag$outputMatchesMedia);
                
$hrefAttrValue = isset($outputMatchesMedia[2][0]) ? trim($outputMatchesMedia[2][0], '"\'') : '';

                
$noScripts .= '<noscript><link rel="stylesheet" href="'.$hrefAttrValue.'" media="'.$mediaAttrValue.'" /></noscript>'."\n";
            }
        }

        return 
str_replace(self::MOVE_NOSCRIPT_TO_BODY_FOR_CERTAIN_LINK_TAGS$noScripts$htmlSource);
    }

    }
x

Windows NT KPTV 6.2 build 9200 (Windows Server 2012 Datacenter Edition) i586