Plugin Directory

source: wp-fastest-cache/trunk/wpFastestCache.php

Last change on this file was 3271457, checked in by emrevona, 8 days ago

v1.3.6 is live

File size: 86.7 KB
Line 
1<?php
2/*
3Plugin Name: WP Fastest Cache
4Plugin URI: http://wordpress.org/plugins/wp-fastest-cache/
5Description: The simplest and fastest WP Cache system
6Version: 1.3.6
7Author: Emre Vona
8Author URI: https://www.wpfastestcache.com/
9Text Domain: wp-fastest-cache
10Domain Path: /languages/
11
12Copyright (C)2013 Emre Vona
13
14This program is free software; you can redistribute it and/or
15modify it under the terms of the GNU General Public License
16as published by the Free Software Foundation; either version 2
17of the License, or (at your option) any later version.
18
19This program is distributed in the hope that it will be useful,
20but WITHOUT ANY WARRANTY; without even the implied warranty of
21MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22GNU General Public License for more details.
23*/
24
25        if (!defined('WPFC_WP_CONTENT_BASENAME')) {
26                if (!defined('WPFC_WP_PLUGIN_DIR')) {
27                        if(preg_match("/(\/trunk\/|\/wp-fastest-cache\/)$/", plugin_dir_path( __FILE__ ))){
28                                define("WPFC_WP_PLUGIN_DIR", preg_replace("/(\/trunk\/|\/wp-fastest-cache\/)$/", "", plugin_dir_path( __FILE__ )));
29                        }else if(preg_match("/\\\wp-fastest-cache\/$/", plugin_dir_path( __FILE__ ))){
30                                //D:\hosting\LINEapp\public_html\wp-content\plugins\wp-fastest-cache/
31                                define("WPFC_WP_PLUGIN_DIR", preg_replace("/\\\wp-fastest-cache\/$/", "", plugin_dir_path( __FILE__ )));
32                        }
33                }
34                define("WPFC_WP_CONTENT_DIR", dirname(WPFC_WP_PLUGIN_DIR));
35                define("WPFC_WP_CONTENT_BASENAME", basename(WPFC_WP_CONTENT_DIR));
36        }
37
38        if (!defined('WPFC_MAIN_PATH')) {
39                define("WPFC_MAIN_PATH", plugin_dir_path( __FILE__ ));
40        }
41
42        if(!isset($GLOBALS["wp_fastest_cache_options"])){
43                if($wp_fastest_cache_options = get_option("WpFastestCache")){
44                        $GLOBALS["wp_fastest_cache_options"] = json_decode($wp_fastest_cache_options);
45                }else{
46                        $GLOBALS["wp_fastest_cache_options"] = array();
47                }
48        }
49
50        function wpfastestcache_activate(){
51                if($options = get_option("WpFastestCache")){
52                        $post = json_decode($options, true);
53
54                        include_once('inc/admin.php');
55                        $wpfc = new WpFastestCacheAdmin();
56                        $wpfc->modifyHtaccess($post);
57                }
58        }
59
60        function wpfastestcache_deactivate(){
61                $wpfc = new WpFastestCache();
62
63                $path = ABSPATH;
64               
65                if($wpfc->is_subdirectory_install()){
66                        $path = $wpfc->getABSPATH();
67                }
68
69                if(is_file($path.".htaccess") && is_writable($path.".htaccess")){
70                        $htaccess = file_get_contents($path.".htaccess");
71                        $htaccess = preg_replace("/#\s?BEGIN\s?WpFastestCache.*?#\s?END\s?WpFastestCache/s", "", $htaccess);
72                        $htaccess = preg_replace("/#\s?BEGIN\s?GzipWpFastestCache.*?#\s?END\s?GzipWpFastestCache/s", "", $htaccess);
73                        $htaccess = preg_replace("/#\s?BEGIN\s?LBCWpFastestCache.*?#\s?END\s?LBCWpFastestCache/s", "", $htaccess);
74                        $htaccess = preg_replace("/#\s?BEGIN\s?WEBPWpFastestCache.*?#\s?END\s?WEBPWpFastestCache/s", "", $htaccess);
75                        @file_put_contents($path.".htaccess", $htaccess);
76                }
77
78                $wpfc->deleteCache();
79        }
80
81        register_activation_hook( __FILE__, "wpfastestcache_activate");
82        register_deactivation_hook( __FILE__, "wpfastestcache_deactivate");
83
84        class WpFastestCache{
85                private $systemMessage = "";
86                private $options = array();
87                public $noscript = "";
88                public $content_url = "";
89                public $deleted_before = false;
90
91                public function __construct(){
92                        $this->set_content_url();
93                       
94                        $optimize_image_ajax_requests = array("wpfc_revert_image_ajax_request", 
95                                                                                                  "wpfc_statics_ajax_request",
96                                                                                                  "wpfc_optimize_image_ajax_request",
97                                                                                                  "wpfc_update_image_list_ajax_request"
98                                                                                                  );
99
100                        add_action('wp_ajax_wpfc_delete_cache', array($this, "deleteCacheToolbar"));
101                        add_action('wp_ajax_wpfc_delete_cache_and_minified', array($this, "deleteCssAndJsCacheToolbar"));
102                        add_action('wp_ajax_wpfc_delete_current_page_cache', array($this, "delete_current_page_cache"));
103
104                        add_action('wp_ajax_wpfc_clear_cache_of_allsites', array($this, "wpfc_clear_cache_of_allsites_callback"));
105
106                        add_action('wp_ajax_wpfc_toolbar_save_settings', array($this, "wpfc_toolbar_save_settings_callback"));
107                        add_action('wp_ajax_wpfc_toolbar_get_settings', array($this, "wpfc_toolbar_get_settings_callback"));
108
109                        //add_action('wp_ajax_wpfc_cache_path_save_settings', array($this, "wpfc_cache_path_save_settings_callback"));
110
111                        add_action( 'wp_ajax_wpfc_save_timeout_pages', array($this, 'wpfc_save_timeout_pages_callback'));
112                        add_action( 'wp_ajax_wpfc_save_exclude_pages', array($this, 'wpfc_save_exclude_pages_callback'));
113                        add_action( 'wp_ajax_wpfc_cdn_options', array($this, 'wpfc_cdn_options_ajax_request_callback'));
114                        add_action( 'wp_ajax_wpfc_remove_cdn_integration', array($this, 'wpfc_remove_cdn_integration_ajax_request_callback'));
115                        add_action( 'wp_ajax_wpfc_pause_cdn_integration', array($this, 'wpfc_pause_cdn_integration_ajax_request_callback'));
116                        add_action( 'wp_ajax_wpfc_start_cdn_integration', array($this, 'wpfc_start_cdn_integration_ajax_request_callback'));
117                        add_action( 'wp_ajax_wpfc_save_cdn_integration', array($this, 'wpfc_save_cdn_integration_ajax_request_callback'));
118                        add_action( 'wp_ajax_wpfc_cdn_template', array($this, 'wpfc_cdn_template_ajax_request_callback'));
119                        add_action( 'wp_ajax_wpfc_check_url', array($this, 'wpfc_check_url_ajax_request_callback'));
120                        add_action( 'wp_ajax_wpfc_cache_statics_get', array($this, 'wpfc_cache_statics_get_callback'));
121                        add_action( 'wp_ajax_wpfc_db_statics', array($this, 'wpfc_db_statics_callback'));
122                        add_action( 'wp_ajax_wpfc_db_fix', array($this, 'wpfc_db_fix_callback'));
123                        add_action( 'rate_post', array($this, 'wp_postratings_clear_fastest_cache'), 10, 2);
124                        add_action( 'user_register', array($this, 'modify_htaccess_for_new_user'), 10, 1);
125                        add_action( 'profile_update', array($this, 'modify_htaccess_for_new_user'), 10, 1);
126                        add_action( 'edit_terms', array($this, 'delete_cache_of_term'), 10, 1);
127
128                        add_action( 'wp_ajax_wpfc_save_csp', array($this, 'wpfc_save_csp_callback'));
129                        add_action( 'wp_ajax_wpfc_remove_csp', array($this, 'wpfc_remove_csp_callback'));
130                        add_action( 'wp_ajax_wpfc_get_list_csp', array($this, 'wpfc_get_list_csp_callback'));
131
132
133                        add_action( 'wp_ajax_wpfc_save_varnish', array($this, 'wpfc_save_varnish_callback'));
134                        add_action( 'wp_ajax_wpfc_remove_varnish', array($this, 'wpfc_remove_varnish_callback'));
135                        add_action( 'wp_ajax_wpfc_pause_varnish', array($this, 'wpfc_pause_varnish_callback'));
136                        add_action( 'wp_ajax_wpfc_start_varnish', array($this, 'wpfc_start_varnish_callback'));
137                        add_action( 'wp_ajax_wpfc_purgecache_varnish', array($this, 'wpfc_purgecache_varnish_callback'));
138
139
140                        if(defined("WPFC_CLEAR_CACHE_AFTER_SWITCH_THEME") && WPFC_CLEAR_CACHE_AFTER_SWITCH_THEME){
141                                add_action('after_switch_theme', array($this, 'clear_cache_after_switch_theme'));
142                        }
143
144                        if(defined("WPFC_CLEAR_CACHE_AFTER_ACTIVATE_DEACTIVATE_PLUGIN") && WPFC_CLEAR_CACHE_AFTER_ACTIVATE_DEACTIVATE_PLUGIN){
145                                add_action('activate_plugin', array($this, 'clear_cache_after_activate_plugin'));
146                                add_action('deactivate_plugin', array($this, 'clear_cache_after_deactivate_plugin'));
147                        }
148
149
150                        add_action('upgrader_process_complete', array($this, 'clear_cache_after_update_plugin'), 10, 2);
151                        add_action('upgrader_process_complete', array($this, 'clear_cache_after_update_theme'), 10, 2);
152
153
154                        if(defined("WPFC_DISABLE_CLEARING_CACHE_AFTER_WOOCOMMERCE_CHECKOUT_ORDER_PROCESSED") && WPFC_DISABLE_CLEARING_CACHE_AFTER_WOOCOMMERCE_CHECKOUT_ORDER_PROCESSED){
155                        }else if(defined("WPFC_DISABLE_CLEARING_CACHE_AFTER_WOOCOMMERCE_ORDER_STATUS_CHANGED") && WPFC_DISABLE_CLEARING_CACHE_AFTER_WOOCOMMERCE_ORDER_STATUS_CHANGED){
156                        }else{
157                                // to clear cache after new Woocommerce orders
158                                add_action('woocommerce_order_status_changed', array($this, 'clear_cache_after_woocommerce_order_status_changed'), 1, 1);
159                        }
160
161
162                        // kk Star Ratings: to clear the cache of the post after voting
163                        add_action('kksr_rate', array($this, 'clear_cache_on_kksr_rate'));
164
165                        // Elementor: to clear cache after Maintenance Mode activation/deactivation
166                        add_action('elementor/maintenance_mode/mode_changed', array($this, 'deleteCache'));
167
168                        // clearing cache hooks
169                        add_action("wpfc_clear_all_cache", array($this, 'deleteCache'), 10, 1);
170                        add_action("wpfc_clear_all_site_cache", array($this, 'wpfc_clear_cache_of_allsites_callback'));
171                        add_action("wpfc_clear_post_cache_by_id", array($this, 'singleDeleteCache'), 10, 2);
172
173                        // create cache by id hook
174                        add_action("wpfc_create_post_cache_by_id", array($this, 'create_post_cache_by_id'), 10, 1);
175
176                        // to enable Auto Cache Panel for the classic editor
177                        add_action( 'admin_init', array($this, 'enable_auto_cache_settings_panel'));
178
179                        // to add settings link
180                        add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array($this, 'action_links'));
181
182                        // to clear cache after ajax request by other plugins
183                        if(isset($_POST["action"])){
184                                // All In One Schema.org Rich Snippets
185                                if(preg_match("/bsf_(update|submit)_rating/i", $_POST["action"])){
186                                        if(isset($_POST["post_id"])){
187                                                $this->singleDeleteCache(false, $_POST["post_id"]);
188                                        }
189                                }
190
191                                // Yet Another Stars Rating
192                                if($_POST["action"] == "yasr_send_visitor_rating"){
193                                        if(isset($_POST["post_id"])){
194                                                // to need call like that because get_permalink() does not work if we call singleDeleteCache() directly
195                                                add_action('init', array($this, "singleDeleteCache"));
196                                        }
197                                }
198                        }
199
200                        // to clear /tmpWpfc folder
201                        if(is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
202                                $this->rm_folder_recursively($this->getWpContentDir("/cache/tmpWpfc"));
203                        }
204
205
206                        if($this->isPluginActive('wp-polls/wp-polls.php')){
207                                        //for WP-Polls
208                                        require_once "inc/wp-polls.php";
209                                        $wp_polls = new WpPollsForWpFc();
210                                        $wp_polls->hook();
211                        }
212
213                        if(isset($_GET) && isset($_GET["action"]) && in_array($_GET["action"], $optimize_image_ajax_requests)){
214                                if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
215                                        include_once $this->get_premium_path("image.php");
216                                        $img = new WpFastestCacheImageOptimisation();
217                                        $img->hook();
218                                }
219                        }else if(isset($_GET) && isset($_GET["action"])  && $_GET["action"] == "wpfastestcache"){
220                                if(isset($_GET) && isset($_GET["type"])  && $_GET["type"] == "preload"){
221                                        // /?action=wpfastestcache&type=preload
222                                       
223                                        add_action('init', array($this, "create_preload_cache"), 11);
224                                }
225
226                                if(isset($_GET) && isset($_GET["type"]) && preg_match("/^clearcache(andminified|allsites)*$/i", $_GET["type"])){
227                                        // /?action=wpfastestcache&type=clearcache&token=123
228                                        // /?action=wpfastestcache&type=clearcacheandminified&token=123
229
230                                        add_action('wp_loaded', array($this, "handle_custom_delete_cache_request"));
231                                }
232                        }else{
233                                $this->setCustomInterval();
234
235                                $this->options = $this->getOptions();
236
237                                add_action('transition_post_status',  array($this, 'on_all_status_transitions'), 10, 3 );
238                               
239                                // when the regular price is updated, the "transition_post_status" action cannot catch it
240                                add_action('woocommerce_update_product',  array($this, 'clear_cache_after_woocommerce_update_product'), 10, 1);
241
242                                $this->commentHooks();
243
244                                $this->checkCronTime();
245
246                                if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
247                                        include_once $this->get_premium_path("mobile-cache.php");
248
249                                        if(file_exists(WPFC_WP_PLUGIN_DIR."/wp-fastest-cache-premium/pro/library/statics.php")){
250                                                include_once $this->get_premium_path("statics.php");
251                                        }
252
253                                        if(!defined('DOING_AJAX')){
254                                                include_once $this->get_premium_path("powerful-html.php");
255                                        }
256                                }
257
258                                if(is_admin()){
259                                        add_action('wp_loaded', array($this, "load_column"));
260                                       
261                                        if(defined('DOING_AJAX') && DOING_AJAX){
262                                                //do nothing
263                                        }else{
264                                                // to avoid loading menu and optionPage() twice
265                                                if(!class_exists("WpFastestCacheAdmin")){
266                                                        //for wp-panel
267                                                       
268                                                        if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
269                                                                include_once $this->get_premium_path("image.php");
270                                                        }
271
272                                                        if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
273                                                                include_once $this->get_premium_path("logs.php");
274                                                        }
275
276                                                        add_action('plugins_loaded', array($this, 'wpfc_load_plugin_textdomain'));
277                                                        add_action('wp_loaded', array($this, "load_admin_toolbar"));
278
279                                                        $this->admin();
280                                                }
281                                        }
282                                }else{
283                                        if(preg_match("/\/([^\/]+)\/([^\/]+(\.css|\.js))(\?.+)?$/", $this->current_url(), $path)){
284                                                // for security
285                                                if(preg_match("/\.{2,}/", $this->current_url())){
286                                                        die("May be Directory Traversal Attack");
287                                                }
288
289                                                if(is_dir($this->getWpContentDir("/cache/wpfc-minified/").$path[1])){
290                                                        if($sources = @scandir($this->getWpContentDir("/cache/wpfc-minified/").$path[1], 1)){
291                                                                if(isset($sources[0])){
292                                                                        // $exist_url = str_replace($path[2], $sources[0], $this->current_url());
293                                                                        // header('Location: ' . $exist_url, true, 301);
294                                                                        // exit;
295
296                                                                        if(preg_match("/\.css/", $this->current_url())){
297                                                                                header('Content-type: text/css');
298                                                                        }else if(preg_match("/\.js/", $this->current_url())){
299                                                                                header('Content-type: text/js');
300                                                                        }
301
302                                                                        echo file_get_contents($this->getWpContentDir("/cache/wpfc-minified/").$path[1]."/".$sources[0]);
303                                                                        exit;
304                                                                }
305                                                        }
306                                                }
307
308
309                                                if(preg_match("/".basename($this->getWpContentDir("/cache/wpfc-minified/"))."/i", $this->current_url())){
310                                                        //for non-exists minified files
311                                                        if(preg_match("/\.css/", $this->current_url())){
312                                                                header('Content-type: text/css');
313                                                                die("/* File not found */");
314                                                        }else if(preg_match("/\.js/", $this->current_url())){
315                                                                header('Content-type: text/js');
316                                                                die("//File not found");
317                                                        }
318                                                }
319
320                                        }else{
321                                                // to show if the user is logged-in
322                                                add_action('wp_loaded', array($this, "load_admin_toolbar"));
323
324                                                //for cache
325                                                $this->cache();
326                                        }
327                                }
328                        }
329                }
330
331                public function handle_custom_delete_cache_request(){
332                        $action = false;
333                        $wpfc_token = false;
334                       
335                        if(defined("WPFC_CLEAR_CACHE_URL_TOKEN") && WPFC_CLEAR_CACHE_URL_TOKEN){
336                                $wpfc_token = WPFC_CLEAR_CACHE_URL_TOKEN;
337                        }else{
338                                $wpfc_token = apply_filters( 'wpfc_clear_cache_url_token', false );
339                        }
340
341                        if(isset($_GET["token"]) && $_GET["token"]){
342                                if($wpfc_token){
343                                        if($wpfc_token == $_GET["token"]){
344                                                $action = true;
345                                        }else{
346                                                die("Wrong token");
347                                        }
348                                }else{
349                                        die("WPFC_CLEAR_CACHE_URL_TOKEN must be defined");
350                                }
351                        }else{
352                                die("Security token must be set.");
353                        }
354
355                        if($action){
356                                if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
357                                        include_once $this->get_premium_path("mobile-cache.php");
358                                }
359
360                                if($_GET["type"] == "clearcache"){
361
362                                        if(isset($_GET["post_id"])){
363                                                $this->singleDeleteCache(false, $_GET["post_id"]);
364                                        }else{
365                                                $this->deleteCache();
366                                        }
367                                       
368                                }
369
370                                if($_GET["type"] == "clearcacheandminified"){
371                                        $this->deleteCache(true);
372                                }
373
374                                if($_GET["type"] == "clearcacheallsites"){
375                                        $this->wpfc_clear_cache_of_allsites_callback();
376                                }
377
378                                die("Done");
379                        }
380                       
381                        exit;
382                }
383
384                public function enable_auto_cache_settings_panel(){
385                        if($this->isPluginActive('classic-editor/classic-editor.php') || $this->isPluginActive('disable-gutenberg/disable-gutenberg.php') || has_filter("use_block_editor_for_post", "__return_false")){
386                                add_action("add_meta_boxes", array($this, "add_meta_box"), 10, 2);
387                                add_action('admin_notices', array($this, 'single_preload_inline_js'));
388                                add_action('wp_ajax_wpfc_preload_single_save_settings', array($this, "wpfc_preload_single_save_settings_callback"));
389                                add_action('wp_ajax_wpfc_preload_single', array($this, "wpfc_preload_single_callback"));
390                        }
391                }
392
393                public function clear_cache_after_activate_plugin(){
394                        $this->deleteCache(true);
395                }
396
397                public function clear_cache_after_deactivate_plugin(){
398                        $this->deleteCache(true);
399                }
400
401                public function clear_cache_after_switch_theme(){
402                        $this->deleteCache(true);
403                }
404
405                public function clear_cache_after_update_plugin($upgrader_object, $options){
406                        if(isset($options['action']) && isset($options['type'])){
407                                if($options['action'] == 'update'){
408                                        if($options['type'] == 'plugin' && (isset($options['plugins']) || isset($options['plugin']))){
409
410                                                $options_json = json_encode($options);
411
412                                                if(preg_match("/elementor\\\\\/elementor\.php/i", $options_json)){
413                                                        $this->deleteCache(true);
414                                                }
415
416                                                if(defined("WPFC_CLEAR_CACHE_AFTER_PLUGIN_UPDATE") && WPFC_CLEAR_CACHE_AFTER_PLUGIN_UPDATE){
417                                                        $this->deleteCache(true);
418                                                }
419                                        }
420                                }
421                        }
422                }
423
424                public function clear_cache_after_update_theme($upgrader_object, $options){
425                        if(isset($options['action']) && isset($options['type'])){
426                                if($options['action'] == 'update'){
427                                        if($options['type'] == 'theme' && isset($options['themes'])){
428
429                                                if(defined("WPFC_CLEAR_CACHE_AFTER_THEME_UPDATE") && WPFC_CLEAR_CACHE_AFTER_THEME_UPDATE){
430                                                        $this->deleteCache(true);
431                                                }
432
433                                        }
434                                }
435                        }
436                }
437
438                public function action_links($actions){
439                        $actions['powered_settings'] = sprintf(__( '<a href="%s">Settings</a>', 'wp-fastest-cache'), esc_url( admin_url( 'admin.php?page=wpfastestcacheoptions')));
440                        return array_reverse($actions);
441                }
442
443                public function wpfc_preload_single_callback(){
444                        if(!wp_verify_nonce($_REQUEST["nonce"], 'wpfc')){
445                                die( 'Security check' );
446                        }
447
448                        include_once('inc/single-preload.php');
449                        SinglePreloadWPFC::create_cache();
450                }
451
452                public function create_post_cache_by_id($id){
453                        include_once('inc/single-preload.php');
454                        SinglePreloadWPFC::init($id);
455                        $res = SinglePreloadWPFC::create_cache_for_all_urls();
456
457                        return $res;
458                }
459
460                public function single_preload_inline_js(){
461                        include_once('inc/single-preload.php');
462                        SinglePreloadWPFC::init();
463                        SinglePreloadWPFC::put_inline_js();
464                }
465                public function add_meta_box(){
466                        include_once('inc/single-preload.php');
467                        SinglePreloadWPFC::add_meta_box();
468                }
469
470                public function wpfc_preload_single_save_settings_callback(){
471                        if(!wp_verify_nonce($_REQUEST["nonce"], 'wpfc')){
472                                die( 'Security check' );
473                        }
474
475                        include_once('inc/single-preload.php');
476                        SinglePreloadWPFC::save_settings();
477                }
478
479                public function notify($message = array()){
480                        if(isset($message[0]) && $message[0]){
481                                if(function_exists("add_settings_error")){
482                                        add_settings_error('wpfc-notice', esc_attr( 'settings_updated' ), $message[0], $message[1]);
483                                }
484                        }
485                }
486
487                public function set_content_url(){
488                        $content_url = content_url();
489
490                        // Hide My WP
491                        if($this->isPluginActive('hide_my_wp/hide-my-wp.php')){
492                                $hide_my_wp = get_option("hide_my_wp");
493
494                                if(isset($hide_my_wp["new_content_path"]) && $hide_my_wp["new_content_path"]){
495                                        $hide_my_wp["new_content_path"] = trim($hide_my_wp["new_content_path"], "/");
496                                        $content_url = str_replace(basename(WPFC_WP_CONTENT_DIR), $hide_my_wp["new_content_path"], $content_url);
497                                }
498                        }
499
500                        // to change content url if a different url is used for other langs
501                        if($this->isPluginActive('polylang/polylang.php') || $this->isPluginActive('polylang-pro/polylang.php')){
502                                $url =  parse_url($content_url);
503
504                                if(isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST']){
505                                        if($url["host"] != $_SERVER['HTTP_HOST']){
506                                                $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
507                                                $content_url = $protocol.$_SERVER['HTTP_HOST'].$url['path'];
508                                        }
509                                }
510                        }
511
512                        if (!defined('WPFC_WP_CONTENT_URL')) {
513                                define("WPFC_WP_CONTENT_URL", $content_url);
514                        }
515
516                        $this->content_url = $content_url;
517                }
518
519                public function clear_cache_on_kksr_rate($id){
520                        $this->singleDeleteCache(false, $id);
521                }
522
523                public function clear_cache_after_woocommerce_order_status_changed($order_id = false){
524                        if(function_exists("wc_get_order")){
525                                if($order_id){
526                                        $order = wc_get_order($order_id);
527
528                                        if($order){
529                                                foreach($order->get_items() as $item_key => $item_values ){
530                                                        if(method_exists($item_values, 'get_product_id')){
531                                                                $this->singleDeleteCache(false, $item_values->get_product_id());
532                                                        }
533                                                }
534                                        }
535                                }
536                        }
537                }
538
539                public function wpfc_db_fix_callback(){
540                        if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
541                                include_once $this->get_premium_path("db.php");
542
543                                if(class_exists("WpFastestCacheDatabaseCleanup")){
544                                        WpFastestCacheDatabaseCleanup::clean($_GET["type"]);
545                                }else{
546                                        die(json_encode(array("success" => false, "showupdatewarning" => true, "message" => "Only available in Premium version")));
547                                }
548
549                        }else{
550                                die(json_encode(array("success" => false, "message" => "Only available in Premium version")));
551                        }
552                }
553
554                public function wpfc_db_statics_callback(){
555                        if(!wp_verify_nonce($_REQUEST["nonce"], 'wpfc')){
556                                die( 'Security check' );
557                        }
558                       
559                        global $wpdb;
560
561            $statics = array("all_warnings" => 0,
562                             "post_revisions" => 0,
563                             "trashed_contents" => 0,
564                             "trashed_spam_comments" => 0,
565                             "trackback_pingback" => 0,
566                             "transient_options" => 0
567                            );
568
569
570            $statics["post_revisions"] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->posts` WHERE post_type = 'revision';");
571            $statics["all_warnings"] = $statics["all_warnings"] + $statics["post_revisions"];
572
573            $statics["trashed_contents"] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->posts` WHERE post_status = 'trash';");
574            $statics["all_warnings"] = $statics["all_warnings"] + $statics["trashed_contents"];
575
576            $statics["trashed_spam_comments"] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_approved = 'spam' OR comment_approved = 'trash' ;");
577            $statics["all_warnings"] = $statics["all_warnings"] + $statics["trashed_spam_comments"];
578
579            $statics["trackback_pingback"] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_type = 'trackback' OR comment_type = 'pingback' ;");
580            $statics["all_warnings"] = $statics["all_warnings"] + $statics["trackback_pingback"];
581
582            $element = "SELECT COUNT(*) FROM `$wpdb->options` WHERE option_name LIKE '%\_transient\_%' ;";
583            $statics["transient_options"] = $wpdb->get_var( $element ) > 100 ? $wpdb->get_var( $element ) : 0;
584            $statics["all_warnings"] = $statics["all_warnings"] + $statics["transient_options"];
585
586            die(json_encode($statics));
587                }
588
589                public function is_trailing_slash(){
590                        // no need to check if Custom Permalinks plugin is active (https://tr.wordpress.org/plugins/custom-permalinks/)
591                        if($this->isPluginActive("custom-permalinks/custom-permalinks.php")){
592                                return false;
593                        }
594
595                        if($permalink_structure = get_option('permalink_structure')){
596                                if(preg_match("/\/$/", $permalink_structure)){
597                                        return true;
598                                }
599                        }
600
601                        return false;
602                }
603
604                public function wpfc_cache_statics_get_callback(){
605                        if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
606                                if(file_exists(WPFC_WP_PLUGIN_DIR."/wp-fastest-cache-premium/pro/library/statics.php")){
607                                        include_once $this->get_premium_path("statics.php");
608                                       
609                                        $cache_statics = new WpFastestCacheStatics();
610                                        $res = $cache_statics->get();
611                                        echo json_encode($res);
612                                        exit;
613                                }
614                        }
615                }
616
617                public function wpfc_check_url_ajax_request_callback(){
618                        if(!wp_verify_nonce($_REQUEST["nonce"], 'cdn-nonce')){
619                                die( 'Security check' );
620                        }
621                       
622                        include_once('inc/cdn.php');
623                        CdnWPFC::check_url();
624                }
625
626                public function wpfc_cdn_template_ajax_request_callback(){
627                        include_once('inc/cdn.php');
628                        CdnWPFC::cdn_template();
629                }
630
631                public function wpfc_save_cdn_integration_ajax_request_callback(){
632                        if(!wp_verify_nonce($_REQUEST["nonce"], 'cdn-nonce')){
633                                die( 'Security check' );
634                        }
635
636                        include_once('inc/cdn.php');
637                        CdnWPFC::save_cdn_integration();
638                }
639
640                public function wpfc_start_cdn_integration_ajax_request_callback(){
641                        if(!wp_verify_nonce($_REQUEST["nonce"], 'cdn-nonce')){
642                                die( 'Security check' );
643                        }
644
645                        include_once('inc/cdn.php');
646                        CdnWPFC::start_cdn_integration();
647                }
648
649                public function wpfc_pause_cdn_integration_ajax_request_callback(){
650                        if(!wp_verify_nonce($_REQUEST["nonce"], 'cdn-nonce')){
651                                die( 'Security check' );
652                        }
653
654                        include_once('inc/cdn.php');
655                        CdnWPFC::pause_cdn_integration();
656                }
657
658                public function wpfc_remove_cdn_integration_ajax_request_callback(){
659                        if(!wp_verify_nonce($_REQUEST["nonce"], 'cdn-nonce')){
660                                die( 'Security check' );
661                        }
662                       
663                        include_once('inc/cdn.php');
664                        CdnWPFC::remove_cdn_integration();
665                }
666
667                public function wpfc_cdn_options_ajax_request_callback(){
668                        include_once('inc/cdn.php');
669                        CdnWPFC::cdn_options();
670                }
671
672                public function wpfc_save_exclude_pages_callback(){
673                        if(!wp_verify_nonce($_POST["security"], 'wpfc-save-exclude-ajax-nonce')){
674                                die( 'Security check' );
675                        }
676                       
677                        if(current_user_can('manage_options')){
678                                if(isset($_POST["rules"])){
679                                        foreach ($_POST["rules"] as $key => &$value) {
680                                                $value["prefix"] = strip_tags($value["prefix"]);
681                                                $value["content"] = strip_tags($value["content"]);
682
683                                                $value["prefix"] = preg_replace("/\'|\"/", "", $value["prefix"]);
684
685                                                if($value["prefix"] == "regex"){
686                                                        $value["content"] = stripslashes($value["content"]);
687
688                                                        $value["content"] = esc_attr($value["content"]);
689                                                }else{
690                                                        $value["content"] = preg_replace("/\'|\"/", "", $value["content"]);
691                                                        $value["content"] = preg_replace("/(\#|\s|\(|\)|\*)/", "", $value["content"]);
692                                                }
693
694                                                if($value["prefix"] == "homepage"){
695                                                        $this->deleteHomePageCache(false);
696                                                }
697                                        }
698
699                                        $data = json_encode($_POST["rules"]);
700
701                                        if(get_option("WpFastestCacheExclude")){
702                                                update_option("WpFastestCacheExclude", $data);
703                                        }else{
704                                                add_option("WpFastestCacheExclude", $data, null, "yes");
705                                        }
706                                }else{
707                                        delete_option("WpFastestCacheExclude");
708                                }
709
710                                $this->modify_htaccess_for_exclude();
711
712                                echo json_encode(array("success" => true));
713                                exit;
714                        }else{
715                                wp_die("Must be admin");
716                        }
717                }
718
719                public function modify_htaccess_for_exclude(){
720                        $path = ABSPATH;
721
722                        if($this->is_subdirectory_install()){
723                                $path = $this->getABSPATH();
724                        }
725
726                        $htaccess = @file_get_contents($path.".htaccess");
727
728                        if(preg_match("/\#\s?Start\sWPFC\sExclude/", $htaccess)){
729                                $exclude_rules = $this->excludeRules();
730
731                                $htaccess = preg_replace("/\#\s?Start\sWPFC\sExclude[^\#]*\#\s?End\sWPFC\sExclude\s+/", $exclude_rules, $htaccess);
732                        }
733
734                        @file_put_contents($path.".htaccess", $htaccess);
735                }
736
737                public function wpfc_purgecache_varnish_callback(){
738                        if(!wp_verify_nonce($_REQUEST["security"], 'wpfc-varnish-ajax-nonce')){
739                                die( 'Security check' );
740                        }
741
742                        if($varnish_datas = get_option("WpFastestCacheVarnish")){
743                                include_once('inc/varnish.php');
744                                $res_arr = VarnishWPFC::purge_cache($varnish_datas["server"]);
745                               
746                                wp_send_json($res_arr);
747                        }
748                }
749
750                public function wpfc_save_varnish_callback(){
751                        include_once('inc/varnish.php');
752                        VarnishWPFC::save();
753                }
754
755                public function wpfc_remove_varnish_callback(){
756                        include_once('inc/varnish.php');
757                        VarnishWPFC::remove();
758                }
759
760                public function wpfc_start_varnish_callback(){
761                        include_once('inc/varnish.php');
762                        VarnishWPFC::start();
763                }
764
765                public function wpfc_pause_varnish_callback(){
766                        include_once('inc/varnish.php');
767                        VarnishWPFC::pause();
768                }
769
770                public function wpfc_status_varnish(){
771                        include_once('inc/varnish.php');
772                        VarnishWPFC::status();
773                }
774
775                public function wpfc_get_list_csp_callback(){
776                        include_once('inc/clearing-specific-pages.php');
777                        ClearingSpecificPagesWPFC::get_list();
778                }
779
780                public function wpfc_save_csp_callback(){
781                        include_once('inc/clearing-specific-pages.php');
782                        ClearingSpecificPagesWPFC::save();
783                }
784
785                public function wpfc_remove_csp_callback(){
786                        include_once('inc/clearing-specific-pages.php');
787                        ClearingSpecificPagesWPFC::remove();
788                }
789
790                public function wpfc_save_timeout_pages_callback(){
791                        if(!wp_verify_nonce($_POST["security"], 'wpfc-save-timeout-ajax-nonce')){
792                                die( 'Security check' );
793                        }
794
795                        if(current_user_can('manage_options')){
796                                $this->setCustomInterval();
797                       
798                        $crons = _get_cron_array();
799
800                        foreach ($crons as $cron_key => $cron_value) {
801                                foreach ( (array) $cron_value as $hook => $events ) {
802                                        if(preg_match("/^wp\_fastest\_cache(.*)/", $hook, $id)){
803                                                if(!$id[1] || preg_match("/^\_(\d+)$/", $id[1])){
804                                                        foreach ( (array) $events as $event_key => $event ) {
805                                                                if($id[1]){
806                                                                        wp_clear_scheduled_hook("wp_fastest_cache".$id[1], $event["args"]);
807                                                                }else{
808                                                                        wp_clear_scheduled_hook("wp_fastest_cache", $event["args"]);
809                                                                }
810                                                        }
811                                                }
812                                        }
813                                }
814                        }
815
816                                if(isset($_POST["rules"]) && count($_POST["rules"]) > 0){
817                                        $i = 0;
818
819                                        foreach ($_POST["rules"] as $key => $value) {
820                                                if(preg_match("/^(daily|onceaday)$/i", $value["schedule"]) && isset($value["hour"]) && isset($value["minute"]) && strlen($value["hour"]) > 0 && strlen($value["minute"]) > 0){
821                                                        $args = array("prefix" => $value["prefix"], "content" => $value["content"], "hour" => $value["hour"], "minute" => $value["minute"]);
822
823                                                        $timestamp = mktime($value["hour"],$value["minute"],0,date("m"),date("d"),date("Y"));
824
825                                                        $timestamp = $timestamp > time() ? $timestamp : $timestamp + 60*60*24;
826                                                }else{
827                                                        $args = array("prefix" => $value["prefix"], "content" => $value["content"]);
828                                                        $timestamp = time();
829                                                }
830
831                                                wp_schedule_event($timestamp, $value["schedule"], "wp_fastest_cache_".$i, array(json_encode($args)));
832                                                $i = $i + 1;
833                                        }
834                                }
835
836                                echo json_encode(array("success" => true));
837                                exit;
838                        }else{
839                                wp_die("Must be admin");
840                        }
841                }
842
843                public function wp_postratings_clear_fastest_cache($rate_userid, $post_id){
844                        // to remove cache if vote is from homepage or category page or tag
845                        if(isset($_SERVER["HTTP_REFERER"]) && $_SERVER["HTTP_REFERER"]){
846                                $url =  parse_url($_SERVER["HTTP_REFERER"]);
847
848                                $url["path"] = isset($url["path"]) ? $url["path"] : "/index.html";
849
850                                if(isset($url["path"])){
851                                        if($url["path"] == "/"){
852                                                $this->rm_folder_recursively($this->getWpContentDir("/cache/all/index.html"));
853                                        }else{
854                                                // to prevent changing path with ../ or with another method
855                                                if($url["path"] == realpath(".".$url["path"])){
856                                                        $this->rm_folder_recursively($this->getWpContentDir("/cache/all").$url["path"]);
857                                                }
858                                        }
859                                }
860                        }
861
862                        if($post_id){
863                                $this->singleDeleteCache(false, $post_id);
864                        }
865                }
866
867                private function admin(){                       
868                        if(isset($_GET["page"]) && $_GET["page"] == "wpfastestcacheoptions"){
869                                include_once('inc/admin.php');
870                                $wpfc = new WpFastestCacheAdmin();
871                                $wpfc->addMenuPage();
872                        }else{
873                                add_action('admin_menu', array($this, 'register_my_custom_menu_page'));
874                        }
875                }
876
877                public function load_column(){
878                        if(!defined('WPFC_HIDE_CLEAR_CACHE_BUTTON') || (defined('WPFC_HIDE_CLEAR_CACHE_BUTTON') && !WPFC_HIDE_CLEAR_CACHE_BUTTON)){
879                                include_once plugin_dir_path(__FILE__)."inc/column.php";
880
881                                $column = new WpFastestCacheColumn();
882                                $column->add();
883                        }
884                }
885
886                public function load_admin_toolbar(){
887                        $display = true;
888                       
889                        if(apply_filters('wpfc_hide_toolbar', false )){
890                                $display = "";
891                        }
892
893                        if(defined('WPFC_HIDE_TOOLBAR') && WPFC_HIDE_TOOLBAR){
894                                $display = "";
895                        }
896
897
898                        if($display){
899                                $user = wp_get_current_user();
900                                $allowed_roles = array('administrator');
901
902                                $wpfc_role_status = get_option("WpFastestCacheToolbarSettings");
903                                if(is_array($wpfc_role_status) && !empty($wpfc_role_status)){
904                                        foreach ($wpfc_role_status as $key => $value){
905                                                $key = str_replace("wpfc_toolbar_", "", $key);
906                                                array_push($allowed_roles, strtolower($key));
907                                        }
908                                }
909
910                               
911                                if(array_intersect($allowed_roles, $user->roles)){
912                                        include_once plugin_dir_path(__FILE__)."inc/admin-toolbar.php";
913
914                                        if(preg_match("/\/cache\/all/", $this->getWpContentDir("/cache/all"))){
915                                                $is_multi = false;
916                                        }else{
917                                                $is_multi = true;
918                                        }
919
920                                        $toolbar = new WpFastestCacheAdminToolbar($is_multi);
921                                        $toolbar->add();
922                                }
923                        }
924                }
925
926                public function tmp_saveOption(){
927                        if(!empty($_POST)){
928                                if(isset($_POST["wpFastestCachePage"])){
929                                        include_once('inc/admin.php');
930                                        $wpfc = new WpFastestCacheAdmin();
931                                        $wpfc->optionsPageRequest();
932                                }
933                        }
934                }
935
936                public function register_mysettings(){
937                        register_setting('wpfc-group', 'wpfc-group', array($this, 'tmp_saveOption'));
938                }
939
940                public function register_my_custom_menu_page(){
941                        if(function_exists('add_menu_page')){
942
943                                if(defined("WPFC_MOVE_MENU_ITEM_UNDER_SETTINGS") && WPFC_MOVE_MENU_ITEM_UNDER_SETTINGS){
944                                        add_options_page("WP Fastest Cache Settings", "WP Fastest Cache", 'manage_options', 'wpfastestcacheoptions', array($this, 'optionsPage'));
945                                }else{
946                                        add_menu_page("WP Fastest Cache Settings", "WP Fastest Cache", 'manage_options', "wpfastestcacheoptions", array($this, 'optionsPage'), plugins_url("wp-fastest-cache/images/icon.svg"));
947                                }
948
949                                add_action('admin_init', array($this, 'register_mysettings'));
950
951                                wp_enqueue_style("wp-fastest-cache", plugins_url("wp-fastest-cache/css/style.css"), array(), time(), "all");
952                        }
953                                               
954                        if(isset($_GET["page"]) && $_GET["page"] == "wpfastestcacheoptions"){
955                                wp_enqueue_style("wp-fastest-cache-buycredit", plugins_url("wp-fastest-cache/css/buycredit.css"), array(), time(), "all");
956                                wp_enqueue_style("wp-fastest-cache-flaticon", plugins_url("wp-fastest-cache/css/flaticon.css"), array(), time(), "all");
957                                wp_enqueue_style("wp-fastest-cache-dialog", plugins_url("wp-fastest-cache/css/dialog.css"), array(), time(), "all");
958                        }
959                }
960
961                public function deleteCacheToolbar(){
962                        if(!wp_verify_nonce($_REQUEST["nonce"], 'wpfc')){
963                                die( 'Security check' );
964                        }
965
966                        $this->deleteCache();
967                }
968
969                public function deleteCssAndJsCacheToolbar(){
970                        if(!wp_verify_nonce($_REQUEST["nonce"], 'wpfc')){
971                                die( 'Security check' );
972                        }
973                       
974                        $this->deleteCache(true);
975                }
976
977                public function wpfc_toolbar_get_settings_callback(){
978                        if(current_user_can('manage_options')){
979                                $result = array("success" => true, "roles" => false);
980
981                                $wpfc_role_status = get_option("WpFastestCacheToolbarSettings");
982                                if(is_array($wpfc_role_status) && !empty($wpfc_role_status)){
983                                        $result["roles"] = $wpfc_role_status;
984                                }
985
986                                die(json_encode($result));
987                        }else{
988                                wp_die("Must be admin");
989                        }
990                }
991
992                public function wpfc_cache_path_save_settings_callback(){
993                        if(current_user_can('manage_options')){
994                                foreach($_POST as $key => &$value){
995                                        $value = esc_html(esc_sql($value));
996                                }
997
998                                $path_arr = array(
999                                                                  "cachepath" => sanitize_text_field($_POST["cachepath"]),
1000                                                                  "optimizedpath" => sanitize_text_field($_POST["optimizedpath"])
1001                                                        );
1002
1003                                if(get_option("WpFastestCachePathSettings") === false){
1004                                        add_option("WpFastestCachePathSettings", $path_arr, 1, "no");
1005                                }else{
1006                                        update_option("WpFastestCachePathSettings", $path_arr);
1007                                }
1008
1009                                die(json_encode(array("success" => true)));
1010                        }else{
1011                                wp_die("Must be admin");
1012                        }
1013                }
1014
1015                public function wpfc_toolbar_save_settings_callback(){
1016                        if(!wp_verify_nonce($_REQUEST["nonce"], 'wpfc')){
1017                                die( 'Security check' );
1018                        }
1019
1020                        if(current_user_can('manage_options')){
1021                                if(isset($_GET["roles"]) && is_array($_GET["roles"]) && !empty($_GET["roles"])){
1022                                        $roles_arr = array();
1023
1024                                        foreach($_GET["roles"] as $key => $value){
1025                                                $value = esc_html(esc_sql($value));
1026                                                $key = esc_html(esc_sql($key));
1027
1028                                                $roles_arr[$key] = $value;
1029                                        }
1030
1031                                        if(get_option("WpFastestCacheToolbarSettings") === false){
1032                                                add_option("WpFastestCacheToolbarSettings", $roles_arr, 1, "no");
1033                                        }else{
1034                                                update_option("WpFastestCacheToolbarSettings", $roles_arr);
1035                                        }
1036                                }else{
1037                                        delete_option("WpFastestCacheToolbarSettings");
1038                                }
1039
1040
1041                                die(json_encode(array("Saved","success")));
1042                        }else{
1043                                wp_die("Must be admin");
1044                        }
1045                }
1046
1047                public function wpfc_clear_cache_of_allsites_callback(){
1048
1049                        if(defined('DOING_AJAX') && DOING_AJAX){
1050                                if(!wp_verify_nonce($_REQUEST["nonce"], 'wpfc')){
1051                                        die( 'Security check' );
1052                                }
1053                        }
1054
1055                        include_once('inc/cdn.php');
1056                        CdnWPFC::cloudflare_clear_cache();
1057
1058                        $path = $this->getWpContentDir("/cache/*");
1059
1060                        $files = glob($this->getWpContentDir("/cache/*"));
1061
1062                        if(!is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
1063                                if(@mkdir($this->getWpContentDir("/cache/tmpWpfc"), 0755, true)){
1064                                        //tmpWpfc has been created
1065                                }
1066                        }
1067                               
1068                        foreach ((array)$files as $file){
1069                                @rename($file, $this->getWpContentDir("/cache/tmpWpfc/").basename($file)."-".time());
1070                        }
1071
1072                        if (is_admin() && defined('DOING_AJAX') && DOING_AJAX){
1073                                die(json_encode(array("The cache of page has been cleared","success")));
1074                        }
1075                }
1076
1077                public function delete_current_page_cache(){
1078                        if(!wp_verify_nonce($_GET["nonce"], "wpfc")){
1079                                die(json_encode(array("Security Error!", "error", "alert")));
1080                        }
1081
1082                        if($varnish_datas = get_option("WpFastestCacheVarnish")){
1083                                include_once('inc/varnish.php');
1084                                VarnishWPFC::purge_cache($varnish_datas);
1085                        }
1086
1087                        include_once('inc/cdn.php');
1088                        CdnWPFC::cloudflare_clear_cache();
1089
1090                        if(isset($_GET["path"])){
1091                                if($_GET["path"]){
1092                                        if($_GET["path"] == "/"){
1093                                                $_GET["path"] = $_GET["path"]."index.html";
1094                                        }
1095                                }else{
1096                                        $_GET["path"] = "/index.html";
1097                                }
1098
1099                                $_GET["path"] = urldecode(esc_url_raw($_GET["path"]));
1100
1101                                // for security
1102                                if(preg_match("/\.{2,}/", $_GET["path"])){
1103                                        die("May be Directory Traversal Attack");
1104                                }
1105
1106                                $paths = array();
1107
1108                                array_push($paths, $this->getWpContentDir("/cache/all").$_GET["path"]);
1109
1110                                if(class_exists("WpFcMobileCache")){
1111                                        $wpfc_mobile = new WpFcMobileCache();
1112                                        array_push($paths, $this->getWpContentDir("/cache/wpfc-mobile-cache").$_GET["path"]);
1113                                }
1114
1115                                foreach ($paths as $key => $value){
1116                                        if(file_exists($value)){
1117                                                if(preg_match("/\/(all|wpfc-mobile-cache)\/index\.html$/i", $value)){
1118                                                        @unlink($value);
1119                                                }else{
1120                                                        $this->rm_folder_recursively($value);
1121                                                }
1122                                        }
1123                                }
1124
1125                                $this->delete_multiple_domain_mapping_cache();
1126
1127                                die(json_encode(array("The cache of page has been cleared","success")));
1128                        }else{
1129                                die(json_encode(array("Path has NOT been defined", "error", "alert")));
1130                        }
1131
1132                        exit;
1133                }
1134
1135                private function cache(){
1136                        if(isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST']){
1137                                include_once('inc/cache.php');
1138                                $wpfc = new WpFastestCacheCreateCache();
1139                                $wpfc->createCache();
1140                        }
1141                }
1142
1143                protected function slug(){
1144                        return "wp_fastest_cache";
1145                }
1146
1147                public function getWpContentDir($path = false){
1148                        /*
1149                        Sample Paths;
1150
1151                        /cache/
1152
1153                        /cache/all/
1154                        /cache/all
1155                        /cache/all/page
1156                        /cache/all/index.html
1157
1158                        /cache/wpfc-minified
1159
1160                        /cache/wpfc-widget-cache
1161
1162                        /cache/wpfc-mobile-cache/
1163                        /cache/wpfc-mobile-cache/page
1164                        /cache/wpfc-mobile-cache/index.html
1165                       
1166                        /cache/tmpWpfc
1167                        /cache/tmpWpfc/
1168                        /cache/tmpWpfc/mobile_
1169                        /cache/tmpWpfc/m
1170                        /cache/tmpWpfc/w
1171
1172                       
1173                        /cache/testWpFc/
1174
1175                        /cache/all/testWpFc/
1176                       
1177                        /cache/wpfc-widget-cache/
1178                        /cache/wpfc-widget-cache
1179                        /cache/wpfc-widget-cache/".$args["widget_id"].".html
1180                        */
1181                       
1182                        if($path){
1183                                if(preg_match("/\/cache\/(all|wpfc-minified|wpfc-widget-cache|wpfc-mobile-cache)/", $path)){
1184                                        //WPML language switch
1185                                        //https://wpml.org/forums/topic/wpml-language-switch-wp-fastest-cache-issue/
1186                                        $language_negotiation_type = apply_filters('wpml_setting', false, 'language_negotiation_type');
1187                                        if(($language_negotiation_type == 2) && $this->isPluginActive('sitepress-multilingual-cms/sitepress.php')){
1188                                                $my_home_url = apply_filters('wpml_home_url', get_option('home'));
1189                                                $my_home_url = preg_replace("/https?\:\/\//i", "", $my_home_url);
1190                                                $my_home_url = trim($my_home_url, "/");
1191                                               
1192                                            $path = preg_replace("/\/cache\/(all|wpfc-minified|wpfc-widget-cache|wpfc-mobile-cache)/", "/cache/".$my_home_url."/$1", $path);
1193                                        }else if(($language_negotiation_type == 1) && $this->isPluginActive('sitepress-multilingual-cms/sitepress.php')){
1194                                                $my_current_lang = apply_filters('wpml_current_language', NULL);
1195
1196                                                if($my_current_lang){
1197                                                        $path = preg_replace("/\/cache\/wpfc-widget-cache\/(.+)/", "/cache/wpfc-widget-cache/".$my_current_lang."-"."$1", $path);
1198                                                }
1199                                        }
1200
1201                                        if($this->isPluginActive('multiple-domain-mapping-on-single-site/multidomainmapping.php')){
1202                                                $path = preg_replace("/\/cache\/(all|wpfc-minified|wpfc-widget-cache|wpfc-mobile-cache)/", "/cache/".$_SERVER['HTTP_HOST']."/$1", $path);
1203                                        }
1204
1205                                        if($this->isPluginActive('polylang/polylang.php') || $this->isPluginActive('polylang-pro/polylang.php')){
1206                                                $polylang_settings = get_option("polylang");
1207
1208                                                if(isset($polylang_settings["force_lang"])){
1209                                                        if($polylang_settings["force_lang"] == 2 || $polylang_settings["force_lang"] == 3){
1210                                                                // The language is set from the subdomain name in pretty permalinks
1211                                                                // The language is set from different domains
1212                                                                $path = preg_replace("/\/cache\/(all|wpfc-minified|wpfc-widget-cache|wpfc-mobile-cache)/", "/cache/".$_SERVER['HTTP_HOST']."/$1", $path);
1213                                                        }
1214                                                }
1215                                        }
1216
1217                                        if($this->isPluginActive('multiple-domain/multiple-domain.php')){
1218                                                $path = preg_replace("/\/cache\/(all|wpfc-minified|wpfc-widget-cache|wpfc-mobile-cache)/", "/cache/".$_SERVER['HTTP_HOST']."/$1", $path);
1219                                        }
1220
1221                                        if(is_multisite()){
1222                                                $path = preg_replace("/\/cache\/(all|wpfc-minified|wpfc-widget-cache|wpfc-mobile-cache)/", "/cache/".$_SERVER['HTTP_HOST']."/$1", $path);
1223                                        }
1224                                }
1225
1226                                return WPFC_WP_CONTENT_DIR.$path;
1227                        }else{
1228                                return WPFC_WP_CONTENT_DIR;
1229                        }
1230                }
1231
1232                protected function getOptions(){
1233                        return $GLOBALS["wp_fastest_cache_options"];
1234                }
1235
1236                protected function getSystemMessage(){
1237                        return $this->systemMessage;
1238                }
1239
1240                protected function get_excluded_useragent(){
1241                        return "facebookexternalhit|WP_FASTEST_CACHE_CSS_VALIDATOR|Twitterbot|LinkedInBot|WhatsApp|Mediatoolkitbot";
1242                }
1243
1244                // protected function detectNewPost(){
1245                //      if(isset($this->options->wpFastestCacheNewPost) && isset($this->options->wpFastestCacheStatus)){
1246                //              add_filter ('save_post', array($this, 'deleteCache'));
1247                //      }
1248                // }
1249
1250                public function deleteWidgetCache(){
1251                        $widget_cache_path = $this->getWpContentDir("/cache/wpfc-widget-cache");
1252                       
1253                        if(is_dir($widget_cache_path)){
1254                                if(!is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
1255                                        if(@mkdir($this->getWpContentDir("/cache/tmpWpfc"), 0755, true)){
1256                                                //tmpWpfc has been created
1257                                        }
1258                                }
1259
1260                                if(@rename($widget_cache_path, $this->getWpContentDir("/cache/tmpWpfc/w").time())){
1261                                        //DONE
1262                                }
1263                        }
1264                }
1265
1266                public function clear_cache_after_woocommerce_update_product($product_id){
1267                        if(!$this->deleted_before){
1268                                $this->singleDeleteCache(false, $product_id);
1269                        }
1270                }
1271
1272                public function on_all_status_transitions($new_status, $old_status, $post){
1273                        $this->deleted_before = true;
1274
1275                        if(!wp_is_post_revision($post->ID)){
1276                                if(isset($post->post_type)){
1277                                        if($post->post_type == "nf_sub"){
1278                                                return 0;
1279                                        }
1280                                }
1281
1282                                if($new_status == "publish" && $old_status != "publish"){
1283                                       
1284                                        $this->specificDeleteCache();
1285                                       
1286                                        if(isset($this->options->wpFastestCacheNewPost) && isset($this->options->wpFastestCacheStatus)){
1287                                                if(isset($this->options->wpFastestCacheNewPost_type) && $this->options->wpFastestCacheNewPost_type){
1288                                                        if($this->options->wpFastestCacheNewPost_type == "all"){
1289                                                                $this->deleteCache();
1290                                                        }else if($this->options->wpFastestCacheNewPost_type == "homepage"){
1291                                                                $this->deleteHomePageCache();
1292
1293                                                                //to clear category cache and tag cache
1294                                                                $this->singleDeleteCache(false, $post->ID);
1295
1296                                                                //to clear widget cache
1297                                                                $this->deleteWidgetCache();
1298                                                        }
1299                                                }else{
1300                                                        $this->deleteCache();
1301                                                }
1302                                        }
1303                                }
1304
1305                                if(isset($this->options->wpFastestCacheStatus) && $new_status == "publish" && $old_status == "publish"){
1306
1307                                        // if(isset($this->options->wpFastestCacheUpdatePost) && isset($this->options->wpFastestCacheStatus)){
1308
1309                                        //      if($this->options->wpFastestCacheUpdatePost_type == "post"){
1310                                        //              $this->singleDeleteCache(false, $post->ID);
1311                                        //      }else if($this->options->wpFastestCacheUpdatePost_type == "all"){
1312                                        //              $this->deleteCache();
1313                                        //      }
1314                                               
1315                                        // }
1316
1317                                        $this->specificDeleteCache();
1318
1319                                        if(isset($this->options->wpFastestCacheUpdatePost)){
1320
1321                                                if($this->options->wpFastestCacheUpdatePost_type == "post"){
1322                                                        $this->singleDeleteCache(false, $post->ID);
1323                                                }else if($this->options->wpFastestCacheUpdatePost_type == "all"){
1324                                                        $this->deleteCache();
1325                                                }
1326                                               
1327                                        }else{
1328                                                // to clear only cache of content even though the "update post" option is disabled
1329                                                $this->singleDeleteCache(false, $post->ID, false);
1330                                        }
1331                                }
1332
1333                                if($new_status == "trash" && $old_status == "publish"){
1334
1335                                        if($post->post_type == "shop_coupon"){
1336                                                // YITH WooCommerce Coupon Email System Premium
1337                                                return;
1338                                        }
1339
1340                                        $this->singleDeleteCache(false, $post->ID);
1341                                }else if(($new_status == "draft" || $new_status == "pending" || $new_status == "private") && $old_status == "publish"){
1342                                        $this->deleteCache();
1343                                }
1344                        }
1345                }
1346
1347                protected function commentHooks(){
1348                        //it works when the status of a comment changes
1349                        add_action('wp_set_comment_status', array($this, 'detect_comment_status_change'), 10, 2);
1350
1351                        //it works when a comment is saved in the database
1352                        add_action('comment_post', array($this, 'detectNewComment'), 10, 2);
1353
1354                        // it work when a commens is updated
1355                        add_action('edit_comment', array($this, 'detectEditComment'), 10, 2);
1356                }
1357
1358                public function detect_comment_status_change($comment_id, $new_status) {
1359                    $comment = get_comment($comment_id);
1360                   
1361                    if (!$comment) {
1362                        return; // Exit if the comment doesn't exist
1363                    }
1364
1365                    // Check if the comment was pending and is now marked as spam
1366                    if($comment->comment_status == 'open' && $new_status === 'spam'){
1367                        return;
1368                    }
1369
1370                    // Check if the comment was pending and is now marked as trash
1371                    if($comment->comment_status == 'open' && $new_status === 'trash'){
1372                        return;
1373                    }
1374
1375                    $this->singleDeleteCache($comment_id);
1376                }
1377
1378                public function detectEditComment($comment_id, $comment_data){
1379                        if($comment_data["comment_approved"] == 1){
1380                                $this->singleDeleteCache($comment_id);
1381                        }
1382                }
1383
1384                public function detectNewComment($comment_id, $comment_approved){
1385                        // if(current_user_can( 'manage_options') || !get_option('comment_moderation')){
1386                        if($comment_approved === 1){
1387                                $this->singleDeleteCache($comment_id);
1388                        }
1389                }
1390
1391                public function specificDeleteCache(){
1392                        $urls = get_option("WpFastestCacheCSP");
1393                        $files = array();
1394
1395                        if(!empty($urls)){
1396                                foreach ($urls as $key => $value) {
1397
1398                                        if(preg_match("/https?:\/\/[^\/]+\/(.+)/", $value->url, $out)){
1399
1400                                                if(preg_match("/\.{2,}/", $out[1])){
1401                                                        // to prevent Directory Traversal Attack
1402                                                        continue;
1403                                                }
1404
1405                                                if(preg_match("/\/\(\.\*\)/", $out[1])){
1406                                                        $out[1] = str_replace("(.*)", "", $out[1]);
1407
1408                                                        $path = $this->getWpContentDir("/cache/all/").$out[1];
1409                                                        $mobile_path = $this->getWpContentDir("/cache/wpfc-mobile-cache/").$out[1];
1410                                                }else{
1411                                                        $out[1] = $out[1]."index.html";
1412
1413                                                        $path = $this->getWpContentDir("/cache/all/").$out[1];
1414                                                        $mobile_path = $this->getWpContentDir("/cache/wpfc-mobile-cache/").$out[1];
1415                                                }
1416
1417                                                if(!is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
1418                                                        @mkdir($this->getWpContentDir("/cache/tmpWpfc"), 0755, true);
1419                                                }
1420
1421                                                if(is_dir($path)){
1422                                                        rename($path, $this->getWpContentDir("/cache/tmpWpfc/").time());
1423                                                }else if(is_file($path)){
1424                                                        @unlink($path);
1425                                                }
1426
1427                                                if(is_dir($mobile_path)){
1428                                                        rename($mobile_path, $this->getWpContentDir("/cache/tmpWpfc/mobile_").time());
1429                                                }else if(is_file($mobile_path)){
1430                                                        @unlink($mobile_path);
1431                                                }
1432                                               
1433                                        }
1434
1435                                }
1436                        }
1437                }
1438
1439                public function singleDeleteCache($comment_id = false, $post_id = false, $to_clear_parents = true){
1440                        if($varnish_datas = get_option("WpFastestCacheVarnish")){
1441                                include_once('inc/varnish.php');
1442                                VarnishWPFC::purge_cache($varnish_datas);
1443                        }
1444
1445                        include_once('inc/cdn.php');
1446                        CdnWPFC::cloudflare_clear_cache();
1447
1448                        $to_clear_feed = true;
1449
1450                        // not to clear cache of homepage/cats/tags after ajax request by other plugins
1451                        if(isset($_POST) && isset($_POST["action"])){
1452                                // kk Star Rating
1453                                if($_POST["action"] == "kksr_ajax"){
1454                                        $to_clear_parents = false;
1455                                }
1456
1457                                // All In One Schema.org Rich Snippets
1458                                if(preg_match("/bsf_(update|submit)_rating/i", $_POST["action"])){
1459                                        $to_clear_parents = false;
1460                                }
1461
1462                                // Yet Another Stars Rating
1463                                if($_POST["action"] == "yasr_send_visitor_rating"){
1464                                        $to_clear_parents = false;
1465                                        $post_id = sanitize_text_field($_POST["post_id"]);
1466                                }
1467
1468                                // All In One Schema.org Rich Snippets
1469                                if(preg_match("/bsf_(update|submit)_rating/i", $_POST["action"])){
1470                                        $to_clear_feed = false;
1471                                }
1472                        }
1473
1474                        if($comment_id){
1475                                $comment_id = intval($comment_id);
1476                               
1477                                $comment = get_comment($comment_id);
1478                               
1479                                if($comment && $comment->comment_post_ID){
1480                                        $post_id = $comment->comment_post_ID;
1481                                }
1482                        }
1483
1484                        if($post_id){
1485                                $post_id = intval($post_id);
1486
1487                                $permalink = get_permalink($post_id);
1488
1489                                $permalink = urldecode(get_permalink($post_id));
1490
1491
1492
1493                                //for trash contents
1494                                if(preg_match("/\/\?p\=\d+/i", $permalink)){
1495                                        $post = get_post($post_id);
1496
1497                                        $clone_post = clone $post;
1498                                        $clone_post->post_status = 'publish';
1499
1500                                        $permalink = get_permalink($clone_post);
1501                                        $permalink = rtrim($permalink, "/");
1502
1503                                        $permalink = preg_replace("/__trashed$/", "", $permalink);
1504                                        //for /%postname%/%post_id% : sample-url__trashed/57595
1505                                        $permalink = preg_replace("/__trashed\/(\d+)$/", "/$1", $permalink);
1506                                }
1507
1508
1509
1510                                if(preg_match("/https?:\/\/[^\/]+\/(.+)/", $permalink, $out)){
1511                                        $path = $this->getWpContentDir("/cache/all/").$out[1];
1512                                        $mobile_path = $this->getWpContentDir("/cache/wpfc-mobile-cache/").$out[1];
1513
1514                                        if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
1515                                                include_once $this->get_premium_path("logs.php");
1516                                                $log = new WpFastestCacheLogs("delete");
1517                                                $log->action();
1518                                        }
1519
1520                                        $files = array();
1521
1522                                        if(is_dir($path)){
1523                                                array_push($files, $path);
1524                                        }
1525
1526                                        if(is_dir($mobile_path)){
1527                                                array_push($files, $mobile_path);
1528                                        }
1529
1530                                        if(defined('WPFC_CACHE_QUERYSTRING') && WPFC_CACHE_QUERYSTRING){
1531                                                $files_with_query_string = glob($path."\?*");
1532                                                $mobile_files_with_query_string = glob($mobile_path."\?*");
1533
1534                                                if(is_array($files_with_query_string) && (count($files_with_query_string) > 0)){
1535                                                        $files = array_merge($files, $files_with_query_string);
1536                                                }
1537
1538                                                if(is_array($mobile_files_with_query_string) && (count($mobile_files_with_query_string) > 0)){
1539                                                        $files = array_merge($files, $mobile_files_with_query_string);
1540                                                }
1541                                        }
1542
1543                                        if($to_clear_feed){
1544                                                // to clear cache of /feed
1545                                                if(preg_match("/https?:\/\/[^\/]+\/(.+)/", get_feed_link(), $feed_out)){
1546                                                        array_push($files, $this->getWpContentDir("/cache/all/").$feed_out[1]);
1547                                                }
1548
1549                                                // to clear cache of /comments/feed/
1550                                                if(preg_match("/https?:\/\/[^\/]+\/(.+)/", get_feed_link("comments_"), $comment_feed_out)){
1551                                                        array_push($files, $this->getWpContentDir("/cache/all/").$comment_feed_out[1]);
1552                                                }
1553                                        }
1554
1555                                        foreach((array)$files as $file){
1556                                                $this->rm_folder_recursively($file);
1557                                        }
1558                                }
1559
1560                                if($to_clear_parents){
1561                                        // to clear cache of homepage
1562                                        $this->deleteHomePageCache();
1563
1564                                        // to clear cache of author page
1565                                        $this->delete_author_page_cache($post_id);
1566
1567                                        // to clear sitemap cache
1568                                        $this->delete_sitemap_cache();
1569
1570                                        // to clear cache of next post and cache of prev post
1571                                        $this->delete_next_prev_cache($post_id);
1572
1573                                        // to clear cache of cats and  tags which contains the post (only first page)
1574                                        global $wpdb;
1575                                        $terms = $wpdb->get_results("SELECT * FROM `".$wpdb->prefix."term_relationships` WHERE `object_id`=".$post_id, ARRAY_A);
1576
1577                                        foreach ($terms as $term_key => $term_val){
1578                                                $this->delete_cache_of_term($term_val["term_taxonomy_id"]);
1579                                        }
1580                                }
1581
1582                                $this->delete_multiple_domain_mapping_cache();
1583                        }
1584                }
1585
1586                public function delete_next_prev_cache($post_id){
1587                        global $wpdb;
1588                       
1589                        $post = get_post($post_id);
1590
1591                        $next_post_query = "SELECT * FROM `".$wpdb->prefix."posts` WHERE ID = (SELECT min(ID) FROM `".$wpdb->prefix."posts` where ID > ".$post_id." AND `post_type` = '".$post->post_type."' AND `post_status` = 'publish')";
1592                        $prev_post_query = "SELECT * FROM `".$wpdb->prefix."posts` WHERE ID = (SELECT max(ID) FROM `".$wpdb->prefix."posts` where ID < ".$post_id." AND `post_type` = '".$post->post_type."' AND `post_status` = 'publish')";
1593
1594                        $res = $wpdb->get_results($next_post_query." UNION ".$prev_post_query);
1595
1596                        if(isset($res[0])){
1597
1598                                foreach ($res as $key => $value) {
1599                                        $permalink = urldecode(get_permalink($value->ID));
1600
1601                                        if(preg_match("/https?:\/\/[^\/]+\/(.+)/", $permalink, $out)){
1602                                                $path = $this->getWpContentDir("/cache/all/").$out[1];
1603                                                $mobile_path = $this->getWpContentDir("/cache/wpfc-mobile-cache/").$out[1];
1604
1605                                                if(is_dir($path)){
1606                                                        $this->rm_folder_recursively($path);
1607                                                }
1608
1609                                                if(is_dir($mobile_path)){
1610                                                        $this->rm_folder_recursively($mobile_path);
1611                                                }
1612                                        }
1613                                }
1614
1615                        }
1616
1617
1618                }
1619
1620                public function delete_sitemap_cache(){
1621                        //to clear sitemap.xml and sitemap-(.+).xml
1622                        $files = array_merge(glob($this->getWpContentDir("/cache/all/")."sitemap*.xml"), glob($this->getWpContentDir("/cache/wpfc-mobile-cache/")."sitemap*.xml"));
1623
1624                        foreach((array)$files as $file){
1625                                $this->rm_folder_recursively($file);
1626                        }
1627                }
1628
1629                public function delete_multiple_domain_mapping_cache($minified = false){
1630                        //https://wordpress.org/plugins/multiple-domain-mapping-on-single-site/
1631                        if($this->isPluginActive("multiple-domain-mapping-on-single-site/multidomainmapping.php")){
1632                                $multiple_arr = get_option('falke_mdm_mappings');
1633
1634                                if(isset($multiple_arr) && isset($multiple_arr["mappings"]) && isset($multiple_arr["mappings"][0])){
1635                                        foreach($multiple_arr["mappings"] as $mapping_key => $mapping_value){
1636                                                if($minified){
1637                                                        $mapping_domain_path = preg_replace("/(\/cache\/[^\/]+\/all\/)/", "/cache/".$mapping_value["domain"]."/", $this->getWpContentDir("/cache/all/"));
1638
1639                                                        if(is_dir($mapping_domain_path)){
1640                                                                if(@rename($mapping_domain_path, $this->getWpContentDir("/cache/tmpWpfc/").$mapping_value["domain"]."_".time())){
1641
1642                                                                }
1643                                                        }
1644                                                }else{
1645                                                        $mapping_domain_path = preg_replace("/(\/cache\/[^\/]+\/all)/", "/cache/".$mapping_value["domain"]."/all", $this->getWpContentDir("/cache/all/index.html"));
1646
1647                                                        @unlink($mapping_domain_path);
1648                                                }
1649                                        }
1650                                }
1651                        }
1652                }
1653
1654                public function delete_author_page_cache($post_id){
1655                        $author_id = get_post_field ('post_author', $post_id);
1656                        $permalink = get_author_posts_url($author_id);
1657
1658                        if(preg_match("/https?:\/\/[^\/]+\/(.+)/", $permalink, $out)){
1659                                $path = $this->getWpContentDir("/cache/all/").$out[1];
1660                                $mobile_path = $this->getWpContentDir("/cache/wpfc-mobile-cache/").$out[1];
1661                                       
1662                                $this->move_folder_to_tmpWpfc($path);
1663                                $this->move_folder_to_tmpWpfc($mobile_path);
1664                        }
1665                }
1666
1667                public function move_folder_to_tmpWpfc($path = false){
1668                        if(!is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
1669                                @mkdir($this->getWpContentDir("/cache/tmpWpfc"), 0755, true);
1670                        }
1671
1672                        if(!$path){
1673                                return false;
1674                        }
1675
1676                        if(!is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
1677                                return false;
1678                        }
1679
1680                        if(is_dir($path)){
1681                                preg_match("/\/([^\/]+)\/?$/", $path, $type);
1682
1683                                if(isset($type[1])){
1684                                        if(preg_match("/\/cache\/wpfc-mobile-cache\//", $path)){
1685                                                $type[1] = "m_".$type[1];
1686                                        }
1687
1688                                        $move_to = $this->getWpContentDir("/cache/tmpWpfc/").$type[1]."_".time();
1689
1690                                        rename($path, $move_to);
1691                                }
1692                        }
1693                }
1694
1695                public function delete_cache_of_term($term_taxonomy_id){
1696                        $term = get_term_by("term_taxonomy_id", $term_taxonomy_id);
1697
1698                        if(!$term || is_wp_error($term)){
1699                                return false;
1700                        }
1701
1702                        //if(preg_match("/cat|tag|store|listing/", $term->taxonomy)){}
1703
1704                        $url = get_term_link($term->term_id, $term->taxonomy);
1705
1706                        if(preg_match("/^http/", $url)){
1707                                $path = preg_replace("/https?\:\/\/[^\/]+/i", "", $url);
1708                                $path = trim($path, "/");
1709                                $path = urldecode($path);
1710
1711                                // to remove the cache of tag/cat
1712                                if(file_exists($this->getWpContentDir("/cache/all/").$path."/index.html")){
1713                                        @unlink($this->getWpContentDir("/cache/all/").$path."/index.html");
1714                                }
1715
1716                                if(file_exists($this->getWpContentDir("/cache/wpfc-mobile-cache/").$path."/index.html")){
1717                                        @unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/").$path."/index.html");
1718                                }
1719
1720
1721                                // to remove the cache of the pages
1722                                $this->rm_folder_recursively($this->getWpContentDir("/cache/all/").$path."/page");
1723                                $this->rm_folder_recursively($this->getWpContentDir("/cache/wpfc-mobile-cache/").$path."/page");
1724
1725                                // to remove the cache of the feeds
1726                                $this->rm_folder_recursively($this->getWpContentDir("/cache/all/").$path."/feed");
1727                                $this->rm_folder_recursively($this->getWpContentDir("/cache/wpfc-mobile-cache/").$path."/feed");
1728                        }
1729
1730                        if($term->parent > 0){
1731                                $parent = get_term_by("id", $term->parent, $term->taxonomy);
1732
1733                                if(isset($parent->term_taxonomy_id)){
1734                                        $this->delete_cache_of_term($parent->term_taxonomy_id);
1735                                }
1736                        }
1737                }
1738
1739                public function unlink($path){
1740                        if(file_exists($path)){
1741                                unlink($path);
1742                        }
1743                }
1744
1745                public function deleteHomePageCache($log = true){
1746                        if($varnish_datas = get_option("WpFastestCacheVarnish")){
1747                                include_once('inc/varnish.php');
1748                                VarnishWPFC::purge_cache($varnish_datas);
1749                        }
1750
1751                        include_once('inc/cdn.php');
1752                        CdnWPFC::cloudflare_clear_cache();
1753
1754                        $site_url_path = preg_replace("/https?\:\/\/[^\/]+/i", "", site_url());
1755                        $home_url_path = preg_replace("/https?\:\/\/[^\/]+/i", "", home_url());
1756
1757                        if($site_url_path){
1758                                $site_url_path = trim($site_url_path, "/");
1759
1760                                if($site_url_path){
1761                                        $this->unlink($this->getWpContentDir("/cache/all/").$site_url_path."/index.html");
1762                                        $this->unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/").$site_url_path."/index.html");
1763
1764                                        //to clear pagination of homepage cache
1765                                        $this->rm_folder_recursively($this->getWpContentDir("/cache/all/").$site_url_path."/page");
1766                                        $this->rm_folder_recursively($this->getWpContentDir("/cache/wpfc-mobile-cache/").$site_url_path."/page");
1767                                }
1768                        }
1769
1770                        if($home_url_path){
1771                                $home_url_path = trim($home_url_path, "/");
1772
1773                                if($home_url_path){
1774                                        $this->unlink($this->getWpContentDir("/cache/all/").$home_url_path."/index.html");
1775                                        $this->unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/").$home_url_path."/index.html");
1776
1777                                        //to clear pagination of homepage cache
1778                                        $this->rm_folder_recursively($this->getWpContentDir("/cache/all/").$home_url_path."/page");
1779                                        $this->rm_folder_recursively($this->getWpContentDir("/cache/wpfc-mobile-cache/").$home_url_path."/page");
1780                                }
1781                        }
1782
1783                        if(function_exists("wc_get_page_id")){
1784                                if($shop_id = wc_get_page_id('shop')){
1785                                        $store_url_path = preg_replace("/https?\:\/\/[^\/]+/i", "", get_permalink($shop_id));
1786
1787                                        if($store_url_path){
1788                                                $store_url_path = trim($store_url_path, "/");
1789
1790                                                if($store_url_path){
1791                                                        if(file_exists($this->getWpContentDir("/cache/all/").$store_url_path."/index.html")){
1792                                                                @unlink($this->getWpContentDir("/cache/all/").$store_url_path."/index.html");
1793                                                        }
1794
1795                                                        if(file_exists($this->getWpContentDir("/cache/wpfc-mobile-cache/").$store_url_path."/index.html")){
1796                                                                @unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/").$store_url_path."/index.html");
1797                                                        }
1798
1799                                                        //to clear pagination of store homepage cache
1800                                                        $this->rm_folder_recursively($this->getWpContentDir("/cache/all/").$store_url_path."/page");
1801                                                        $this->rm_folder_recursively($this->getWpContentDir("/cache/wpfc-mobile-cache/").$store_url_path."/page");
1802                                                }
1803                                        }
1804                                }
1805                        }
1806
1807                        $this->unlink($this->getWpContentDir("/cache/all/index.html"));
1808                        $this->unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/index.html"));
1809
1810                        //to clear pagination of homepage cache
1811                        $this->rm_folder_recursively($this->getWpContentDir("/cache/all/page"));
1812                        $this->rm_folder_recursively($this->getWpContentDir("/cache/wpfc-mobile-cache/page"));
1813
1814                        // options-reading.php - static posts page
1815                        if($page_for_posts_id = get_option('page_for_posts')){
1816                                $page_for_posts_permalink = urldecode(get_permalink($page_for_posts_id));
1817
1818                                $page_for_posts_permalink = rtrim($page_for_posts_permalink, "/");
1819                                $page_for_posts_permalink = preg_replace("/__trashed$/", "", $page_for_posts_permalink);
1820                                //for /%postname%/%post_id% : sample-url__trashed/57595
1821                                $page_for_posts_permalink = preg_replace("/__trashed\/(\d+)$/", "/$1", $page_for_posts_permalink);
1822
1823                                if(preg_match("/https?:\/\/[^\/]+\/(.+)/", $page_for_posts_permalink, $out)){
1824                                        $page_for_posts_path = $this->getWpContentDir("/cache/all/").$out[1];
1825                                        $page_for_posts_mobile_path = $this->getWpContentDir("/cache/wpfc-mobile-cache/").$out[1];
1826                                       
1827                                        $this->rm_folder_recursively($page_for_posts_path);
1828                                        $this->rm_folder_recursively($page_for_posts_mobile_path);
1829                                }
1830                        }
1831
1832
1833                        if($log){
1834                                if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
1835                                        include_once $this->get_premium_path("logs.php");
1836
1837                                        $log = new WpFastestCacheLogs("delete");
1838                                        $log->action();
1839                                }
1840                        }
1841                }
1842
1843                public function deleteCache($minified = false){
1844                        if($varnish_datas = get_option("WpFastestCacheVarnish")){
1845                                include_once('inc/varnish.php');
1846                                VarnishWPFC::purge_cache($varnish_datas);
1847                        }
1848
1849                        include_once('inc/cdn.php');
1850                        CdnWPFC::cloudflare_clear_cache();
1851
1852                        $this->set_preload();
1853
1854                        $created_tmpWpfc = false;
1855                        $cache_deleted = false;
1856                        $minifed_deleted = false;
1857
1858                        $cache_path = $this->getWpContentDir("/cache/all");
1859                        $minified_cache_path = $this->getWpContentDir("/cache/wpfc-minified");
1860
1861                        if(class_exists("WpFcMobileCache")){
1862
1863
1864
1865
1866                                if(is_dir($this->getWpContentDir("/cache/wpfc-mobile-cache"))){
1867                                        if(is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
1868                                                rename($this->getWpContentDir("/cache/wpfc-mobile-cache"), $this->getWpContentDir("/cache/tmpWpfc/mobile_").time());
1869                                        }else if(@mkdir($this->getWpContentDir("/cache/tmpWpfc"), 0755, true)){
1870                                                rename($this->getWpContentDir("/cache/wpfc-mobile-cache"), $this->getWpContentDir("/cache/tmpWpfc/mobile_").time());
1871                                        }
1872                                }
1873
1874
1875                        }
1876                       
1877                        if(!is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
1878                                if(@mkdir($this->getWpContentDir("/cache/tmpWpfc"), 0755, true)){
1879                                        $created_tmpWpfc = true;
1880                                }else{
1881                                        $created_tmpWpfc = false;
1882                                        //$this->systemMessage = array("Permission of <strong>/wp-content/cache</strong> must be <strong>755</strong>", "error");
1883                                }
1884                        }else{
1885                                $created_tmpWpfc = true;
1886                        }
1887
1888                        //to clear widget cache path
1889                        $this->deleteWidgetCache();
1890
1891                        $this->delete_multiple_domain_mapping_cache($minified);
1892
1893                        if(is_dir($cache_path)){
1894                                if(@rename($cache_path, $this->getWpContentDir("/cache/tmpWpfc/").time())){
1895                                        delete_option("WpFastestCacheHTML");
1896                                        delete_option("WpFastestCacheHTMLSIZE");
1897                                        delete_option("WpFastestCacheMOBILE");
1898                                        delete_option("WpFastestCacheMOBILESIZE");
1899
1900                                        $cache_deleted = true;
1901                                }
1902                        }else{
1903                                $cache_deleted = true;
1904                        }
1905
1906                        if($minified){
1907                                if(is_dir($minified_cache_path)){
1908                                        if(@rename($minified_cache_path, $this->getWpContentDir("/cache/tmpWpfc/m").time())){
1909                                                delete_option("WpFastestCacheCSS");
1910                                                delete_option("WpFastestCacheCSSSIZE");
1911                                                delete_option("WpFastestCacheJS");
1912                                                delete_option("WpFastestCacheJSSIZE");
1913
1914                                                $minifed_deleted = true;
1915                                        }
1916                                }else{
1917                                        $minifed_deleted = true;
1918                                }
1919                        }else{
1920                                $minifed_deleted = true;
1921                        }
1922
1923                        if($created_tmpWpfc && $cache_deleted && $minifed_deleted){
1924                                do_action('wpfc_delete_cache');
1925                               
1926                                $this->notify(array("All cache files have been deleted", "updated"));
1927
1928                                if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
1929                                        include_once $this->get_premium_path("logs.php");
1930
1931                                        $log = new WpFastestCacheLogs("delete");
1932                                        $log->action();
1933                                }
1934                        }else{
1935                                $this->notify(array("Permissions Problem: <a href='http://www.wpfastestcache.com/warnings/delete-cache-problem-related-to-permission/' target='_blank'>Read More</a>", "error"));
1936                        }
1937
1938                        // for ajax request
1939                        if(isset($_GET["action"]) && in_array($_GET["action"], array("wpfc_delete_cache", "wpfc_delete_cache_and_minified"))){
1940                                die(json_encode($this->systemMessage));
1941                        }
1942                }
1943
1944                public function checkCronTime(){
1945                        $crons = _get_cron_array();
1946
1947                foreach ((array)$crons as $cron_key => $cron_value) {
1948                        foreach ( (array) $cron_value as $hook => $events ) {
1949                                if(preg_match("/^wp\_fastest\_cache(.*)/", $hook, $id)){
1950                                        if(!$id[1] || preg_match("/^\_(\d+)$/", $id[1])){
1951                                                foreach ( (array) $events as $event_key => $event ) {
1952                                                        add_action("wp_fastest_cache".$id[1],  array($this, 'setSchedule'));
1953                                                }
1954                                        }
1955                                }
1956                        }
1957                    }
1958
1959                    add_action($this->slug()."_Preload",  array($this, 'create_preload_cache'), 11);
1960                }
1961
1962                public function set_preload(){
1963                        include_once('inc/preload.php');
1964                        PreloadWPFC::set_preload($this->slug());
1965                }
1966
1967                public function create_preload_cache(){
1968                        $this->options = $this->getOptions();
1969                       
1970                        include_once('inc/preload.php');
1971                        PreloadWPFC::create_preload_cache($this->options);
1972                }
1973
1974                public function wpfc_remote_get($url, $user_agent, $return_content = false){
1975                        //$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)));
1976                        $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")));
1977
1978                        if (!$response || is_wp_error($response)){
1979                                echo $response->get_error_message()." - ";
1980
1981                                return false;
1982                        }else{
1983                                if(wp_remote_retrieve_response_code($response) != 200){
1984                                        return false;
1985                                }
1986
1987                                if($return_content){
1988                                        if(wp_remote_retrieve_response_code($response) == 200){
1989                                                $data = wp_remote_retrieve_body($response);
1990
1991                                                return $data;
1992                                        }
1993                                }
1994                        }
1995
1996                        return true;
1997                }
1998
1999                public function setSchedule($args = ""){
2000                        if($args){
2001                                $rule = json_decode($args);
2002
2003                                if($rule->prefix == "all"){
2004                                        $this->deleteCache();
2005                                }else if($rule->prefix == "homepage"){
2006                                        $this->deleteHomePageCache();
2007
2008                                        if(isset($this->options->wpFastestCachePreload_homepage) && $this->options->wpFastestCachePreload_homepage){
2009                                                $this->wpfc_remote_get(get_option("home"), "WP Fastest Cache Preload Bot - After Cache Timeout");
2010                                                $this->wpfc_remote_get(get_option("home"), "WP Fastest Cache Preload iPhone Mobile Bot - After Cache Timeout");
2011                                        }
2012                                }else if($rule->prefix == "startwith"){
2013                                                if(!is_dir($this->getWpContentDir("/cache/tmpWpfc"))){
2014                                                        if(@mkdir($this->getWpContentDir("/cache/tmpWpfc"), 0755, true)){}
2015                                                }
2016
2017                                                $rule->content = trim($rule->content, "/");
2018
2019                                                $files = glob($this->getWpContentDir("/cache/all/").$rule->content."*");
2020
2021                                                foreach ((array)$files as $file) {
2022                                                        $mobile_file = str_replace("/cache/all/", "/cache/wpfc-mobile-cache/", $file);
2023                                                       
2024                                                        @rename($file, $this->getWpContentDir("/cache/tmpWpfc/").time());
2025                                                        @rename($mobile_file, $this->getWpContentDir("/cache/tmpWpfc/mobile_").time());
2026                                                }
2027                                }else if($rule->prefix == "exact"){
2028                                        $rule->content = trim($rule->content, "/");
2029
2030                                        @unlink($this->getWpContentDir("/cache/all/").$rule->content."/index.html");
2031                                        @unlink($this->getWpContentDir("/cache/wpfc-mobile-cache/").$rule->content."/index.html");
2032                                }
2033
2034                                if($rule->prefix != "all"){
2035                                        if($this->isPluginActive("wp-fastest-cache-premium/wpFastestCachePremium.php")){
2036                                                include_once $this->get_premium_path("logs.php");
2037                                                $log = new WpFastestCacheLogs("delete");
2038                                                $log->action($rule);
2039                                        }
2040                                }
2041                        }else{
2042                                //for old cron job
2043                                $this->deleteCache();
2044                        }
2045                }
2046
2047                public function modify_htaccess_for_new_user($user_id){
2048                        $path = ABSPATH;
2049
2050                        if($this->is_subdirectory_install()){
2051                                $path = $this->getABSPATH();
2052                        }
2053
2054                        $htaccess = @file_get_contents($path.".htaccess");
2055
2056                        if(preg_match("/\#\s?Start_WPFC_Exclude_Admin_Cookie/", $htaccess)){
2057                                $rules = $this->excludeAdminCookie();
2058
2059                                $htaccess = preg_replace("/\#\s?Start_WPFC_Exclude_Admin_Cookie[^\#]*\#\s?End_WPFC_Exclude_Admin_Cookie\s+/", $rules, $htaccess);
2060                        }
2061
2062                        @file_put_contents($path.".htaccess", $htaccess);
2063                }
2064
2065                public function excludeAdminCookie(){
2066                        $usernames = array();
2067                        $users_groups = array_chunk(get_users(array("role" => "administrator", "fields" => array("user_login"))), 5);
2068
2069                        foreach ($users_groups as $group_key => $group) {
2070                                $tmp_user = "";
2071                                $tmp_rule = "";
2072
2073                                foreach ($group as $key => $value) {
2074                                        $tmp_user = sanitize_user(wp_unslash($value->user_login), true);
2075
2076                                        /*
2077                                                to replace spaces with %20
2078
2079                                                1. Empty space character causes 500 internal server error
2080                                                2. "\s" is not detected by htaccess so we added "%20"
2081                                        */
2082
2083                                        $tmp_user = preg_replace("/\s/", "%20", $tmp_user);
2084                                       
2085                                        array_push($usernames, $tmp_user);
2086                                }
2087                        }
2088
2089                        $rule = "# Start_WPFC_Exclude_Admin_Cookie\n"; 
2090                        $rule = $rule."RewriteCond %{HTTP:Cookie} !wordpress_logged_in_[^\=]+\=".implode("|", $usernames);
2091                        $rule = $rule."\n# End_WPFC_Exclude_Admin_Cookie\n";
2092
2093                        return $rule;
2094                }
2095
2096                public function excludeRules(){
2097                        $htaccess_page_rules = "";
2098                        $htaccess_page_useragent = "";
2099                        $htaccess_page_cookie = "";
2100
2101                        if($rules_json = get_option("WpFastestCacheExclude")){
2102                                if($rules_json != "null"){
2103                                        $rules_std = json_decode($rules_json);
2104
2105                                        foreach ($rules_std as $key => $value) {
2106                                                $value->type = isset($value->type) ? $value->type : "page";
2107
2108                                                // escape the chars
2109                                                $value->content = str_replace("?", "\?", $value->content);
2110
2111                                                if($value->type == "page"){
2112                                                        if($value->prefix == "startwith"){
2113                                                                $value->content = ltrim($value->content, "/");
2114
2115                                                                $htaccess_page_rules = $htaccess_page_rules."RewriteCond %{REQUEST_URI} !^/".$value->content." [NC]\n";
2116                                                        }
2117
2118                                                        if($value->prefix == "contain"){
2119                                                                $htaccess_page_rules = $htaccess_page_rules."RewriteCond %{REQUEST_URI} !".$value->content." [NC]\n";
2120                                                        }
2121
2122                                                        if($value->prefix == "exact"){
2123                                                                $value->content = trim($value->content, "/");
2124                                                               
2125                                                                $htaccess_page_rules = $htaccess_page_rules."RewriteCond %{REQUEST_URI} !\/".$value->content." [NC]\n";
2126                                                        }
2127                                                }else if($value->type == "useragent"){
2128                                                        $htaccess_page_useragent = $htaccess_page_useragent."RewriteCond %{HTTP_USER_AGENT} !".$value->content." [NC]\n";
2129                                                }else if($value->type == "cookie"){
2130                                                        $htaccess_page_cookie = $htaccess_page_cookie."RewriteCond %{HTTP:Cookie} !".$value->content." [NC]\n";
2131                                                }
2132                                        }
2133                                }
2134                        }
2135
2136                        return "# Start WPFC Exclude\n".$htaccess_page_rules.$htaccess_page_useragent.$htaccess_page_cookie."# End WPFC Exclude\n";
2137                }
2138
2139                public function getABSPATH(){
2140
2141                        if(function_exists("get_home_path")){
2142                                return get_home_path();
2143                        }else{
2144
2145                                $path = ABSPATH;
2146                                $siteUrl = site_url();
2147                                $homeUrl = home_url();
2148                                $diff = str_replace($homeUrl, "", $siteUrl);
2149                                $diff = trim($diff,"/");
2150
2151                            $pos = strrpos($path, $diff);
2152
2153                            if($pos !== false){
2154                                $path = substr_replace($path, "", $pos, strlen($diff));
2155                                $path = trim($path,"/");
2156                                $path = "/".$path."/";
2157                            }
2158                            return $path;
2159
2160                        }
2161                       
2162                }
2163
2164                public function rm_folder_recursively($dir, $i = 1) {
2165                        if(is_dir($dir)){
2166                                $files = @scandir($dir);
2167                            foreach((array)$files as $file) {
2168                                if($i > 50 && !preg_match("/wp-fastest-cache-premium/i", $dir)){
2169                                        return true;
2170                                }else{
2171                                        $i++;
2172                                }
2173                                if ('.' === $file || '..' === $file) continue;
2174                                if (is_dir("$dir/$file")){
2175                                        $this->rm_folder_recursively("$dir/$file", $i);
2176                                }else{
2177                                        if(file_exists("$dir/$file")){
2178                                                @unlink("$dir/$file");
2179                                        }
2180                                }
2181                            }
2182                        }
2183       
2184                    if(is_dir($dir)){
2185                            $files_tmp = @scandir($dir);
2186                           
2187                            if(!isset($files_tmp[2])){
2188                                @rmdir($dir);
2189                            }
2190                    }
2191
2192                    return true;
2193                }
2194
2195                public function is_subdirectory_install(){
2196                        if(strlen(site_url()) > strlen(home_url())){
2197                                return true;
2198                        }
2199                        return false;
2200                }
2201
2202                protected function getMobileUserAgents(){
2203                        return implode("|", $this->get_mobile_browsers())."|".implode("|", $this->get_operating_systems());
2204                }
2205
2206                public function get_premium_path($name){
2207                        return WPFC_WP_PLUGIN_DIR."/wp-fastest-cache-premium/pro/library/".$name;
2208                }
2209
2210                public function cron_add_minute( $schedules ) {
2211                        $schedules['everyminute'] = array(
2212                            'interval' => 60*1,
2213                            'display' => __( 'Once Every 1 Minute' ),
2214                            'wpfc' => true
2215                    );
2216
2217                        $schedules['everyfiveminute'] = array(
2218                            'interval' => 60*5,
2219                            'display' => __( 'Once Every 5 Minutes' ),
2220                            'wpfc' => true
2221                    );
2222
2223                        $schedules['everyfifteenminute'] = array(
2224                            'interval' => 60*15,
2225                            'display' => __( 'Once Every 15 Minutes' ),
2226                            'wpfc' => true
2227                    );
2228
2229                    $schedules['twiceanhour'] = array(
2230                            'interval' => 60*30,
2231                            'display' => __( 'Twice an Hour' ),
2232                            'wpfc' => true
2233                    );
2234
2235                    $schedules['onceanhour'] = array(
2236                            'interval' => 60*60,
2237                            'display' => __( 'Once an Hour' ),
2238                            'wpfc' => true
2239                    );
2240
2241                    $schedules['everytwohours'] = array(
2242                            'interval' => 60*60*2,
2243                            'display' => __( 'Once Every 2 Hours' ),
2244                            'wpfc' => true
2245                    );
2246
2247                    $schedules['everythreehours'] = array(
2248                            'interval' => 60*60*3,
2249                            'display' => __( 'Once Every 3 Hours' ),
2250                            'wpfc' => true
2251                    );
2252
2253                    $schedules['everyfourhours'] = array(
2254                            'interval' => 60*60*4,
2255                            'display' => __( 'Once Every 4 Hours' ),
2256                            'wpfc' => true
2257                    );
2258
2259                    $schedules['everyfivehours'] = array(
2260                            'interval' => 60*60*5,
2261                            'display' => __( 'Once Every 5 Hours' ),
2262                            'wpfc' => true
2263                    );
2264
2265                    $schedules['everysixhours'] = array(
2266                            'interval' => 60*60*6,
2267                            'display' => __( 'Once Every 6 Hours' ),
2268                            'wpfc' => true
2269                    );
2270
2271                    $schedules['everysevenhours'] = array(
2272                            'interval' => 60*60*7,
2273                            'display' => __( 'Once Every 7 Hours' ),
2274                            'wpfc' => true
2275                    );
2276
2277                    $schedules['everyeighthours'] = array(
2278                            'interval' => 60*60*8,
2279                            'display' => __( 'Once Every 8 Hours' ),
2280                            'wpfc' => true
2281                    );
2282
2283                    $schedules['everyninehours'] = array(
2284                            'interval' => 60*60*9,
2285                            'display' => __( 'Once Every 9 Hours' ),
2286                            'wpfc' => true
2287                    );
2288
2289                    $schedules['everytenhours'] = array(
2290                            'interval' => 60*60*10,
2291                            'display' => __( 'Once Every 10 Hours' ),
2292                            'wpfc' => true
2293                    );
2294
2295                    $schedules['onceaday'] = array(
2296                            'interval' => 60*60*24,
2297                            'display' => __( 'Once a Day' ),
2298                            'wpfc' => true
2299                    );
2300
2301                    $schedules['everythreedays'] = array(
2302                            'interval' => 60*60*24*3,
2303                            'display' => __( 'Once Every 3 Days' ),
2304                            'wpfc' => true
2305                    );
2306
2307                    $schedules['everysevendays'] = array(
2308                            'interval' => 60*60*24*7,
2309                            'display' => __( 'Once Every 7 Days' ),
2310                            'wpfc' => true
2311                    );
2312
2313                    $schedules['everytendays'] = array(
2314                            'interval' => 60*60*24*10,
2315                            'display' => __( 'Once Every 10 Days' ),
2316                            'wpfc' => true
2317                    );
2318
2319                    $schedules['everyfifteendays'] = array(
2320                            'interval' => 60*60*24*15,
2321                            'display' => __( 'Once Every 15 Days' ),
2322                            'wpfc' => true
2323                    );
2324
2325                    $schedules['montly'] = array(
2326                            'interval' => 60*60*24*30,
2327                            'display' => __( 'Once a Month' ),
2328                            'wpfc' => true
2329                    );
2330
2331                    $schedules['yearly'] = array(
2332                            'interval' => 60*60*24*30*12,
2333                            'display' => __( 'Once a Year' ),
2334                            'wpfc' => true
2335                    );
2336
2337                    return $schedules;
2338                }
2339
2340                public function setCustomInterval(){
2341                        add_filter( 'cron_schedules', array($this, 'cron_add_minute'));
2342                }
2343
2344                public function isPluginActive( $plugin ) {
2345                        return in_array( $plugin, (array) get_option( 'active_plugins', array() ) ) || $this->isPluginActiveForNetwork( $plugin );
2346                }
2347               
2348                public function isPluginActiveForNetwork( $plugin ) {
2349                        if ( !is_multisite() )
2350                                return false;
2351
2352                        $plugins = get_site_option( 'active_sitewide_plugins');
2353                        if ( isset($plugins[$plugin]) )
2354                                return true;
2355
2356                        return false;
2357                }
2358
2359                public function current_url(){
2360                        global $wp;
2361                    $current_url = home_url($_SERVER['REQUEST_URI']);
2362
2363                    return $current_url;
2364
2365
2366                        // if(defined('WP_CLI')){
2367                        //      $_SERVER["SERVER_NAME"] = isset($_SERVER["SERVER_NAME"]) ? $_SERVER["SERVER_NAME"] : "";
2368                        //      $_SERVER["SERVER_PORT"] = isset($_SERVER["SERVER_PORT"]) ? $_SERVER["SERVER_PORT"] : 80;
2369                        // }
2370                       
2371                 //    $pageURL = 'http';
2372                 
2373                 //    if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'){
2374                 //        $pageURL .= 's';
2375                 //    }
2376                 
2377                 //    $pageURL .= '://';
2378                 
2379                 //    if($_SERVER['SERVER_PORT'] != '80'){
2380                 //        $pageURL .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
2381                 //    }else{
2382                 //        $pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
2383                 //    }
2384                 
2385                 //    return $pageURL;
2386                }
2387
2388                public function wpfc_load_plugin_textdomain(){
2389                        load_plugin_textdomain('wp-fastest-cache', FALSE, basename( dirname( __FILE__ ) ) . '/languages/' );
2390                }
2391
2392                public function cdn_replace_urls($matches){
2393                        if(count($this->cdn) > 0){
2394                                foreach ($this->cdn as $key => $cdn) {
2395                                        if($cdn->id == "cloudflare"){
2396                                                continue;
2397                                        }
2398
2399                                        if(isset($cdn->status) && $cdn->status == "pause"){
2400                                                continue;
2401                                        }
2402
2403                                        if(preg_match("/manifest\.json\.php/i", $matches[0])){
2404                                                return $matches[0];
2405                                        }
2406
2407                                        //https://site.com?brizy_media=AttachmentName.jpg&brizy_crop=CropSizes&brizy_post=TheCurrentPost
2408                                        if(preg_match("/brizy_media\=/i", $matches[0])){
2409                                                return $matches[0];
2410                                        }
2411
2412                                        //https://cdn.shortpixel.ai/client/q_glossy,ret_img,w_736/http://wpfc.com/stories.png
2413                                        if(preg_match("/cdn\.shortpixel\.ai\/client/i", $matches[0])){
2414                                                return $matches[0];
2415                                        }
2416
2417
2418                                        if(preg_match("/^\/\/random/", $cdn->cdnurl) || preg_match("/\/\/i\d\.wp\.com/", $cdn->cdnurl)){
2419                                                // Photon will no longer be supported
2420                                                continue;
2421                                        }
2422
2423                                        $cdnurl = $cdn->cdnurl;
2424
2425                                        $cdn->file_types = str_replace(",", "|", $cdn->file_types);
2426
2427                                        if(preg_match("/\.(".$cdn->file_types.")(\"|\'|\?|\)|\s|\&quot\;)/i", $matches[0])){
2428                                                //nothing
2429                                        }else{
2430                                                if(preg_match("/js/", $cdn->file_types)){
2431                                                        if(!preg_match("/\/revslider\/public\/assets\/js/", $matches[0])){
2432                                                                continue;
2433                                                        }
2434                                                }else{
2435                                                        continue;
2436                                                }
2437                                        }
2438
2439                                        if($cdn->keywords){
2440                                                $cdn->keywords = str_replace(",", "|", $cdn->keywords);
2441
2442                                                if(!preg_match("/".preg_quote($cdn->keywords, "/")."/i", $matches[0])){
2443                                                        continue;
2444                                                }
2445                                        }
2446
2447                                        if(isset($cdn->excludekeywords) && $cdn->excludekeywords){
2448                                                $cdn->excludekeywords = str_replace(",", "|", $cdn->excludekeywords);
2449
2450                                                if(preg_match("/".preg_quote($cdn->excludekeywords, "/")."/i", $matches[0])){
2451                                                        continue;
2452                                                }
2453                                        }
2454
2455                                        if(preg_match("/(data-product_variations|data-siteorigin-parallax)\=[\"\'][^\"\']+[\"\']/i", $matches[0])){
2456                                                $cdnurl = preg_replace("/(https?\:)?(\/\/)(www\.)?/", "", $cdnurl);
2457
2458                                                // if(preg_match("/i\d\.wp\.com/i", $cdnurl)){
2459                                                //      $matches[0] = preg_replace("/(quot\;|\s)(https?\:)?(\\\\\/\\\\\/|\/\/)(www\.)?".$cdn->originurl."/i", "$1$2$3".$cdnurl, $matches[0]);
2460                                                // }else{
2461                                                //      $matches[0] = preg_replace("/(quot\;|\s)(https?\:)?(\\\\\/\\\\\/|\/\/)(www\.)?".$cdn->originurl."/i", "$1$2$3$4".$cdnurl, $matches[0]);
2462                                                // }
2463
2464                                                $matches[0] = preg_replace("/(quot\;|\s)(https?\:)?(\\\\\/\\\\\/|\/\/)(www\.)?".$cdn->originurl."/i", '${1}${2}${3}'.$cdnurl, $matches[0]);
2465
2466                                               
2467                                        }else if(preg_match("/\{\"concatemoji\"\:\"[^\"]+\"\}/i", $matches[0])){
2468                                                $matches[0] = preg_replace("/(http(s?)\:)?".preg_quote("\/\/", "/")."(www\.)?/i", "", $matches[0]);
2469                                                $matches[0] = preg_replace("/".preg_quote($cdn->originurl, "/")."/i", $cdnurl, $matches[0]);
2470                                        }else if(isset($matches[2]) && preg_match("/".preg_quote($cdn->originurl, "/")."/", $matches[2])){
2471                                                $matches[0] = preg_replace("/(http(s?)\:)?\/\/(www\.)?".preg_quote($cdn->originurl, "/")."/i", $cdnurl, $matches[0]);
2472                                        }else if(isset($matches[2]) && preg_match("/^(\/?)(wp-includes|wp-content)/", $matches[2])){
2473                                                $matches[0] = preg_replace("/(\/?)(wp-includes|wp-content)/i", $cdnurl."/"."$2", $matches[0]);
2474                                        }else if(preg_match("/[\"\']https?\:\\\\\/\\\\\/[^\"\']+[\"\']/i", $matches[0])){
2475                                                if(preg_match("/^(logo|url|image)$/i", $matches[1])){
2476                                                        //If the url is called with "//", it causes an error on https://search.google.com/structured-data/testing-tool/u/0/
2477                                                        //<script type="application/ld+json">"logo":{"@type":"ImageObject","url":"\/\/cdn.site.com\/image.png"}</script>
2478                                                        //<script type="application/ld+json">{"logo":"\/\/cdn.site.com\/image.png"}</script>
2479                                                        //<script type="application/ld+json">{"image":"\/\/cdn.site.com\/image.jpg"}</script>
2480                                                }else{
2481                                                        //<script>var loaderRandomImages=["https:\/\/www.site.com\/wp-content\/uploads\/2016\/12\/image.jpg"];</script>
2482                                                        $matches[0] = preg_replace("/\\\\\//", "/", $matches[0]);
2483                                                       
2484                                                        if(preg_match("/".preg_quote($cdn->originurl, "/")."/", $matches[0])){
2485                                                                $matches[0] = preg_replace("/(http(s?)\:)?\/\/(www\.)?".preg_quote($cdn->originurl, "/")."/i", $cdnurl, $matches[0]);
2486                                                                $matches[0] = preg_replace("/\//", "\/", $matches[0]);
2487                                                        }
2488                                                }
2489                                        }
2490                                }
2491                        }
2492
2493                        return $matches[0];
2494                }
2495
2496                public function read_file($url){
2497                        if(!preg_match("/\.php/", $url)){
2498                                $url = preg_replace("/\?.*/", "", $url);
2499
2500                                if(preg_match("/wp-content/", $url)){
2501                                        $path = preg_replace("/.+\/wp-content\/(.+)/", WPFC_WP_CONTENT_DIR."/"."$1", $url);
2502                                }else if(preg_match("/wp-includes/", $url)){
2503                                        $path = preg_replace("/.+\/wp-includes\/(.+)/", ABSPATH."wp-includes/"."$1", $url);
2504                                }
2505
2506                                if(isset($path)){
2507                                        if(@file_exists($path)){
2508                                                $filesize = filesize($path);
2509
2510                                                if($filesize > 0){
2511                                                        $myfile = fopen($path, "r") or die("Unable to open file!");
2512                                                        $data = fread($myfile, $filesize);
2513                                                        fclose($myfile);
2514
2515                                                        return $data;
2516                                                }else{
2517                                                        return false;
2518                                                }
2519                                        }
2520                                }
2521
2522
2523                        }
2524
2525                        return false;
2526                }
2527
2528                public function get_operating_systems(){
2529                        $operating_systems  = array(
2530                                                                        'Android',
2531                                                                        'blackberry|\bBB10\b|rim\stablet\sos',
2532                                                                        'PalmOS|avantgo|blazer|elaine|hiptop|palm|plucker|xiino',
2533                                                                        'Symbian|SymbOS|Series60|Series40|SYB-[0-9]+|\bS60\b',
2534                                                                        'Windows\sCE.*(PPC|Smartphone|Mobile|[0-9]{3}x[0-9]{3})|Window\sMobile|Windows\sPhone\s[0-9.]+|WCE;',
2535                                                                        'Windows\sPhone\s10.0|Windows\sPhone\s8.1|Windows\sPhone\s8.0|Windows\sPhone\sOS|XBLWP7|ZuneWP7|Windows\sNT\s6\.[23]\;\sARM\;',
2536                                                                        '\biPhone.*Mobile|\biPod|\biPad',
2537                                                                        'Apple-iPhone7C2',
2538                                                                        'MeeGo',
2539                                                                        'Maemo',
2540                                                                        'J2ME\/|\bMIDP\b|\bCLDC\b', // '|Java/' produces bug #135
2541                                                                        'webOS|hpwOS',
2542                                                                        '\bBada\b',
2543                                                                        'BREW'
2544                                                            );
2545                        return $operating_systems;
2546                }
2547
2548                public function get_mobile_browsers(){
2549                        $mobile_browsers  = array(
2550                                                                '\bCrMo\b|CriOS|Android.*Chrome\/[.0-9]*\s(Mobile)?',
2551                                                                '\bDolfin\b',
2552                                                                'Opera.*Mini|Opera.*Mobi|Android.*Opera|Mobile.*OPR\/[0-9.]+|Coast\/[0-9.]+',
2553                                                                'Skyfire',
2554                                                                'Mobile\sSafari\/[.0-9]*\sEdge',
2555                                                                'IEMobile|MSIEMobile', // |Trident/[.0-9]+
2556                                                                'fennec|firefox.*maemo|(Mobile|Tablet).*Firefox|Firefox.*Mobile|FxiOS',
2557                                                                'bolt',
2558                                                                'teashark',
2559                                                                'Blazer',
2560                                                                'Version.*Mobile.*Safari|Safari.*Mobile|MobileSafari',
2561                                                                'Tizen',
2562                                                                'UC.*Browser|UCWEB',
2563                                                                'baiduboxapp',
2564                                                                'baidubrowser',
2565                                                                'DiigoBrowser',
2566                                                                'Puffin',
2567                                                                '\bMercury\b',
2568                                                                'Obigo',
2569                                                                'NF-Browser',
2570                                                                'NokiaBrowser|OviBrowser|OneBrowser|TwonkyBeamBrowser|SEMC.*Browser|FlyFlow|Minimo|NetFront|Novarra-Vision|MQQBrowser|MicroMessenger',
2571                                                                'Android.*PaleMoon|Mobile.*PaleMoon'
2572                                                            );
2573                        return $mobile_browsers;
2574                }
2575
2576
2577        }
2578
2579        // Load WP CLI command(s) on demand.
2580        if ( defined( 'WP_CLI' ) && WP_CLI ) {
2581            require_once "inc/cli.php";
2582        }
2583
2584        function wpfc_clear_all_site_cache(){
2585                if(defined('WPFC_DISABLE_HOOK_CLEAR_ALL_CACHE') && WPFC_DISABLE_HOOK_CLEAR_ALL_CACHE){
2586                        return array("success" => false, "message" => "Clearing Cache Hook system has been disabled");
2587                }
2588
2589                do_action("wpfc_clear_all_cache");
2590        }
2591
2592        function wpfc_clear_all_cache($minified = false){
2593                if(defined('WPFC_DISABLE_HOOK_CLEAR_ALL_CACHE') && WPFC_DISABLE_HOOK_CLEAR_ALL_CACHE){
2594                        return array("success" => false, "message" => "Clearing Cache Hook system has been disabled");
2595                }
2596
2597                do_action("wpfc_clear_all_cache", $minified);
2598        }
2599
2600        function wpfc_exclude_current_page(){
2601                do_action("wpfc_exclude_current_page");
2602        }
2603
2604        function wpfc_clear_post_cache_by_id($post_id = false){
2605                if($post_id){
2606                        do_action("wpfc_clear_post_cache_by_id", false, $post_id);
2607                }
2608        }
2609
2610        function wpfc_create_post_cache_by_id($post_id = false){
2611                if($post_id){
2612                        do_action("wpfc_create_post_cache_by_id", $post_id);
2613                }
2614        }
2615
2616
2617
2618        $GLOBALS["wp_fastest_cache"] = new WpFastestCache();
2619
2620
2621
2622?>
Note: See TracBrowser for help on using the repository browser.