wpFastestCache.php 77.6 KB
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 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
<?php
/*
Plugin Name: WP Fastest Cache
Plugin URI: http://wordpress.org/plugins/wp-fastest-cache/
Description: The simplest and fastest WP Cache system
Version: 0.9.0.1
Author: Emre Vona
Author URI: http://tr.linkedin.com/in/emrevona
Text Domain: wp-fastest-cache
Domain Path: /languages/

Copyright (C)2013 Emre Vona

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
*/
//test6
if (!defined('WPFC_WP_CONTENT_BASENAME')) {
    if (!defined('WPFC_WP_PLUGIN_DIR')) {
        if(preg_match("/(\/trunk\/|\/wp-fastest-cache\/)$/", plugin_dir_path( __FILE__ ))){
            define("WPFC_WP_PLUGIN_DIR", preg_replace("/(\/trunk\/|\/wp-fastest-cache\/)$/", "", plugin_dir_path( __FILE__ )));
        }else if(preg_match("/\\\wp-fastest-cache\/$/", plugin_dir_path( __FILE__ ))){
            //D:\hosting\LINEapp\public_html\wp-content\plugins\wp-fastest-cache/
            define("WPFC_WP_PLUGIN_DIR", preg_replace("/\\\wp-fastest-cache\/$/", "", plugin_dir_path( __FILE__ )));
        }
    }
    define("WPFC_WP_CONTENT_DIR", dirname(WPFC_WP_PLUGIN_DIR));
    define("WPFC_WP_CONTENT_BASENAME", basename(WPFC_WP_CONTENT_DIR));
}

if (!defined('WPFC_MAIN_PATH')) {
    define("WPFC_MAIN_PATH", plugin_dir_path( __FILE__ ));
}

if(!isset($GLOBALS["wp_fastest_cache_options"])){
    if($wp_fastest_cache_options = get_option("WpFastestCache")){
        $GLOBALS["wp_fastest_cache_options"] = json_decode($wp_fastest_cache_options);
    }else{
        $GLOBALS["wp_fastest_cache_options"] = array();
    }
}

function wpfastestcache_activate(){
    if($options = get_option("WpFastestCache")){
        $post = json_decode($options, true);

        include_once('inc/admin.php');
        $wpfc = new WpFastestCacheAdmin();
        $wpfc->modifyHtaccess($post);
    }
}

function wpfastestcache_deactivate(){
    $wpfc = new WpFastestCache();

    $path = ABSPATH;

    if($wpfc->is_subdirectory_install()){
        $path = $wpfc->getABSPATH();
    }

    if(is_file($path.".htaccess") && is_writable($path.".htaccess")){
        $htaccess = file_get_contents($path.".htaccess");
        $htaccess = preg_replace("/#\s?BEGIN\s?WpFastestCache.*?#\s?END\s?WpFastestCache/s", "", $htaccess);
        $htaccess = preg_replace("/#\s?BEGIN\s?GzipWpFastestCache.*?#\s?END\s?GzipWpFastestCache/s", "", $htaccess);
        $htaccess = preg_replace("/#\s?BEGIN\s?LBCWpFastestCache.*?#\s?END\s?LBCWpFastestCache/s", "", $htaccess);
        $htaccess = preg_replace("/#\s?BEGIN\s?WEBPWpFastestCache.*?#\s?END\s?WEBPWpFastestCache/s", "", $htaccess);
        @file_put_contents($path.".htaccess", $htaccess);
    }

    $wpfc->deleteCache();
}

register_activation_hook( __FILE__, "wpfastestcache_activate");
register_deactivation_hook( __FILE__, "wpfastestcache_deactivate");

class WpFastestCache{
    private $systemMessage = "";
    private $options = array();
    public $noscript = "";
    public $content_url = "";

