This commit is contained in:
User A0264400
2026-04-19 17:13:54 +03:00
parent c19df05b57
commit 75fa754dba
192 changed files with 39819 additions and 0 deletions

View File

@@ -0,0 +1,131 @@
<?php
class WpFastestCacheAdminToolbar{
private $is_multi = false;
public function __construct($is_multi){
$this->is_multi = $is_multi;
}
public function add(){
if(is_admin()){
add_action('wp_before_admin_bar_render', array($this, "wpfc_tweaked_toolbar_on_admin_panel"));
add_action('admin_enqueue_scripts', array($this, 'load_toolbar_js'));
add_action('admin_enqueue_scripts', array($this, 'load_toolbar_css'));
add_action('wp_print_scripts', array($this, 'print_my_inline_script'));
}else{
if(is_admin_bar_showing()){
add_action('wp_before_admin_bar_render', array($this, "wpfc_tweaked_toolbar_on_frontpage"));
add_action('wp_enqueue_scripts', array($this, 'load_toolbar_js'));
add_action('wp_enqueue_scripts', array($this, 'load_toolbar_css'));
add_action('wp_footer', array($this, 'print_my_inline_script'));
}
}
}
public function load_toolbar_js(){
wp_enqueue_script("wpfc-toolbar", plugins_url("wp-fastest-cache/js/toolbar.js"), array('jquery'), time(), true);
}
public function load_toolbar_css(){
wp_enqueue_style("wp-fastest-cache-toolbar", plugins_url("wp-fastest-cache/css/toolbar.css"), array(), time(), "all");
}
public function print_my_inline_script() {
$script = "
var wpfc_ajaxurl = '" . admin_url('admin-ajax.php') . "';
var wpfc_nonce = '" . wp_create_nonce("wpfc") . "';
";
echo wp_print_inline_script_tag($script);
}
public function wpfc_tweaked_toolbar_on_frontpage() {
global $wp_admin_bar;
$wp_admin_bar->add_node(array(
'id' => 'wpfc-toolbar-parent',
'title' => 'WP Fastest Cache',
'href' => admin_url( 'admin.php?page=wpfastestcacheoptions')
));
$wp_admin_bar->add_menu( array(
'id' => 'wpfc-toolbar-parent-clear-cache-of-this-page',
'title' => 'Clear Cache of This Page',
'parent'=> 'wpfc-toolbar-parent',
'href' => '#',
'meta' => array("class" => "wpfc-toolbar-child")
));
$wp_admin_bar->add_menu( array(
'id' => 'wpfc-toolbar-parent-delete-cache',
'title' => __("Clear All Cache", "wp-fastest-cache"),
'parent'=> 'wpfc-toolbar-parent',
'href' => '#',
'meta' => array("class" => "wpfc-toolbar-child")
));
$wp_admin_bar->add_menu( array(
'id' => 'wpfc-toolbar-parent-delete-cache-and-minified',
'title' => 'Clear Cache and Minified CSS/JS',
'parent'=> 'wpfc-toolbar-parent',
'href' => '#',
'meta' => array("class" => "wpfc-toolbar-child")
));
if($this->is_multi){
$wp_admin_bar->add_menu( array(
'id' => 'wpfc-toolbar-parent-clear-cache-of-allsites',
'title' => __("Clear Cache of All Sites", "wp-fastest-cache"),
'parent'=> 'wpfc-toolbar-parent',
'href' => '#',
'meta' => array("class" => "wpfc-toolbar-child")
));
}
}
public function wpfc_tweaked_toolbar_on_admin_panel() {
global $wp_admin_bar;
$wp_admin_bar->add_node(array(
'id' => 'wpfc-toolbar-parent',
'title' => 'WP Fastest Cache',
'href' => admin_url( 'admin.php?page=wpfastestcacheoptions')
));
$wp_admin_bar->add_menu( array(
'id' => 'wpfc-toolbar-parent-delete-cache',
'title' => __("Clear All Cache", "wp-fastest-cache"),
'parent'=> 'wpfc-toolbar-parent',
'href' => '#',
'meta' => array("class" => "wpfc-toolbar-child")
));
$wp_admin_bar->add_menu( array(
'id' => 'wpfc-toolbar-parent-delete-cache-and-minified',
'title' => __("Clear Cache and Minified CSS/JS", "wp-fastest-cache"),
'parent'=> 'wpfc-toolbar-parent',
'href' => '#',
'meta' => array("class" => "wpfc-toolbar-child")
));
if($this->is_multi){
$wp_admin_bar->add_menu( array(
'id' => 'wpfc-toolbar-parent-clear-cache-of-allsites',
'title' => __("Clear Cache of All Sites", "wp-fastest-cache"),
'parent'=> 'wpfc-toolbar-parent',
'href' => '#',
'meta' => array("class" => "wpfc-toolbar-child")
));
}
if(isset($_GET["page"]) && $_GET["page"] == "wpfastestcacheoptions"){
$wp_admin_bar->add_menu( array(
'id' => 'wpfc-toolbar-parent-settings',
'title' => __("Toolbar Settings", "wp-fastest-cache"),
'parent'=> 'wpfc-toolbar-parent',
'href' => '#',
'meta' => array("class" => "wpfc-toolbar-child")
));
}
}
}
?>

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,651 @@
<?php
class CdnWPFC{
public static function cloudflare_generate_header($email, $key){
if($email == "wpfc"){
$header = array(
"Authorization" => "Bearer ".$key,
"Content-Type" => "application/json"
);
}else{
$header = array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
);
}
return $header;
}
public static function cloudflare_clear_cache($email = false, $key = false, $zoneid = false){
if(isset($GLOBALS["wpfc_cloudflare_purge_cache_executed"])){
return;
}
if(!$key && !$zoneid){
if($cdn_values = get_option("WpFastestCacheCDN")){
$std_obj = json_decode($cdn_values);
foreach ($std_obj as $key => $value) {
if($value->id == "cloudflare"){
$email = $value->cdnurl;
$key = $value->originurl;
break;
}
}
if($key){
$zone = self::cloudflare_get_zone_id($email, $key, false);
if($zone["success"]){
$zoneid = $zone["zoneid"];
}
}
}
}
if($key && $zoneid){
$header = array("method" => "DELETE",
'headers' => self::cloudflare_generate_header($email, $key),
"body" => '{"purge_everything":true}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/purge_cache', $header);
if(!$response || is_wp_error($response)){
return array("success" => false, "error_message" => "Unable to disable rocket loader option");
}else{
$body = json_decode(wp_remote_retrieve_body($response));
if(!$body->success){
CdnWPFC::cloudflare_delete_zone_id_value();
}else{
$GLOBALS["wpfc_cloudflare_purge_cache_executed"] = true;
}
}
}
}
public static function cloudflare_disable_rocket_loader($email = false, $key = false, $zoneid = false){
if($key && $zoneid){
$header = array("method" => "PATCH",
'timeout' => 10,
'headers' => self::cloudflare_generate_header($email, $key),
'body' => '{"value":"off"}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/settings/rocket_loader', $header);
if(!$response || is_wp_error($response)){
return array("success" => false, "error_message" => "Unable to disable rocket loader option");
}else{
$body = json_decode(wp_remote_retrieve_body($response));
if($body->success){
return array("success" => true);
}else if(isset($body->errors) && isset($body->errors[0])){
return array("success" => false, "error_message" => $body->errors[0]->message);
}else{
return array("success" => false, "error_message" => "Unknown error: 101");
}
}
return array("success" => false, "error_message" => "Unknown error");
}
}
public static function cloudflare_set_browser_caching($email = false, $key = false, $zoneid = false){
if($key && $zoneid){
$header = array("method" => "PATCH",
'timeout' => 10,
'headers' => self::cloudflare_generate_header($email, $key),
'body' => '{"value":16070400}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/settings/browser_cache_ttl', $header);
if(!$response || is_wp_error($response)){
return array("success" => false, "error_message" => "Unable to set the browser caching option");
}else{
$body = json_decode(wp_remote_retrieve_body($response));
if($body->success){
return array("success" => true);
}else if(isset($body->errors) && isset($body->errors[0])){
return array("success" => false, "error_message" => $body->errors[0]->message);
}else{
return array("success" => false, "error_message" => "Unknown error: 101");
}
}
return array("success" => false, "error_message" => "Unknown error");
}
}
public static function cloudflare_disable_minify($email = false, $key = false, $zoneid = false){
// Deprecated
// https://developers.cloudflare.com/speed/optimization/content/auto-minify/
return array("success" => true);
if($key && $zoneid){
$header = array("method" => "PATCH",
'timeout' => 10,
'headers' => self::cloudflare_generate_header($email, $key),
'body' => '{"value":{"css":"off","html":"off","js":"off"}}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/settings/minify', $header);
if(!$response || is_wp_error($response)){
return array("success" => false, "error_message" => "Unable to disable minify options");
}else{
$body = json_decode(wp_remote_retrieve_body($response));
if($body->success){
return array("success" => true);
}else if(isset($body->errors) && isset($body->errors[0])){
return array("success" => false, "error_message" => $body->errors[0]->message);
}else{
return array("success" => false, "error_message" => "Unknown error: 101");
}
}
return array("success" => false, "error_message" => "Unknown error");
}else{
wp_die("bad request");
}
}
public static function cloudflare_get_zone_id($email = false, $key = false){
$cache_zone_id = CdnWPFC::cloudflare_get_zone_id_value();
if($cache_zone_id){
return $cache_zone_id;
}
if(substr_count($_SERVER["HTTP_HOST"], ".") == 1){
$hostname = preg_replace("/^(https?\:\/\/)/", "", $_SERVER["HTTP_HOST"]);
}else{
$hostname = preg_replace("/^(https?\:\/\/)?(www\d*\.)?/", "", $_SERVER["HTTP_HOST"]);
}
if(extension_loaded('intl') && function_exists("idn_to_utf8")){
$hostname = idn_to_utf8($hostname);
}
$header = array(
"method" => "GET",
'headers' => self::cloudflare_generate_header($email, $key)
);
$all_zones = [];
// Request page 1 and page 2
for ($page = 1; $page <= 2; $page++) {
$response = wp_remote_request("https://api.cloudflare.com/client/v4/zones/?page=$page&per_page=1000", $header);
if (!$response || is_wp_error($response)) {
return array("success" => false, "error_message" => $response->get_error_message());
}
$zone = json_decode(wp_remote_retrieve_body($response));
if (isset($zone->errors) && isset($zone->errors[0])) {
$error_message = $zone->errors[0]->message;
if (isset($zone->errors[0]->error_chain[0])) {
$error_message = $zone->errors[0]->error_chain[0]->message;
}
return array("success" => false, "error_message" => $error_message);
}
if (isset($zone->result)) {
$all_zones = array_merge($all_zones, $zone->result);
}
}
// Search for the matching zone
foreach ($all_zones as $zone_value) {
if (preg_match("/" . preg_quote($zone_value->name, '/') . "/", $hostname)) {
$res = array(
"success" => true,
"zoneid" => $zone_value->id,
"plan" => $zone_value->plan->legacy_id
);
CdnWPFC::cloudflare_save_zone_id_value($res);
return $res;
}
}
return array("success" => false, "error_message" => "No zone name " . $hostname);
}
public static function cloudflare_get_zone_id_value(){
if($data = get_option("WpFastestCacheCDN")){
$arr = json_decode($data);
if(is_array($arr)){
foreach ($arr as $cdn_key => $cdn_value) {
if($cdn_value->id == "cloudflare" && isset($cdn_value->zone_id)){
return unserialize($cdn_value->zone_id);
}
}
}
}
return false;
}
public static function cloudflare_delete_zone_id_value(){
if($data = get_option("WpFastestCacheCDN")){
$arr = json_decode($data);
if(is_array($arr)){
foreach ($arr as $cdn_key => $cdn_value) {
if($cdn_value->id == "cloudflare"){
if(isset($cdn_value->zone_id)){
unset($cdn_value->zone_id);
}
}
}
update_option("WpFastestCacheCDN", json_encode($arr));
}
}
}
public static function cloudflare_save_zone_id_value($value){
if($data = get_option("WpFastestCacheCDN")){
$arr = json_decode($data);
if(is_array($arr)){
foreach ($arr as $cdn_key => &$cdn_value) {
if($cdn_value->id == "cloudflare"){
$value["time"] = time();
$cdn_value->zone_id = serialize($value);
}
}
update_option("WpFastestCacheCDN", json_encode($arr));
}
}
}
public static function cloudflare_remove_webp(){
$path = ABSPATH.".htaccess";
if(file_exists($path)){
if(is_writable($path)){
$htaccess = file_get_contents($path);
$htaccess = preg_replace("/#\s?BEGIN\s?WEBPWpFastestCache.*?#\s?END\s?WEBPWpFastestCache/s", "", $htaccess);
file_put_contents($path, $htaccess);
}
}
}
public static function cloudflare_change_settings(){
//admin OR author OR editor
if(current_user_can('manage_options') || current_user_can('delete_published_posts') || current_user_can('edit_published_posts')){
if(isset($_GET["url"]) && isset($_GET["origin_url"])){
$email = sanitize_text_field($_GET["url"]);
$key = sanitize_text_field($_GET["origin_url"]);
}
$zone = CdnWPFC::cloudflare_get_zone_id($email, $key);
if($zone["success"]){
$minify = CdnWPFC::cloudflare_disable_minify($email, $key, $zone["zoneid"]);
$rocket_loader = CdnWPFC::cloudflare_disable_rocket_loader($email, $key, $zone["zoneid"]);
$purge_cache = CdnWPFC::cloudflare_clear_cache($email, $key, $zone["zoneid"]);
$browser_caching = CdnWPFC::cloudflare_set_browser_caching($email, $key, $zone["zoneid"]);
if($zone["plan"] == "free"){
CdnWPFC::cloudflare_remove_webp();;
}
if($minify["success"]){
if($rocket_loader["success"]){
if($browser_caching["success"]){
$res = array("success" => true);
}else{
$res = array("success" => false, "error_message" => $browser_caching["error_message"]);
}
}else{
$res = array("success" => false, "error_message" => $rocket_loader["error_message"]);
}
}else{
$res = array("success" => false, "error_message" => $minify["error_message"]);
}
}else{
$res = $zone;
}
wp_send_json($res);
}else{
wp_die("Must be admin");
}
}
public static function check_url(){
if(current_user_can('manage_options')){
if(isset($_GET["type"]) && $_GET["type"] == "cloudflare"){
CdnWPFC::cloudflare_change_settings();
}
if(preg_match("/wp\.com/", $_GET["url"]) || $_GET["url"] == "random"){
wp_send_json(array("success" => true));
}
if(
// IPv6
preg_match("/\:\:/", $_GET["url"]) ||
// decimal
(preg_match("/\d{10}/", $_GET["url"]) && !preg_match("/\./", $_GET["url"])) ||
// hex
(preg_match("/0x[0-9a-fA-F]{1,8}/", $_GET["url"]) && !preg_match("/\./", $_GET["url"])) ||
preg_match("/0x[0-9a-fA-F]{1,2}\.0x[0-9a-fA-F]{1,2}\.0x[0-9a-fA-F]{1,2}\.0x[0-9a-fA-F]{1,2}/", $_GET["url"]) ||
// octal
preg_match("/(https?\:\/\/)?[0-9]{4,5}\.[0-9]{1,5}\.[0-9]{1,5}\.[0-9]{1,5}/", $_GET["url"]) ||
// localhost
preg_match("/(\/\/)?localhost/i", $_GET["url"]) ||
preg_match("/(https?\:\/\/)?(127|10|172|169|100|198|192)\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $_GET["url"])
){
$res = array("success" => false, "error_message" => "Localhost is not allowed");
wp_send_json($res);
}
$host = str_replace("www.", "", $_SERVER["HTTP_HOST"]);
$_GET["url"] = esc_url_raw($_GET["url"]);
if(!preg_match("/^http/", $_GET["url"])){
$_GET["url"] = "http://".$_GET["url"];
}
if(preg_match("/^https/i", site_url()) && preg_match("/^https/i", home_url())){
$_GET["url"] = preg_replace("/http\:\/\//i", "https://", $_GET["url"]);
}
$response = wp_safe_remote_get($_GET["url"], array('timeout' => 20, 'redirection' => 0, 'user-agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36"));
$header = wp_remote_retrieve_headers($response);
if ( !$response || is_wp_error( $response ) ) {
$res = array("success" => false, "error_message" => esc_html($response->get_error_message()) );
if($response->get_error_code() == "http_request_failed"){
if(esc_html($response->get_error_message()) == "Failure when receiving data from the peer"){
$res = array("success" => true);
}else if(preg_match("/cURL\serror\s60/i", esc_html($response->get_error_message()) )){
//cURL error 60: SSL: no alternative certificate subject name matches target host name
$res = array("success" => false, "error_message" => "<a href='https://www.wpfastestcache.com/warnings/how-to-use-cdn-on-ssl-sites/' target='_blank'>Please Read: https://www.wpfastestcache.com/warnings/how-to-use-cdn-on-ssl-sites/</a>");
}else if(preg_match("/cURL\serror\s6/i", esc_html($response->get_error_message()) )){
//cURL error 6: Couldn't resolve host
if(preg_match("/".preg_quote($host, "/")."/i", $_GET["url"])){
$res = array("success" => true);
}
}
}
}else{
$response_code = wp_remote_retrieve_response_code( $response );
if($response_code == 200){
$res = array("success" => true);
}else{
if (is_object($response) && method_exists($response, "get_error_message")) {
$res = array("success" => false, "error_message" => esc_html($response->get_error_message()) );
}else{
$res = array("success" => false, "error_message" => esc_html(wp_remote_retrieve_response_message($response)) );
}
if(isset($header["server"]) && preg_match("/squid/i", $header["server"])){
$res = array("success" => true);
}
if(($response_code == 400) && (preg_match("/speedsize\.com/i", $_GET["url"]))){
$res = array("success" => true);
}
if(($response_code == 401) && (preg_match("/res\.cloudinary\.com/i", $_GET["url"]))){
$res = array("success" => true);
}
if(($response_code == 403) && (preg_match("/stackpathdns\.com/i", $_GET["url"]))){
$res = array("success" => true);
}
if(($response_code == 403) && (preg_match("/cloudfront\.net/i", $_GET["url"]))){
$res = array("success" => false, "error_message" => "<a href='https://www.wpfastestcache.com/blog/how-to-fix-403-access-denied-errors-during-cdn-integration/#wpft-amazon-cloudfront' target='_blank'>Please Read: Amazon CloudFront 403 Error</a>");
}
if(($response_code == 403) && (preg_match("/b\-cdn\.net/i", $_GET["url"]))){
$res = array("success" => false, "error_message" => "<a href='https://www.wpfastestcache.com/blog/how-to-fix-403-access-denied-errors-during-cdn-integration/#wpft-bunny-cdn' target='_blank'>Please Read: BunnyCDN 403 Error</a>");
}
}
}
wp_send_json($res);
}else{
wp_die("Must be admin");
}
}
public static function cdn_options(){
if(current_user_can('manage_options')){
$cdn_values = get_option("WpFastestCacheCDN");
if($cdn_values){
echo $cdn_values;
}else{
echo json_encode(array("success" => false));
}
exit;
}else{
wp_die("Must be admin");
}
}
public static function start_cdn_integration(){
if(current_user_can('manage_options')){
$cdn_values = get_option("WpFastestCacheCDN");
if($cdn_values){
$std_obj = json_decode($cdn_values);
$cdn_values_arr = array();
if(is_array($std_obj)){
$cdn_values_arr = $std_obj;
}else{
array_push($cdn_values_arr, $std_obj);
}
foreach ($cdn_values_arr as $cdn_key => $cdn_value) {
if($cdn_value->id == "amazonaws" || $cdn_value->id == "keycdn" || $cdn_value->id == "cdn77"){
$cdn_value->id = "other";
}
if($cdn_value->id == $_POST["id"]){
unset($cdn_value->status);
}
}
$cdn_values_arr = array_values($cdn_values_arr);
update_option("WpFastestCacheCDN", json_encode($cdn_values_arr));
}
echo json_encode(array("success" => true));
exit;
}else{
wp_die("Must be admin");
}
}
public static function pause_cdn_integration(){
if(current_user_can('manage_options')){
$cdn_values = get_option("WpFastestCacheCDN");
if($cdn_values){
$std_obj = json_decode($cdn_values);
$cdn_values_arr = array();
if(is_array($std_obj)){
$cdn_values_arr = $std_obj;
}else{
array_push($cdn_values_arr, $std_obj);
}
foreach ($cdn_values_arr as $cdn_key => $cdn_value) {
if($cdn_value->id == "amazonaws" || $cdn_value->id == "keycdn" || $cdn_value->id == "cdn77"){
$cdn_value->id = "other";
}
if($cdn_value->id == $_POST["id"]){
$cdn_value->status = "pause";
}
}
$cdn_values_arr = array_values($cdn_values_arr);
update_option("WpFastestCacheCDN", json_encode($cdn_values_arr));
}
echo json_encode(array("success" => true));
exit;
}else{
wp_die("Must be admin");
}
}
public static function remove_cdn_integration(){
if(current_user_can('manage_options')){
$cdn_values = get_option("WpFastestCacheCDN");
if($cdn_values){
$std_obj = json_decode($cdn_values);
$cdn_values_arr = array();
if(is_array($std_obj)){
$cdn_values_arr = $std_obj;
}else{
array_push($cdn_values_arr, $std_obj);
}
foreach ($cdn_values_arr as $cdn_key => $cdn_value) {
if($cdn_value->id == "amazonaws" || $cdn_value->id == "keycdn" || $cdn_value->id == "cdn77"){
$cdn_value->id = "other";
}
if($cdn_value->id == $_POST["id"]){
unset($cdn_values_arr[$cdn_key]);
}
}
$cdn_values_arr = array_values($cdn_values_arr);
}
if(count($cdn_values_arr) > 0){
update_option("WpFastestCacheCDN", json_encode($cdn_values_arr));
}else{
delete_option("WpFastestCacheCDN");
}
echo json_encode(array("success" => true));
exit;
}else{
wp_die("Must be admin");
}
}
public static function cdn_template(){
if(current_user_can('manage_options')){
if($_POST["id"] == "maxcdn"){
$path = WPFC_MAIN_PATH."templates/cdn/maxcdn.php";
}else if($_POST["id"] == "other"){
$path = WPFC_MAIN_PATH."templates/cdn/other.php";
}else if($_POST["id"] == "cloudflare"){
$path = WPFC_MAIN_PATH."templates/cdn/cloudflare.php";
}else{
die("Wrong cdn");
}
ob_start();
include_once($path);
$content = ob_get_contents();
ob_end_clean();
$res = array("success" => false, "content" => "");
if($data = @file_get_contents($path)){
$res["success"] = true;
$res["content"] = $content;
}
echo json_encode($res);
exit;
}else{
wp_die("Must be admin");
}
}
public static function save_cdn_integration(){
if(current_user_can('manage_options') && wp_verify_nonce($_POST["nonce"], "cdn-nonce")){
$values = array();
if(isset($_POST) && isset($values)){
foreach ($_POST["values"] as $val_key => $val_value) {
$values[$val_key] = sanitize_text_field($val_value);
}
}
if($data = get_option("WpFastestCacheCDN")){
$cdn_exist = false;
$arr = json_decode($data);
if(is_array($arr)){
foreach ($arr as $cdn_key => &$cdn_value) {
if($cdn_value->id == $values["id"]){
$cdn_value = $values;
$cdn_exist = true;
}
}
if(!$cdn_exist){
array_push($arr, $values);
}
update_option("WpFastestCacheCDN", json_encode($arr));
}else{
$tmp_arr = array();
if($arr->id == $values["id"]){
array_push($tmp_arr, $values);
}else{
array_push($tmp_arr, $arr);
array_push($tmp_arr, $values);
}
update_option("WpFastestCacheCDN", json_encode($tmp_arr));
}
}else{
$arr = array();
array_push($arr, $values);
add_option("WpFastestCacheCDN", json_encode($arr), null, "yes");
}
echo json_encode(array("success" => true));
exit;
}else{
wp_die("Must be admin");
}
}
}
?>

View File

@@ -0,0 +1,118 @@
<?php
class ClearingSpecificPagesWPFC{
public static function remove(){
if(!wp_verify_nonce($_POST["security"], 'wpfc-save-csp-ajax-nonce')){
die( 'Security check' );
}
$_POST["order"] = sanitize_text_field($_POST["order"]);
$urls = get_option("WpFastestCacheCSP");
if(!empty($urls)){
foreach ($urls as $key => $value) {
if($value->order == ($_POST["order"])){
unset($urls[$key]);
}
}
}
if(empty($urls)){
delete_option("WpFastestCacheCSP");
}else{
update_option("WpFastestCacheCSP", $urls, 1, "no");
}
wp_send_json_success();
}
public static function check_url(){
$home_url = parse_url(get_option("home"), PHP_URL_HOST);
$specific_url = parse_url($_POST["url"], PHP_URL_HOST);
if($home_url == $specific_url){
return true;
}
return false;
}
public static function check_wild_card(){
if(preg_match("/[^\/]\(\.\*\)/", $_POST["url"])){
return false;
}
if(substr_count($_POST["url"], "(.*)") > 1){
return false;
}
return true;
}
public static function save(){
if(!wp_verify_nonce($_POST["security"], 'wpfc-save-csp-ajax-nonce')){
die( 'Security check' );
}
if(!self::check_url()){
wp_send_json_error("The URL must start with ".parse_url(get_option("home"), PHP_URL_SCHEME)."//".parse_url(get_option("home"), PHP_URL_HOST));
}
if(!self::check_wild_card()){
wp_send_json_error("Wrong Wild Card Usage");
}
if(preg_match("/\.{2,}/", $_POST["url"])){
wp_send_json_error("May be Directory Traversal Attack");
}
$_POST["url"] = sanitize_url($_POST["url"]);
$_POST["order"] = sanitize_text_field($_POST["order"]);
$urls = get_option("WpFastestCacheCSP");
$url = (object)array("url" => $_POST["url"], "order" => $_POST["order"]);
if(!is_array($urls)){
$urls = array();
array_push($urls, $url);
add_option("WpFastestCacheCSP", $urls, 1, "no");
}else{
$is_update = false;
foreach ($urls as $key => &$value) {
if($value->order == ($_POST["order"])){
$is_update = true;
$value->url = $_POST["url"];
}
}
if(!$is_update){
array_push($urls, $url);
}
update_option("WpFastestCacheCSP", $urls, 1, "no");
}
wp_send_json_success();
}
public static function get_list(){
if(!wp_verify_nonce($_POST["security"], 'wpfc-save-csp-ajax-nonce')){
die( 'Security check' );
}
$urls = get_option("WpFastestCacheCSP");
if(!is_array($urls)){
$urls = array();
}
wp_send_json_success($urls);
}
}
?>

View File

@@ -0,0 +1,86 @@
<?php
/**
* WP-CLI commands for WP Fastest Cache.
*/
if(!defined('ABSPATH')){
exit;
}
// This is a WP-CLI command, so bail if it's not available.
if(!defined('WP_CLI')){
return;
}
class wpfcCLI extends \WP_CLI_Command
{
/**
* Clears the cache.
*
* ## EXAMPLES
* wp fastest-cache clear all
* wp fastest-cache clear all and minified
*
*
* @subcommand clear
*
* @param array $args Args.
* @param array $args_assoc Associative args.
*
* @return void
*/
public function wrong_usage(){
$message = array("*************************************************************************",
"* Wrong usage! *",
"* Please read: https://www.wpfastestcache.com/features/wp-cli-commands/ *",
"*************************************************************************");
WP_CLI::error_multi_line($message);
}
public function clear($args, $args_assoc){
if(isset($GLOBALS['wp_fastest_cache'])){
if(method_exists($GLOBALS['wp_fastest_cache'], 'deleteCache')){
if(isset($args_assoc["post_id"])){
$post_ids = explode(',' , $args_assoc['post_id'] );
foreach($post_ids as $post_id){
WP_CLI::line("Clearing the cache of the post with ID number ".$post_id);
$GLOBALS['wp_fastest_cache']->singleDeleteCache(false, $post_id);
WP_CLI::success("The cache has been cleared!");
}
}else if(isset($args[0])){
if($args[0] == "all"){
if(isset($args[1]) && isset($args[2])){
if($args[1] == "and" && $args[2] == "minified"){
WP_CLI::line("Clearing the ALL cache...");
$GLOBALS['wp_fastest_cache']->deleteCache(true);
WP_CLI::success("The cache has been cleared!");
}else{
self::wrong_usage();
}
}else{
WP_CLI::line("Clearing the ALL cache...");
$GLOBALS['wp_fastest_cache']->deleteCache();
WP_CLI::success("The cache has been cleared!");
}
}else{
self::wrong_usage();
}
}else{
self::wrong_usage();
}
}else{
WP_CLI::error("deleteCache() does not exist!");
}
}else{
WP_CLI::error("GLOBALS['wp_fastest_cache'] has not been defined!");
}
}
}
WP_CLI::add_command( 'fastest-cache', 'wpfcCLI' );
?>

View File

@@ -0,0 +1,33 @@
<?php
class WpFastestCacheColumn{
public function __construct(){}
public function add(){
add_filter('post_row_actions', array($this, 'add_clear_cache_link'), 10, 2);
add_filter('page_row_actions', array($this, 'add_clear_cache_link'), 10, 2);
add_action('admin_enqueue_scripts', array($this, 'load_js'));
add_action('wp_ajax_wpfc_clear_cache_column', array($this, "clear_cache_column"));
}
public function add_clear_cache_link($actions, $post){
$actions['clear_cache_link'] = '<a data-id="'.$post->ID.'" data-nonce="'.wp_create_nonce('clear-cache_'.$post->ID).'" id="wpfc-clear-cache-link-'.$post->ID.'" style="cursor:pointer;">' . __('Clear Cache') . '</a>';
return $actions;
}
public function clear_cache_column(){
if(wp_verify_nonce($_GET["nonce"], 'clear-cache_'.$_GET["id"])){
$GLOBALS["wp_fastest_cache"]->singleDeleteCache(false, esc_sql($_GET["id"]));
die(json_encode(array("success" => true)));
}else{
die(json_encode(array("success" => false)));
}
}
public function load_js(){
wp_enqueue_script("wpfc-column", plugins_url("wp-fastest-cache/js/column.js"), array(), time(), true);
}
}
?>

View File

@@ -0,0 +1,767 @@
<?php
class CssUtilities{
private $html = "";
private $tags = array();
private $except = "";
private $wpfc;
private $url = "";
private $url_for_fix = "";
public function __construct($wpfc, $html){
$this->wpfc = $wpfc;
$this->html = $html;
$this->set_except_tags();
$this->set_tags();
$this->tags_reorder();
}
public function check_exclude($css_url = false){
if($css_url){
// to exclude the css source of elementor which is /elementor/css/post-[number].css to avoid increasing the size of minified sources
if(preg_match("/\/elementor\/css\/post-\d+\.css/i", $css_url)){
return true;
}
foreach((array)$this->wpfc->exclude_rules as $key => $value){
if(isset($value->prefix) && $value->prefix && $value->type == "css"){
if($value->prefix == "contain"){
$preg_match_rule = preg_quote($value->content, "/");
}
if(preg_match("/".$preg_match_rule."/i", $css_url)){
return true;
}
}
}
}
}
public function combineCss(){
$all = array();
$group = array();
foreach ($this->tags as $key => $value) {
if(preg_match("/<link/i", $value["text"])){
if($this->except){
if(strpos($this->except, $value["text"]) !== false){
array_push($all, $group);
$group = array();
continue;
}
}
if(!$this->checkInternal($value["text"])){
array_push($all, $group);
$group = array();
continue;
}
if($this->check_exclude($value["text"])){
array_push($all, $group);
$group = array();
continue;
}
if(count($group) > 0){
if($group[0]["media"] == $value["media"]){
array_push($group, $value);
}else{
array_push($all, $group);
$group = array();
array_push($group, $value);
}
}else{
array_push($group, $value);
}
if($value === end($this->tags)){
array_push($all, $group);
}
}
if(preg_match("/<style/i", $value["text"])){
if(count($group) > 0){
array_push($all, $group);
$group = array();
}
}
}
if(count($all) > 0){
$all = array_reverse($all);
foreach ($all as $group_key => $group_value) {
if(count($group_value) > 0){
$combined_css = "";
$combined_name = $this->wpfc->create_name($group_value);
$combined_link = "";
$cachFilePath = $this->wpfc->getWpContentDir("/cache/wpfc-minified")."/".$combined_name;
$cssLink = $this->convert_path_to_link($cachFilePath);
if(is_dir($cachFilePath)){
if($cssFiles = @scandir($cachFilePath, 1)){
$combined_link = '<link rel="stylesheet" type="text/css" href="'.$cssLink."/".$cssFiles[0].'" media="'.$group_value[0]["media"].'"/>';
if($css_content = $this->wpfc->read_file($cssLink."/".$cssFiles[0])){
$css_content = $this->apply_filter($css_content);
$combined_link = $this->to_inline($combined_link, $css_content);
}
}
}else{
$combined_css = $this->create_content(array_reverse($group_value));
$combined_css = $this->fix_charset($combined_css);
if($combined_css){
if($this->wpfc->cdn){
$combined_css = preg_replace_callback("/(url)\(([^\)]+)\)/i", array($this->wpfc, 'cdn_replace_urls'), $combined_css);
}
$this->wpfc->createFolder($cachFilePath, $combined_css, "css");
if(is_dir($cachFilePath)){
if($cssFiles = @scandir($cachFilePath, 1)){
$combined_link = '<link rel="stylesheet" type="text/css" href="'.$cssLink."/".$cssFiles[0].'" media="'.$group_value[0]["media"].'"/>';
$combined_css = $this->apply_filter($combined_css);
$combined_link = $this->to_inline($combined_link, $combined_css);
}
}
}
}
if($combined_link){
foreach (array_reverse($group_value) as $tag_key => $tag_value) {
$text = substr($this->html, $tag_value["start"], ($tag_value["end"]-$tag_value["start"] + 1));
if($tag_key > 0){
$this->html = substr_replace($this->html, "<!-- ".$text." -->", $tag_value["start"], ($tag_value["end"] - $tag_value["start"] + 1));
}else{
$this->html = substr_replace($this->html, "<!-- ".$text." -->"."\n".$combined_link, $tag_value["start"], ($tag_value["end"] - $tag_value["start"] + 1));
}
}
}
}
}
}
return $this->html;
}
public function create_content($group_value){
$combined_css = "";
foreach ($group_value as $tag_key => $tag_value) {
$minifiedCss = $this->minify($tag_value["href"]);
if($minifiedCss){
$combined_css = $minifiedCss["cssContent"].$combined_css;
}else{
return false;
}
}
return $combined_css;
}
public function minifyCss(){
$data = $this->html;
if(count($this->tags) > 0){
foreach (array_reverse($this->tags) as $key => $value) {
$text = substr($data, $value["start"], ($value["end"]-$value["start"] + 1));
if(preg_match("/<link/i", $text)){
if($href = $this->checkInternal($text)){
if($this->check_exclude($href)){
continue;
}
$minifiedCss = $this->minify($href);
if($minifiedCss){
$prefixLink = str_replace(array("http:", "https:"), "", $minifiedCss["url"]);
$text = preg_replace("/href\=[\"\'][^\"\']+[\"\']/", "href='".$prefixLink."'", $text);
$minifiedCss["cssContent"] = $this->apply_filter($minifiedCss["cssContent"]);
$text = $this->to_inline($text, $minifiedCss["cssContent"]);
$this->html = substr_replace($this->html, $text, $value["start"], ($value["end"] - $value["start"] + 1));
}
}
}
}
}
return $this->html;
}
public function to_inline($link, $css_content){
if(!isset($GLOBALS["wp_fastest_cache_options"]->wpFastestCacheRenderBlocking)){
return $link;
}
if(!preg_match("/\smedia\=[\'\"]all[\'\"]/i", $link)){
return $link;
}
if(isset($css_content["11000"])){
return $link;
}
$link = "<style>".$css_content."</style>";
return $link;
}
public function tags_reorder(){
$sorter = array();
$ret = array();
foreach ($this->tags as $ii => $va) {
$sorter[$ii] = $va['start'];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii] = $this->tags[$ii];
}
$this->tags = $ret;
}
public function set_except_tags(){
$comment_tags = $this->find_tags("<!--", "-->");
foreach ($comment_tags as $key => $value) {
$this->except = $value["text"].$this->except;
}
// to execute if html contains <noscript> tag
if(preg_match("/<noscript/i", $this->html)){
$noscript_tags = $this->find_tags("<noscript", "</noscript>");
foreach ($noscript_tags as $key => $value) {
$this->except = $value["text"].$this->except;
if(isset($GLOBALS["wp_fastest_cache_options"]->wpFastestCacheLazyLoad)){
// to set noscript for lazy load
// <noscript><img src="http://google.com/image.jpg"></noscript>
$GLOBALS["wp_fastest_cache"]->noscript = $value["text"].$GLOBALS["wp_fastest_cache"]->noscript;
}
}
}
// $("head").append( "<link rel='stylesheet' id='ms-fonts' href='//fonts.googleapis.com/css?family=Exo+2:regular' type='text/css' media='all' />" );
$script_tags = $this->find_tags("<script", "</script>");
foreach ($script_tags as $key => $value) {
$link_tags = $this->find_tags("<link", ">", $value["text"]);
if(count($link_tags) > 0){
$this->except = $value["text"].$this->except;
}
}
}
public function set_tags(){
$style_tags = $this->find_tags("<style", "</style>");
$this->tags = array_merge($this->tags, $style_tags);
$link_tags = $this->find_tags("<link", ">");
foreach ($link_tags as $key => $value) {
//<link rel='stylesheet' id='avada-dynamic-css-css' href='/wp-content/uploads/avada-styles/avada-9.css?timestamp=1485306359&#038;ver=4.7.2' type='text/css' media='all' />
if(preg_match("/avada-dynamic-css-css/", $value["text"])){
continue;
}
preg_match("/media\=[\'\"]([^\'\"]+)[\'\"]/", $value["text"], $media);
preg_match("/href\=[\'\"]([^\'\"]+)[\'\"]/", $value["text"], $href);
$media[1] = (isset($media[1]) && $media[1]) ? trim($media[1]) : "";
$value["media"] = (isset($media[1]) && $media[1]) ? $media[1] : "all";
if(isset($href[1])){
$href[1] = trim($href[1]);
$value["href"] = (isset($href[1]) && $href[1]) ? $href[1] : "";
if(preg_match("/href\s*\=/i", $value["text"])){
if(preg_match("/rel\s*\=\s*[\'\"]\s*stylesheet\s*[\'\"]/i", $value["text"])){
array_push($this->tags, $value);
}
}
}
}
}
public function find_tags($start_string, $end_string, $source = false){
if($source){
$data = $source;
}else{
$data = $this->html;
}
$list = array();
$start_index = false;
$end_index = false;
for($i = 0; $i < strlen( $data ); $i++) {
if(substr($data, $i, strlen($start_string)) == $start_string){
$start_index = $i;
}
if($start_index && $i > $start_index){
if(substr($data, $i, strlen($end_string)) == $end_string){
$end_index = $i + strlen($end_string)-1;
$text = substr($data, $start_index, ($end_index-$start_index + 1));
array_push($list, array("start" => $start_index, "end" => $end_index, "text" => $text));
$start_index = false;
$end_index = false;
}
}
}
return $list;
}
public function minify($url){
$this->url = $url;
$md5 = $this->wpfc->create_name($url);
$cachFilePath = $this->wpfc->getWpContentDir("/cache/wpfc-minified")."/".$md5;
$cssLink = $this->convert_path_to_link($cachFilePath);
if(is_dir($cachFilePath)){
if($cssFiles = @scandir($cachFilePath, 1)){
if($cssContent = $this->file_get_contents_curl($cssLink."/".$cssFiles[0])){
$cssContent = $this->apply_filter($cssContent);
return array("cachFilePath" => $cachFilePath, "cssContent" => $cssContent, "url" => $cssLink."/".$cssFiles[0], "realUrl" => $url);
}else{
return false;
}
}
}else{
if($cssContent = $this->file_get_contents_curl($url, "?v=".time())){
$original_content_length = strlen($cssContent);
if(isset($this->wpfc->options->wpFastestCacheMinifyCss) && $this->wpfc->options->wpFastestCacheMinifyCss){
$cssContent = $this->_process($cssContent);
}
$cssContent = $this->fixPathsInCssContent($cssContent, $url);
$cssContent = $this->apply_filter($cssContent);
if(isset($this->wpfc->options->wpFastestCacheMinifyCssPowerFul) && $this->wpfc->options->wpFastestCacheMinifyCssPowerFul){
if(class_exists("WpFastestCachePowerfulHtml")){
$powerful_html = new WpFastestCachePowerfulHtml();
$cssContent = $powerful_html->minify_css($cssContent);
}
}
$cssContent = str_replace("\xEF\xBB\xBF", '', $cssContent);
// If the content is empty, the file is not created. This breaks "combine css" feature
if(strlen($cssContent) == 0 && $original_content_length > 0){
return array("cssContent" => "", "url" => $url);
}
if(!is_dir($cachFilePath)){
if($this->wpfc->cdn){
$cssContent = preg_replace_callback("/(url)\(([^\)]+)\)/i", array($this->wpfc, 'cdn_replace_urls'), $cssContent);
}
$this->wpfc->createFolder($cachFilePath, $cssContent, "css");
}
if($cssFiles = @scandir($cachFilePath, 1)){
return array("cachFilePath" => $cachFilePath, "cssContent" => $cssContent, "url" => $cssLink."/".$cssFiles[0], "realUrl" => $url);
}
}
}
return false;
}
public function fixPathsInCssContent($css, $url){
$this->url_for_fix = $url;
$css = preg_replace("/@import\s+[\"\']([^\;\"\'\)]+)[\"\'];/", "@import url($1);", $css);
$css = preg_replace_callback("/url\(([^\)\n]*)\)/", array($this, 'newImgPath'), $css);
$css = preg_replace_callback('/@import\s+url\(([^\)]+)\);/i', array($this, 'fix_import_rules'), $css);
$css = $this->fix_charset($css);
return $css;
}
public function svg_to_file($source){
return $source;
if(preg_match("/base64\,/", $source)){
$is_base64 = true;
}else{
$is_base64 = false;
}
if(preg_match("/\,(%3Csvg|<svg)/", $source) || $is_base64){
$source = preg_replace("/\"|\'/", "", $source);
$source = preg_replace("/data[^\,]+\,/", "", $source);
if($is_base64){
$source = base64_decode($source);
}else{
$source = rawurldecode($source);
}
$md5 = $this->wpfc->create_name($source);
$cachFilePath = $this->wpfc->getWpContentDir("/cache/wpfc-minified")."/svg-".$md5;
$this->wpfc->createFolder($cachFilePath, $source, "svg");
if(is_dir($cachFilePath)){
if($cssFiles = @scandir($cachFilePath, 1)){
$source = $this->convert_path_to_link($cachFilePath."/".$cssFiles[0]);
}
}
}
return $source;
}
public function woff_to_file($source){
return $source;
// url("data:application/x-font-woff;charset=utf-8;base64,d09GRgABAAAA")
if(preg_match("/base64\,/", $source)){
$is_base64 = true;
}else{
$is_base64 = false;
}
if($is_base64){
// not to use preg_match() for the speed
$source = strstr($source, 'base64,');
$source = str_replace("base64,", "", $source);
$source = trim($source);
$source = str_replace(array("'", '"'), "", $source);
$md5 = $this->wpfc->create_name($source);
$cachFilePath = $this->wpfc->getWpContentDir("/cache/wpfc-minified")."/woff-".$md5;
$this->wpfc->createFolder($cachFilePath, $source, "woff");
if(is_dir($cachFilePath)){
if($cssFiles = @scandir($cachFilePath, 1)){
$link = $this->convert_path_to_link($cachFilePath."/".$cssFiles[0]);
return $link;
}
}
}
return $source;
}
public function newImgPath($matches){
$matches[1] = trim($matches[1]);
if(preg_match("/data\:font\/opentype/i", $matches[1])){
}else if(preg_match("/^%23/", $matches[1])){
// %23 => #
// data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='url(%23d)'
$matches[1] = $matches[1];
}else if(preg_match("/data\:application\/(x-)?font-woff/i", $matches[1])){
// data:application/font-woff
// data:application/x-font-woff
$matches[1] = $this->woff_to_file($matches[1]);
}else if(preg_match("/data\:image\/svg\+xml/i", $matches[1])){
$matches[1] = $this->svg_to_file($matches[1]);
}else{
$matches[1] = str_replace(array("\"","'"), "", $matches[1]);
$matches[1] = trim($matches[1]);
if(!$matches[1]){
$matches[1] = "";
}else if(preg_match("/^\#/", $matches[1])){
$matches[1] = $matches[1];
}else if(preg_match("/^(\/\/|http|\/\/fonts|data:image|data:application)/", $matches[1])){
if(preg_match("/fonts\.googleapis\.com/", $matches[1])){ // for safari browser
$matches[1] = '"'.$matches[1].'"';
}else{
$matches[1] = $matches[1];
}
}else if(preg_match("/^\//", $matches[1])){
$homeUrl = str_replace(array("http:", "https:"), "", home_url());
$matches[1] = $homeUrl.$matches[1];
}else if(preg_match("/^\.\/.+/i", $matches[1])){
//$matches[1] = str_replace("./", get_template_directory_uri()."/", $matches[1]);
$matches[1] = str_replace("./", dirname($this->url_for_fix)."/", $matches[1]);
}else if(preg_match("/^(?P<up>(\.\.\/)+)(?P<name>.+)/", $matches[1], $out)){
$count = strlen($out["up"])/3;
$url = dirname($this->url);
for($i = 1; $i <= $count; $i++){
$url = substr($url, 0, strrpos($url, "/"));
}
$url = str_replace(array("http:", "https:"), "", $url);
$matches[1] = $url."/".$out["name"];
}else{
$url = str_replace(array("http:", "https:"), "", dirname($this->url));
$matches[1] = $url."/".$matches[1];
}
}
return "url(".$matches[1].")";
}
public function apply_filter($content){
return apply_filters('wpfc_css_content', $content, null, null);
}
public function fix_charset($css){
preg_match_all('/@charset[^\;]+\;/i', $css, $charsets);
if(count($charsets[0]) > 0){
$css = preg_replace('/@charset[^\;]+\;/i', "", $css);
foreach($charsets[0] as $charset){
$css = $charset."\n".$css;
}
}
return $css;
}
public function fix_import_rules($matches){
if($this->is_internal_css($matches[1])){
if($cssContent = $this->file_get_contents_curl($matches[1], "?v=".time())){
$tmp_url = $this->url;
$this->url = $matches[1];
$cssContent = $this->fixPathsInCssContent($cssContent, $matches[1]);
$this->url = $tmp_url;
// to minify again because of the @import css sources
if(isset($this->wpfc->options->wpFastestCacheMinifyCss) && $this->wpfc->options->wpFastestCacheMinifyCss){
$cssContent = $this->_process($cssContent);
}
return $cssContent;
}
}
return $matches[0];
}
protected $_inHack = false;
protected function _process($css){
$css = preg_replace("/^\s+/m", "", ((string) $css));
$css = str_replace("\r", "", $css);
$css = preg_replace_callback('@\\s*/\\*([\\s\\S]*?)\\*/\\s*@'
,array($this, '_commentCB'), $css);
//to remove empty chars from url()
$css = preg_replace("/url\((\s+)([^\)]+)(\s+)\)/", "url($2)", $css);
return trim($css);
}
protected function _commentCB($m){
$hasSurroundingWs = (trim($m[0]) !== $m[1]);
$m = $m[1];
// $m is the comment content w/o the surrounding tokens,
// but the return value will replace the entire comment.
if ($m === 'keep') {
return '/**/';
}
if ($m === '" "') {
// component of http://tantek.com/CSS/Examples/midpass.html
return '/*" "*/';
}
if (preg_match('@";\\}\\s*\\}/\\*\\s+@', $m)) {
// component of http://tantek.com/CSS/Examples/midpass.html
return '/*";}}/* */';
}
if ($this->_inHack) {
// inversion: feeding only to one browser
if (preg_match('@
^/ # comment started like /*/
\\s*
(\\S[\\s\\S]+?) # has at least some non-ws content
\\s*
/\\* # ends like /*/ or /**/
@x', $m, $n)) {
// end hack mode after this comment, but preserve the hack and comment content
$this->_inHack = false;
return "/*/{$n[1]}/**/";
}
}
if (substr($m, -1) === '\\') { // comment ends like \*/
// begin hack mode and preserve hack
$this->_inHack = true;
return '/*\\*/';
}
if ($m !== '' && $m[0] === '/') { // comment looks like /*/ foo */
// begin hack mode and preserve hack
$this->_inHack = true;
return '/*/*/';
}
if ($this->_inHack) {
// a regular comment ends hack mode but should be preserved
$this->_inHack = false;
return '/**/';
}
// Issue 107: if there's any surrounding whitespace, it may be important, so
// replace the comment with a single space
return $hasSurroundingWs // remove all other comments
? ' '
: '';
}
public function checkInternal($link){
$httpHost = str_replace("www.", "", $_SERVER["HTTP_HOST"]);
if(preg_match("/href=[\"\'](.*?)[\"\']/", $link, $href)){
if(preg_match("/^\/[^\/]/", $href[1])){
return $href[1];
}
if(@strpos($href[1], $httpHost)){
return $href[1];
}
// if(preg_match("/fonts\.googleapis\.com/i", $href[1])){
// //http://fonts.googleapis.com/css?family=Raleway%3A400%2C600
// if(preg_match("/Raleway/i", $href[1])){
// return false;
// }
// return $href[1];
// }
}
return false;
}
public function is_internal_css($url){
$http_host = trim($_SERVER["HTTP_HOST"], "www.");
$url = trim($url);
$url = trim($url, "'");
$url = trim($url, '"');
$url = str_replace(array("http://", "https://"), "", $url);
$url = trim($url, '//');
$url = trim($url, 'www.');
if($url){
if(preg_match("/".$http_host."/i", $url)){
return true;
}
// if(preg_match("/fonts\.googleapis\.com/i", $url)){
// //http://fonts.googleapis.com/css?family=Raleway%3A400%2C600
// if(preg_match("/Raleway/i", $url)){
// return false;
// }
// return true;
// }
}
return false;
}
public function convert_path_to_link($path){
preg_match("/\/cache\/.+/", $path, $out);
$prefixLink = str_replace(array("http:", "https:"), "", WPFC_WP_CONTENT_URL);
return $prefixLink.$out[0];
}
public function file_get_contents_curl($url, $version = ""){
if($data = $this->wpfc->read_file($url)){
return $data;
}
$url = str_replace('&#038;', '&', $url);
if(preg_match("/\.php\?/i", $url)){
$version = "";
}
if(preg_match("/(fonts\.googleapis\.com|iire-social-icons)/i", $url)){
$version = "";
$url = str_replace(array("'",'"'), "", $url);
}
$url = $url.$version;
if(preg_match("/^\/[^\/]/", $url)){
$url = get_option("home").$url;
}
if(preg_match("/http\:\/\//i", home_url())){
$url = preg_replace("/^\/\//", "http://", $url);
}else if(preg_match("/https\:\/\//i", home_url())){
$url = preg_replace("/^\/\//", "https://", $url);
}
//$response = wp_remote_get($url, array('timeout' => 10, 'headers' => array("cache-control" => array("no-store, no-cache, must-revalidate", "post-check=0, pre-check=0"))));
$response = wp_remote_get($url, array('timeout' => 10, 'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36'));
if ( !$response || is_wp_error( $response ) ) {
return false;
}else{
if(wp_remote_retrieve_response_code($response) == 200){
$data = wp_remote_retrieve_body( $response );
if(preg_match("/\<\!DOCTYPE/i", $data) || preg_match("/<\/\s*html\s*>/i", $data)){
return false;
}else if(!$data){
return "/* empty */";
}else{
return $data;
}
}else if(wp_remote_retrieve_response_code($response) == 404){
if(preg_match("/\.css/", $url)){
return "/*404*/";
}else{
return "<!-- 404 -->";
}
}
}
}
}
?>

View File

@@ -0,0 +1 @@
Silence is golden.

View File

@@ -0,0 +1,341 @@
<?php
class JsUtilities{
private $wpfc;
private $html = "";
private $jsLinks = array();
private $jsLinksExcept = "";
private $url = "";
private $minify;
public function __construct($wpfc, $html, $minify = false){
//$this->html = preg_replace("/\s+/", " ", ((string) $html));
$this->minify = $minify;
$this->wpfc = $wpfc;
$this->html = $html;
$this->setJsLinksExcept();
$this->setJsLinks();
}
public function check_exclude($js_url = false){
if($js_url){
foreach((array)$this->wpfc->exclude_rules as $key => $value){
if(isset($value->prefix) && $value->prefix && $value->type == "js"){
if($value->prefix == "contain"){
$preg_match_rule = preg_quote($value->content, "/");
}
if(preg_match("/".$preg_match_rule."/i", $js_url)){
return true;
}
}
}
}
}
public function combine_js(){
if(count($this->jsLinks) > 0){
$prev_content = "";
foreach($this->jsLinks as $key => $value){
$script_tag = substr($this->html, $value["start"], ($value["end"] - $value["start"] + 1));
if(!preg_match("/<script[^>]+json[^>]+>.+/", $script_tag) && !preg_match("/<script[^>]+text\/template[^>]+>.+/", $script_tag)){
if($href = $this->checkInternal($script_tag)){
if(strpos($this->jsLinksExcept, $href) === false){
if($key == 0 && $this->check_exclude($href)){
continue;
}
if($key > 0 && $this->check_exclude($href)){
$this->mergeJs($prev_content, $this->jsLinks[$key - 1]);
$prev_content = "";
continue;
}
if(preg_match("/data-no-minify/i", $script_tag) || preg_match("/type\s*=\s*[\"\']\s*module\s*[\"\']/i", $script_tag)){
if($key > 0 && $prev_content){
$this->mergeJs($prev_content, $this->jsLinks[$key - 1]);
$prev_content = "";
continue;
}else{
continue;
}
}
$minifiedJs = $this->minify($href);
if($minifiedJs){
if(!is_dir($minifiedJs["cachFilePath"])){
$this->wpfc->createFolder($minifiedJs["cachFilePath"], $minifiedJs["jsContent"], "js");
}
if($jsFiles = @scandir($minifiedJs["cachFilePath"], 1)){
$jsFiles[0] = preg_replace("/\.gz$/", "", $jsFiles[0]);
if($jsContent = $this->file_get_contents_curl($minifiedJs["url"]."/".$jsFiles[0]."?v=".time())){
if($key > 0 && preg_match("/^[\"\']use strict[\"\']/i", $jsContent)){
$this->mergeJs($prev_content, $this->jsLinks[$key - 1]);
$prev_content = "";
}else{
$prev_content = $jsContent."\n".$prev_content;
$script_tag = "<!-- ".$script_tag." -->";
if(($key + 1) == count($this->jsLinks)){
$this->mergeJs($prev_content, $value, true);
$prev_content = "";
}else{
$this->html = substr_replace($this->html, $script_tag, $value["start"], ($value["end"] - $value["start"] + 1));
}
}
}
}
}else{
if($key > 0 && $prev_content){
$this->mergeJs($prev_content, $this->jsLinks[$key - 1]);
$prev_content = "";
}
}
}else{
if($key > 0 && $prev_content){
$this->mergeJs($prev_content, $this->jsLinks[$key - 1]);
$prev_content = "";
}
}
}else{
if($key > 0 && $prev_content){
$this->mergeJs($prev_content, $this->jsLinks[$key - 1]);
$prev_content = "";
}
}
}else{
if($key > 0 && $prev_content){
$this->mergeJs($prev_content, $this->jsLinks[$key - 1]);
$prev_content = "";
}
}
}
}
return $this->html;
}
public function setJsLinks(){
$data = $this->html;
$script_list = array();
$script_start_index = false;
for($i = 0; $i < strlen( $data ); $i++) {
if(isset($data[$i-6])){
if(substr($data, $i-6, 7) == "<script"){
$script_start_index = $i-6;
}
}
if(isset($data[$i-8])){
if($script_start_index){
if(substr($data, $i-8, 9) == "</script>"){
array_push($script_list, array("start" => $script_start_index, "end" => $i));
$script_start_index = false;
}
}
}
}
if(count($script_list) > 0){
$this->jsLinks = array_reverse($script_list);
}
// to update jsLinksExcept
foreach($this->jsLinks as $key => $value){
$script_tag = substr($this->html, $value["start"], ($value["end"] - $value["start"] + 1));
if(preg_match("/wp-spamshield\/js\/jscripts\.php/i", $script_tag)){
$this->jsLinksExcept = $this->jsLinksExcept.$script_tag;
}
//amazonjs/components/js/jquery-tmpl/jquery.tmpl.min.js?ver=1.0.0pre
if(preg_match("/jquery-tmpl\/jquery\.tmpl\.min\.js/i", $script_tag)){
$this->jsLinksExcept = $this->jsLinksExcept.$script_tag;
}
}
}
public function setJsLinksExcept(){
$comment_tags = $this->find_tags("<!--", "-->");
$document_write = $this->find_tags("document.write(", ")");
foreach ($comment_tags as $key => $value) {
if(preg_match("/<script/i", $value["text"]) && preg_match("/<\/script/i", $value["text"])){
$this->jsLinksExcept = $value["text"].$this->jsLinksExcept;
}
}
foreach ($document_write as $key => $value) {
$this->jsLinksExcept = $value["text"].$this->jsLinksExcept;
}
}
public function minify($url){
$this->url = $url;
$md5 = $this->wpfc->create_name($url);
$cachFilePath = $this->wpfc->getWpContentDir("/cache/wpfc-minified")."/".$md5;
$jsLink = $this->convert_path_to_link($cachFilePath);
if(is_dir($cachFilePath)){
return array("cachFilePath" => $cachFilePath, "jsContent" => "", "url" => $jsLink);
}else{
if($js = $this->file_get_contents_curl($url)){
if($this->minify){
if(class_exists("WpFastestCachePowerfulHtml")){
$powerful_html = new WpFastestCachePowerfulHtml();
$js = $powerful_html->minify_js($js);
}else{
$js = "\n// source --> ".$url." \n".$js;
}
}else{
$js = "\n// source --> ".$url." \n".$js;
}
return array("cachFilePath" => $cachFilePath, "jsContent" => $js, "url" => $jsLink);
}
}
return false;
}
public function checkInternal($link){
$httpHost = str_replace("www.", "", $_SERVER["HTTP_HOST"]);
if(preg_match("/^<script[^\>]+\>/i", $link, $script)){
if(preg_match("/src=[\"\'](.*?)[\"\']/", $script[0], $src)){
if(preg_match("/alexa\.com\/site\_stats/i", $src[1])){
return false;
}
if(preg_match("/^\/[^\/]/", $src[1])){
return $src[1];
}
if(preg_match("/".preg_quote($httpHost, "/")."/i", $src[1])){
//<script src="https://server1.opentracker.net/?site=www.site.com"></script>
if(preg_match("/[\?\=].*".preg_quote($httpHost, "/")."/i", $src[1])){
return false;
}
return $src[1];
}
}
}
return false;
}
public function mergeJs($js_content, $value, $last = false){
$name = md5($js_content);
$name = base_convert(crc32($name), 20, 36);
$cachFilePath = $this->wpfc->getWpContentDir("/cache/wpfc-minified")."/".$name;
$jsLink = $this->convert_path_to_link($cachFilePath);
if(!is_dir($cachFilePath)){
$this->wpfc->createFolder($cachFilePath, $js_content, "js");
}
if(is_dir($cachFilePath)){
if($jsFiles = @scandir($cachFilePath, 1)){
$newLink = "<script src='".$jsLink."/".$jsFiles[0]."' type=\"text/javascript\"></script>";
$script_tag = substr($this->html, $value["start"], ($value["end"] - $value["start"] + 1));
if($last){
$script_tag = $newLink."\n<!-- ".$script_tag." -->\n";
}else{
$script_tag = $newLink."\n".$script_tag;
}
$this->html = substr_replace($this->html, $script_tag, $value["start"], ($value["end"] - $value["start"] + 1));
}
}
}
public function convert_path_to_link($path){
preg_match("/\/cache\/.+/", $path, $out);
$prefixLink = str_replace(array("http:", "https:"), "", WPFC_WP_CONTENT_URL);
return $prefixLink.$out[0];
}
public function file_get_contents_curl($url) {
if($data = $this->wpfc->read_file($url)){
return $data;
}
if(!preg_match("/\.php$/", $url)){
$url = $url."?v=".time();
}
if(preg_match("/^\/[^\/]/", $url)){
$url = home_url().$url;
}
$url = preg_replace("/^\/\//", "http://", $url);
$response = wp_remote_get($url, array('timeout' => 10 ) );
if ( !$response || is_wp_error( $response ) ) {
return false;
}else{
if(wp_remote_retrieve_response_code($response) == 200){
$data = wp_remote_retrieve_body( $response );
if(preg_match("/<\/\s*html\s*>\s*$/i", $data)){
return false;
}else{
return $data;
}
}
}
}
public function find_tags($start_string, $end_string){
$data = $this->html;
$list = array();
$start_index = false;
$end_index = false;
for($i = 0; $i < strlen( $data ); $i++) {
if(substr($data, $i, strlen($start_string)) == $start_string){
$start_index = $i;
}
if($start_index && $i > $start_index){
if(substr($data, $i, strlen($end_string)) == $end_string){
$end_index = $i + strlen($end_string)-1;
$text = substr($data, $start_index, ($end_index-$start_index + 1));
array_push($list, array("start" => $start_index, "end" => $end_index, "text" => $text));
$start_index = false;
$end_index = false;
}
}
}
return $list;
}
}
?>

View File

@@ -0,0 +1,892 @@
<?php
class PreloadWPFC{
private static $exclude_rules = false;
public static function wpml_get_permalink($post_id, $permalink){
$my_post_language_details = apply_filters( 'wpml_post_language_details', NULL, $post_id) ;
if(is_array($my_post_language_details) && isset($my_post_language_details["language_code"])){
$wpml_permalink = apply_filters( 'wpml_permalink', $permalink , $my_post_language_details["language_code"] );
return $wpml_permalink;
}
return $permalink;
}
public static function set_preload($slug){
$preload_arr = array();
if(!empty($_POST) && isset($_POST["wpFastestCachePreload"])){
if(!current_user_can('manage_options')){
wp_die("Must be admin");
}
if(isset($_POST["wpFastestCachePreload_sitemap"]) && $_POST["wpFastestCachePreload_sitemap"]){
$sitemap_url = explode(",", $_POST["wpFastestCachePreload_sitemap"]);
$sitemap_arr = array();
foreach ($sitemap_url as $s_key => $s_value) {
$s_value = esc_url($s_value);
array_push($sitemap_arr, array("url" => $s_value, "pointer" => 0));
}
$preload_arr["sitemaps"] = $sitemap_arr;
}else{
foreach ($_POST as $key => $value) {
$key = esc_attr($key);
$value = esc_attr($value);
preg_match("/wpFastestCachePreload_(.+)/", $key, $type);
if(!empty($type)){
if($type[1] == "restart" || $type[1] == "sitemap"){
//to need to remove "restart" value
}else if($type[1] == "number"){
$preload_arr[$type[1]] = $value;
}else{
$preload_arr[$type[1]] = 0;
}
}
}
}
}
if($data = get_option("WpFastestCachePreLoad")){
$preload_std = json_decode($data);
if(empty($preload_arr)){
// clear cache process
if(isset($preload_std->sitemaps) && !empty($preload_std->sitemaps)){
foreach ($preload_std->sitemaps as $s_key => $s_value) {
$s_value->pointer = 0;
}
}else{
foreach ($preload_std as $key => &$value) {
if($key != "number"){
$value = 0;
}
}
}
}else{
// save settings process
if(isset($preload_arr["sitemaps"])){
if(isset($preload_std->sitemaps) && !empty($preload_std->sitemaps)){
for ($i=0; $i < count($preload_arr["sitemaps"]) ; $i++) {
for ($j=0; $j < count($preload_std->sitemaps); $j++) {
if($preload_arr["sitemaps"][$i]["url"] == $preload_std->sitemaps[$j]->url){
if(isset($preload_std->sitemaps[$j]->pointer)){
$preload_arr["sitemaps"][$i]["pointer"] = $preload_std->sitemaps[$j]->pointer;
}
if(isset($preload_std->sitemaps[$j]->total)){
$preload_arr["sitemaps"][$i]["total"] = $preload_std->sitemaps[$j]->total;
}
}
}
}
$preload_std = $preload_arr;
}else{
foreach ($preload_arr as $key => &$value) {
if(!empty($preload_std->$key)){
if($key != "number"){
$value = $preload_std->$key;
}
}
}
$preload_std = $preload_arr;
}
}else{
foreach ($preload_arr as $key => &$value) {
if(!empty($preload_std->$key)){
if($key != "number"){
$value = $preload_std->$key;
}
}
}
$preload_std = $preload_arr;
}
}
update_option("WpFastestCachePreLoad", json_encode($preload_std));
if(!wp_next_scheduled($slug."_Preload")){
wp_schedule_event(time() + 5, 'everyfiveminute', $slug."_Preload");
}
}else{
if(!empty($preload_arr)){
add_option("WpFastestCachePreLoad", json_encode($preload_arr), null, "yes");
if(!wp_next_scheduled($slug."_Preload")){
wp_schedule_event(time() + 5, 'everyfiveminute', $slug."_Preload");
}
}else{
//toDO
}
}
}
public static function statistic($pre_load = false){
$total = new stdClass();
if(isset($pre_load->homepage)){
$total->homepage = 1;
}
if(isset($pre_load->customposttypes)){
global $wpdb;
$post_types = get_post_types(array('public' => true), "names", "and");
$where_query = "";
foreach ($post_types as $post_type_key => $post_type_value) {
if(!in_array($post_type_key, array("post", "page", "attachment"))){
$where_query = $where_query.$wpdb->prefix."posts.post_type = '".$post_type_value."' OR ";
}
}
if($where_query){
$where_query = preg_replace("/(\s*OR\s*)$/", "", $where_query);
$recent_custom_posts = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS COUNT(".$wpdb->prefix."posts.ID) as total FROM ".$wpdb->prefix."posts WHERE 1=1 AND (".$where_query.") AND ((".$wpdb->prefix."posts.post_status = 'publish')) ORDER BY ".$wpdb->prefix."posts.ID", ARRAY_A);
$total->customposttypes = $recent_custom_posts[0]["total"];
}
}
if(isset($pre_load->post)){
$count_posts = wp_count_posts("post", array('post_status' => 'publish', 'suppress_filters' => true));
$total->post = $count_posts->publish;
}
if(isset($pre_load->attachment)){
$total_attachments = wp_count_attachments();
$total->attachment = array_sum((array)$total_attachments) - $total_attachments->trash;
}
if(isset($pre_load->page)){
$count_pages = wp_count_posts("page", array('post_status' => 'publish', 'suppress_filters' => true));
$total->page = $count_pages->publish;
}
if(isset($pre_load->category)){
$total->category = wp_count_terms("category", array('hide_empty' => false));
}
if(isset($pre_load->tag)){
$total->tag = wp_count_terms("post_tag", array('hide_empty' => false));
}
if(isset($pre_load->customTaxonomies)){
$taxo = get_taxonomies(array('public' => true, '_builtin' => false), "names", "and");
if(count($taxo) > 0){
$total->customTaxonomies = wp_count_terms($taxo, array('hide_empty' => false));
}
}
foreach ($total as $key => $value) {
$pre_load->$key = $pre_load->$key == -1 ? $value : $pre_load->$key;
echo esc_html($key).": ".esc_html($pre_load->$key)."/".esc_html($value)."<br>";
}
}
public static function create_preload_cache_default($pre_load, $options){
if(defined("WPFC_PRELOAD_NUMBER") && WPFC_PRELOAD_NUMBER){
$number = WPFC_PRELOAD_NUMBER;
}else{
$number = $pre_load->number;
}
//START:ORDER
if(isset($pre_load->order) && $pre_load->order){
$order_arr = explode(",", $pre_load->order);
}else{
if(isset($options->wpFastestCachePreload_order) && $options->wpFastestCachePreload_order){
$order_arr = explode(",", $options->wpFastestCachePreload_order);
}
}
if(isset($order_arr) && is_array($order_arr)){
foreach ($order_arr as $o_key => $o_value){
if($o_value == "order" || $o_value == "number"){
unset($order_arr[$o_key]);
}
if(!isset($pre_load->$o_value)){
unset($order_arr[$o_key]);
}
}
$order_arr = array_values($order_arr);
}
$current_order = isset($order_arr[0]) ? $order_arr[0] : "go";
//START:END
$urls_limit = isset($options->wpFastestCachePreload_number) ? $options->wpFastestCachePreload_number : 4; // must be even
$urls = array();
if(isset($options->wpFastestCacheMobileTheme) && $options->wpFastestCacheMobileTheme){
$mobile_theme = true;
$number = round($number/2);
}else{
$mobile_theme = false;
}
// HOME
if(isset($current_order) && ($current_order == "homepage" || $current_order == "go")){
if(isset($pre_load->homepage) && $pre_load->homepage > -1){
if($mobile_theme){
array_push($urls, array("url" => get_option("home"), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_option("home"), "user-agent" => "desktop"));
$number--;
$pre_load->homepage = -1;
}
}
// CUSTOM POSTS
if(isset($current_order) && ($current_order == "customposttypes" || $current_order == "go")){
if($number > 0 && isset($pre_load->customposttypes) && $pre_load->customposttypes > -1){
global $wpdb;
$post_types = get_post_types(array('public' => true), "names", "and");
$where_query = "";
foreach ($post_types as $post_type_key => $post_type_value) {
if(!in_array($post_type_key, array("post", "page", "attachment"))){
$where_query = $where_query.$wpdb->prefix."posts.post_type = '".$post_type_value."' OR ";
}
}
if($where_query){
$where_query = preg_replace("/(\s*OR\s*)$/", "", $where_query);
$recent_custom_posts = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS ".$wpdb->prefix."posts.ID FROM ".$wpdb->prefix."posts WHERE 1=1 AND (".$where_query.") AND ((".$wpdb->prefix."posts.post_status = 'publish')) ORDER BY ".$wpdb->prefix."posts.ID DESC LIMIT ".$pre_load->customposttypes.", ".$number, ARRAY_A);
if(count($recent_custom_posts) > 0){
foreach ($recent_custom_posts as $key => $post) {
if($mobile_theme){
array_push($urls, array("url" => self::wpml_get_permalink($post["ID"], get_permalink($post["ID"])), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => self::wpml_get_permalink($post["ID"], get_permalink($post["ID"])), "user-agent" => "desktop"));
$number--;
$pre_load->customposttypes = $pre_load->customposttypes + 1;
}
}else{
$pre_load->customposttypes = -1;
}
}
}
}
// POST
if(isset($current_order) && ($current_order == "post" || $current_order == "go")){
if($number > 0 && isset($pre_load->post) && $pre_load->post > -1){
// $recent_posts = wp_get_recent_posts(array(
// 'numberposts' => $number,
// 'offset' => $pre_load->post,
// 'orderby' => 'ID',
// 'order' => 'DESC',
// 'post_type' => 'post',
// 'post_status' => 'publish',
// 'suppress_filters' => true
// ), ARRAY_A);
global $wpdb;
$recent_posts = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS ".$wpdb->prefix."posts.ID FROM ".$wpdb->prefix."posts WHERE 1=1 AND (".$wpdb->prefix."posts.post_type = 'post') AND ((".$wpdb->prefix."posts.post_status = 'publish')) ORDER BY ".$wpdb->prefix."posts.ID DESC LIMIT ".$pre_load->post.", ".$number, ARRAY_A);
if(count($recent_posts) > 0){
foreach ($recent_posts as $key => $post) {
if($mobile_theme){
array_push($urls, array("url" => self::wpml_get_permalink($post["ID"], get_permalink($post["ID"])), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => self::wpml_get_permalink($post["ID"], get_permalink($post["ID"])), "user-agent" => "desktop"));
$number--;
$pre_load->post = $pre_load->post + 1;
}
}else{
$pre_load->post = -1;
}
}
}
// ATTACHMENT
if(isset($current_order) && ($current_order == "attachment" || $current_order == "go")){
if($number > 0 && isset($pre_load->attachment) && $pre_load->attachment > -1){
global $wpdb;
$recent_attachments = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS ".$wpdb->prefix."posts.ID FROM ".$wpdb->prefix."posts WHERE 1=1 AND (".$wpdb->prefix."posts.post_type = 'attachment') ORDER BY ".$wpdb->prefix."posts.ID DESC LIMIT ".$pre_load->attachment.", ".$number, ARRAY_A);
if(count($recent_attachments) > 0){
foreach ($recent_attachments as $key => $attachment) {
if($mobile_theme){
array_push($urls, array("url" => get_permalink($attachment["ID"]), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_permalink($attachment["ID"]), "user-agent" => "desktop"));
$number--;
$pre_load->attachment = $pre_load->attachment + 1;
}
}else{
$pre_load->attachment = -1;
}
}
}
// PAGE
if(isset($current_order) && ($current_order == "page" || $current_order == "go")){
if($number > 0 && isset($pre_load->page) && $pre_load->page > -1){
global $wpdb;
$pages = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS ".$wpdb->prefix."posts.ID FROM ".$wpdb->prefix."posts WHERE 1=1 AND (".$wpdb->prefix."posts.post_type = 'page') AND ((".$wpdb->prefix."posts.post_status = 'publish')) ORDER BY ".$wpdb->prefix."posts.ID DESC LIMIT ".$pre_load->page.", ".$number, ARRAY_A);
if(count($pages) > 0){
foreach ($pages as $key => $page) {
if($mobile_theme){
array_push($urls, array("url" => get_page_link($page["ID"]), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_page_link($page["ID"]), "user-agent" => "desktop"));
$number--;
$pre_load->page = $pre_load->page + 1;
}
}else{
$pre_load->page = -1;
}
}
}
// CATEGORY
if(isset($current_order) && ($current_order == "category" || $current_order == "go")){
if($number > 0 && isset($pre_load->category) && $pre_load->category > -1){
$categories = get_terms(array(
'taxonomy' => array('category'),
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => false,
'number' => $number,
'fields' => 'all',
'pad_counts' => false,
'offset' => $pre_load->category
));
if(count($categories) > 0){
foreach ($categories as $key => $category) {
$term_link = get_term_link($category->slug, $category->taxonomy);
if(isset($term_link->errors)){
continue;
}
if($mobile_theme){
array_push($urls, array("url" => $term_link, "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => $term_link, "user-agent" => "desktop"));
$number--;
$pre_load->category = $pre_load->category + 1;
}
}else{
$pre_load->category = -1;
}
}
}
// TAG
if(isset($current_order) && ($current_order == "tag" || $current_order == "go")){
if($number > 0 && isset($pre_load->tag) && $pre_load->tag > -1){
$tags = get_terms(array(
'taxonomy' => array('post_tag'),
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => false,
'number' => $number,
'fields' => 'all',
'pad_counts' => false,
'offset' => $pre_load->tag
));
if(count($tags) > 0){
foreach ($tags as $key => $tag) {
if($mobile_theme){
array_push($urls, array("url" => get_term_link($tag->slug, $tag->taxonomy), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_term_link($tag->slug, $tag->taxonomy), "user-agent" => "desktop"));
$number--;
$pre_load->tag = $pre_load->tag + 1;
}
}else{
$pre_load->tag = -1;
}
}
}
// Custom Taxonomies
if(isset($current_order) && ($current_order == "customTaxonomies" || $current_order == "go")){
if($number > 0 && isset($pre_load->customTaxonomies) && $pre_load->customTaxonomies > -1){
$taxo = get_taxonomies(array('public' => true, '_builtin' => false), "names", "and");
if(count($taxo) > 0){
$custom_taxos = get_terms(array(
'taxonomy' => array_values($taxo),
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => false,
'number' => $number,
'fields' => 'all',
'pad_counts' => false,
'offset' => $pre_load->customTaxonomies
));
if(count($custom_taxos) > 0){
foreach ($custom_taxos as $key => $custom_tax) {
if($mobile_theme){
array_push($urls, array("url" => get_term_link($custom_tax->slug, $custom_tax->taxonomy), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_term_link($custom_tax->slug, $custom_tax->taxonomy), "user-agent" => "desktop"));
$number--;
$pre_load->customTaxonomies = $pre_load->customTaxonomies + 1;
}
}else{
$pre_load->customTaxonomies = -1;
}
}else{
$pre_load->customTaxonomies = -1;
}
}
}
if(isset($pre_load->$current_order) && $pre_load->$current_order == -1){
array_shift($order_arr);
if(isset($order_arr[0])){
$pre_load->order = implode(",", $order_arr);
update_option("WpFastestCachePreLoad", json_encode($pre_load));
self::create_preload_cache($options);
}else{
unset($pre_load->order);
}
}
if(count($urls) > 0){
foreach ($urls as $key => $arr) {
$user_agent = "";
if($arr["user-agent"] == "desktop"){
$user_agent = "WP Fastest Cache Preload Bot";
}else if($arr["user-agent"] == "mobile"){
$user_agent = "WP Fastest Cache Preload iPhone Mobile Bot";
}
if(self::is_excluded($arr["url"])){
$status = "<strong style=\"color:blue;\">Excluded</strong>";
}else{
if($GLOBALS["wp_fastest_cache"]->wpfc_remote_get($arr["url"], $user_agent)){
$status = "<strong style=\"color:lightgreen;\">OK</strong>";
}else{
$status = "<strong style=\"color:red;\">ERROR</strong>";
}
}
echo $status." ".esc_html($arr["url"])." (".esc_html($arr["user-agent"]).")<br>";
}
echo "<br>";
echo count($urls)." page have been cached";
update_option("WpFastestCachePreLoad", json_encode($pre_load));
echo "<br><br>";
self::statistic($pre_load);
}else{
if(isset($options->wpFastestCachePreload_restart)){
foreach ($pre_load as $pre_load_key => &$pre_load_value) {
//if($pre_load_key != "number" && $pre_load_key != "order"){
if($pre_load_key != "number"){
$pre_load_value = 0;
}
}
update_option("WpFastestCachePreLoad", json_encode($pre_load));
echo "Preload Restarted";
if($varnish_datas = get_option("WpFastestCacheVarnish")){
include_once('varnish.php');
VarnishWPFC::purge_cache($varnish_datas);
}
include_once('cdn.php');
CdnWPFC::cloudflare_clear_cache();
}else{
echo "Completed";
wp_clear_scheduled_hook("wp_fastest_cache_Preload");
}
}
}
public static function prepare_sitemap($url, $sitemap_cache_path){
if(!empty($url)){
$content = $GLOBALS["wp_fastest_cache"]->wpfc_remote_get($url, "xxxx", true);
$content = strtolower($content);
$content = preg_replace("/<\?\s*xml[^\>]*>/i", "", $content);
// to remove comments
$content = preg_replace("/\<\!\-\-((?:(?!-->).)+)\-\-\>/", "", $content);
$content = preg_replace("/<((?:(?!url|loc).)+)>((?:(?!http).)+)<((?:(?!url|loc).)+)>/i", "", $content);
// to remove <image:image></image:image> tag
$content = preg_replace("/<\s*image\s*:\s*image\s*>((?:(?!\<\s*\/\s*image\s*:\s*image\s*>).)+)<\s*\/\s*image\s*\:\s*image\s*>/s", "", $content);
if(preg_match("/<\s*sitemapindex[^\>]+>/", $content)){
$content = preg_replace("/<\/?sitemapindex[^\>]*>/i", "", $content);
$content = preg_replace("/\s/i", "", $content);
$content = preg_replace("/<\/sitemap>/i", "</sitemap>\n", $content);
}else{
$content = preg_replace("/<\/?urlset[^\>]*>/i", "", $content);
$content = preg_replace("/\s/i", "", $content);
$content = preg_replace("/<\/url>/i", "</url>\n", $content);
}
if(!is_dir($GLOBALS["wp_fastest_cache"]->getWpContentDir("/cache/all/"))){
@mkdir($GLOBALS["wp_fastest_cache"]->getWpContentDir("/cache/all/"), 0755, true);
}
if(!is_dir($GLOBALS["wp_fastest_cache"]->getWpContentDir("/cache/all/preload-sitemap"))){
@mkdir($GLOBALS["wp_fastest_cache"]->getWpContentDir("/cache/all/preload-sitemap"), 0755, true);
}
file_put_contents($sitemap_cache_path, $content);
return $content;
}
return false;
}
public static function extract_sitemap_index($content, $sitemaps){
if($content){
preg_match_all("/<sitemap><loc>([^\>\<]+)<\/loc><\/sitemap>/", $content, $out);
if(isset($out[1]) && isset($out[1][0])){
foreach ($out[1] as $key => $value) {
$sm_obj = (object) array("url" => $value, "pointer" => 0, "total" => 0);
if(!in_array($value, array_column($sitemaps, 'url'))){
array_push($sitemaps, $sm_obj);
}
}
}
}
return $sitemaps;
}
public static function create_preload_cache_sitemap($pre_load, $options){
if(!isset($pre_load->sitemaps[0])){
die("No sitemap detected!");
}
if(defined("WPFC_PRELOAD_NUMBER") && WPFC_PRELOAD_NUMBER){
$number = WPFC_PRELOAD_NUMBER;
}else{
$number = $options->wpFastestCachePreload_number;
}
$urls = array();
if(isset($options->wpFastestCacheMobileTheme) && $options->wpFastestCacheMobileTheme){
$mobile_theme = true;
$number = round($number/2);
}else{
$mobile_theme = false;
}
foreach ($pre_load->sitemaps as $s_key => &$s_value) {
$sitemap_cache_path = $GLOBALS["wp_fastest_cache"]->getWpContentDir("/cache/all/preload-sitemap/".base64_encode($s_value->url).".xml");
if(!file_exists($sitemap_cache_path) || !isset($s_value->total)){
$content = self::prepare_sitemap($s_value->url, $sitemap_cache_path);
$s_value->total = substr_count($content, '<url>');
if($s_value->total == 0){
$pre_load->sitemaps = self::extract_sitemap_index($content, $pre_load->sitemaps);
unset($pre_load->sitemaps[$s_key]);
$pre_load->sitemaps = array_values($pre_load->sitemaps);
update_option("WpFastestCachePreLoad", json_encode($pre_load));
die($s_value->url." was extracted");
}
}
$s_value->pointer = $s_value->pointer > 0 ? $s_value->pointer : 1;
if($s_value->pointer < $s_value->total){
$file = fopen($sitemap_cache_path, "r");
for ($i = 1; $i < $s_value->pointer; $i++) {
fgets($file);
}
for ($j=0; $j < $number; $j++) {
$specific_line = fgets($file);
$specific_line = strip_tags($specific_line);
$specific_line = trim($specific_line);
if($specific_line){
if($mobile_theme){
array_push($urls, array("url" => $specific_line, "user-agent" => "mobile"));
}
array_push($urls, array("url" => $specific_line, "user-agent" => "desktop"));
}
}
fclose($file);
$s_value->pointer = $s_value->pointer + $number;
$s_value->pointer = $s_value->pointer > $s_value->total ? $s_value->total : $s_value->pointer;
break;
}
}
if(count($urls) > 0){
foreach ($urls as $key => $arr) {
$user_agent = "";
if($arr["user-agent"] == "desktop"){
$user_agent = "WP Fastest Cache Preload Bot";
}else if($arr["user-agent"] == "mobile"){
$user_agent = "WP Fastest Cache Preload iPhone Mobile Bot";
}
if(self::is_excluded($arr["url"])){
$status = "<strong style=\"color:blue;\">Excluded</strong>";
}else{
if($GLOBALS["wp_fastest_cache"]->wpfc_remote_get($arr["url"], $user_agent)){
$status = "<strong style=\"color:lightgreen;\">OK</strong>";
}else{
$status = "<strong style=\"color:red;\">ERROR</strong>";
}
}
echo $status." ".esc_html($arr["url"])." (".esc_html($arr["user-agent"]).")<br>";
}
echo "\n\n<br><br>";
foreach ($pre_load->sitemaps as $sres_key => $sres_value) {
if(isset($sres_value->total)){
$cached_page_number = $sres_value->pointer;
if($sres_value->pointer == $sres_value->total){
$cached_page_number = $sres_value->pointer;
}else{
$cached_page_number--;
$cached_page_number = max($cached_page_number, 0);
}
echo esc_html($sres_value->url).": ".esc_html($cached_page_number)."/".esc_html($sres_value->total)."<br>\n";
}else{
echo esc_html($sres_value->url).": -<br>\n";
}
}
update_option("WpFastestCachePreLoad", json_encode($pre_load));
}else{
if(isset($options->wpFastestCachePreload_restart)){
foreach ($pre_load->sitemaps as $r_key => &$r_value) {
$r_value->pointer = 0;
}
update_option("WpFastestCachePreLoad", json_encode($pre_load));
echo "Preload Restarted";
// clearing the sitemap cache in order to get the latest sitemap updates
$GLOBALS["wp_fastest_cache"]->rm_folder_recursively($GLOBALS["wp_fastest_cache"]->getWpContentDir("/cache/all/preload-sitemap"));
if($varnish_datas = get_option("WpFastestCacheVarnish")){
include_once('varnish.php');
VarnishWPFC::purge_cache($varnish_datas);
}
include_once('cdn.php');
CdnWPFC::cloudflare_clear_cache();
}else{
echo "Completed";
wp_clear_scheduled_hook("wp_fastest_cache_Preload");
}
}
}
public static function create_preload_cache($options){
if(!isset($options->wpFastestCacheStatus)){
die("Cache System must be enabled");
}
if($data = get_option("WpFastestCachePreLoad")){
$pre_load = json_decode($data);
if(isset($pre_load->sitemaps)){
self::create_preload_cache_sitemap($pre_load, $options);
}else{
self::create_preload_cache_default($pre_load, $options);
}
}
if(isset($_GET) && isset($_GET["type"]) && $_GET["type"] == "preload"){
die();
}
}
public static function is_excluded($url){
if(!is_string($url)){
return false;
}
$request_url = parse_url($url, PHP_URL_PATH);
if($request_url){
$request_url = urldecode(trim($request_url, "/"));
}
if(!$request_url){
return false;
}
if(self::$exclude_rules === false){
if($json_data = get_option("WpFastestCacheExclude")){
self::$exclude_rules = json_decode($json_data);
}else{
self::$exclude_rules = array();
}
}
foreach((array)self::$exclude_rules as $key => $value){
if($value->prefix == "exact"){
if(strtolower($value->content) == strtolower($request_url)){
return true;
}
}else{
if($value->prefix == "startwith"){
$preg_match_rule = "^".preg_quote($value->content, "/");
}else if($value->prefix == "contain"){
$preg_match_rule = preg_quote($value->content, "/");
}
if(isset($preg_match_rule)){
if(preg_match("/".$preg_match_rule."/i", $request_url)){
return true;
}
}
}
}
return false;
}
}
?>

View File

@@ -0,0 +1,347 @@
<?php
class SinglePreloadWPFC{
public static $id = 0;
public static $urls = array();
public static function init($id = false){
if($id){
self::set_id($id);
}else if(isset($_GET["post"]) && $_GET["post"]){
self::set_id($_GET["post"]);
}
SinglePreloadWPFC::set_urls();
SinglePreloadWPFC::set_urls_with_terms();
}
public static function add_meta_box(){
add_meta_box(
'auto_cache_custom_meta_box', // this is HTML id
'Auto Cache Settings',
array("SinglePreloadWPFC", "auto_cache_custom_box_html"), // the callback function
array('page', 'post', 'product'),
'side',
'high'
);
}
public static function auto_cache_custom_box_html(){
$yes_selected = "";
$no_selected = "";
if($data = get_option("WpFastestCache_autocache")){
if($data == "yes"){
$yes_selected = "selected";
}else if($data == "no"){
$no_selected = "selected";
}
}else{
$no_selected = "selected";
}
?>
<p>
<label>Enable:</label>
<select data-type='auto-cache-enable'>
<option <?php echo $yes_selected; ?> value="yes">Yes</option>
<option <?php echo $no_selected; ?> value="no">No</option>
</select>
<span class="spinner" style="float: none;display: inline-block;margin:0;"></span>
</p>
<p id="wpfc-single-preload-process" style="display: none;">
<label>Status: <span id="wpfc-single-preload-status-runnig">Running</span><span id="wpfc-single-preload-status-completed" style="display: none; color: #33CD32; font-weight: bold;">Completed</span></label><br>
<label>Total: <span id="wpfc-single-preload-total-number"><?php echo count(self::$urls); ?></span></label><br>
<label>Cached: <span id="wpfc-single-preload-cached-number">0</span></label><br>
<label>Errors: <span id="wpfc-single-preload-error-number">0</span></label>
</p>
<p class="post-attributes-help-text">The cache will be created automatically after the contents are saved. <a href="https://www.wpfastestcache.com/features/automatic-cache/" target="_blank">More Info</a></p>
<script type="text/javascript">
var Wpfc_Single_Preload_save_settings = function(){
var enable_form = jQuery("#auto_cache_custom_meta_box select[data-type='auto-cache-enable']");
if(enable_form.length == 1){
enable_form.change(function(){
enable_form.attr("disabled", true);
jQuery("#auto_cache_custom_meta_box span.spinner").css({"visibility" : "visible"});
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "wpfc_preload_single_save_settings", "is_enable": jQuery(this).val(), "nonce" : wpfc_nonce},
dataType: "json",
cache: false,
success: function(data){
enable_form.attr("disabled", false);
jQuery("#auto_cache_custom_meta_box span.spinner").css({"visibility" : "hidden"});
console.log(data);
},
error: function(error){
enable_form.attr("disabled", false);
jQuery("#auto_cache_custom_meta_box span.spinner").css({"visibility" : "hidden"});
console.log(error.statusText);
}
});
});
}
};
Wpfc_Single_Preload_save_settings();
</script>
<?php
// Add the HTML for the post meta
}
public static function save_settings(){
if(current_user_can('manage_options')){
$res = array("success" => true);
if(get_option("WpFastestCache_autocache")){
update_option("WpFastestCache_autocache", sanitize_text_field($_POST["is_enable"]));
}else{
add_option("WpFastestCache_autocache", sanitize_text_field($_POST["is_enable"]), null, "yes");
}
wp_send_json($res);
}
wp_die("Must be admin");
}
public static function set_id($id) {
$id = (int)$id;
if(get_post_status($id) === "publish"){
self::$id = $id;
}
}
public static function create_cache_for_all_urls(){
if(preg_match("/include\s*\(\s*[\'\"]\/themes\//i", wp_debug_backtrace_summary())){
return array("success" => false, "error_message" => "You cannot call this function in any theme file");
}
if(empty(self::$urls)){
return false;
}
$res_arr = array();
foreach (self::$urls as $url) {
$res = $GLOBALS["wp_fastest_cache"]->wpfc_remote_get($url["url"], $url["user-agent"]);
array_push($res_arr, array("url" => $url["url"], "success" => $res));
}
return $res_arr;
}
public static function create_cache(){
$res = $GLOBALS["wp_fastest_cache"]->wpfc_remote_get($_GET["url"], $_GET["user_agent"]);
if($res){
die("true");
}
}
public static function is_mobile_active(){
if(isset($GLOBALS["wp_fastest_cache_options"]->wpFastestCacheMobile) && isset($GLOBALS["wp_fastest_cache_options"]->wpFastestCacheMobileTheme)){
return true;
}else{
return false;
}
}
public static function set_term_urls($term_taxonomy_id){
$term = get_term_by("term_taxonomy_id", $term_taxonomy_id);
if($term && !is_wp_error($term)){
$url = get_term_link($term->term_id, $term->taxonomy);
array_push(static::$urls, array("url" => $url, "user-agent" => "WP Fastest Cache Preload Bot"));
if(self::is_mobile_active()){
array_push(static::$urls, array("url" => $url, "user-agent" => "WP Fastest Cache Preload iPhone Mobile Bot"));
}
if($term->parent > 0){
$parent = get_term_by("id", $term->parent, $term->taxonomy);
static::set_term_urls($parent->term_taxonomy_id);
}
}
}
public static function set_urls_with_terms(){
global $wpdb;
$terms = $wpdb->get_results("SELECT * FROM `".$wpdb->prefix."term_relationships` WHERE `object_id`=".static::$id, ARRAY_A);
foreach ($terms as $term_key => $term_val){
static::set_term_urls($term_val["term_taxonomy_id"]);
}
}
public static function set_urls(){
if(static::$id){
$permalink = get_permalink(static::$id);
array_push(static::$urls, array("url" => $permalink, "user-agent" => "WP Fastest Cache Preload Bot"));
if(self::is_mobile_active()){
array_push(static::$urls, array("url" => $permalink, "user-agent" => "WP Fastest Cache Preload iPhone Mobile Bot"));
}
}
}
public static function put_inline_js(){
if($data = get_option("WpFastestCache_autocache")){
if($data == "no"){
return false;
}
}else{
return false;
}
?>
<script type="text/javascript">
var WpfcSinglePreload = {
error_message: "",
init: function(){
jQuery("#wpfc-single-preload-process").show("slow")
},
change_status: function(){
var error_number = jQuery("#wpfc-single-preload-error-number").text();
var cached_number = jQuery("#wpfc-single-preload-cached-number").text();
var total_number = jQuery("#wpfc-single-preload-total-number").text();
error_number = parseInt(error_number);
cached_number = parseInt(cached_number);
total_number = parseInt(total_number);
if(total_number == (cached_number + error_number)){
jQuery("#wpfc-single-preload-status-completed").show();
jQuery("#wpfc-single-preload-status-runnig").hide();
}
},
increase_error: function(){
var number = jQuery("#wpfc-single-preload-error-number").text();
number = parseInt(number) + 1;
jQuery("#wpfc-single-preload-error-number").text(number);
WpfcSinglePreload.change_status();
},
increase_cached: function(){
var number = jQuery("#wpfc-single-preload-cached-number").text();
number = parseInt(number) + 1;
jQuery("#wpfc-single-preload-cached-number").text(number);
WpfcSinglePreload.change_status();
},
running_animation: function(){
let label = jQuery("#wpfc-single-preload-status-runnig");
let text = label.text();
let dot = 0;
label.text(text + ".");
self.interval = setInterval(function(){
text = label.text();
dot = text.match(/\./g);
if(dot){
if(dot.length < 3){
label.text(text + ".");
}else{
label.text(text.replace(/\.+$/, ""));
}
}else{
label.text(text + ".");
}
}, 300);
},
create_cache: function(list){
var action = function(url, user_agent, list){
var self = this;
jQuery("#wpfc-single-preload").show();
jQuery.ajax({
type: 'GET',
url: ajaxurl,
data: {"action": "wpfc_preload_single", "url": url, "user_agent": user_agent, "nonce" : wpfc_nonce},
dataType: "html",
timeout: 10000,
cache: false,
success: function(data){
if(data == "true"){
WpfcSinglePreload.increase_cached();
}else{
self.error_message = data;
WpfcSinglePreload.increase_error();
}
if(typeof list == "object"){
WpfcSinglePreload.create_cache(list);
}
},
error: function(error){
self.error_message = error.statusText;
WpfcSinglePreload.increase_error();
if(typeof list == "object"){
WpfcSinglePreload.create_cache(list);
}
}
});
};
let number_to_used = 3;
let sliced = list.slice(0, number_to_used);
list.splice(0, number_to_used);
jQuery.each(sliced, function( index, value ) {
console.log( value["url"] );
if(index == (number_to_used-1)){
setTimeout(function(){
action(value["url"], value["user-agent"], list);
}, 500);
}else{
setTimeout(function(){
action(value["url"], value["user-agent"], false);
}, 500);
}
});
}
};
jQuery(document).ready(function(){
if(!jQuery("#auto_cache_custom_meta_box").is(":visible")){
return;
}
if(jQuery("#message").find("a").attr("href")){
WpfcSinglePreload.init();
WpfcSinglePreload.running_animation();
WpfcSinglePreload.create_cache(<?php echo json_encode(self::$urls); ?>);
}
});
</script>
<?php
}
}
?>

View File

@@ -0,0 +1,178 @@
<?php
class VarnishWPFC{
public static function purge_cache($data = false) {
if(isset($GLOBALS["wpfc_varnish_purge_cache_executed"])){
return;
}else{
$GLOBALS["wpfc_varnish_purge_cache_executed"] = true;
}
if(gettype($data) == "array"){
// Clearing page cache action sends the data as Array
if(isset($data["status"]) && $data["status"] == "pause"){
return array("success" => true);
}
$server = $data["server"];
}else{
// Ajax request and save() function send the data as string
$server = $data;
}
$home = get_option('home');
$host = preg_replace("/(https?\:\/\/)(.+)/", "$2", $home);
$host = preg_replace("/\/.*/", "", $host);
$schema = preg_replace("/(https?\:\/\/).+/", "$1", $home);
$schema = strtolower($schema);
$ssl_verification = $schema == 'https://' ? true : false;
$request_url = $schema.$server."/.*";
$request_args = array(
'method' => "PURGE",
'headers' => array(
'Host' => $host,
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
),
'sslverify' => $ssl_verification,
);
$response = wp_remote_request($request_url, $request_args );
if(is_wp_error( $response ) || $response['response']['code'] != '200'){
if($schema === 'https://'){
$request_url = str_replace("https://", "http://", $request_url);
}else{
$request_url = str_replace("http://", "https://", $request_url);
}
$response = wp_remote_request($request_url, $request_args );
if(is_wp_error( $response ) || $response['response']['code'] != '200'){
if($response->get_error_messages()){
return array("success" => "", "message" => $response->get_error_message());
}
if($response['response']['code'] == "501"){
$text = '"Purge" method is not allowed';
if(isset($response['headers']['allow'])){
$text = $text.". The allowed methods are ".$response['headers']['allow'];
$text = $text.". Please contact your hosting provider";
}
return array("success" => "", "message" => $text);
}
}
}
return array("success" => true);
}
public static function save(){
if(!wp_verify_nonce($_POST["security"], 'wpfc-varnish-ajax-nonce')){
die( 'Security check' );
}
$_POST["server"] = sanitize_text_field($_POST["server"]);
$purce_res = self::purge_cache($_POST["server"]);
if(!$purce_res["success"]){
wp_send_json($purce_res);
}
$datas = get_option("WpFastestCacheVarnish");
if(!is_array($datas)){
$datas = array();
$datas["server"] = $_POST["server"];
add_option("WpFastestCacheVarnish", $datas, 1, "yes");
}else{
$datas["server"] = $_POST["server"];
update_option("WpFastestCacheVarnish", $datas, 1, "yes");
}
wp_send_json_success();
}
public static function status(){
$datas = get_option("WpFastestCacheVarnish");
if(is_array($datas)){
if(isset($datas["status"]) && $datas["status"] == "pause"){
echo "isConnected pause";
}else{
echo "isConnected";
}
}
}
public static function start(){
if(!wp_verify_nonce($_POST["security"], 'wpfc-varnish-ajax-nonce')){
die( 'Security check' );
}
$datas = get_option("WpFastestCacheVarnish");
if(is_array($datas)){
unset($datas["status"]);
$purce_res = self::purge_cache($datas);
if(!$purce_res["success"]){
wp_send_json($purce_res);
}
update_option("WpFastestCacheVarnish", $datas, 1, "yes");
}
wp_send_json_success();
}
public static function pause(){
if(!wp_verify_nonce($_POST["security"], 'wpfc-varnish-ajax-nonce')){
die( 'Security check' );
}
$datas = get_option("WpFastestCacheVarnish");
if(is_array($datas)){
$datas["status"] = "pause";
update_option("WpFastestCacheVarnish", $datas, 1, "yes");
}
wp_send_json_success();
}
public static function remove(){
if(!wp_verify_nonce($_POST["security"], 'wpfc-varnish-ajax-nonce')){
die( 'Security check' );
}
delete_option("WpFastestCacheVarnish");
wp_send_json_success();
}
}
?>

View File

@@ -0,0 +1,63 @@
<?php
class WpPollsForWpFc{
public function __construct(){
}
public function hook(){
add_action( 'wp_ajax_nopriv_wpfc_wppolls_ajax_request', array($this, "wpfc_wppolls_ajax_request"));
add_action( 'wp_ajax_wpfc_wppolls_ajax_request', array($this, "wpfc_wppolls_ajax_request"));
add_action( 'wp_footer', array($this, "wpfc_wp_polls") );
}
public function wpfc_wp_polls() { ?>
<script type="text/javascript">
jQuery(document).ready(function(){
var wpfcWpfcAjaxCall = function(polls){
if(polls.length > 0){
poll_id = polls.last().attr('id').match(/\d+/)[0];
jQuery.ajax({
type: 'POST',
url: pollsL10n.ajax_url,
dataType : "json",
data : {"action": "wpfc_wppolls_ajax_request", "poll_id": poll_id, "nonce" : "<?php echo wp_create_nonce('wpfcpoll'); ?>"},
cache: false,
success: function(data){
if(data === true){
poll_result(poll_id);
}else if(data === false){
poll_booth(poll_id);
}
polls.length = polls.length - 1;
setTimeout(function(){
wpfcWpfcAjaxCall(polls);
}, 1000);
}
});
}
};
var polls = jQuery('div[id^=\"polls-\"][id$=\"-loading\"]');
wpfcWpfcAjaxCall(polls);
});
</script><?php
}
public function wpfc_wppolls_ajax_request(){
if(wp_verify_nonce(esc_attr($_POST["nonce"]), 'wpfcpoll')){
$result = check_voted(esc_attr($_POST["poll_id"]));
if($result){
die("true");
}else{
die("false");
}
}else{
die("Expired: wpfcpoll");
}
}
}
?>