C:\xampp\htdocs\landing\wp-content\plugins\wp-asset-clean-up\classes\Misc.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
<?php
namespace WpAssetCleanUp;

use 
WpAssetCleanUp\OptimiseAssets\OptimizeCommon;

/**
 * Class Misc
 * contains various common functions that are used by the plugin
 * @package WpAssetCleanUp
 */
class Misc
{
    
/**
     * @var array
     */
    
public static $potentialCachePlugins = array(
        
'wp-rocket/wp-rocket.php'// WP Rocket
        
'wp-super-cache/wp-cache.php'// WP Super Cache
        
'w3-total-cache/w3-total-cache.php'// W3 Total Cache
        
'wp-fastest-cache/wpFastestCache.php'// WP Fastest Cache
        
'swift-performance-lite/performance.php'// Swift Performance Lite
        
'breeze/breeze.php'// Breeze – WordPress Cache Plugin
        
'comet-cache/comet-cache.php'// Comet Cache
        
'cache-enabler/cache-enabler.php'// Cache Enabler
        
'hyper-cache/plugin.php'// Hyper Cache
        
'cachify/cachify.php'// Cachify
        
'simple-cache/simple-cache.php'// Simple Cache
        
'litespeed-cache/litespeed-cache.php' // LiteSpeed Cache
    
);

    
/**
     * @var array
     */
    
public $activeCachePlugins = array();

    
/**
     * @var
     */
    
public static $showOnFront;

    
/**
     *
     */
    
public function getActiveCachePlugins()
    {
        if (empty(
$this->activeCachePlugins)) {
            
$activePlugins get_option'active_plugins', array() );

            foreach ( 
self::$potentialCachePlugins as $cachePlugin ) {
                if ( 
in_array$cachePlugin$activePlugins ) ) {
                    
$this->activeCachePlugins[] = $cachePlugin;
                }
            }
        }

        return 
$this->activeCachePlugins;
    }

    
/**
     * @param $string
     * @param $start
     * @param $end
     * @return string
     */
    
public static function extractBetween($string$start$end)
    {
        
$pos stripos($string$start);

        
$str substr($string$pos);

        
$strTwo substr($strstrlen($start));

        
$secondPos stripos($strTwo$end);

        
$strThree substr($strTwo0$secondPos);

        return 
trim($strThree); // remove whitespaces;
    
}

    
/**
     * @param $string
     * @param $endsWithString
     * @return bool
     */
    
public static function endsWith($string$endsWithString)
    {
        
$stringLen strlen($string);
        
$endsWithStringLen strlen($endsWithString);

        if (
$endsWithStringLen $stringLen) {
            return 
false;
        }

        return (
substr_compare(
                    
$string,
                    
$endsWithString,
                    
$stringLen $endsWithStringLen$endsWithStringLen
                
) === 0);
    }

    
/**
     * @return string
     */
    
public static function isHttpsSecure()
    {
        
$isSecure false;

        if (isset(
$_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
            
$isSecure true;
        } elseif (
            ( ! empty(
$_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' )
            || ( ! empty(
$_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] === 'on' )
        ) {
            
// Is it behind a load balancer?
            
$isSecure true;
        }

        return 
$isSecure;
    }

    
/**
     * @param $postId
     * @return false|mixed|string
     */
    
public static function getPageUrl($postId)
    {
        
// Was the home page detected?
        
if (self::isHomePage()) {
            if (
get_site_url() !== get_home_url()) {
                
$pageUrl get_home_url();
            } else {
                
$pageUrl get_site_url();
            }

            return 
self::_filterPageUrl($pageUrl);
        }

        
// It's singular page: post, page, custom post type (e.g. 'product' from WooCommerce)
        
if ($postId 0) {
            return 
self::_filterPageUrl(get_permalink($postId));
        }

        
// If it's not a singular page, nor the home page, continue...
        // It could be: Archive page (e.g. author, category, tag, date, custom taxonomy), Search page, 404 page etc.
        
global $wp;

        
$permalinkStructure get_option('permalink_structure');

        if (
$permalinkStructure) {
            
$pageUrl home_url($wp->request);
        } else {
            
$pageUrl home_url($_SERVER['REQUEST_URI']);
        }

        if (
strpos($_SERVER['REQUEST_URI'], '?') !== false) {
            list( 
$cleanRequestUri ) = explode'?'$_SERVER['REQUEST_URI'] );
        } else {
            
$cleanRequestUri $_SERVER['REQUEST_URI'];
        }

        if (
substr($cleanRequestUri, -1) === '/') {
            
$pageUrl .= '/';
        }

        return 
self::_filterPageUrl($pageUrl);
    }

    
/**
     * @param $postUrl
     * @return mixed
     */
    
private static function _filterPageUrl($postUrl)
    {
        
// If we are in the Dashboard on a HTTPS connection,
        // then we will make the AJAX call over HTTPS as well for the front-end
        // to avoid blocking
        
if (self::isHttpsSecure() && strpos($postUrl'http://') === 0) {
            
$postUrl str_ireplace('http://''https://'$postUrl);
        }

        return 
$postUrl;
    }

    
/**
     * @return bool
     */
    
public static function isElementorMaintenanceModeOn()
    {
        
// Elementor's maintenance or coming soon mode
        
if (class_exists('\Elementor\Maintenance_Mode') && Misc::isPluginActive('elementor/elementor.php')) {
            try {
                
$elementorMaintenanceMode = \Elementor\Maintenance_Mode::get'mode' ); // if any
                
if ( $elementorMaintenanceMode && in_array($elementorMaintenanceMode, array('maintenance''coming_soon')) ) {
                    return 
true;
                    }
            } catch (\
Exception $err) {}
        }

        return 
false;
    }

    
/**
     * @return bool
     */
    
public static function isElementorMaintenanceModeOnForCurrentAdmin()
    {
        if ( 
defined('WPACU_IS_ELEMENTOR_MAINTENANCE_MODE_TEMPLATE_ID') ) {
            return 
true;
        }

        if (
class_exists('\Elementor\Maintenance_Mode') && Misc::isPluginActive('elementor/elementor.php')) {
            try {
                
// Elementor Template ID (Chosen for maintenance or coming soon mode)
                
$elementorMaintenanceModeTemplateId = \Elementor\Maintenance_Mode::get'template_id' );

                if ( isset( 
$GLOBALS['post']->ID ) && (int)$elementorMaintenanceModeTemplateId === (int)$GLOBALS['post']->ID ) {
                    
define'WPACU_IS_ELEMENTOR_MAINTENANCE_MODE_TEMPLATE_ID'$elementorMaintenanceModeTemplateId );
                    return 
true;
                }
            } catch (\
Exception $err) {}
        }

        return 
