false, "ttl" => 900, self::EXCLUDED_PATHS => [], "lazy" => true, "hero" => 0, "defer" => [], "products" => false, ]; } public static function settings(): array { return array_merge( self::defaults(), (array) get_option(self::OPTION, []), ); } public static function dir(): string { return WP_CONTENT_DIR . "/cache/ssf-speed-cache"; } public static function config_file(): string { return self::dir() . "/config.php"; } public static function ready(): bool { $drop = WP_CONTENT_DIR . "/advanced-cache.php"; return defined("WP_CACHE") && WP_CACHE && is_file($drop) && str_contains((string) file_get_contents($drop), self::MARKER); } public static function boot(): void { add_action("template_redirect", [self::class, "capture"], PHP_INT_MAX); foreach ( [ "save_post", "deleted_post", "transition_post_status", "switch_theme", "customize_save_after", "edited_term", "created_term", "delete_term", "comment_post", "edit_comment", "transition_comment_status", "woocommerce_product_set_stock", "woocommerce_variation_set_stock", ] as $hook ) { add_action($hook, [self::class, "changed"]); } add_action("updated_option", [self::class, "option_changed"], 10, 3); add_action("activated_plugin", [self::class, "changed"]); add_action("deactivated_plugin", [self::class, "changed"]); add_action("ssfspeed_maintenance", [self::class, "cleanup"]); add_filter( "ssfseo_cache_allowed", static fn($allowed) => self::settings()["enabled"] && self::ready() && self::conflict() === "" ? false : $allowed, ); } public static function activate(): void { add_option(self::OPTION, self::defaults(), "", "no"); self::sync(true); if (!wp_next_scheduled("ssfspeed_maintenance")) { wp_schedule_event(time() + 3600, "daily", "ssfspeed_maintenance"); } } public static function deactivate(): void { $s = self::settings(); $s["enabled"] = false; update_option(self::OPTION, $s, false); self::sync(true); $drop = WP_CONTENT_DIR . "/advanced-cache.php"; if ( is_file($drop) && str_contains((string) file_get_contents($drop), self::MARKER) ) { wp_delete_file($drop); } wp_clear_scheduled_hook("ssfspeed_maintenance"); wp_clear_scheduled_hook("ssfspeed_preload"); } public static function conflict(): string { $known = [ "wp-rocket/", "litespeed-cache/", "wp-super-cache/", "w3-total-cache/", "wp-fastest-cache/", "cache-enabler/", "breeze/", "wp-optimize/", "sg-cachepress/", ]; $plugins = array_merge( (array) get_option("active_plugins", []), array_keys((array) get_site_option("active_sitewide_plugins", [])), ); foreach ($plugins as $plugin) { foreach ($known as $name) { if (str_starts_with($plugin, $name)) { return $name; } } } if (!empty(get_option("ssfseo_performance", [])["cache"])) { return "SSF SEO Toolkit rendering cache"; } $drop = WP_CONTENT_DIR . "/advanced-cache.php"; if ( is_file($drop) && !str_contains((string) file_get_contents($drop), self::MARKER) ) { return "another advanced-cache.php"; } if (is_multisite()) { return "multisite-not-supported-in-1.0"; } return ""; } public static function paths(): array { $paths = []; $page = 1; do { $ids = get_posts([ "post_type" => self::settings()["products"] ? ["post", "page", "product"] : ["post", "page"], "post_status" => "publish", "posts_per_page" => 200, "paged" => $page, "fields" => "ids", "orderby" => "ID", "order" => "ASC", "has_password" => false, "suppress_filters" => false, ]); foreach ($ids as $id) { $post = get_post($id); if (!$post || $post->post_password !== "") { continue; } if ( $post->post_type === "product" && function_exists("wc_get_product") ) { $p = wc_get_product($id); if (!$p || $p->get_catalog_visibility() === "hidden") { continue; } } $url = get_permalink($id); $path = wp_parse_url($url, PHP_URL_PATH); if ( !wp_parse_url($url, PHP_URL_QUERY) && Engine::path((string) $path) !== "" ) { $paths[] = $path; } } ++$page; } while (count($ids) === 200); if (get_option("show_on_front") === "posts") { $paths[] = wp_parse_url(home_url("/"), PHP_URL_PATH); } return array_values(array_unique($paths)); } public static function exclusions(): array { $paths = self::settings()["exclude"]; if (function_exists("wc_get_page_id")) { foreach (["cart", "checkout", "myaccount"] as $name) { $id = wc_get_page_id($name); if ($id > 0) { $paths[] = wp_parse_url(get_permalink($id), PHP_URL_PATH); } } } return array_values(array_filter(array_unique($paths))); } public static function sync(bool $rotate = false): bool { $dir = self::dir(); if (!is_dir($dir) && !wp_mkdir_p($dir)) { return false; } if (!is_file($dir . "/index.php")) { file_put_contents($dir . "/index.php", " $s["enabled"] && self::ready(), "ttl" => $s["ttl"], self::EXCLUDED_PATHS => self::exclusions(), "paths" => $s["enabled"] && self::ready() && !self::conflict() ? self::paths() : [], "generation" => $gen, "host" => $host, "scheme" => $home["scheme"], "dir" => $dir, "conflict" => self::conflict(), ]; return Engine::atomic( self::config_file(), " $old, "after" => $new]); } public static function rollback(): string { $old = get_option("ssfspeed_previous"); if (!is_array($old)) { return "No previous settings snapshot."; } self::save($old, "Restore previous settings"); return "Previous settings restored and cache invalidated."; } public static function log(string $label, array $data = []): void { $rows = (array) get_option("ssfspeed_history", []); $rows[] = [ "time" => gmdate("c"), "action" => $label, "user" => get_current_user_id(), "data" => $data, ]; update_option("ssfspeed_history", array_slice($rows, -30), false); } public static function changed(...$unused): void { self::sync(true); } public static function option_changed(string $name, $old, $new): void { if (str_starts_with($name, "ssfspeed_")) { return; } if ( in_array( $name, [ "active_plugins", "home", "siteurl", "permalink_structure", "show_on_front", "page_on_front", "page_for_posts", "ssfseo_performance", "ssfseo_images", "blogname", "blogdescription", "WPLANG", "timezone_string", "date_format", "time_format", "blog_public", ], true, ) || str_starts_with($name, "woocommerce_") || str_starts_with($name, "theme_mods_") || str_starts_with($name, "widget_") || $name === "sidebars_widgets" ) { self::sync(true); } } public static function purge(?string $path = null): void { if ($path === null) { self::sync(true); self::log("Purge all cache"); return; } if (Engine::path($path) === "") { return; } Engine::atomic( self::dir() . "/v-" . hash("sha256", $path) . ".php", Engine::GUARD . bin2hex(random_bytes(12)), ); self::log("Purge one path", ["path" => $path]); } public static function config(): array { $f = self::config_file(); return is_file($f) ? (array) include $f : []; } public static function capture(): void { if ( is_admin() || wp_doing_ajax() || wp_doing_cron() || is_feed() || is_404() || is_search() || is_preview() || is_user_logged_in() || (is_singular() && !is_post_publicly_viewable(get_queried_object())) || post_password_required() || (defined("DONOTCACHEPAGE") && DONOTCACHEPAGE) ) { return; } $c = self::config(); $reason = Engine::reason($_SERVER, $c); if ($reason !== "eligible") { if (!headers_sent()) { header("X-SSF-Speed-Cache: BYPASS; " . $reason); } return; } if (self::conflict() !== "" || !self::ready()) { return; } $path = Engine::request_path($_SERVER); if ($path === "") { return; } $key = Engine::key($c, $path); self::$capture = [$c, $path, $key]; ob_start([self::class, "finish"]); } public static function finish(string $html, int $phase = 0): string { if (!self::$capture) { return $html; } [$c, $path, $key] = self::$capture; self::$capture = null; // An explicitly flushed or cleaned buffer is not a complete document. if ( $phase && (!($phase & PHP_OUTPUT_HANDLER_FINAL) || $phase & PHP_OUTPUT_HANDLER_CLEAN) ) { return $html; } $reason = Engine::safe_response( $html, headers_list(), http_response_code() ?: 200, ); $current = self::config(); if ( $reason === "eligible" && !empty($current["enabled"]) && ($current["generation"] ?? "") === $c["generation"] && Engine::key($current, $path) === $key && !(defined("DONOTCACHEPAGE") && DONOTCACHEPAGE) ) { $safe = array_values( array_filter( headers_list(), fn($h) => preg_match( '~^(?:Content-Language|X-Frame-Options|X-Content-Type-Options|Referrer-Policy|Permissions-Policy|Strict-Transport-Security|Cross-Origin-Opener-Policy|Cross-Origin-Embedder-Policy|Cross-Origin-Resource-Policy|Content-Security-Policy-Report-Only|Content-Security-Policy):[^\r\n]+$~i', $h, ), ), ); $entry = [ "created" => time(), "expires" => time() + $c["ttl"], "html" => $html, "headers" => $safe, ]; $saved = Engine::atomic( $c["dir"] . "/p-" . $key . ".php", Engine::GUARD . wp_json_encode($entry, JSON_HEX_TAG), ); if (!headers_sent()) { header( "X-SSF-Speed-Cache: " . ($saved ? "MISS; stored" : "MISS; write-failed"), ); } } elseif (!headers_sent()) { header("X-SSF-Speed-Cache: BYPASS; " . $reason); } return $html; } public static function inspect(string $path): array { $c = self::config(); $fake = [ "REQUEST_METHOD" => "GET", "HTTP_HOST" => $c["host"] ?? "", "HTTPS" => ($c["scheme"] ?? "") === "https" ? "on" : "off", "REQUEST_URI" => $path, ]; $r = Engine::reason($fake, $c); $entry = $r === "eligible" ? Engine::read($c, $path) : null; return [ "path" => $path, "anonymous_request_rule" => $r, "fresh_entry" => (bool) $entry, "created" => $entry ? gmdate("c", $entry["created"]) : null, "bytes" => $entry ? strlen($entry["html"]) : 0, "note" => "Configuration and stored-file evidence; a real request may bypass for cookies, tokens, forms, response headers or a host cache.", ]; } public static function cleanup(): void { $files = glob(self::dir() . "/p-*.php") ?: []; $count = 0; foreach ($files as $f) { if (++$count > 500) { break; } if (is_file($f) && filemtime($f) < time() - 86400) { wp_delete_file($f); } } } }