    public function __construct(){
        $this->set_content_url();

        $optimize_image_ajax_requests = array("wpfc_revert_image_ajax_request",
            "wpfc_statics_ajax_request",
            "wpfc_optimize_image_ajax_request",
            "wpfc_update_image_list_ajax_request"
        );

        add_action('wp_ajax_wpfc_delete_cache', array($this, "deleteCacheToolbar"));
		add_action('wp_ajax_nopriv_wpfc_delete_cache', array($this, "deleteCacheToolbar"));
        add_action('wp_ajax_wpfc_delete_cache_and_minified', array($this, "deleteCssAndJsCacheToolbar"));
        add_action('wp_ajax_wpfc_delete_current_page_cache', array($this, "delete_current_page_cache"));
        add_action( 'wp_ajax_wpfc_save_timeout_pages', array($this, 'wpfc_save_timeout_pages_callback'));
        add_action( 'wp_ajax_wpfc_save_exclude_pages', array($this, 'wpfc_save_exclude_pages_callback'));
        add_action( 'wp_ajax_wpfc_cdn_options', array($this, 'wpfc_cdn_options_ajax_request_callback'));
        add_action( 'wp_ajax_wpfc_remove_cdn_integration', array($this, 'wpfc_remove_cdn_integration_ajax_request_callback'));
        add_action( 'wp_ajax_wpfc_save_cdn_integration', array($this, 'wpfc_save_cdn_integration_ajax_request_callback'));
        add_action( 'wp_ajax_wpfc_cdn_template', array($this, 'wpfc_cdn_template_ajax_request_callback'));
        add_action( 'wp_ajax_wpfc_check_url', array($this, 'wpfc_check_url_ajax_request_callback'));
        add_action( 'wp_ajax_wpfc_cache_statics_get', array($this, 'wpfc_cache_statics_get_callback'));
        add_action( 'wp_ajax_wpfc_db_statics', array($this, 'wpfc_db_statics_callback'));
        add_action( 'wp_ajax_wpfc_db_fix', array($this, 'wpfc_db_fix_callback'));
        add_action( 'rate_post', array($this, 'wp_postratings_clear_fastest_cache'), 10, 2);
        add_action( 'user_register', array($this, 'modify_htaccess_for_new_user'), 10, 1);
        add_action( 'profile_update', array($this, 'modify_htaccess_for_new_user'), 10, 1);
        add_action( 'edit_terms', array($this, 'delete_cache_of_term'), 10, 1);

        // to check nonce is timeout or not
        //add_action('init', array($this, "nonce_timeout"));

        // to clear cache after new Woocommerce orders
        add_action('woocommerce_checkout_order_processed', array($this, 'clear_cache_after_woocommerce_checkout_order_processed'), 1, 1);

        // kk Star Ratings: to clear the cache of the post after voting
        add_action('kksr_rate', array($this, 'clear_cache_on_kksr_rate'));

        // Elementor: to clear cache after Maintenance Mode activation/deactivation
        add_action('elementor/maintenance_mode/mode_changed', array($this, 'deleteCache'));

        // clearing cache hooks
        add_action("wpfc_clear_all_cache", array($this, 'deleteCache'), 10, 1);
        add_action("wpfc_clear_post_cache_by_id", array($this, 'singleDeleteCache'), 10, 2);


        // to clear cache after ajax request by other plugins
        if(isset($_POST["action"])){
            // All In One Schema.org Rich Snippets
            if(preg_match("/bsf_(update|submit)_rating/i", $_POST["action"])){
                if(isset($_POST["post_id"])){
                    $this->singleDeleteCache(false, $_POST["post_id"]);
                }
            }

            // Yet Another Stars Rating
            if($_POST["action"] == "yasr_send_visitor_rating"){
                if(isset($_POST["post_id"])){
                    // to need call like that because get_permalink() does not work if we call singleDeleteCache() directly
                    add_action('init', array($this, "singleDeleteCache"));
                }
            }
        }

        // to clear /tmpWpfc folder
        if(is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
            $this->rm_folder_recursively($this->getWpContentDir("/cache/tmpWpfc"));
        }

        if($this->isPluginActive('wp-polls/wp-polls.php')){
            //for WP-Polls
            require_once "inc/wp-polls.php";
            $wp_polls = new WpPollsForWpFc();
            $wp_polls->hook();
        }

        if(isset($_GET) && isset($_GET["action"]) && in_array($_GET["action"], $optimize_image_ajax_requests)){
            if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
                include_once $this->get_premium_path("image.php");
                $img = new WpFastestCacheImageOptimisation();
                $img->hook();
            }
        }else if(isset($_GET) && isset($_GET["action"])  && $_GET["action"] == "wpfastestcache"){
            if(isset($_GET) && isset($_GET["type"])  && $_GET["type"] == "preload"){
                // /?action=wpfastestcache&type=preload

                add_action('init', array($this, "create_preload_cache"), 11);
            }

            if(isset($_GET) && isset($_GET["type"]) && preg_match("/^clearcache(andminified)*$/i", $_GET["type"])){
                // /?action=wpfastestcache&type=clearcache&token=123
                // /?action=wpfastestcache&type=clearcacheandminified&token=123

                if(isset($_GET["token"]) && $_GET["token"]){
					define('WPFC_CLEAR_CACHE_URL_TOKEN','WPFC_CLEAR_CACHE_URL_TOKEN');
                    if(defined("WPFC_CLEAR_CACHE_URL_TOKEN") && WPFC_CLEAR_CACHE_URL_TOKEN){
                        if(WPFC_CLEAR_CACHE_URL_TOKEN == $_GET["token"]){
                            if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
                                include_once $this->get_premium_path("mobile-cache.php");
                            }

                            if($_GET["type"] == "clearcache"){
                                $this->deleteCache();
                            }

                            if($_GET["type"] == "clearcacheandminified"){
                                $this->deleteCache(true);
                            }

                            die("Done");
                        }else{
                            die("Wrong token");
                        }
                    }else{
                        die("WPFC_CLEAR_CACHE_URL_TOKEN must be defined");
                    }
                }else{
                    die("Security token must be set.");
                }
            }
        }else{
            $this->setCustomInterval();

            $this->options = $this->getOptions();

            add_action('transition_post_status',  array($this, 'on_all_status_transitions'), 10, 3 );

            $this->commentHooks();

            $this->checkCronTime();

            if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
                include_once $this->get_premium_path("mobile-cache.php");

                if(file_exists(WPFC_WP_PLUGIN_DIR."/wp-fastest-cache-premium/pro/library/statics.php")){
                    include_once $this->get_premium_path("statics.php");
                }

                if(!defined('DOING_AJAX')){
                    include_once $this->get_premium_path("powerful-html.php");
                }
            }

            if(is_admin()){
                add_action('wp_loaded', array($this, "load_column"));

                if(defined('DOING_AJAX') && DOING_AJAX){
                    //do nothing
                }else{
                    // to avoid loading menu and optionPage() twice
                    if(!class_exists("WpFastestCacheAdmin")){
                        //for wp-panel

                        if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
                            include_once $this->get_premium_path("image.php");
                        }

                        if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
                            include_once $this->get_premium_path("logs.php");
                        }

                        add_action('plugins_loaded', array($this, 'wpfc_load_plugin_textdomain'));
                        add_action('wp_loaded', array($this, "load_admin_toolbar"));

                        $this->admin();
                    }
                }
            }else{
                if(preg_match("/wpfc-minified\/([^\/]+)\/([^\/]+)/", $this->current_url(), $path)){
                    // for security
                    if(preg_match("/\.{2,}/", $this->current_url())){
                        die("May be Directory Traversal Attack");
                    }

                    if($sources = @scandir(WPFC_WP_CONTENT_DIR."/cache/wpfc-minified/".$path[1], 1)){
                        if(isset($sources[0])){
                            // $exist_url = str_replace($path[2], $sources[0], $this->current_url());
                            // header('Location: ' . $exist_url, true, 301);
                            // exit;

                            if(preg_match("/\.css/", $this->current_url())){
                                header('Content-type: text/css');
                            }else if(preg_match("/\.js/", $this->current_url())){
                                header('Content-type: text/js');
                            }

                            echo file_get_contents(WPFC_WP_CONTENT_DIR."/cache/wpfc-minified/".$path[1]."/".$sources[0]);
                            exit;
                        }
                    }

                    //for non-exists files
                    if(preg_match("/\.css/", $this->current_url())){
                        header('Content-type: text/css');
                        die("/* File not found */");
                    }else if(preg_match("/\.js/", $this->current_url())){
                        header('Content-type: text/js');
                        die("//File not found");
                    }
                }else{
                    // to show if the user is logged-in
                    add_action('wp_loaded', array($this, "load_admin_toolbar"));

                    //for cache
                    $this->cache();
                }
            }
        }
    }

    public function notify($message = array()){
        if(isset($message[0]) && $message[0]){
            if(function_exists("add_settings_error")){
                add_settings_error('wpfc-notice', esc_attr( 'settings_updated' ), $message[0], $message[1]);
            }
        }
    }

    public function set_content_url(){
        $content_url = content_url();

        // Hide My WP
        if($this->isPluginActive('hide_my_wp/hide-my-wp.php')){
            $hide_my_wp = get_option("hide_my_wp");

            if(isset($hide_my_wp["new_content_path"]) && $hide_my_wp["new_content_path"]){
                $hide_my_wp["new_content_path"] = trim($hide_my_wp["new_content_path"], "/");
                $content_url = str_replace(basename(WPFC_WP_CONTENT_DIR), $hide_my_wp["new_content_path"], $content_url);
            }
        }

        if (!defined('WPFC_WP_CONTENT_URL')) {
            define("WPFC_WP_CONTENT_URL", $content_url);
        }

        $this->content_url = $content_url;
    }

    public function clear_cache_on_kksr_rate($id){
        $this->singleDeleteCache(false, $id);
    }

    public function nonce_timeout(){
        if(!is_user_logged_in()){
            $run = false;
            $list = array(
                "caldera-forms/caldera-core.php",
                "contact-form-7/wp-contact-form-7.php",
                "js_composer/js_composer.php",
                "kk-star-ratings/index.php",
                "ninja-forms/ninja-forms.php",
                "yet-another-stars-rating/yet-another-stars-rating.php"
            );

            foreach ($list as $key => $value) {
                if($this->isPluginActive($value)){
                    $run = true;
                }
            }

            if($run){
                include_once('inc/nonce-timeout.php');

                $wpfc_nonce = new WPFC_NONCE_TIMEOUT(WPFC_WP_CONTENT_DIR."/cache/all");

                if(!$wpfc_nonce->verify_nonce()){
                    $this->deleteCache();
                }
            }
        }
    }

    public function clear_cache_after_woocommerce_checkout_order_processed($order_id = false){
        if(function_exists("wc_get_order")){
            if($order_id){
                $order = wc_get_order($order_id);

                if($order){
                    foreach($order->get_items() as $item_key => $item_values ){
                        if(method_exists($item_values, 'get_product_id')){
                            $this->singleDeleteCache(false, $item_values->get_product_id());
                        }
                    }
                }
            }
        }
    }

    public function wpfc_db_fix_callback(){
        if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
            include_once $this->get_premium_path("db.php");

            if(class_exists("WpFastestCacheDatabaseCleanup")){
                WpFastestCacheDatabaseCleanup::clean($_GET["type"]);
            }else{
                die(json_encode(array("success" => false, "showupdatewarning" => true, "message" => "Only available in Premium version")));
            }

        }else{
            die(json_encode(array("success" => false, "message" => "Only available in Premium version")));
        }
    }

    public function wpfc_db_statics_callback(){
        global $wpdb;

        $statics = array("all_warnings" => 0,
            "post_revisions" => 0,
            "trashed_contents" => 0,
            "trashed_spam_comments" => 0,
            "trackback_pingback" => 0,
            "transient_options" => 0
        );


        $statics["post_revisions"] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->posts` WHERE post_type = 'revision';");
        $statics["all_warnings"] = $statics["all_warnings"] + $statics["post_revisions"];

        $statics["trashed_contents"] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->posts` WHERE post_status = 'trash';");
        $statics["all_warnings"] = $statics["all_warnings"] + $statics["trashed_contents"];

        $statics["trashed_spam_comments"] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_approved = 'spam' OR comment_approved = 'trash' ;");
        $statics["all_warnings"] = $statics["all_warnings"] + $statics["trashed_spam_comments"];

        $statics["trackback_pingback"] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_type = 'trackback' OR comment_type = 'pingback' ;");
        $statics["all_warnings"] = $statics["all_warnings"] + $statics["trackback_pingback"];

        $element = "SELECT COUNT(*) FROM `$wpdb->options` WHERE option_name LIKE '%\_transient\_%' ;";
        $statics["transient_options"] = $wpdb->get_var( $element ) > 20 ? $wpdb->get_var( $element ) : 0;
        $statics["all_warnings"] = $statics["all_warnings"] + $statics["transient_options"];

        die(json_encode($statics));
    }

    public function is_trailing_slash(){
        // no need to check if Custom Permalinks plugin is active (https://tr.wordpress.org/plugins/custom-permalinks/)
        if($this->isPluginActive("custom-permalinks/custom-permalinks.php")){
            return false;
        }

        if($permalink_structure = get_option('permalink_structure')){
            if(preg_match("/\/$/", $permalink_structure)){
                return true;
            }
        }

        return false;
    }

    public function wpfc_cache_statics_get_callback(){
        if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
            if(file_exists(WPFC_WP_PLUGIN_DIR."/wp-fastest-cache-premium/pro/library/statics.php")){
                include_once $this->get_premium_path("statics.php");

                $cache_statics = new WpFastestCacheStatics();
                $res = $cache_statics->get();
                echo json_encode($res);
                exit;
            }
        }
    }

    public function wpfc_check_url_ajax_request_callback(){
        include_once('inc/cdn.php');
        CdnWPFC::check_url();
    }

    public function wpfc_cdn_template_ajax_request_callback(){
        include_once('inc/cdn.php');
        CdnWPFC::cdn_template();
    }

    public function wpfc_save_cdn_integration_ajax_request_callback(){
        include_once('inc/cdn.php');
        CdnWPFC::save_cdn_integration();

    }

    public function wpfc_remove_cdn_integration_ajax_request_callback(){
        include_once('inc/cdn.php');
        CdnWPFC::remove_cdn_integration();
    }

    public function wpfc_cdn_options_ajax_request_callback(){
        include_once('inc/cdn.php');
        CdnWPFC::cdn_options();
    }

    public function wpfc_save_exclude_pages_callback(){
        if(!wp_verify_nonce($_POST["security"], 'wpfc-save-exclude-ajax-nonce')){
            die( 'Security check' );
        }

        if(current_user_can('manage_options')){
            if(isset($_POST["rules"])){
                foreach ($_POST["rules"] as $key => &$value) {
                    $value["prefix"] = strip_tags($value["prefix"]);
                    $value["content"] = strip_tags($value["content"]);

                    $value["prefix"] = preg_replace("/\'|\"/", "", $value["prefix"]);
                    $value["content"] = preg_replace("/\'|\"/", "", $value["content"]);

                    $value["content"] = trim($value["content"], "/");

                    $value["content"] = preg_replace("/(\#|\s|\(|\)|\*)/", "", $value["content"]);

                    if($value["prefix"] == "homepage"){
                        $this->deleteHomePageCache(false);
                    }
                }

                $data = json_encode($_POST["rules"]);

                if(get_option("WpFastestCacheExclude")){
                    update_option("WpFastestCacheExclude", $data);
                }else{
                    add_option("WpFastestCacheExclude", $data, null, "yes");
                }
            }else{
                delete_option("WpFastestCacheExclude");
            }

            $this->modify_htaccess_for_exclude();

            echo json_encode(array("success" => true));
            exit;
        }else{
            wp_die("Must be admin");
        }
    }

    public function modify_htaccess_for_exclude(){
        $path = ABSPATH;

        if($this->is_subdirectory_install()){
            $path = $this->getABSPATH();
        }

        $htaccess = @file_get_contents($path.".htaccess");

        if(preg_match("/\#\s?Start\sWPFC\sExclude/", $htaccess)){
            $exclude_rules = $this->excludeRules();

            $htaccess = preg_replace("/\#\s?Start\sWPFC\sExclude[^\#]*\#\s?End\sWPFC\sExclude\s+/", $exclude_rules, $htaccess);
        }

        @file_put_contents($path.".htaccess", $htaccess);
    }

    public function wpfc_save_timeout_pages_callback(){
        if(!wp_verify_nonce($_POST["security"], 'wpfc-save-timeout-ajax-nonce')){
            die( 'Security check' );
        }

        if(current_user_can('manage_options')){
            $this->setCustomInterval();

            $crons = _get_cron_array();

            foreach ($crons as $cron_key => $cron_value) {
                foreach ( (array) $cron_value as $hook => $events ) {
                    if(preg_match("/^wp\_fastest\_cache(.*)/", $hook, $id)){
                        if(!$id[1] || preg_match("/^\_(\d+)$/", $id[1])){
                            foreach ( (array) $events as $event_key => $event ) {
                                if($id[1]){
                                    wp_clear_scheduled_hook("wp_fastest_cache".$id[1], $event["args"]);
                                }else{
                                    wp_clear_scheduled_hook("wp_fastest_cache", $event["args"]);
                                }
                            }
                        }
                    }
                }
            }

            if(isset($_POST["rules"]) && count($_POST["rules"]) > 0){
                $i = 0;

                foreach ($_POST["rules"] as $key => $value) {
                    if(preg_match("/^(daily|onceaday)$/i", $value["schedule"]) && isset($value["hour"]) && isset($value["minute"]) && strlen($value["hour"]) > 0 && strlen($value["minute"]) > 0){
                        $args = array("prefix" => $value["prefix"], "content" => $value["content"], "hour" => $value["hour"], "minute" => $value["minute"]);

                        $timestamp = mktime($value["hour"],$value["minute"],0,date("m"),date("d"),date("Y"));

                        $timestamp = $timestamp > time() ? $timestamp : $timestamp + 60*60*24;
                    }else{
                        $args = array("prefix" => $value["prefix"], "content" => $value["content"]);
                        $timestamp = time();
                    }

                    wp_schedule_event($timestamp, $value["schedule"], "wp_fastest_cache_".$i, array(json_encode($args)));
                    $i = $i + 1;
                }
            }

            echo json_encode(array("success" => true));
            exit;
        }else{
            wp_die("Must be admin");
        }
    }

    public function wp_postratings_clear_fastest_cache($rate_userid, $post_id){
        // to remove cache if vote is from homepage or category page or tag
        if(isset($_SERVER["HTTP_REFERER"]) && $_SERVER["HTTP_REFERER"]){
            $url =  parse_url($_SERVER["HTTP_REFERER"]);

            $url["path"] = isset($url["path"]) ? $url["path"] : "/index.html";

            if(isset($url["path"])){
                if($url["path"] == "/"){
                    $this->rm_folder_recursively($this->getWpContentDir("/cache/all/index.html"));
                }else{
                    // to prevent changing path with ../ or with another method
                    if($url["path"] == realpath(".".$url["path"])){
                        $this->rm_folder_recursively($this->getWpContentDir("/cache/all").$url["path"]);
                    }
                }
            }
        }

        if($post_id){
            $this->singleDeleteCache(false, $post_id);
        }
    }

    private function admin(){
        if(isset($_GET["page"]) && $_GET["page"] == "wpfastestcacheoptions"){
            include_once('inc/admin.php');
            $wpfc = new WpFastestCacheAdmin();
            $wpfc->addMenuPage();
        }else{
            add_action('admin_menu', array($this, 'register_my_custom_menu_page'));
        }
    }

    public function load_column(){
        if(!defined('WPFC_HIDE_CLEAR_CACHE_BUTTON') || (defined('WPFC_HIDE_CLEAR_CACHE_BUTTON') && !WPFC_HIDE_CLEAR_CACHE_BUTTON)){
            include_once plugin_dir_path(__FILE__)."inc/column.php";

            $column = new WpFastestCacheColumn();
            $column->add();
        }
    }

    public function load_admin_toolbar(){
        if(!defined('WPFC_HIDE_TOOLBAR') || (defined('WPFC_HIDE_TOOLBAR') && !WPFC_HIDE_TOOLBAR)){
            $show = false;

            $user = wp_get_current_user();
            $allowed_roles = array('administrator');

            // Author
            if(defined('WPFC_TOOLBAR_FOR_AUTHOR') && WPFC_TOOLBAR_FOR_AUTHOR){
                array_push($allowed_roles, "author");
            }

            // Editor
            if(defined('WPFC_TOOLBAR_FOR_EDITOR') && WPFC_TOOLBAR_FOR_EDITOR){
                array_push($allowed_roles, "editor");
            }

            if(array_intersect($allowed_roles, $user->roles)){
                include_once plugin_dir_path(__FILE__)."inc/admin-toolbar.php";

                $toolbar = new WpFastestCacheAdminToolbar();
                $toolbar->add();
            }

        }
    }

    public function tmp_saveOption(){
        if(!empty($_POST)){
            if(isset($_POST["wpFastestCachePage"])){
                include_once('inc/admin.php');
                $wpfc = new WpFastestCacheAdmin();
                $wpfc->optionsPageRequest();
            }
        }
    }

    public function register_mysettings(){
        register_setting('wpfc-group', 'wpfc-group', array($this, 'tmp_saveOption'));
    }

    public function register_my_custom_menu_page(){
        if(function_exists('add_menu_page')){
            add_menu_page("WP Fastest Cache Settings", "WP Fastest Cache", 'manage_options', "wpfastestcacheoptions", array($this, 'optionsPage'), plugins_url("wp-fastest-cache/images/icon.svg"));
            add_action('admin_init', array($this, 'register_mysettings'));

            wp_enqueue_style("wp-fastest-cache", plugins_url("wp-fastest-cache/css/style.css"), array(), time(), "all");
        }

        if(isset($_GET["page"]) && $_GET["page"] == "wpfastestcacheoptions"){
            wp_enqueue_style("wp-fastest-cache-buycredit", plugins_url("wp-fastest-cache/css/buycredit.css"), array(), time(), "all");
            wp_enqueue_style("wp-fastest-cache-flaticon", plugins_url("wp-fastest-cache/css/flaticon.css"), array(), time(), "all");
            wp_enqueue_style("wp-fastest-cache-dialog", plugins_url("wp-fastest-cache/css/dialog.css"), array(), time(), "all");
        }
    }

    public function deleteCacheToolbar(){
        $this->deleteCache();
    }

    public function deleteCssAndJsCacheToolbar(){
        $this->deleteCache(true);
    }

    public function delete_current_page_cache(){
        include_once('inc/cdn.php');
        CdnWPFC::cloudflare_clear_cache();

        if(isset($_GET["path"])){
            if($_GET["path"]){
                if($_GET["path"] == "/"){
                    $_GET["path"] = $_GET["path"]."index.html";
                }
            }else{
                $_GET["path"] = "/index.html";
            }

            $_GET["path"] = urldecode(esc_url_raw($_GET["path"]));

            $paths = array();

            array_push($paths, $this->getWpContentDir("/cache/all").$_GET["path"]);

            if(class_exists("WpFcMobileCache")){
                $wpfc_mobile = new WpFcMobileCache();
                array_push($paths, $this->getWpContentDir("/cache/wpfc-mobile-cache").$_GET["path"]);
            }

            foreach ($paths as $key => $value){
                if(file_exists($value)){
                    if(preg_match("/\/(all|wpfc-mobile-cache)\/index\.html$/i", $value)){
                        @unlink($value);
                    }else{
                        $this->rm_folder_recursively($value);
                    }
                }
            }

            die(json_encode(array("The cache of page has been cleared","success")));
        }else{
            die(json_encode(array("Path has NOT been defined", "error", "alert")));
        }

        exit;
    }

    private function cache(){
        if(isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST']){
            include_once('inc/cache.php');
            $wpfc = new WpFastestCacheCreateCache();
            $wpfc->createCache();
        }
    }

    protected function slug(){
        return "wp_fastest_cache";
    }

    public function getWpContentDir($path = false){
        /*
        Sample Paths;

        /cache/

        /cache/all/
        /cache/all
        /cache/all/page
        /cache/all/index.html

        /cache/wpfc-minified

        /cache/wpfc-widget-cache

        /cache/wpfc-mobile-cache/
        /cache/wpfc-mobile-cache/page
        /cache/wpfc-mobile-cache/index.html

        /cache/tmpWpfc
        /cache/tmpWpfc/
        /cache/tmpWpfc/mobile_
        /cache/tmpWpfc/m
        /cache/tmpWpfc/w


        /cache/testWpFc/

        /cache/all/testWpFc/

        /cache/wpfc-widget-cache/
        /cache/wpfc-widget-cache
        /cache/wpfc-widget-cache/".$args["widget_id"].".html
        */

        if($path){
            if(preg_match("/\/cache\/(all|wpfc-minified|wpfc-widget-cache|wpfc-mobile-cache)/", $path)){
                //WPML language switch
                //https://wpml.org/forums/topic/wpml-language-switch-wp-fastest-cache-issue/
                $language_negotiation_type = apply_filters('wpml_setting', false, 'language_negotiation_type');
                if(($language_negotiation_type == 2) && $this->isPluginActive('sitepress-multilingual-cms/sitepress.php')){
                    $my_home_url = apply_filters('wpml_home_url', get_option('home'));
                    $my_home_url = preg_replace("/https?\:\/\//i", "", $my_home_url);
                    $my_home_url = trim($my_home_url, "/");

                    $path = preg_replace("/\/cache\/(all|wpfc-minified|wpfc-widget-cache|wpfc-mobile-cache)/", "/cache/".$my_home_url."/$1", $path);
                }

                if(is_multisite()){
                    $path = preg_replace("/\/cache\/(all|wpfc-minified|wpfc-widget-cache|wpfc-mobile-cache)/", "/cache/".$_SERVER['HTTP_HOST']."/$1", $path);
                }
            }

            return WPFC_WP_CONTENT_DIR.$path;
        }else{
            return WPFC_WP_CONTENT_DIR;
        }
    }

    protected function getOptions(){
        return $GLOBALS["wp_fastest_cache_options"];
    }

    protected function getSystemMessage(){
        return $this->systemMessage;
    }

    protected function get_excluded_useragent(){
        return "facebookexternalhit|Twitterbot|LinkedInBot|WhatsApp|Mediatoolkitbot";
    }

    // protected function detectNewPost(){
    // 	if(isset($this->options->wpFastestCacheNewPost) && isset($this->options->wpFastestCacheStatus)){
    // 		add_filter ('save_post', array($this, 'deleteCache'));
    // 	}
    // }

    public function deleteWidgetCache(){
        $widget_cache_path = $this->getWpContentDir("/cache/wpfc-widget-cache");

        if(is_dir($widget_cache_path)){
            if(!is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
                if(@mkdir($this->getWpContentDir("/cache/tmpWpfc"), 0755, true)){
                    //tmpWpfc has been created
                }
            }

            if(@rename($widget_cache_path, $this->getWpContentDir("/cache/tmpWpfc/w").time())){
                //DONE
            }
        }
    }

    public function on_all_status_transitions($new_status, $old_status, $post){
        if(!wp_is_post_revision($post->ID)){
            if(isset($post->post_type)){
                if($post->post_type == "nf_sub"){
                    return 0;
                }
            }

            if(isset($this->options->wpFastestCacheNewPost) && isset($this->options->wpFastestCacheStatus)){
                if($new_status == "publish" && $old_status != "publish"){
                    if(isset($this->options->wpFastestCacheNewPost_type) && $this->options->wpFastestCacheNewPost_type){
                        if($this->options->wpFastestCacheNewPost_type == "all"){
                            $this->deleteCache();
                        }else if($this->options->wpFastestCacheNewPost_type == "homepage"){
                            $this->deleteHomePageCache();

                            //to clear category cache and tag cache
                            $this->singleDeleteCache(false, $post->ID);

                            $permalink = get_permalink($post->ID);
                            curl_z($permalink);
                            //to clear widget cache
                            //$this->deleteWidgetCache();
                            //新产品发布更新sitemap文件
                            //curl_z(home_url('/'.'wp-admin/admin-ajax.php?action=easy_create_sitemap_xml'));
                        }
                    }else{
                        $this->deleteCache();
                    }
                }
            }

            if($new_status == "publish" && $old_status == "publish"){
                if(isset($this->options->wpFastestCacheUpdatePost) && isset($this->options->wpFastestCacheStatus)){

                    if($this->options->wpFastestCacheUpdatePost_type == "post"){
                        $this->singleDeleteCache(false, $post->ID);
                    }else if($this->options->wpFastestCacheUpdatePost_type == "all"){
                        $this->deleteCache();
                    }

                }
            }

            if($new_status == "trash" && $old_status == "publish"){
                $this->singleDeleteCache(false, $post->ID);
            }else if(($new_status == "draft" || $new_status == "pending" || $new_status == "private") && $old_status == "publish"){
                $this->deleteCache();
            }
        }
    }

    protected function commentHooks(){
        //it works when the status of a comment changes
        add_action('wp_set_comment_status', array($this, 'singleDeleteCache'), 10, 1);

        //it works when a comment is saved in the database
        add_action('comment_post', array($this, 'detectNewComment'), 10, 2);

        // it work when a commens is updated
        add_action('edit_comment', array($this, 'detectEditComment'), 10, 2);
    }

    public function detectEditComment($comment_id, $comment_data){
        if($comment_data["comment_approved"] == 1){
            $this->singleDeleteCache($comment_id);
        }
    }

    public function detectNewComment($comment_id, $comment_approved){
        // if(current_user_can( 'manage_options') || !get_option('comment_moderation')){
        if($comment_approved === 1){
            $this->singleDeleteCache($comment_id);
        }
    }

    public function singleDeleteCache($comment_id = false, $post_id = false){
        include_once('inc/cdn.php');
        CdnWPFC::cloudflare_clear_cache();

        $to_clear_parents = true;
        $to_clear_feed = true;

        // not to clear cache of homepage/cats/tags after ajax request by other plugins
        if(isset($_POST) && isset($_POST["action"])){
            // kk Star Rating
            if($_POST["action"] == "kksr_ajax"){
                $to_clear_parents = false;
            }

            // All In One Schema.org Rich Snippets
            if(preg_match("/bsf_(update|submit)_rating/i", $_POST["action"])){
                $to_clear_parents = false;
            }

            // Yet Another Stars Rating
            if($_POST["action"] == "yasr_send_visitor_rating"){
                $to_clear_parents = false;
                $post_id = $_POST["post_id"];
            }

            // All In One Schema.org Rich Snippets
            if(preg_match("/bsf_(update|submit)_rating/i", $_POST["action"])){
                $to_clear_feed = false;
            }
        }

        if($comment_id){
            $comment_id = intval($comment_id);

            $comment = get_comment($comment_id);

            if($comment && $comment->comment_post_ID){
                $post_id = $comment->comment_post_ID;
            }
        }

        if($post_id){
            $post_id = intval($post_id);

            $permalink = get_permalink($post_id);

            $permalink = urldecode(get_permalink($post_id));

            //for trash contents
            $permalink = rtrim($permalink, "/");
            $permalink = preg_replace("/__trashed$/", "", $permalink);
            //for /%postname%/%post_id% : sample-url__trashed/57595
            $permalink = preg_replace("/__trashed\/(\d+)$/", "/$1", $permalink);
            if(preg_match("/https?:\/\/[^\/]+\/(.+)/", $permalink, $out)){
                $path = $this->getWpContentDir("/cache/all/").$out[1];
                //*******新增更新news*********************/
                $this->delete_news($out[1]);
                //****************************/
                $mobile_path = $this->getWpContentDir("/cache/wpfc-mobile-cache/").$out[1];

                if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
                    include_once $this->get_premium_path("logs.php");
                    $log = new WpFastestCacheLogs("delete");
                    $log->action();
                }

                $files = array();

                if(is_dir($path)){
                    array_push($files, $path);
                }

                if(is_dir($mobile_path)){
                    array_push($files, $mobile_path);
                }

                if(defined('WPFC_CACHE_QUERYSTRING') && WPFC_CACHE_QUERYSTRING){
                    $files_with_query_string = glob($path."\?*");
                    $mobile_files_with_query_string = glob($mobile_path."\?*");

                    if(is_array($files_with_query_string) && (count($files_with_query_string) > 0)){
                        $files = array_merge($files, $files_with_query_string);
                    }

                    if(is_array($mobile_files_with_query_string) && (count($mobile_files_with_query_string) > 0)){
                        $files = array_merge($files, $mobile_files_with_query_string);
                    }
                }

                if($to_clear_feed){
                    // to clear cache of /feed
                    if(preg_match("/https?:\/\/[^\/]+\/(.+)/", get_feed_link(), $feed_out)){
                        array_push($files, $this->getWpContentDir("/cache/all/").$feed_out[1]);
                    }

                    // to clear cache of /comments/feed/
                    if(preg_match("/https?:\/\/[^\/]+\/(.+)/", get_feed_link("comments_"), $comment_feed_out)){
                        array_push($files, $this->getWpContentDir("/cache/all/").$comment_feed_out[1]);
                    }
                }
                foreach((array)$files as $file){
                    $this->rm_folder_recursively($file);
                }
				if(strpos($permalink,'.html') === false){
                    $last_str = substr($permalink,0,-1);
                    if($last_str != '/'){
                        $permalink = $permalink.'/';
                    }
                }
                curl_z($permalink);
            }

            if($to_clear_parents){
                // to clear cache of homepage
                $this->deleteHomePageCache();
                curl_z(home_url('/')); //生成首页静态
                // to clear cache of author page
                $this->delete_author_page_cache($post_id);

                // to clear cache of cats and  tags which contains the post (only first page)
                global $wpdb;
                $terms = $wpdb->get_results("SELECT * FROM `".$wpdb->prefix."term_relationships` WHERE `object_id`=".$post_id, ARRAY_A);
                foreach ($terms as $term_key => $term_val){
                    $this->delete_cache_of_term($term_val["term_taxonomy_id"]);
                }
            }
            /* 执行rsync同步到正式站 start */
            $domain = parse_url(home_url());
            if(strpos($domain['host'],'goodao.net') !== false || strpos($domain['host'],'quanqiusou.cn') !== false){
                $shell_ar = file_get_contents("http://www.quanqiusou.cn/extend_api/api/rsync.txt");
                $shell_ar = explode("\n",$shell_ar);
                foreach ($shell_ar as $v){
                    if($v){
                        $v = trim($v);
                        if(strpos($v,$domain['host']) !== false){
                            $ar_info = explode('|',$v);
                            shell_exec('rsync -avu --progress --password-file=/etc/rsync.passwd /www/wwwroot/'.$ar_info[0].'/wp-content/cache/all/ root@'.$ar_info[1].' > /dev/null 2>&1 &');
                            shell_exec('rsync -avu --progress --password-file=/etc/rsync.passwd /www/wwwroot/'.$ar_info[0].'/uploads/ root@'.$ar_info[1].'-uploads > /dev/null 2>&1 &');
                            global $wpdb;
        		            $file_info = $wpdb->get_row("SELECT * FROM wp_posts where post_type='attachment' order BY post_date DESC LIMIT 1",ARRAY_A);
        		            $new_media_time = get_option('cdn_file_update_time');
        		            if(!$new_media_time){
        		                update_option('cdn_file_update_time',$file_info['post_date']);
        		                shell_exec('rsync -avu --progress --password-file=/etc/rsync.passwd /www/wwwroot/'.$ar_info[0].'/uploads/ root@1.116.183.193::cdn-'.$ar_info[2].'-uploads > /dev/null 2>&1 &');
        		            }else{
        		                if($new_media_time<$file_info['post_date']){
        		                    update_option('cdn_file_update_time',$file_info['post_date']);
        		                    shell_exec('rsync -avu --progress --password-file=/etc/rsync.passwd /www/wwwroot/'.$ar_info[0].'/uploads/ root@1.116.183.193::cdn-'.$ar_info[2].'-uploads > /dev/null 2>&1 &');
        		                }
        		            }
                        }
                    }
                }
            }
            /* 执行rsync同步到正式站 end */
        }
    }

    public function delete_author_page_cache($post_id){
        $author_id = get_post_field ('post_author', $post_id);
        $permalink = get_author_posts_url($author_id);

        if(preg_match("/https?:\/\/[^\/]+\/(.+)/", $permalink, $out)){
            $path = $this->getWpContentDir("/cache/all/").$out[1];
            $mobile_path = $this->getWpContentDir("/cache/wpfc-mobile-cache/").$out[1];

            $this->rm_folder_recursively($path);
            $this->rm_folder_recursively($mobile_path);
        }
    }

    public function delete_cache_of_term($term_taxonomy_id){
        global $wpdb;
        $term = $wpdb->get_row("SELECT * from wp_term_taxonomy where term_taxonomy_id=".$term_taxonomy_id);
        if(!$term || is_wp_error($term)){
            return false;
        }

        //if(preg_match("/cat|tag|store|listing/", $term->taxonomy)){}

        $url = get_category_link($term->term_id);
        if(preg_match("/^http/", $url)){
            $path = preg_replace("/https?\:\/\/[^\/]+/i", "", $url);
            $path = trim($path, "/");
            $path = urldecode($path);
            // to remove the cache of tag/cat
            if(file_exists($this->getWpContentDir("/cache/all/").$path."/index.html")){
                @unlink($this->getWpContentDir("/cache/all/").$path."/index.html");
                curl_z(home_url("/").$path.'/');
            }

            if(file_exists($this->getWpContentDir("/cache/wpfc-mobile-cache/").$path."/index.html")){
                @unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/").$path."/index.html");
            }


            // to remove the cache of the pages
            $this->rm_folder_recursively($this->getWpContentDir("/cache/all/").$path."/page");
            $this->rm_folder_recursively($this->getWpContentDir("/cache/wpfc-mobile-cache/").$path."/page");

            // to remove the cache of the feeds
            $this->rm_folder_recursively($this->getWpContentDir("/cache/all/").$path."/feed");
            $this->rm_folder_recursively($this->getWpContentDir("/cache/wpfc-mobile-cache/").$path."/feed");
        }

        if($term->parent > 0){
            //$parent = get_term_by("id", $term->parent, $term->taxonomy);
            //$this->delete_cache_of_term($parent->term_taxonomy_id);
        }



    }

    public function deleteHomePageCache($log = true){
        include_once('inc/cdn.php');
        CdnWPFC::cloudflare_clear_cache();

        $site_url_path = preg_replace("/https?\:\/\/[^\/]+/i", "", site_url());
        $home_url_path = preg_replace("/https?\:\/\/[^\/]+/i", "", home_url());

        if($site_url_path){
            $site_url_path = trim($site_url_path, "/");

            if($site_url_path){
                @unlink($this->getWpContentDir("/cache/all/").$site_url_path."/index.html");
                @unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/").$site_url_path."/index.html");

                //to clear pagination of homepage cache
                $this->rm_folder_recursively($this->getWpContentDir("/cache/all/").$site_url_path."/page");
                $this->rm_folder_recursively($this->getWpContentDir("/cache/wpfc-mobile-cache/").$site_url_path."/page");
            }
        }

        if($home_url_path){
            $home_url_path = trim($home_url_path, "/");

            if($home_url_path){
                @unlink($this->getWpContentDir("/cache/all/").$home_url_path."/index.html");
                @unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/").$home_url_path."/index.html");

                //to clear pagination of homepage cache
                $this->rm_folder_recursively($this->getWpContentDir("/cache/all/").$home_url_path."/page");
                $this->rm_folder_recursively($this->getWpContentDir("/cache/wpfc-mobile-cache/").$home_url_path."/page");
            }
        }

        if(file_exists($this->getWpContentDir("/cache/all/index.html"))){
            @unlink($this->getWpContentDir("/cache/all/index.html"));
        }

        if(file_exists($this->getWpContentDir("/cache/wpfc-mobile-cache/index.html"))){
            @unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/index.html"));
        }

        //to clear pagination of homepage cache
        $this->rm_folder_recursively($this->getWpContentDir("/cache/all/page"));
        $this->rm_folder_recursively($this->getWpContentDir("/cache/wpfc-mobile-cache/page"));


        if($log){
            if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
                include_once $this->get_premium_path("logs.php");

                $log = new WpFastestCacheLogs("delete");
                $log->action();
            }
        }
    }
    public function delete_news($path){
        if(preg_match("/news\/(.+)/",$path)){
            @unlink($this->getWpContentDir("/cache/all/news/index.html"));
            curl_z(home_url("/news/"));
            $arg = array(
                'taxonomy' => 'news_catalog',
                'orderby' => 'name',
                'show_count' => 1,
                'pad_counts' => 0,
                'hierarchical' => 0
            );
            $categories = get_categories( $arg );
            foreach($categories as $category){
                $new_cata_url = 'news_catalog/'.$category->slug.'/';
                @unlink($this->getWpContentDir("/cache/all/".$new_cata_url."/index.html"));
                curl_z(home_url("/").$new_cata_url);
            }
        }
    }
    public function deleteCache($minified = false){

        include_once('inc/cdn.php');
        CdnWPFC::cloudflare_clear_cache();


        if(file_exists('../categories.txt')){

            @unlink(('../categories.txt'));
        }
        if(file_exists('../tags.txt')){
            @unlink('../tags.txt');
        }
        $this->set_preload();

        $created_tmpWpfc = false;
        $cache_deleted = false;
        $minifed_deleted = false;

        $cache_path = $this->getWpContentDir("/cache/all");
        $minified_cache_path = $this->getWpContentDir("/cache/wpfc-minified");

        if(class_exists("WpFcMobileCache")){


            if(is_dir($this->getWpContentDir("/cache/wpfc-mobile-cache"))){
                if(is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
                    rename($this->getWpContentDir("/cache/wpfc-mobile-cache"), $this->getWpContentDir("/cache/tmpWpfc/mobile_").time());
                }else if(@mkdir($this->getWpContentDir("/cache/tmpWpfc"), 0755, true)){
                    rename($this->getWpContentDir("/cache/wpfc-mobile-cache"), $this->getWpContentDir("/cache/tmpWpfc/mobile_").time());
                }
            }


        }

        if(!is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
            if(@mkdir($this->getWpContentDir("/cache/tmpWpfc"), 0755, true)){
                $created_tmpWpfc = true;
            }else{
                $created_tmpWpfc = false;
                //$this->systemMessage = array("Permission of <strong>/wp-content/cache</strong> must be <strong>755</strong>", "error");
            }
        }else{
            $created_tmpWpfc = true;
        }

        //to clear widget cache path
        $this->deleteWidgetCache();

        if(is_dir($cache_path)){
            if(@rename($cache_path, $this->getWpContentDir("/cache/tmpWpfc/").time())){
                delete_option("WpFastestCacheHTML");
                delete_option("WpFastestCacheHTMLSIZE");
                delete_option("WpFastestCacheMOBILE");
                delete_option("WpFastestCacheMOBILESIZE");

                $cache_deleted = true;
            }
        }else{
            $cache_deleted = true;
        }

        if($minified){
            if(is_dir($minified_cache_path)){
                if(@rename($minified_cache_path, $this->getWpContentDir("/cache/tmpWpfc/m").time())){
                    delete_option("WpFastestCacheCSS");
                    delete_option("WpFastestCacheCSSSIZE");
                    delete_option("WpFastestCacheJS");
                    delete_option("WpFastestCacheJSSIZE");

                    $minifed_deleted = true;
                }
            }else{
                $minifed_deleted = true;
            }
        }else{
            $minifed_deleted = true;
        }

        if($created_tmpWpfc && $cache_deleted && $minifed_deleted){
            do_action('wpfc_delete_cache');

            $this->notify(array("All cache files have been deleted", "updated"));
			/*创建all文件夹*/
            if(!is_dir($this->getWpContentDir("/cache/all"))){
                @mkdir($this->getWpContentDir("/cache/all"), 0755, true);
            }
            /*创建all文件夹*/
            if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
                include_once $this->get_premium_path("logs.php");

                $log = new WpFastestCacheLogs("delete");
                $log->action();
            }
        }else{
            $this->notify(array("Permissions Problem: <a href='http://www.wpfastestcache.com/warnings/delete-cache-problem-related-to-permission/' target='_blank'>Read More</a>", "error"));
        }

        // for ajax request
        if(isset($_GET["action"]) && in_array($_GET["action"], array("wpfc_delete_cache", "wpfc_delete_cache_and_minified"))){
            die(json_encode($this->systemMessage));
        }
    }

    public function checkCronTime(){
        $crons = _get_cron_array();

        foreach ((array)$crons as $cron_key => $cron_value) {
            foreach ( (array) $cron_value as $hook => $events ) {
                if(preg_match("/^wp\_fastest\_cache(.*)/", $hook, $id)){
                    if(!$id[1] || preg_match("/^\_(\d+)$/", $id[1])){
                        foreach ( (array) $events as $event_key => $event ) {
                            add_action("wp_fastest_cache".$id[1],  array($this, 'setSchedule'));
                        }
                    }
                }
            }
        }

        add_action($this->slug()."_Preload",  array($this, 'create_preload_cache'), 11);
    }

    public function set_preload(){
        include_once('inc/preload.php');
        PreloadWPFC::set_preload($this->slug());
    }

    public function create_preload_cache(){
        $this->options = $this->getOptions();

        include_once('inc/preload.php');
        PreloadWPFC::create_preload_cache($this->options);
    }

    public function wpfc_remote_get($url, $user_agent){
        //$response = wp_remote_get($url, array('timeout' => 10, 'sslverify' => false, 'headers' => array("cache-control" => array("no-store, no-cache, must-revalidate", "post-check=0, pre-check=0"),'user-agent' => $user_agent)));
        $response = wp_remote_get($url, array('user-agent' => $user_agent, 'timeout' => 10, 'sslverify' => false, 'headers' => array("cache-control" => "no-store, no-cache, must-revalidate, post-check=0, pre-check=0")));

        if (!$response || is_wp_error($response)){
            echo $response->get_error_message()." - ";

            return false;
        }else{
            if(wp_remote_retrieve_response_code($response) != 200){
                return false;
            }
        }

        return true;
    }

    public function setSchedule($args = ""){
        if($args){
            $rule = json_decode($args);

            if($rule->prefix == "all"){
                $this->deleteCache();
            }else if($rule->prefix == "homepage"){
                @unlink($this->getWpContentDir("/cache/all/index.html"));
                @unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/index.html"));

                if(isset($this->options->wpFastestCachePreload_homepage) && $this->options->wpFastestCachePreload_homepage){
                    $this->wpfc_remote_get(get_option("home"), "WP Fastest Cache Preload Bot - After Cache Timeout");
                    $this->wpfc_remote_get(get_option("home"), "WP Fastest Cache Preload iPhone Mobile Bot - After Cache Timeout");
                }
            }else if($rule->prefix == "startwith"){
                if(!is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
                    if(@mkdir($this->getWpContentDir("/cache/tmpWpfc"), 0755, true)){}
                }

                $rule->content = trim($rule->content, "/");

                $files = glob($this->getWpContentDir("/cache/all/").$rule->content."*");

                foreach ((array)$files as $file) {
                    $mobile_file = str_replace("/cache/all/", "/cache/wpfc-mobile-cache/", $file);

                    @rename($file, $this->getWpContentDir("/cache/tmpWpfc/").time());
                    @rename($mobile_file, $this->getWpContentDir("/cache/tmpWpfc/mobile_").time());
                }
            }else if($rule->prefix == "exact"){
                $rule->content = trim($rule->content, "/");

                @unlink($this->getWpContentDir("/cache/all/").$rule->content."/index.html");
                @unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/").$rule->content."/index.html");
            }

            if($rule->prefix != "all"){
                if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
                    include_once $this->get_premium_path("logs.php");
                    $log = new WpFastestCacheLogs("delete");
                    $log->action($rule);
                }
            }
        }else{
            //for old cron job
            $this->deleteCache();
        }
    }

    public function modify_htaccess_for_new_user($user_id){
        $path = ABSPATH;

        if($this->is_subdirectory_install()){
            $path = $this->getABSPATH();
        }

        $htaccess = @file_get_contents($path.".htaccess");

        if(preg_match("/\#\s?Start_WPFC_Exclude_Admin_Cookie/", $htaccess)){
            $rules = $this->excludeAdminCookie();

            $htaccess = preg_replace("/\#\s?Start_WPFC_Exclude_Admin_Cookie[^\#]*\#\s?End_WPFC_Exclude_Admin_Cookie\s+/", $rules, $htaccess);
        }

        @file_put_contents($path.".htaccess", $htaccess);
    }

    public function excludeAdminCookie(){
        $rules = "";
        $users_groups = array_chunk(get_users(array("role" => "administrator", "fields" => array("user_login"))), 5);

        foreach ($users_groups as $group_key => $group) {
            $tmp_users = "";
            $tmp_rule = "";

            foreach ($group as $key => $value) {
                if($tmp_users){
                    $tmp_users = $tmp_users."|".sanitize_user(wp_unslash($value->user_login), true);
                }else{
                    $tmp_users = sanitize_user(wp_unslash($value->user_login), true);
                }

                // to replace spaces with \s
                $tmp_users = preg_replace("/\s/", "\s", $tmp_users);

                if(!next($group)){
                    $tmp_rule = "RewriteCond %{HTTP:Cookie} !wordpress_logged_in_[^\=]+\=".$tmp_users;
                }
            }

            if($rules){
                $rules = $rules."\n".$tmp_rule;
            }else{
                $rules = $tmp_rule;
            }
        }

        return "# Start_WPFC_Exclude_Admin_Cookie\n".$rules."\n# End_WPFC_Exclude_Admin_Cookie\n";
    }

    public function excludeRules(){
        $htaccess_page_rules = "";
        $htaccess_page_useragent = "";
        $htaccess_page_cookie = "";

        if($rules_json = get_option("WpFastestCacheExclude")){
            if($rules_json != "null"){
                $rules_std = json_decode($rules_json);

                foreach ($rules_std as $key => $value) {
                    $value->type = isset($value->type) ? $value->type : "page";

                    // escape the chars
                    $value->content = str_replace("?", "\?", $value->content);

                    if($value->type == "page"){
                        if($value->prefix == "startwith"){
                            $htaccess_page_rules = $htaccess_page_rules."RewriteCond %{REQUEST_URI} !^/".$value->content." [NC]\n";
                        }

                        if($value->prefix == "contain"){
                            $htaccess_page_rules = $htaccess_page_rules."RewriteCond %{REQUEST_URI} !".$value->content." [NC]\n";
                        }

                        if($value->prefix == "exact"){
                            $htaccess_page_rules = $htaccess_page_rules."RewriteCond %{REQUEST_URI} !\/".$value->content." [NC]\n";
                        }
                    }else if($value->type == "useragent"){
                        $htaccess_page_useragent = $htaccess_page_useragent."RewriteCond %{HTTP_USER_AGENT} !".$value->content." [NC]\n";
                    }else if($value->type == "cookie"){
                        $htaccess_page_cookie = $htaccess_page_cookie."RewriteCond %{HTTP:Cookie} !".$value->content." [NC]\n";
                    }
                }
            }
        }

        return "# Start WPFC Exclude\n".$htaccess_page_rules.$htaccess_page_useragent.$htaccess_page_cookie."# End WPFC Exclude\n";
    }

    public function getABSPATH(){
        $path = ABSPATH;
        $siteUrl = site_url();
        $homeUrl = home_url();
        $diff = str_replace($homeUrl, "", $siteUrl);
        $diff = trim($diff,"/");

        $pos = strrpos($path, $diff);

        if($pos !== false){
            $path = substr_replace($path, "", $pos, strlen($diff));
            $path = trim($path,"/");
            $path = "/".$path."/";
        }
        return $path;
    }

    public function rm_folder_recursively($dir, $i = 1) {
        if(is_dir($dir)){
            $files = @scandir($dir);
            foreach((array)$files as $file) {
                if($i > 50 && !preg_match("/wp-fastest-cache-premium/i", $dir)){
                    return true;
                }else{
                    $i++;
                }
                if ('.' === $file || '..' === $file) continue;
                if (is_dir("$dir/$file")){
                    $this->rm_folder_recursively("$dir/$file", $i);
                }else{
                    if(file_exists("$dir/$file")){
                        @unlink("$dir/$file");
                    }
                }
            }
        }

        if(is_dir($dir)){
            $files_tmp = @scandir($dir);

            if(!isset($files_tmp[2])){
                @rmdir($dir);
            }
        }

        return true;
    }

    public function is_subdirectory_install(){
        if(strlen(site_url()) > strlen(home_url())){
            return true;
        }
        return false;
    }

    protected function getMobileUserAgents(){
        return implode("|", $this->get_mobile_browsers())."|".implode("|", $this->get_operating_systems());
    }

    public function get_premium_path($name){
        return WPFC_WP_PLUGIN_DIR."/wp-fastest-cache-premium/pro/library/".$name;
    }

    public function cron_add_minute( $schedules ) {
        $schedules['everyminute'] = array(
            'interval' => 60*1,
            'display' => __( 'Once Every 1 Minute' ),
            'wpfc' => true
        );

        $schedules['everyfiveminute'] = array(
            'interval' => 60*1,
            'display' => __( 'Once Every 5 Minutes' ),
            'wpfc' => true
        );

        $schedules['everyfifteenminute'] = array(
            'interval' => 60*15,
            'display' => __( 'Once Every 15 Minutes' ),
            'wpfc' => true
        );

        $schedules['twiceanhour'] = array(
            'interval' => 60*30,
            'display' => __( 'Twice an Hour' ),
            'wpfc' => true
        );

        $schedules['onceanhour'] = array(
            'interval' => 60*60,
            'display' => __( 'Once an Hour' ),
            'wpfc' => true
        );

        $schedules['everytwohours'] = array(
            'interval' => 60*60*2,
            'display' => __( 'Once Every 2 Hours' ),
            'wpfc' => true
        );

        $schedules['everythreehours'] = array(
            'interval' => 60*60*3,
            'display' => __( 'Once Every 3 Hours' ),
            'wpfc' => true
        );

        $schedules['everyfourhours'] = array(
            'interval' => 60*60*4,
            'display' => __( 'Once Every 4 Hours' ),
            'wpfc' => true
        );

        $schedules['everyfivehours'] = array(
            'interval' => 60*60*5,
            'display' => __( 'Once Every 5 Hours' ),
            'wpfc' => true
        );

        $schedules['everysixhours'] = array(
            'interval' => 60*60*6,
            'display' => __( 'Once Every 6 Hours' ),
            'wpfc' => true
        );

        $schedules['everysevenhours'] = array(
            'interval' => 60*60*7,
            'display' => __( 'Once Every 7 Hours' ),
            'wpfc' => true
        );

        $schedules['everyeighthours'] = array(
            'interval' => 60*60*8,
            'display' => __( 'Once Every 8 Hours' ),
            'wpfc' => true
        );

        $schedules['everyninehours'] = array(
            'interval' => 60*60*9,
            'display' => __( 'Once Every 9 Hours' ),
            'wpfc' => true
        );

        $schedules['everytenhours'] = array(
            'interval' => 60*60*10,
            'display' => __( 'Once Every 10 Hours' ),
            'wpfc' => true
        );

        $schedules['onceaday'] = array(
            'interval' => 60*60*24,
            'display' => __( 'Once a Day' ),
            'wpfc' => true
        );

        $schedules['everythreedays'] = array(
            'interval' => 60*60*24*3,
            'display' => __( 'Once Every 3 Days' ),
            'wpfc' => true
        );

        $schedules['everysevendays'] = array(
            'interval' => 60*60*24*7,
            'display' => __( 'Once Every 7 Days' ),
            'wpfc' => true
        );

        $schedules['everytendays'] = array(
            'interval' => 60*60*24*10,
            'display' => __( 'Once Every 10 Days' ),
            'wpfc' => true
        );

        $schedules['everyfifteendays'] = array(
            'interval' => 60*60*24*15,
            'display' => __( 'Once Every 15 Days' ),
            'wpfc' => true
        );

        $schedules['montly'] = array(
            'interval' => 60*60*24*30,
            'display' => __( 'Once a Month' ),
            'wpfc' => true
        );

        $schedules['yearly'] = array(
            'interval' => 60*60*24*30*12,
            'display' => __( 'Once a Year' ),
            'wpfc' => true
        );

        return $schedules;
    }

    public function setCustomInterval(){
        //add_filter( 'cron_schedules', array($this, 'cron_add_minute'));
    }

    public function isPluginActive( $plugin ) {
        return in_array( $plugin, (array) get_option( 'active_plugins', array() ) ) || $this->isPluginActiveForNetwork( $plugin );
    }

    public function isPluginActiveForNetwork( $plugin ) {
        if ( !is_multisite() )
            return false;

        $plugins = get_site_option( 'active_sitewide_plugins');
        if ( isset($plugins[$plugin]) )
            return true;

        return false;
    }

    public function current_url(){
        global $wp;
        $current_url = home_url($_SERVER['REQUEST_URI']);

        return $current_url;


        // if(defined('WP_CLI')){
        // 	$_SERVER["SERVER_NAME"] = isset($_SERVER["SERVER_NAME"]) ? $_SERVER["SERVER_NAME"] : "";
        // 	$_SERVER["SERVER_PORT"] = isset($_SERVER["SERVER_PORT"]) ? $_SERVER["SERVER_PORT"] : 80;
        // }

        //    $pageURL = 'http';

        //    if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'){
        //        $pageURL .= 's';
        //    }

        //    $pageURL .= '://';

        //    if($_SERVER['SERVER_PORT'] != '80'){
        //        $pageURL .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
        //    }else{
        //        $pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        //    }

        //    return $pageURL;
    }

    public function wpfc_load_plugin_textdomain(){
        load_plugin_textdomain('wp-fastest-cache', FALSE, basename( dirname( __FILE__ ) ) . '/languages/' );
    }

    public function cdn_replace_urls($matches){
        if(count($this->cdn) > 0){
            foreach ($this->cdn as $key => $cdn) {
                if($cdn->id == "cloudflare"){
                    continue;
                }

                if(preg_match("/manifest\.json\.php/i", $matches[0])){
                    return $matches[0];
                }

                //https://cdn.shortpixel.ai/client/q_glossy,ret_img,w_736/http://wpfc.com/stories.png
                if(preg_match("/cdn\.shortpixel\.ai\/client/i", $matches[0])){
                    return $matches[0];
                }

                //https://i0.wp.com/i0.wp.com/wpfc.com/stories.png
                if(preg_match("/i\d\.wp\.com/i", $matches[0])){
                    return $matches[0];
                }


                if(preg_match("/^\/\/random/", $cdn->cdnurl) || preg_match("/\/\/i\d\.wp\.com/", $cdn->cdnurl)){
                    if(preg_match("/^\/\/random/", $cdn->cdnurl)){
                        $cdnurl = "//i".rand(0,3).".wp.com/".str_replace("www.", "", $_SERVER["HTTP_HOST"]);
                        $cdnurl = preg_replace("/\/\/i\d\.wp\.com/", "//i".rand(0,3).".wp.com", $cdnurl);
                    }else{
                        $cdnurl = $cdn->cdnurl;
                    }

                    //to add www. if exists
                    if(preg_match("/\/\/www\./", $matches[0])){
                        $cdnurl = preg_replace("/(\/\/i\d\.wp\.com\/)(www\.)?/", "$1www.", $cdnurl);
                    }
                }else{
                    $cdnurl = $cdn->cdnurl;
                }

                $cdn->file_types = str_replace(",", "|", $cdn->file_types);

                if(preg_match("/\.(".$cdn->file_types.")[\"\'\?\)\s]/i", $matches[0])){
                    //nothing
                }else{
                    if(preg_match("/js/", $cdn->file_types)){
                        if(!preg_match("/\/revslider\/public\/assets\/js/", $matches[0])){
                            continue;
                        }
                    }else{
                        continue;
                    }
                }

                if($cdn->keywords){
                    $cdn->keywords = str_replace(",", "|", $cdn->keywords);

                    if(!preg_match("/".preg_quote($cdn->keywords, "/")."/i", $matches[0])){
                        continue;
                    }
                }

                if(preg_match("/data-product_variations\=[\"\'][^\"\']+[\"\']/i", $matches[0])){
                    $cdn->originurl = preg_quote($cdn->originurl, "/");
                    $cdn->originurl = str_replace("\/", "\\\\\/", $cdn->originurl);

                    if(preg_match("/".$cdn->originurl."/", $matches[0])){
                        $matches[0] = preg_replace("/(quot\;|\s)(http(s?)\:)?".preg_quote("\/\/", "/")."(www\.)?/i", "$1", $matches[0]);
                        $matches[0] = preg_replace("/".$cdn->originurl."/i", $cdnurl, $matches[0]);
                    }
                }else if(preg_match("/\{\"concatemoji\"\:\"[^\"]+\"\}/i", $matches[0])){
                    $matches[0] = preg_replace("/(http(s?)\:)?".preg_quote("\/\/", "/")."(www\.)?/i", "", $matches[0]);
                    $matches[0] = preg_replace("/".preg_quote($cdn->originurl, "/")."/i", $cdnurl, $matches[0]);
                }else if(isset($matches[2]) && preg_match("/".preg_quote($cdn->originurl, "/")."/", $matches[2])){
                    $matches[0] = preg_replace("/(http(s?)\:)?\/\/(www\.)?".preg_quote($cdn->originurl, "/")."/i", $cdnurl, $matches[0]);
                }else if(isset($matches[2]) && preg_match("/^(\/?)(wp-includes|wp-content)/", $matches[2])){
                    $matches[0] = preg_replace("/(\/?)(wp-includes|wp-content)/i", $cdnurl."/"."$2", $matches[0]);
                }else if(preg_match("/[\"\']https?\:\\\\\/\\\\\/[^\"\']+[\"\']/i", $matches[0])){
                    if(preg_match("/^(logo|url|image)$/i", $matches[1])){
                        //If the url is called with "//", it causes an error on https://search.google.com/structured-data/testing-tool/u/0/
                        //<script type="application/ld+json">"logo":{"@type":"ImageObject","url":"\/\/cdn.site.com\/image.png"}</script>
                        //<script type="application/ld+json">{"logo":"\/\/cdn.site.com\/image.png"}</script>
                        //<script type="application/ld+json">{"image":"\/\/cdn.site.com\/image.jpg"}</script>
                    }else{
                        //<script>var loaderRandomImages=["https:\/\/www.site.com\/wp-content\/uploads\/2016\/12\/image.jpg"];</script>
                        $matches[0] = preg_replace("/\\\\\//", "/", $matches[0]);

                        if(preg_match("/".preg_quote($cdn->originurl, "/")."/", $matches[0])){
                            $matches[0] = preg_replace("/(http(s?)\:)?\/\/(www\.)?".preg_quote($cdn->originurl, "/")."/i", $cdnurl, $matches[0]);
                            $matches[0] = preg_replace("/\//", "\/", $matches[0]);
                        }
                    }
                }
            }
        }

        return $matches[0];
    }

    public function read_file($url){
        if(!preg_match("/\.php/", $url)){
            $url = preg_replace("/\?.*/", "", $url);

            if(preg_match("/wp-content/", $url)){
                $path = preg_replace("/.+\/wp-content\/(.+)/", WPFC_WP_CONTENT_DIR."/"."$1", $url);
            }else if(preg_match("/wp-includes/", $url)){
                $path = preg_replace("/.+\/wp-includes\/(.+)/", ABSPATH."wp-includes/"."$1", $url);
            }

            if(@file_exists($path)){
                $filesize = filesize($path);

                if($filesize > 0){
                    $myfile = fopen($path, "r") or die("Unable to open file!");
                    $data = fread($myfile, $filesize);
                    fclose($myfile);

                    return $data;
                }else{
                    return false;
                }
            }
        }

        return false;
    }

    public function get_operating_systems(){
        $operating_systems  = array(
            'Android',
            'blackberry|\bBB10\b|rim\stablet\sos',
            'PalmOS|avantgo|blazer|elaine|hiptop|palm|plucker|xiino',
            'Symbian|SymbOS|Series60|Series40|SYB-[0-9]+|\bS60\b',
            'Windows\sCE.*(PPC|Smartphone|Mobile|[0-9]{3}x[0-9]{3})|Window\sMobile|Windows\sPhone\s[0-9.]+|WCE;',
            'Windows\sPhone\s10.0|Windows\sPhone\s8.1|Windows\sPhone\s8.0|Windows\sPhone\sOS|XBLWP7|ZuneWP7|Windows\sNT\s6\.[23]\;\sARM\;',
            '\biPhone.*Mobile|\biPod|\biPad',
            'Apple-iPhone7C2',
            'MeeGo',
            'Maemo',
            'J2ME\/|\bMIDP\b|\bCLDC\b', // '|Java/' produces bug #135
            'webOS|hpwOS',
            '\bBada\b',
            'BREW'
        );
        return $operating_systems;
    }

    public function get_mobile_browsers(){
        $mobile_browsers  = array(
            '\bCrMo\b|CriOS|Android.*Chrome\/[.0-9]*\s(Mobile)?',
            '\bDolfin\b',
            'Opera.*Mini|Opera.*Mobi|Android.*Opera|Mobile.*OPR\/[0-9.]+|Coast\/[0-9.]+',
            'Skyfire',
            'Mobile\sSafari\/[.0-9]*\sEdge',
            'IEMobile|MSIEMobile', // |Trident/[.0-9]+
            'fennec|firefox.*maemo|(Mobile|Tablet).*Firefox|Firefox.*Mobile|FxiOS',
            'bolt',
            'teashark',
            'Blazer',
            'Version.*Mobile.*Safari|Safari.*Mobile|MobileSafari',
            'Tizen',
            'UC.*Browser|UCWEB',
            'baiduboxapp',
            'baidubrowser',
            'DiigoBrowser',
            'Puffin',
            '\bMercury\b',
            'Obigo',
            'NF-Browser',
            'NokiaBrowser|OviBrowser|OneBrowser|TwonkyBeamBrowser|SEMC.*Browser|FlyFlow|Minimo|NetFront|Novarra-Vision|MQQBrowser|MicroMessenger',
            'Android.*PaleMoon|Mobile.*PaleMoon'
        );
        return $mobile_browsers;
    }


}
function curl_z($url){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246');
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSLVERSION, 'all');
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}
// Load WP CLI command(s) on demand.
if ( defined( 'WP_CLI' ) && WP_CLI ) {
    require_once "inc/cli.php";
}

function wpfc_clear_all_cache($minified = false){
    do_action("wpfc_clear_all_cache", $minified);
}

function wpfc_clear_post_cache_by_id($post_id = false){
    if($post_id){
        do_action("wpfc_clear_post_cache_by_id", false, $post_id);
    }
}

$GLOBALS["wp_fastest_cache"] = new WpFastestCache();
?>