false;
    }

    
/**
     * @return mixed
     */
    
public static function isHomePage()
    {
        
// Docs: https://codex.wordpress.org/Conditional_Tags

        // Elementor's Maintenance Mode is ON
        
if (defined('WPACU_IS_ELEMENTOR_MAINTENANCE_MODE_TEMPLATE_ID')) {
            return 
false;
        }

        
// "Your latest posts" -> sometimes it works as is_front_page(), sometimes as is_home())
        // "A static page (select below)" -> In this case is_front_page() should work

        // Sometimes neither of these two options are selected
        // (it happens with some themes that have an incorporated page builder)
        // and is_home() tends to work fine

        // Both will be used to be sure the home page is detected

        // VARIOUS SCENARIOS for "Your homepage displays" option from Settings -> Reading

        // 1) "Your latest posts" is selected
        
if (self::getShowOnFront() === 'posts' && is_front_page()) {
            
// Default homepage
            
return true;
        }

        
// 2) "A static page (select below)" is selected

        // Note: Either "Homepage:" or "Posts page:" need to have a value set
        // Otherwise, it will default to "Your latest posts", the other choice from "Your homepage displays"

        
if (self::getShowOnFront() === 'page') {
            
$pageOnFront get_option('page_on_front');

            
// "Homepage:" has a value
            
if ($pageOnFront && is_front_page()) {
                
// Static Homepage
                
return true;
            }

            
// "Homepage:" has no value
            
if (! $pageOnFront && self::isBlogPage()) {
                
// Blog page
                
return true;
            }

            
// Another scenario is when both 'Homepage:' and 'Posts page:' have values
            // If we are on the blog page (which is "Posts page:" value), then it will return false
            // As it's not the main page of the website
            // e.g. Main page: www.yoursite.com - Blog page: www.yoursite.com/blog/
        
}

        
// Some WordPress themes such as "Extra" have their own custom value
        
return ( ( ( self::getShowOnFront() !== '') || ( self::getShowOnFront() === 'layout') )
                 &&
                 ((
is_home() || self::isBlogPage()) || self::isRootUrl())
        );
    }

    
/**
     * @return bool
     */
    
public static function isRootUrl()
    {
        
$siteUrl get_bloginfo('url');

        
$urlPath parse_url($siteUrlPHP_URL_PATH);
        
$requestURI $_SERVER['REQUEST_URI'];

        
$urlPathNoForwardSlash $urlPath;
        
$requestURINoForwardSlash $requestURI;

        if (
substr($urlPath, -1) === '/') {
            
$urlPathNoForwardSlash substr($urlPath0, -1);
        }

        if (
substr($requestURI, -1) === '/') {
            
$requestURINoForwardSlash substr($requestURI0, -1);
        }

        return (
$urlPathNoForwardSlash === $requestURINoForwardSlash);
    }

    
/**
     * @param $handleData
     *
     * @return bool
     */
    
public static function isCoreFile($handleData)
    {
        
$handleData = (object)$handleData;

        
$part str_replace(
            array(
                
'http://',
                
'https://',
                
'//'
            
),
            
'',
            
$handleData->src
        
);

        
$parts     explode('/'$part);
        
$parentDir = isset($parts[1]) ? $parts[1] : '';

        
// Loaded from WordPress directories (Core)
        
return in_array$parentDir, array( 'wp-includes''wp-admin' ) ) || strpos$handleData->src,
                
'/plugins/jquery-updater/js/jquery-' ) !== false;
    }

    
/**
     * @param $src
     *
     * @return array
     */
    
public static function getLocalSrc($src)
    {
        if (! 
$src) {
            return array();
        }

        
// Clean it up first
        
if (strpos($src'.css?') !== false) {
            list(
$src) = explode('.css?'$src);
            
$src .= '.css';
        }

        if (
strpos($src'.js?') !== false) {
            list(
$src) = explode('.js?'$src);
            
$src .= '.js';
        }

        
$paths = array('wp-includes/''wp-content/');

        foreach (
$paths as $path) {
            if (
strpos($src$path) !== false) {
                list (
$baseUrl$relSrc) = explode($path$src);

                
$localPathToFile ABSPATH $path $relSrc;

                if (
is_file($localPathToFile)) {
                    return array(
'base_url' => $baseUrl'rel_src' => $path $relSrc'file_exists' => 1);
                }
            }
        }

        return array();
    }

    
/**
     * @param bool $clean
     *
     * @return mixed|string
     */
    
public static function getCurrentPageUrl($clean true)
    {
        
$currentPageUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' 'https' 'http') . '://' parse_url(site_url(), PHP_URL_HOST) . $_SERVER['REQUEST_URI'];

        if (
$clean && strpos($currentPageUrl'?') !== false) {
            list(
$currentPageUrl) = explode('?'$currentPageUrl);
        }

        return 
$currentPageUrl;
    }

    
/**
     * @param $src
     * @param $assetKey
     *
     * @return string|string[]
     */
    
public static function assetFromHrefToRelativeUri($src$assetKey)
    {
        
// Make the "src" relative in case the information will be imported from Staging to Live, it won't show the handle's link referencing to the staging URL in the "Overview" page and other similar pages as it's confusing
        
$localAssetPath OptimizeCommon::getLocalAssetPath($src, (($assetKey === 'styles') ? 'css' 'js'));

        
$relSrc $src;

        if (
$localAssetPath) {
            
$relSrc str_replace(ABSPATH''$relSrc);
        }

        
$relSrc str_replace(site_url(), ''$relSrc);

        
// Does it start with '//'? (protocol is missing) - the replacement above wasn't made
        
if (strpos($relSrc'//') === 0) {
            
$siteUrlNoProtocol str_replace(array('http:''https:'), ''site_url());
            
$relSrc str_replace($siteUrlNoProtocol''$relSrc);
        }

        return 
$relSrc;
    }

    
/**
     * @return bool
     */
    
public static function isBlogPage()
    {
        return (
is_home() && !is_front_page());
    }

    
/**
     * @return mixed
     */
    
public static function getShowOnFront()
    {
        if (! 
self::$showOnFront) {
            
self::$showOnFront get_option('show_on_front');
        }

        return 
self::$showOnFront;
    }

    
/**
     * @param $plugin
     *
     * @return bool
     */
    
public static function isPluginActive($plugin)
    {
        return 
in_array($pluginapply_filters('active_plugins'get_option('active_plugins', array())));
    }

    
/**
     * @return bool|mixed
     */
    
public static function isWpRocketMinifyHtmlEnabled()
    {
        
// Only relevant if WP Rocket's version is below 3.7
        
if (defined('WP_ROCKET_VERSION') && version_compare(WP_ROCKET_VERSION'3.7') >= 0) {
            return 
false;
        }

        if (
self::isPluginActive('wp-rocket/wp-rocket.php')) {
            if (
function_exists('get_rocket_option')) {
                
$wpRocketMinifyHtml trim(get_rocket_option('minify_html')) ?: false;
            } else {
                
$wpRocketSettings get_option('wp_rocket_settings');
                
$wpRocketMinifyHtml = (isset($wpRocketSettings['minify_html']) && $wpRocketSettings['minify_html']);
            }

            return 
$wpRocketMinifyHtml;
        }

        return 
false;
    }

    
/**
     * If it matches true, it's very likely there is no need for the Gutenberg CSS Block Library
     * The user will be reminded about it
     *
     * @return bool
     */
    
public static function isClassicEditorUsed()
    {
        if (
self::isPluginActive('classic-editor/classic-editor.php')) {
            
$ceReplaceOption get_option('classic-editor-replace');
            
$ceAllowUsersOption get_option('classic-editor-allow-users');

            if (
$ceReplaceOption === 'classic' && $ceAllowUsersOption === 'disallow') {
                return 
true;
            }
        }

        return 
false;
    }

    
/**
     * @return array|string
     */
    
public static function getW3tcMasterConfig()
    {
        if (! 
ObjectCache::wpacu_cache_get('wpacu_w3tc_master_config')) {
            
$w3tcConfigMasterFile WP_CONTENT_DIR '/w3tc-config/master.php';
            
$w3tcMasterConfig FileSystem::file_get_contents($w3tcConfigMasterFile);
            
ObjectCache::wpacu_cache_set('wpacu_w3tc_master_config'trim($w3tcMasterConfig));
        } else {
            
$w3tcMasterConfig ObjectCache::wpacu_cache_get('wpacu_w3tc_master_config');
        }

        return 
$w3tcMasterConfig;
    }

    
/**
     * @param bool $forceReturn
     *
     * @return string
     */
    
public static function preloadAsyncCssFallbackOutput($forceReturn false)
    {
        
// Unless it has to be returned (e.g. for debugging purposes), check it if it was returned before
        // To avoid duplicated HTML code
        
if (! $forceReturn) {
            if ( 
defined'WPACU_PRELOAD_ASYNC_SCRIPT_SHOWN' ) ) {
                return 
'';
            }

            
define'WPACU_PRELOAD_ASYNC_SCRIPT_SHOWN'); // mark it as already printed
        
}

        return <<<HTML
<script id="wpacu-preload-async-css-fallback">
    /*! LoadCSS. [c]2017 Filament Group, Inc. MIT License */
    /* This file is meant as a standalone workflow for
    - testing support for link[rel=preload]
    - enabling async CSS loading in browsers that do not support rel=preload
    - applying rel preload css once loaded, whether supported or not.
    */
    !function(n){"use strict";n.wpacuLoadCSS||(n.wpacuLoadCSS=function(){});var o=wpacuLoadCSS.relpreload={};if(o.support=function(){var e;try{e=n.document.createElement("link").relList.supports("preload")}catch(t){e=!1}return function(){return e}}(),o.bindMediaToggle=function(t){var e=t.media||"all";function a(){t.addEventListener?t.removeEventListener("load",a):t.attachEvent&&t.detachEvent("onload",a),t.setAttribute("onload",null),t.media=e}t.addEventListener?t.addEventListener("load",a):t.attachEvent&&t.attachEvent("onload",a),setTimeout(function(){t.rel="stylesheet",t.media="only x"}),setTimeout(a,3e3)},o.poly=function(){if(!o.support())for(var t=n.document.getElementsByTagName("link"),e=0;e<t.length;e++){var a=t[e];"preload"!==a.rel||"style"!==a.getAttribute("as")||a.getAttribute("data-wpacuLoadCSS")||(a.setAttribute("data-wpacuLoadCSS",!0),o.bindMediaToggle(a))}},!o.support()){o.poly();var t=n.setInterval(o.poly,500);n.addEventListener?n.addEventListener("load",function(){o.poly(),n.clearInterval(t)}):n.attachEvent&&n.attachEvent("onload",function(){o.poly(),n.clearInterval(t)})}"undefined"!=typeof exports?exports.wpacuLoadCSS=wpacuLoadCSS:n.wpacuLoadCSS=wpacuLoadCSS}("undefined"!=typeof global?global:this);
</script>
HTML;
    }

    
/**
     * @param $array
     *
     * @return mixed
     */
    
public static function arrayKeyFirst($array)
    {
        if (
function_exists('array_key_first')) {
            return 
array_key_first($array);
        }

        
$arrayKeys array_keys($array);

        return 
$arrayKeys[0];
    }

    
/**
     * @return bool|int
     */
    
public static function jsonLastError()
    {
        if (
function_exists('json_last_error')) {
            return 
json_last_error();
        }

        
// Fallback (notify the user through a warning)
        
return 0;
    }

    
/**
     * @param $requestMethod
     * @param $key
     * @param mixed $defaultValue
     *
     * @return mixed
     */
    
public static function getVar($requestMethod$key$defaultValue '')
    {
        if (
$requestMethod === 'get' && $key && isset($_GET[$key])) {
            return 
$_GET[$key];
        }

        if (
$requestMethod === 'post' && $key && isset($_POST[$key])) {
            return 
$_POST[$key];
        }

        if (
$requestMethod === 'request' && $key && isset($_REQUEST[$key])) {
            return 
$_REQUEST[$key];
        }

        return 
$defaultValue;
    }

    
/**
     * @param $requestMethod
     * @param $key
     *
     * @return bool|mixed
     */
    
public static function isValidRequest($requestMethod$key)
    {
        if (
$requestMethod === 'post' && $key && isset($_POST[$key]) && ! empty($_POST[$key])) {
            return 
true;
        }

        if (
$requestMethod === 'get' && $key && isset($_GET[$key]) && ! empty($_GET[$key])) {
            return 
true;
        }

        return 
false;
    }

    
/**
     * @param $pageId
     */
    
public static function doNotApplyOptimizationOnPage($pageId)
    {
        
// Do not trigger the code below if there is already a change in place
        
if (get_post_meta($pageId'_' WPACU_PLUGIN_ID '_page_options'true)) {
            return;
        }

        
$pageOptionsJson json_encode(array(
            
'no_css_minify'   => 1,
            
'no_css_optimize' => 1,
            
'no_js_minify'    => 1,
            
'no_js_optimize'  => 1
        
));

        if (! 
add_post_meta($pageId'_' WPACU_PLUGIN_ID '_page_options'$pageOptionsJsontrue)) {
            
update_post_meta($pageId'_' WPACU_PLUGIN_ID '_page_options'$pageOptionsJson);
        }
    }

    
/**
     * @param $optionName
     * @param $optionValue
     * @param string $autoload
     */
    
public static function addUpdateOption($optionName$optionValue$autoload 'no')
    {
        
// Nothing in the database | Add it
        
if (! get_option($optionName)) {
            
add_option($optionName$optionValue''$autoload);
            return;
        }

        
// Empty array encoded into JSON; No point in keeping the option in the database
        
if ($optionValue === '[]') {
            
delete_option($optionName);
            return;
        }

        
// Value is in the database already | Update it
        
update_option($optionName$optionValue$autoload);
    }

    
/**
     * @param $type
     * e.g. 'per_page' will fetch only per page rules, excluding the bulk ones
     * such as unload everywhere, on this post type etc.
     *
     * @return int
     */
    
public static function getTotalUnloadedAssets($type 'all')
    {
        if (
$unloadedTotalAssets get_transient(WPACU_PLUGIN_ID'_total_unloaded_assets_'.$type)) {
            return 
$unloadedTotalAssets;
        }

        global 
$wpdb;

        
$frontPageNoLoad      get_option(WPACU_PLUGIN_ID '_front_page_no_load');
        
$frontPageNoLoadArray json_decode($frontPageNoLoadARRAY_A);

        
$unloadedTotalAssets 0;

        
// Home Page: Unloads
        
if (isset($frontPageNoLoadArray['styles'])) {
            
$unloadedTotalAssets += count($frontPageNoLoadArray['styles']);
        }

        if (isset(
$frontPageNoLoadArray['scripts'])) {
            
$unloadedTotalAssets += count($frontPageNoLoadArray['scripts']);
        }

        
// Posts, Pages, Custom Post Types: Individual Page Unloads
        
$sqlPart '_' WPACU_PLUGIN_ID '_no_load';
        
$sqlQuery = <<<SQL
SELECT pm.meta_value FROM `{$wpdb->prefix}postmeta` pm
LEFT JOIN `
{$wpdb->prefix}posts` p ON (p.ID = pm.post_id)
WHERE (p.post_status='publish' OR p.post_status='private') AND pm.meta_key='
{$sqlPart}'
SQL;

        
$sqlResults $wpdb->get_results($sqlQueryARRAY_A);

        if (! empty(
$sqlResults)) {
            foreach (
$sqlResults as $row) {
                
$metaValue    $row['meta_value'];
                
$unloadedList = @json_decode($metaValueARRAY_A);

                if (empty(
$unloadedList)) {
                    continue;
                }

                foreach (
$unloadedList as $assets) {
                    if (! empty(
$assets)) {
                        
$unloadedTotalAssets += count($assets);
                    }
                }
            }
        }

        if (
$type === 'all') {
            
$unloadedTotalAssets += self::getTotalBulkUnloadsFor'all' );
        }

        
// To avoid the complex SQL query next time
        
set_transient(WPACU_PLUGIN_ID'_total_unloaded_assets_'.$type$unloadedTotalAssets28800);

        return 
$unloadedTotalAssets;
    }

    
/**
     * @param string $for
     *
     * @return int
     */
    
public static function getTotalBulkUnloadsFor($for)
    {
        
$unloadedTotalAssets 0;

        if (
in_array($for, array('everywhere''all'))) {
            
// Everywhere (Site-wide) unloads
            
$globalUnloadListJson get_option(WPACU_PLUGIN_ID '_global_unload');
            
$globalUnloadArray    = @json_decode($globalUnloadListJsonARRAY_A);

            foreach (array(
'styles''scripts') as $assetType) {
                if ( isset( 
$globalUnloadArray[$assetType] ) && ! empty( $globalUnloadArray[$assetType] ) ) {
                    
$unloadedTotalAssets += count$globalUnloadArray[$assetType] );
                }
            }
        }

        if (
in_array($for, array('bulk''all'))) {
            
// Any bulk unloads? e.g. unload specific CSS/JS on all pages of a specific post type
            
$bulkUnloadListJson get_option(WPACU_PLUGIN_ID '_bulk_unload');
            
$bulkUnloadArray  = @json_decode($bulkUnloadListJsonARRAY_A);

            
$bulkUnloadedAllTypes = array('search''date''404''taxonomy''post_type''author');

            foreach (
$bulkUnloadedAllTypes as $bulkUnloadedType) {
                if (
in_array($bulkUnloadedType, array('search''date''404'))) {
                    foreach (array(
'styles''scripts') as $assetType) {
                        if ( isset( 
$bulkUnloadArray[$assetType][ $bulkUnloadedType ] ) && ! empty( $bulkUnloadArray[$assetType][ $bulkUnloadedType ] ) ) {
                            
$unloadedTotalAssets += count$bulkUnloadArray[$assetType][ $bulkUnloadedType ] );
                        }
                    }
                } elseif (
$bulkUnloadedType === 'author') {
                    foreach (array(
'styles''scripts') as $assetType) {
                        if ( isset( 
$bulkUnloadArray[$assetType][ $bulkUnloadedType ]['all'] ) && ! empty( $bulkUnloadArray[$assetType][ $bulkUnloadedType ]['all'] ) ) {
                            
$unloadedTotalAssets += count$bulkUnloadArray[$assetType][ $bulkUnloadedType ]['all'] );
                        }
                    }
                } elseif (
in_array($bulkUnloadedType, array('post_type''taxonomy'))) {
                    foreach (array(
'styles''scripts') as $assetType) {
                        if ( isset( 
$bulkUnloadArray[$assetType][ $bulkUnloadedType ] ) && ! empty( $bulkUnloadArray[$assetType][ $bulkUnloadedType ] ) ) {
                            foreach ( 
$bulkUnloadArray[$assetType][ $bulkUnloadedType ] as $objectValues ) {
                                
$unloadedTotalAssets += count$objectValues );
                            }
                        }
                    }
                }
            }
        }

        return 
$unloadedTotalAssets;
    }

    
/**
     * @param $data
     * @param $assetTypeKey
     *
     * @return bool
     */
    
public static function handleHasAtLeastOneRule($data$assetTypeKey)
    {
        
// Is it unloaded?
        
if (strpos($data['row']['class'], 'wpacu_not_load') !== false) {
            return 
true;
        }

        
$isAssetPreloaded = (isset($data['preloads'][$assetTypeKey][$data['row']['obj']->handle]) && $data['preloads'][$assetTypeKey][$data['row']['obj']->handle])
            ? 
$data['preloads'][$assetTypeKey][$data['row']['obj']->handle]
            : 
false;

        
// Preloaded? (either 'basic' for any CSS/JS or 'async' for CSS files)
        
if ($isAssetPreloaded) {
            return 
true;
        }

        
// Is it a Google Font request that was stripped site-wide?
        
if ($assetTypeKey === 'styles') {
            
$isGoogleFontLink stripos($data['row']['obj']->srcHref'//fonts.googleapis.com/') !== false;

            if (
$isGoogleFontLink && $data['plugin_settings']['google_fonts_remove']) {
                return 
true;
            }
        }

        
// Was a filer hook used to load an alternative version of the handle?
        
if (isset($data['row']['obj']->src_origin$data['row']['obj']->ver_origin)) {
            return 
true;
        }

        
// Finally, return false as the asset has no rules set
        
return false;
    }

    
/**
     * @param $src
     *
     * @return bool|mixed
     */
    
public static function maybeIsInactiveAsset($src)
    {
        
// Quickest way
        
preg_match_all('#/wp-content/plugins/(.*?)/#'$src$matchesPREG_PATTERN_ORDER);

        if (isset(
$matches[1][0]) && $matches[1][0]) {
            
$pluginDirName $matches[1][0];

            
$activePlugins get_option'active_plugins', array() );
            
$activePluginsStr implode(','$activePlugins);

            if (
strpos($activePluginsStr$pluginDirName.'/') === false) {
                return 
$pluginDirName// it belongs to an inactive plugin
            
}
        }

        
$relPluginsUrl str_replace(site_url(), ''plugins_url());

        
$srcAlt $src;

        if (
strpos($srcAlt'//') === 0) {
            
$srcAlt str_replace(
                
str_replace(array('http://''https://'),'//'site_url()),
                
'',
                
$srcAlt
            
);
        }

        
$relSrc str_replacesite_url(), ''$srcAlt );

        if (
strpos($relSrc'/wp-content/plugins') !== false) {
            list (,
$relSrc) = explode('/wp-content/plugins'$relSrc);
        }

        if (
strpos($relSrc$relPluginsUrl) !== false) {
            
// Determine the plugin behind the $src
            
$relSrc trim(str_replace($relPluginsUrl''$relSrc), '/');

            if (
strpos($relSrc'/') !== false) {
                list ( 
$pluginDirName, ) = explode'/'$relSrc );

                
$activePlugins get_option'active_plugins', array() );
                
$activePluginsStr implode(','$activePlugins);

                if (
strpos($activePluginsStr$pluginDirName.'/') === false) {
                    return 
$pluginDirName// it belongs to an inactive plugin
                
}
            }
        }

        return 
false;
    }

    
/**
     * @param bool $onlyTransient
     *
     * @return array|bool|mixed|object
     */
    
public static function fetchActiveFreePluginsIcons($onlyTransient false)
    {
        
$activePluginsIconsJson get_transient('wpacu_active_plugins_icons');

        if (
$activePluginsIconsJson) {
            
$activePluginsIcons = @json_decode($activePluginsIconsJsonARRAY_A);
        }

        if (! empty(
$activePluginsIcons) && is_array($activePluginsIcons)) {
            return 
$activePluginsIcons;
        }

        
// Do not fetch the icons from the WordPress.org repository if only transient was required
        
if ($onlyTransient) {
            return array();
        }

        
$allActivePlugins array_unique(get_option('active_plugins', array()));

        if (empty(
$allActivePlugins)) {
            return array();
        }

        foreach (
$allActivePlugins as $activePlugin) {
            if (! 
is_string($activePlugin) || strpos($activePlugin'/') === false) {
                continue;
            }

            list(
$pluginSlug) = explode('/'$activePlugin);
            
$pluginSlug trim($pluginSlug);

            if (! 
$pluginSlug) {
                continue;
            }

            
// Avoid the calls to WordPress.org as much as possible
            // as it would decrease the resources and timing to fetch the data we need

            // not relevant to check Asset CleanUp's plugin info in this case
            
if (in_array($pluginSlug, array('wp-asset-clean-up''wp-asset-clean-up-pro'))) {
                continue;
            }

            
// no readme.txt file in the plugin's root folder? skip it
            
if (! is_file(WP_PLUGIN_DIR.'/'.$pluginSlug.'/readme.txt')) {
                continue;
            }

            
$payload = array(
                
'action'  => 'plugin_information',
                
'request' => serialize( (object) array(
                    
'slug'   => $pluginSlug,
                    
'fields' => array(
                        
'tags'          => false,
                        
'icons'         => true// that's what will get fetched
                        
'sections'      => false,
                        
'description'   => false,
                        
'tested'        => false,
                        
'requires'      => false,
                        
'rating'        => false,
                        
'downloaded'    => false,
                        
'downloadlink'  => false,
                        
'last_updated'  => false,
                        
'homepage'      => false,
                        
'compatibility' => false,
                        
'ratings'       => false,
                        
'added'         => false,
                        
'donate_link'   => false
                    
),
                ) ),
            );

            
$body = @wp_remote_post('http://api.wordpress.org/plugins/info/1.0/', array('body' => $payload));

            if (
is_wp_error($body) || (! (isset($body['body']) && is_serialized($body['body'])))) {
                continue;
            }

            
$pluginInfo = @unserialize($body['body']);

            if (! isset(
$pluginInfo->name$pluginInfo->icons)) {
                continue;
            }

            if (empty(
$pluginInfo->icons)) {
                continue;
            }

            
$pluginIcon array_shift($pluginInfo->icons);

            if (
$pluginIcon !== '') {
                
$activePluginsIcons[$pluginSlug] = $pluginIcon;
            }
        }

        if (empty(
$activePluginsIcons)) {
            return array();
        }

        
set_transient('wpacu_active_plugins_icons'json_encode($activePluginsIcons), 1209600); // in seconds

        
return $activePluginsIcons;
    }

    
/**
     * @return array|bool|mixed|object
     */
    
public static function getAllActivePluginsIcons()
    {
        
$popularPluginsIcons = array(
            
'all-in-one-wp-migration-s3-extension' => WPACU_PLUGIN_URL '/assets/icons/premium-plugins/all-in-one-wp-migration-s3-extension.png',
            
'elementor'     => WPACU_PLUGIN_URL '/assets/icons/premium-plugins/elementor.svg',
            
'elementor-pro' => WPACU_PLUGIN_URL '/assets/icons/premium-plugins/elementor-pro.jpg',
            
'oxygen'        => WPACU_PLUGIN_URL '/assets/icons/premium-plugins/oxygen.png',
            
'gravityforms'  => WPACU_PLUGIN_URL '/assets/icons/premium-plugins/gravityforms-blue.svg',
            
'revslider'     => WPACU_PLUGIN_URL '/assets/icons/premium-plugins/revslider.png',
            
'LayerSlider'   => WPACU_PLUGIN_URL '/assets/icons/premium-plugins/LayerSlider.jpg',
            
'wpdatatables'  => WPACU_PLUGIN_URL '/assets/icons/premium-plugins/wpdatatables.jpg',
            
'monarch'       => WPACU_PLUGIN_URL '/assets/icons/premium-plugins/monarch.jpg',
            
'wp-rocket'     => WPACU_PLUGIN_URL '/assets/icons/premium-plugins/wp-rocket.png'
        
);

        
$allActivePluginsIcons self::fetchActiveFreePluginsIcons(true) ?: array();

        foreach (
array_unique(get_option('active_plugins', array())) as $activePlugin) {
            if (
strpos($activePlugin'/') !== false) {
                list (
$pluginSlug) = explode('/'$activePlugin);

                if (! 
array_key_exists($pluginSlug$allActivePluginsIcons) && array_key_exists($pluginSlug$popularPluginsIcons)) {
                    
$allActivePluginsIcons[$pluginSlug] = $popularPluginsIcons[$pluginSlug];
                }
            }
        }

        return 
$allActivePluginsIcons;
    }

    
/**
     * @param $themeName
     *
     * @return array|string
     */
    
public static function getThemeIcon($themeName)
    {
        
$themesIconsPathToDir WPACU_PLUGIN_DIR.'/assets/icons/themes/';
        
$themesIconsUrlDir    WPACU_PLUGIN_URL.'/assets/icons/themes/';

        if (! 
is_dir($themesIconsPathToDir)) {
            return array();
        }

        
$themeName strtolower($themeName);

        
$themesIcons scandir($themesIconsPathToDir);

        foreach (
$themesIcons as $themesIcon) {
            if (
strpos($themesIcon$themeName.'.') !== false) {
                return 
$themesIconsUrlDir $themesIcon;
            }
        }

        return 
'';
    }

    
/**
     * Triggers only in the front-end view (e.g. Homepage URL, /contact/, /about/ etc.)
     * Except the situations below: no page builders edit mode etc.
     *
     * @return bool
     */
    
public static function triggerFrontendOptimization()
    {
        
// Not when the CSS/JS is fetched
        
if (WPACU_GET_LOADED_ASSETS_ACTION === true) {
            return 
false;
        }

        
// "Elementor" Edit Mode
        
if (isset($_GET['elementor-preview']) && $_GET['elementor-preview']) {
            return 
false;
        }

        
// "Divi" Edit Mode
        
if (isset($_GET['et_fb']) && $_GET['et_fb']) {
            return 
false;
        }

        
// Not within the Dashboard
        
if (is_admin()) {
            return 
false;
        }

        
// Default (triggers in most cases)
        
return true;
    }

    
/**
     * @return bool
     */
    
public static function doingCron()
    {
        if (
function_exists('wp_doing_cron') && wp_doing_cron()) {
            return 
true;
        }

        if (
defined'DOING_CRON') && (true === DOING_CRON)) {
            return 
true;
        }

        
// Default to false
        
return false;
    }

    
/**
     * Adapted from: https://stackoverflow.com/questions/2510434/format-bytes-to-kilobytes-megabytes-gigabytes
     *
     * @param $size
     * @param int $precision
     * @param string $getItIn
     *
     * @return string
     */
    
public static function formatBytes($size$precision 2$getItIn '')
    {
        if ((int)
$size === 0) {
            return 
'<span style="vertical-align: middle;" class="dashicons dashicons-warning"></span> '.__('The file appears to be empty''wp-asset-clean-up');
        }

        
// In case a string is passed, make it to float
        
$size = (float)$size;

        
// Just for internal usage (no printing in nice format)
        
if ($getItIn === 'bytes') {
            return 
$size;
        }

        if (
$getItIn === 'KB') {
            return 
round(($size 1024), $precision);
        }

        if (
$getItIn === 'MB') {
            return 
round((($size 1024) / 1024), $precision);
        }

        
$base log($size1024);

        
$suffixes = array('bytes''KB''MB');

        
$floorBase floor($base);

        if (
$floorBase 2) {
            
$floorBase 2;
        }

        
$result round(
            
// 1024 ** ($base - $floorBase) is available only from PHP 5.6+
            
pow(1024, ($base $floorBase)),
            
$precision
        
);

        
$resultForPrint $result;

        if (
$suffixes[$floorBase] === 'KB' && $floorBase !== 1) {
            
$resultForPrint str_replace('.''<span style="font-size: 80%; font-weight: 200;">.'$result).'</span>';
        }

        
$output $resultForPrint.' '$suffixes[$floorBase];

        
// If KB, also show the MB equivalent
        
if ($floorBase === 1) {
            
$output .= ' ('.number_format($result 10244).' MB)';
        }

        return 
$output;
    }

    
/**
     * @param array $targetDirs
     * @param string $filterExt
     *
     * @return array|bool
     */
    
public static function getSizeOfDirectoryRootFiles($targetDirs = array(), $filterExt '')
    {
        if ( empty(
$targetDirs) ) {
            return array(); 
// no relevant target dirs set as a parameter
        
}

        
$totalSize 0;

        foreach ( 
$targetDirs as $targetDir ) {
            if ( ! 
is_dir($targetDir) ) {
                continue; 
// skip it as the directory does not exist
            
}

            
$listOfFiles scandir$targetDir );

            if ( ! empty( 
$listOfFiles ) ) {
                foreach ( 
$listOfFiles as $fileName ) {
                    
// Only relevant root files matter
                    
if ( $fileName === '.' || $fileName === '..' || $fileName === 'index.php' || is_dir$fileName ) ) {
                        continue;
                    }

                    
// If .js is specified, then do not consider any other extension
                    
if ( $filterExt !== '' && ! strrchr$fileName$filterExt ) ) {
                        continue;
                    }

                    
$totalSize += filesize$targetDir $fileName );
                }
            }
        }

        if (
$totalSize 0) {
            
$totalSizeMb self::formatBytes$totalSize2'MB' );

            return array(
                
'total_size'    => $totalSize,
                
'total_size_mb' => $totalSizeMb
            
);
        }

        return array(); 
// no relevant files
    
}

    
/**
     * @param $targetDir
     */
    
public static function rmDir($targetDir)
    {
        if (! 
is_dir($targetDir)) {
            return;
        }

        
$scanDirResult = @scandir($targetDir);

        if (! 
is_array($scanDirResult)) {
            return;
        }

        
$totalFiles count($scanDirResult) - 2// exclude . and ..

        
if ($totalFiles 1) { // could be 0 or negative
            
@rmdir($targetDir); // @ was appended just in case
        
}
    }

    
/**
     * @param $targetVersion
     *
     * @return bool
     */
    
public static function isWpVersionAtLeast($targetVersion)
    {
        global 
$wp_version;
        return ( 
version_compare($wp_version$targetVersion) >= );
    }

    
/**
     * @param $list
     * @param string $for
     *
     * @return array
     */
    
public static function filterList($list$for 'empty_values')
    {
        if (! empty(
$list) && $for === 'empty_values') {
            
$list self::arrayUnsetRecursive($list);
        }

        return 
$list;
    }

    
/**
     * Source: https://stackoverflow.com/questions/7696548/php-how-to-remove-empty-entries-of-an-array-recursively
     *
     * @param $array
     *
     * @return array
     */
    
public static function arrayUnsetRecursive($array)
    {
        
$array = (array)$array// in case it's object, convert it to array

        
foreach ($array as $key => $value) {
            if (
is_array($value) || is_object($value)) {
                
$array[$key] = self::arrayUnsetRecursive($array[$key]);
            }

            
// Values such as '0' are not considered empty values
            
if (is_string($value) && trim($value) === '0') {
                continue;
            }

            
// Clear it if it's empty
            
if (empty($array[$key])) {
                unset(
$array[$key]);
            }
        }

        return 
$array;
    }

    
/**
     * Single value (no multiple RegExes)
     *
     * @param $regexValue
     *
     * @return mixed|string
     */
    
public static function purifyRegexValue($regexValue)
    {
        try {
            if ( 
class_exists'\CleanRegex\Pattern' )
                 && 
class_exists'\SafeRegex\preg' )
                 && 
method_exists'\CleanRegex\Pattern''delimitered' )
                 && 
method_exists'\SafeRegex\preg''match' ) ) {
                    
$cleanRegexPattern = new \CleanRegex\Pattern$regexValue );
                    
$delimiteredValue  $cleanRegexPattern->delimitered(); // auto-correct it if there's no delimiter

                    
if ( $delimiteredValue ) {
                        
// Tip: https://stackoverflow.com/questions/4440626/how-can-i-validate-regex
                        // Validate it and if it doesn't match, do not add it to the list
                        
@preg_match$delimiteredValuenull );

                        if ( 
preg_last_error() !== PREG_NO_ERROR ) {
                            return 
$regexValue;
                        }

                        }
                
$regexValue trim($regexValue);
            }
        } catch( \
Exception $e) {} // if T-Regx library didn't load as it should, the textarea value will be kept as it is

        
return $regexValue;
    }

    
/**
     * @param $name
     * @param $action
     *
     * @return mixed|string
     */
    
public static function scriptExecTimer($name$action 'start')
    {
        if (! 
array_key_exists('wpacu_debug'$_GET)) {
            return 
''// only trigger it in debugging mode
        
}

        
$wpacuStartTimeName 'wpacu_' $name '_start_time';
        
$wpacuExecTimeName  'wpacu_' $name '_exec_time';

        if (
$action === 'start') {
            
$startTime = (microtime(true) * 1000);
            
ObjectCache::wpacu_cache_set($wpacuStartTimeName$startTime'wpacu_exec_time');
        }

        if (
$action === 'end' && ($startTime ObjectCache::wpacu_cache_get($wpacuStartTimeName'wpacu_exec_time'))) {
            
// End clock time in seconds
            
$endTime = (microtime(true) * 1000);
            
$scriptExecTime = ($endTime !== $startTime && $endTime $startTime) ? ($endTime $startTime) : 0;

            
// Calculate script execution time
            // Is there an existing exec time (e.g. from a function called several times)?
            // Append it to the total execution time
            
if ($scriptExecTimeExisting ObjectCache::wpacu_cache_get($wpacuExecTimeName'wpacu_exec_time')) {
                
$scriptExecTime += $scriptExecTimeExisting;
            }

            
ObjectCache::wpacu_cache_set($wpacuExecTimeName$scriptExecTime'wpacu_exec_time');
            return 
$scriptExecTime;
        }

        return 
'';
    }

    
/**
     * @param $wpacuCacheKey
     *
     * @return array
     */
    
public static function getTimingValues($wpacuCacheKey)
    {
        
$wpacuExecTiming ObjectCache::wpacu_cache_get$wpacuCacheKey'wpacu_exec_time' ) ?: 0;

        
$wpacuTimingFormatMs str_replace('.00'''number_format($wpacuExecTiming2));
        
$wpacuTimingFormatS  str_replace(array('.00'','), ''number_format(($wpacuExecTiming 1000), 3));

        return array(
'ms' => $wpacuTimingFormatMs's' => $wpacuTimingFormatS);
    }

    
/**
     * @param $timingKey
     * @param $htmlSource
     *
     * @return string|string[]
     */
    
public static function printTimingFor($timingKey$htmlSource)
    {
        
$wpacuCacheKey       'wpacu_' $timingKey '_exec_time';
        
$timingValues        self::getTimingValues$wpacuCacheKey);
        
$wpacuTimingFormatMs $timingValues['ms'];
        
$wpacuTimingFormatS  $timingValues['s'];

        return 
str_replace(
            array(
                
'{' $wpacuCacheKey '}',
                
'{' $wpacuCacheKey '_sec}'
            
),
            array(
                
$wpacuTimingFormatMs 'ms',
                
$wpacuTimingFormatS 's',
            ), 
// clean it up
            
$htmlSource );
    }
}
x

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