includes/class-util.php
PerformanceOptimise Utility Class
Class Util
Utility class for performing various file system and resource management tasks.
class UtilConstants
| Constant | Visibility | Value | Line |
|---|---|---|---|
ALLOWED_SETTINGS_KEYS | public | Settings_Store::ALLOWED_SETTINGS_KEYS | 50 |
ALLOWED_SETTINGS_TABS | public | Settings_Store::ALLOWED_SETTINGS_TABS | 66 |
UNINSTALL_OPTIONS | public | array( \'wppo_settings\', \'wppo_img_info\', \'wppo_transient_index\', \'wppo_preload_cron_offset\', \'wppo_last_db_cleanup\', \'wppo_version\', \'wppo_block_assets_migrated\', \'wppo_cache_last_cleared\', \'wppo_cache_last_cleared_time\', \'wppo_activation_time\', \'wppo_activity_cache_version\', \'wppo_audit_salt\', \'wppo_db_cleanup_salt\', \'wppo_activity_log_salt\', \'wppo_img_info_salt\', \'wppo_review_dismissed\', \'wppo_review_snoozed_until\', \'wppo_web_vitals_rum\', \'wppo_ai_model\', \'wppo_web_vitals_trends\', \'wppo_web_vitals_trends_lock\', \'wppo_web_vitals_last_rescan\', \'wppo_preload_cron_last_id\', \'wppo_preload_cron_migrated\', \'wppo_img_scan_cursor\', \'wppo_img_scan_cursor_max\', \'wppo_litespeed_purge_queue\', \'wppo_autoload_remediated\', \'wppo_autoload_migrated\', \'wppo_ccss_salt\', \'wppo_sysinfo_salt\', \'wppo_rum_top_url_gen\', \'wppo_remove_query_strings_deprecated_logged\', \'wppo_ai_anomaly_last_alarm\', \'wppo_object_cache_circuit\', \'wppo_object_cache_circuit_dismissed\', \'wppo_used_css_last_full_regen\', \'wppo_used_css_last_targeted_regen\', \'wppo_ccss_last_full_regen\', \'wppo_ccss_last_targeted_regen\', \'wppo_settings_snapshot\', \'wppo_preload_queue\', \'wppo_ai_css_refresh_snapshots\', \'wppo_ai_anomaly_breach_state\', \'wppo_ai_deploy_notes\', \'wppo_callback_secret\', \'wppo_last_purge\', ) | 89 |
FRONT_PAGE_LCP_OPTION_PREFIX | public | \'wppo_front_page_lcp_\' | 151 |
EDITOR_PREVIEW_PARAMS | public | array( \'elementor-preview\', \'et_fb\', \'et_pb_preview\', \'vc_action\', \'vc_editable\', \'bricks\', \'preview\', \'preview_id\', \'customize_changeset_uuid\', \'customizer\', ) | 163 |
SETTINGS_SNAPSHOT_OPTION | public | \'wppo_settings_snapshot\' | 202 |
OPTIMIZATION_PRESET_NAMES | public | array( \'safe\', \'balanced\', \'aggressive\' ) | 253 |
CALLBACK_SECRET_OPTION | public | \'wppo_callback_secret\' | 2677 |
CSS_STORAGE_MAX_BYTES | public | 1048576 | 2689 |
Properties
| Property | Visibility | Type | Default | Line |
|---|---|---|---|---|
$permalink_cache | private static | array | array() | 1213 |
$callback_secret_memo | private static | ?string | null | 2866 |
$html_processor_available | private static | ?bool | null | 4012 |
$committed_inline_bytes | private static | int | 0 | 4551 |
publicstatic get_allowed_settings_keys()
public static function get_allowed_settings_keys(): arrayGet the allowlisted top-level settings keys.
Return: string[].
publicstatic get_settings_snapshot()
public static function get_settings_snapshot(): ?arrayRead the stored prior-settings snapshot.
Return: array|null — Snapshot array with `settings` + `taken_at` keys, or null when absent/malformed.
publicstatic take_settings_snapshot()
public static function take_settings_snapshot(?array=null $settings): boolStore the given settings as the one-click-undo snapshot. Parameter Type Default Description $settings?array=null— Settings to snapshot (defaults to the current stored settings).
Return: bool — True when the snapshot was written.
publicstatic restore_settings_snapshot()
public static function restore_settings_snapshot(): ?arrayRestore `wppo_settings` from the stored snapshot.
Return: array|null — The restored settings array, or null when no valid snapshot exists or the write failed.
publicstatic get_preset_safety_guards()
public static function get_preset_safety_guards(): arrayFail-safe keys that presets must never turn off.
Return: array<string, — array<string, bool>> Guards keyed by tab.
publicstatic get_optimization_presets()
public static function get_optimization_presets(): arrayOne-click Safe / Balanced / Aggressive preset definitions.
Return: array<string, — array<string, array<string, mixed>>> Preset name => tab => key => value.
publicstatic get_preset_diff()
public static function get_preset_diff(string $preset, ?array=null $current): arrayDiff a preset against the current settings (preview before apply). Parameter Type Default Description $presetstring— Preset name (safe|balanced|aggressive). $current?array=null— Optional current settings (defaults to get_settings()).
Return: array[] — List of {tab, key, from, to} entries that would change.
publicstatic apply_optimization_preset()
public static function apply_optimization_preset(string $preset): ?arrayApply a one-click optimization preset on top of the current settings. Parameter Type Default Description $presetstring— Preset name (safe|balanced|aggressive).
Return: array|null — {preset, settings, diff} on success, null on failure.
publicstatic get_default_settings()
public static function get_default_settings(): arrayGet default settings structure for fresh installs.
Return: array<string, — array<string, mixed>> Default settings keyed by tab.
publicstatic get_settings_schema()
public static function get_settings_schema(): arrayCanonical settings schema for verify/validation.
Return: array<string, — array<string, string>> Schema keyed by tab.
publicstatic is_woo_safe_mode_enabled()
public static function is_woo_safe_mode_enabled(?array=null $settings): boolWhether WooCommerce safe mode is enabled. Parameter Type Default Description $settings?array=null— Optional settings array (defaults to get_settings()).
Return: bool — True when safe mode is enabled.
publicstatic is_woo_store_api_path()
public static function is_woo_store_api_path(string $path): boolWhether a normalized request path is a WooCommerce Store API route. Parameter Type Default Description $pathstring— Request path (leading slash optional) or a `rest_route` value.
Return: bool — True when the path is a Store API route.
publicstatic is_woo_store_api_request()
public static function is_woo_store_api_request(string=\'\' $path, ?string=null $query_string, ?string=null $rest_route): boolWhether the current request targets a WooCommerce Store API route. Parameter Type Default Description $pathstring=\'\'— Request path (leading slash optional). $query_string?string=null— Optional raw query string (defaults to `$_SERVER[\’QUERY_STRING\’]`). $rest_route?string=null— Optional `rest_route` value (defaults to `$_GET[\’rest_route\’]`).
Return: bool — True when the request is a Store API request.
publicstatic is_woo_dynamic_path()
public static function is_woo_dynamic_path(string $path): boolWhether a request path belongs to a WooCommerce dynamic page. Parameter Type Default Description $pathstring— Request path (leading slash optional).
Return: bool — True when the path is Woo-dynamic.
publicstatic get_woo_excluded_paths()
public static function get_woo_excluded_paths(): arrayRelative paths treated as WooCommerce endpoints for static-cache bypass.
Return: string[] — Relative paths (e.g. `cart`, `shop/basket`), unique, lowercased.
publicstatic is_woo_active()
public static function is_woo_active(): boolWhether WooCommerce is active on the current site.
Return: bool — True when any WooCommerce symbol is available.
publicstatic is_woo_faceted_query()
public static function is_woo_faceted_query(?string=null $query_string): boolWhether a query string carries WooCommerce layered-nav / faceted-filter params. Parameter Type Default Description $query_string?string=null— Raw query string. Defaults to `$_SERVER[\’QUERY_STRING\’]`.
Return: bool — True when faceted params are present.
publicstatic is_admin_path()
public static function is_admin_path(string $path): boolWhether a request path targets a wp-admin / login / AJAX entry point. Parameter Type Default Description $pathstring— Request path (leading slash optional).
Return: bool — True when the path is an admin entry point.
publicstatic is_editor_preview_path()
public static function is_editor_preview_path(string=\'\' $path, string=\'\' $query_string, string=\'\' $rest_route): boolWhether path/query values indicate a builder or core preview context. Parameter Type Default Description $pathstring=\'\'— Request path (leading slash optional). $query_stringstring=\'\'— Raw query string (without leading `?`). $rest_routestring=\'\'— Optional `rest_route` value (plain permalinks).
Return: bool — True when the values indicate a preview context.
publicstatic is_woo_ajax_request()
public static function is_woo_ajax_request(string=\'\' $path, string=\'\' $query_string): boolWhether path/query values indicate a WooCommerce AJAX endpoint. Parameter Type Default Description $pathstring=\'\'— Request path (leading slash optional). $query_stringstring=\'\'— Raw query string (without leading `?`).
Return: bool — True when the values indicate a wc-ajax request.
publicstatic is_woo_add_to_cart_request()
public static function is_woo_add_to_cart_request(string=\'\' $query_string): boolWhether a query string carries a WooCommerce add-to-cart action. Parameter Type Default Description $query_stringstring=\'\'— Raw query string (without leading `?`).
Return: bool — True when the query carries an add-to-cart action.
publicstatic is_woo_excluded_url()
public static function is_woo_excluded_url(string $url, string=\'\' $query, string=\'\' $rest_route): boolWhether an absolute URL targets a WooCommerce dynamic route. Parameter Type Default Description $urlstring— Absolute URL. $querystring=\'\'— Optional pre-parsed query string (parsed from $url when \’\’). $rest_routestring=\'\'— Optional pre-parsed rest_route value.
Return: bool — True when the URL must not be cached/preloaded.
publicstatic is_editor_preview_url()
public static function is_editor_preview_url(string $url): boolWhether an absolute URL targets an admin or preview context. Parameter Type Default Description $urlstring— Absolute URL.
Return: bool — True when the URL must bypass cache/preload.
publicstatic is_editor_preview_request()
public static function is_editor_preview_request(): boolWhether the current request is an admin, AJAX/REST, or preview context.
Return: bool — True when the current request must bypass the cache.
publicstatic woo_cache_self_test()
public static function woo_cache_self_test(): arrayVerifiable WooCommerce cart/checkout cache-exclusion self-test.
Return: array{woo_active: — bool, safe_mode: bool, runnable: bool, excluded_paths: string[], donotcachepage_honored: bool, checks: array<int, array{url: string, path: string, is_dynamic: bool, cacheable: bool, donotcachepage_honored: bool, pass: bool, error?: string}>, fragment_checks: array<int, array{url: string, path: string, is_dynamic: bool, cacheable: bool, donotcachepage_honored: bool, pass: bool, error?: string}>, editor_checks: array<int, array{url: string, bypass: bool, cacheable: bool, donotcachepage_honored: bool, pass: bool, error?: string}>, preload_checks: array<int, array{url: string, path: string, skipped: bool, pass: bool, error?: string}>, cart_checks: array<int, array{key: string, url: string, bypass: bool, cacheable: bool, donotcachepage_honored: bool, pass: bool, error?: string}>, force_exclude: bool, all_pass: bool} Structured self-test result.
publicstatic reset_cached_home_urls()
public static function reset_cached_home_urls(): voidResets the home_url static cache for testing isolation.
Return: void.
publicstatic reset_runtime_caches()
public static function reset_runtime_caches(): voidResets all Util runtime memos (test-isolation entry point).
Return: void.
publicstatic memoized_permalink()
public static function memoized_permalink(int $post_id): stringGet a permalink through the per-request memo. Parameter Type Default Description $post_idint— Post ID.
Return: string — Permalink, or \’\’ when unavailable (false from get_permalink()).
publicstatic clear_permalink_cache()
public static function clear_permalink_cache(): voidClear the per-request permalink memo (testing isolation, switch_blog).
Return: void.
privatestatic current_blog_id()
private static function current_blog_id(): intResolve current blog ID safely (handles Brain Monkey stub mis-configuration in tests).
Return: int — Blog ID.
publicstatic get_settings()
public static function get_settings(): arrayGet wppo_settings with per-request memoization.
Return: array — The plugin settings.
publicstatic set_settings_cache()
public static function set_settings_cache(array $settings): voidSet the settings cache to a known value (e.g. after update_option in same request). Parameter Type Default Description $settingsarray— The settings to cache.
Return: void.
publicstatic save_settings()
public static function save_settings(array $settings): boolPersist wppo_settings with autoload disabled (audit #1325). Parameter Type Default Description $settingsarray— Settings array to store.
Return: bool — True on success (mirrors update_option()).
publicstatic clear_settings_cache()
public static function clear_settings_cache(=null $blog_id): voidClear the settings memo (e.g. in tests or on delete). Parameter Type Default Description $blog_id=null— Optional blog ID to clear. Null clears all.
Return: void.
publicstatic on_switch_blog()
public static function on_switch_blog($new_blog_id, $prev_blog_id): voidHandler for switch_blog — clears stale memo association. Parameter Type Default Description $new_blog_idint— New blog ID. $prev_blog_idint— Previous blog ID.
Return: void.
publicstatic register_settings_cache_hooks()
public static function register_settings_cache_hooks(): voidRegister the settings-cache invalidation hooks eagerly.
Return: void.
privatestatic ensure_settings_cache_hook()
private static function ensure_settings_cache_hook(): voidEnsure the invalidation hooks for wppo_settings are registered once per request.
Return: void.
publicstatic on_settings_update()
public static function on_settings_update($old_value, $value): voidInvalidate/update the memo when wppo_settings is updated. Parameter Type Default Description $old_valuemixed— Previous value. $valuemixed— New value.
Return: void.
publicstatic on_settings_add()
public static function on_settings_add($option, $value): voidPopulate the memo when wppo_settings is added. Parameter Type Default Description $optionstring— Option name. $valuemixed— Option value.
Return: void.
publicstatic prepare_cache_dir()
public static function prepare_cache_dir($cache_dir): boolRecursively creates cache directory if not exists. Parameter Type Default Description $cache_dirstring— Path to the cache directory.
Return: bool — True if created or exists, false otherwise.
publicstatic init_filesystem()
public static function init_filesystem()Initializes the WP_Filesystem API.
Return: mixed — WP_Filesystem_Base|false The filesystem object or false on failure.
publicstatic get_local_path()
public static function get_local_path(string $url): stringGets the local file path from a URL. Parameter Type Default Description $urlstring— The URL to process.
Return: string — The local file path.
publicstatic get_minify_allowed_roots()
public static function get_minify_allowed_roots(): arrayGets the allow-listed filesystem roots for minify/combine file serving.
Return: string[] — Normalized absolute root paths.
publicstatic is_minify_path_allowed()
public static function is_minify_path_allowed($path): boolWhether a minify/combine source path is allowed to be read. Parameter Type Default Description $pathmixed— Candidate filesystem path.
Return: bool — True when the path resolves inside an allowed root.
publicstatic validate_minify_path()
public static function validate_minify_path($path): stringValidates a minify/combine source path and returns its resolved form. Parameter Type Default Description $pathmixed— Candidate filesystem path.
Return: string — Resolved allowed path, or \’\’ when rejected.
publicstatic get_js_css_minified_file()
public static function get_js_css_minified_file()Gets the number of minified JS and CSS files.
Return: array — Associative array with counts for JS and CSS files.
publicstatic get_image_mime_type()
public static function get_image_mime_type($url)Gets MIME type based on image URL extension. Parameter Type Default Description $urlstring— The image URL.
Return: string — The MIME type.
publicstatic generate_preload_link()
public static function generate_preload_link($href, $rel, =\'\' $resource_type, =false $crossorigin, =\'\' $type, =\'\' $media, =\'\' $fetchpriority, =\'\' $imagesrcset, =\'\' $imagesizes)Generates a preload link tag for resources. Parameter Type Default Description $hrefstring— The resource URL. $relstring— The relationship attribute. $resource_type=\'\'— The type of the resource (optional). $crossorigin=false— If the resource should be crossorigin (optional). $type=\'\'— The type attribute (optional). $media=\'\'— The media attribute (optional). $fetchpriority=\'\'— The fetchpriority attribute (optional). $imagesrcset=\'\'— Responsive srcset for image preloads (optional). $imagesizes=\'\'— Responsive sizes for image preloads (optional).
publicstatic get_preload_link()
public static function get_preload_link($href, $rel, =\'\' $resource_type, =false $crossorigin, =\'\' $type, =\'\' $media, =\'\' $fetchpriority, =\'\' $imagesrcset, =\'\' $imagesizes): stringBuild a sanitized preload <link> tag and return it. Parameter Type Default Description $hrefstring— The resource URL. $relstring— The relationship attribute. $resource_type=\'\'— The type of the resource (optional). $crossorigin=false— If the resource should be crossorigin (optional). $type=\'\'— The type attribute (optional). $media=\'\'— The media attribute (optional). $fetchpriority=\'\'— The fetchpriority attribute (optional). $imagesrcset=\'\'— Responsive srcset for image preloads (optional). $imagesizes=\'\'— Responsive sizes for image preloads (optional).
Return: string — The sanitized `<link …>` tag.
publicstatic get_preload_link_args()
public static function get_preload_link_args(string $href, array=array() $args): stringBuild a sanitized preload <link> tag from an args array. Parameter Type Default Description $hrefstring— Resource URL. $argsarray=array()— Optional args: rel, as, crossorigin, type, media, fetchpriority, imagesrcset, imagesizes.
Return: string — Sanitized `<link …>` tag.
publicstatic process_urls()
public static function process_urls($urls)Normalize and deduplicate a list of URLs. Parameter Type Default Description $urlsstring|array— Raw URLs as a newline-delimited string or an array of strings.
Return: array — Cleaned list of unique, trimmed URLs with empty values removed and numeric keys reindexed.
publicstatic coerce_string_list()
public static function coerce_string_list($raw): arrayCoerce an untrusted string list (e.g. filter output) to a clean list. Parameter Type Default Description $rawmixed— Untrusted list value.
Return: string[] — Clean list.
publicstatic is_url_excluded()
public static function is_url_excluded(string $url, array $exclude_urls): boolCheck whether a URL matches any of the exclusion rules. Parameter Type Default Description $urlstring— The URL to check. $exclude_urlsarray— List of exclusion rules.
Return: bool — True when the URL matches any exclusion rule, false otherwise.
publicstatic get_current_url()
public static function get_current_url(): stringGet the current front-end URL including scheme and host.
Return: string — Current URL.
publicstatic normalize_rum_path()
public static function normalize_rum_path(string $path): stringNormalize a RUM page path for storage and lookup. Parameter Type Default Description $pathstring— Raw page path.
Return: string — Normalized path (e.g. \’/hero-page\’, \’/\’).
publicstatic normalize_url()
public static function normalize_url(string $url): stringNormalize a URL for LCP matching. Parameter Type Default Description $urlstring— The raw URL to normalize.
Return: string — Normalized host + path, or empty string when unparseable.
publicstatic normalize_site_url()
public static function normalize_site_url(string $url): stringResolve a site URL to an absolute https URL. Parameter Type Default Description $urlstring— Raw URL.
Return: string — Absolute URL or \’\’ when empty/data:.
publicstatic normalize_image_key()
public static function normalize_image_key(string $url): stringNormalize a URL to a stable image/cache key (host + path). Parameter Type Default Description $urlstring— Raw URL.
Return: string — Normalized key or \’\’.
publicstatic mint_placeholder_namespace()
public static function mint_placeholder_namespace(): stringMint a per-request placeholder token namespace.
Return: string — Non-empty namespace string.
publicstatic min_cache_base_dir()
public static function min_cache_base_dir(): stringBase (shared) minify cache directory.
Return: string — Normalized absolute path to the shared min cache root.
publicstatic min_cache_dir()
public static function min_cache_dir(string=\'\' $subdir): stringGet the current site\’s blog-scoped minify cache directory. Parameter Type Default Description $subdirstring=\'\'— Optional \’css\’ or \’js\’ subdirectory.
Return: string — Normalized absolute path to the site-scoped min cache dir.
publicstatic min_cache_url()
public static function min_cache_url(string=\'\' $subdir, string=\'\' $filename): stringGet the content URL for a file in the current site\’s min cache dir. Parameter Type Default Description $subdirstring=\'\'— Optional \’css\’ or \’js\’ subdirectory. $filenamestring=\'\'— Optional file name appended to the URL.
Return: string — The blog-scoped content URL.
publicstatic cached_content_url()
public static function cached_content_url($path)Get a content URL, cached per site per request. Parameter Type Default Description $pathstring— Path relative to the content directory.
Return: string — The content URL for the given path.
publicstatic canonical_scheme()
public static function canonical_scheme(): stringThe site\’s canonical URL scheme, independent of the current request.
Return: string — Either \’http\’ or \’https\’.
publicstatic cached_home_url()
public static function cached_home_url(string=\'\' $path): stringGet the home URL, cached per site per request. Parameter Type Default Description $pathstring=\'\'— Optional. Path relative to the home URL. Default empty.
Return: string — The untrailingslashed home URL, with path appended if provided.
publicstatic is_same_site_host()
public static function is_same_site_host(string $url): boolWhether a URL\’s host matches the home host (case-insensitive). Parameter Type Default Description $urlstring— URL to check.
Return: bool — True when hosts match and home host is known.
publicstatic is_same_site_url()
public static function is_same_site_url(string $url): boolWhether a URL is same-site and safe for server-side fetching. Parameter Type Default Description $urlstring— URL to check.
Return: bool — True when safe.
publicstatic same_site_url_or_home()
public static function same_site_url_or_home(string $url, string $fallback): stringValidate a caller-supplied URL as same-site, else the fallback. Parameter Type Default Description $urlstring— Caller URL (already esc_url_raw\’d by caller). $fallbackstring— Fallback (home URL, or \’\’ to fail closed).
Return: string — Same-site URL or the fallback.
publicstatic resolve_same_host_redirect()
public static function resolve_same_host_redirect(string $location, string $current_url): string|falseResolve a redirect Location against the current URL and validate it. Parameter Type Default Description $locationstring— Raw Location header value. $current_urlstring— URL of the response that sent the Location.
Return: string|false — Absolute validated URL, or false when the hop is not allowed.
publicstatic normalize_cache_host()
public static function normalize_cache_host(string $raw_host): stringNormalize a raw host value into a safe cache-key domain. Parameter Type Default Description $raw_hoststring— Raw host value (e.g. $_SERVER[\’HTTP_HOST\’] or a home_url() host).
Return: string — Normalized lowercase host, or \’\’ when invalid.
publicstatic get_canonical_host()
public static function get_canonical_host(): stringResolve the canonical host for cache keying from home_url().
Return: string — Canonical lowercase host, or \’\’ when it cannot be resolved.
publicstatic sanitize_cache_url_path()
public static function sanitize_cache_url_path(?string $url_path, ?string=null $allowed_host): stringSanitize a URL path for cache file mapping. Parameter Type Default Description $url_path?string— Raw URL path or URL. $allowed_host?string=null— Optional canonical host (alias: $domain / $canonical_host at call-sites); same-host absolute URLs map to their path, others refuse.
Return: string — Sanitized relative path or empty string.
publicstatic get_cache_query_allowlist()
public static function get_cache_query_allowlist(): arrayFilterable list of cache-neutral (tracking/marketing) query params.
Return: string[] — Lowercase cache-neutral query param names.
publicstatic has_uncacheable_query()
public static function has_uncacheable_query(?string=null $query_string): boolWhether a query string forces a dynamic (uncached) response. Parameter Type Default Description $query_string?string=null— Raw query string. Defaults to `$_SERVER[\’QUERY_STRING\’]`.
Return: bool — True when the request must bypass the cache.
publicstatic is_cache_path_contained()
public static function is_cache_path_contained(string $cache_root_dir, string $domain, string $path): boolWhether an absolute path stays inside the cache tree. Parameter Type Default Description $cache_root_dirstring— Absolute cache root directory. $domainstring— Canonical domain directory segment. $pathstring— Absolute file or directory path to check.
Return: bool — True when contained.
publicstatic is_realpath_contained()
public static function is_realpath_contained(string $cache_root_dir, string $domain, string $path): boolSymlink-aware containment check for cache write targets. Parameter Type Default Description $cache_root_dirstring— Absolute cache root directory. $domainstring— Canonical domain directory segment. $pathstring— Absolute file or directory path to check.
Return: bool — True when contained.
publicstatic resolve_realpath()
public static function resolve_realpath(string $lexical_path): ?stringResolve a path via realpath(), keeping the lexical remainder. Parameter Type Default Description $lexical_pathstring— Normalized absolute path to resolve.
Return: string|null — Resolved absolute path, or null when unresolvable.
publicstatic validate_cache_write_path()
public static function validate_cache_write_path(string $cache_root_dir, string $domain, string $path): boolSingle-call validator for absolute cache write targets. Parameter Type Default Description $cache_root_dirstring— Absolute cache root directory. $domainstring— Canonical domain directory segment. $pathstring— Absolute file path to validate.
Return: bool — True when the target may be written.
publicstatic is_htaccess_path_allowed()
public static function is_htaccess_path_allowed(string $htaccess_file): boolWhether an .htaccess target may be written by the plugin. Parameter Type Default Description $htaccess_filestring— Absolute .htaccess path candidate.
Return: bool — True when the target may be written.
publicstatic sanitize_cache_path()
public static function sanitize_cache_path(string $cache_root_dir, string $domain, $url_path_or_url, string $filename): stringBuild a contained absolute cache file path from its parts. Parameter Type Default Description $cache_root_dirstring— Absolute cache root directory. $domainstring— Canonical domain directory segment. $url_path_or_urlstring|null— Raw URL path or URL. $filenamestring— File name (e.g. `index.html`).
Return: string — Contained absolute path, or \’\’ when refused.
publicstatic atomic_tmp_path()
public static function atomic_tmp_path(string $final_path): stringBuild a unique sibling tmp path for atomic writes. Parameter Type Default Description $final_pathstring— Final file path the tmp sits beside.
Return: string — Tmp sibling path (\’\’ when input is empty).
publicstatic atomic_file_put_contents()
public static function atomic_file_put_contents($fs, string $path, string $contents): boolAtomically write contents via tmp-file + rename. Parameter Type Default Description $fsmixed— Filesystem object exposing put_contents()/move()/delete(). $pathstring— Final file path. $contentsstring— File contents.
Return: bool — True on success.
publicstatic verify_php_syntax()
public static function verify_php_syntax(string $code, string=\'\' $tmp_file_for_lint): boolCheck that PHP code parses without a syntax error. Parameter Type Default Description $codestring— PHP source to check. $tmp_file_for_lintstring=\'\'— Optional tmp file holding $code for `php -l`.
Return: bool — True when the code looks parseable.
publicstatic atomic_write_php_verified()
public static function atomic_write_php_verified($fs, string $path, string $contents, =null $expect): ?boolAtomically write PHP source with syntax verification and rollback. Parameter Type Default Description $fsmixed— Filesystem object exposing exists()/get_contents()/put_contents()/move()/copy()/delete(). $pathstring— Final file path. $contentsstring— New file contents. $expect=null— Optional assertion receiving contents, returning bool.
Return: bool|null — True on verified success, false on verified failure, null when unsupported.
publicstatic compute_css_checksum()
public static function compute_css_checksum(string $css): stringStable content hash of CSS source (issue #1038 / audit #7). Parameter Type Default Description $cssstring— CSS content.
Return: string — SHA-256 checksum, or \’\’ for empty input.
publicstatic sanitize_css_for_storage()
public static function sanitize_css_for_storage(string $css): stringSanitize derived CSS for safe storage inside <style> or a .css file. Parameter Type Default Description $cssstring— Raw CSS content.
Return: string — Sanitized CSS, or \’\’ when empty or on failure.
publicstatic css_within_storage_bounds()
public static function css_within_storage_bounds(string $css, int=self::CSS_STORAGE_MAX_BYTES $max_bytes): boolWhether derived CSS is within the size/charset storage bounds. Parameter Type Default Description $cssstring— CSS content. $max_bytesint=self::CSS_STORAGE_MAX_BYTES— Maximum accepted size in bytes.
Return: bool — True when the payload may be stored.
publicstatic reset_callback_secret_memo()
public static function reset_callback_secret_memo(): voidReset the per-request callback-secret memo (tests, switch_blog).
Return: void.
publicstatic get_callback_secret()
public static function get_callback_secret(bool=true $create): stringRead (or lazily create) the per-site callback HMAC secret. Parameter Type Default Description $createbool=true— Whether a missing secret may be created. Verify paths pass false (read-only) so a background worker never writes options on the hot verify path.
Return: string — Site secret, or \’\’ when unavailable.
publicstatic sign_callback_payload()
public static function sign_callback_payload(array $payload): stringSign a regeneration-callback payload with the site secret. Parameter Type Default Description $payloadarray— Job payload (scalar values).
Return: string — Hex signature, or \’\’ when unavailable.
publicstatic verify_callback_signature()
public static function verify_callback_signature(array $payload, string $signature): boolVerify a regeneration-callback payload signature. Parameter Type Default Description $payloadarray— Job payload as signed. $signaturestring— Hex signature to check.
Return: bool — True when the signature is valid.
publicstatic supports_script_strategy()
public static function supports_script_strategy(): boolWhether core supports the native `strategy` script args (WP 6.3+).
Return: bool — True on WP 6.3+.
publicstatic transient_key()
public static function transient_key(string $key): stringQualify a transient key with the current blog ID on multisite. Parameter Type Default Description $keystring— The bare transient key.
Return: string — Blog-ID-prefixed key on multisite, or the original key.
publicstatic option_key()
public static function option_key(string $key): stringQualify an option name with the current blog ID on multisite. Parameter Type Default Description $keystring— The bare option name.
Return: string — Blog-ID-prefixed option name on multisite, or the original name.
publicstatic supports_action_scheduler_unique()
public static function supports_action_scheduler_unique(): boolWhether the loaded Action Scheduler supports atomic unique actions.
Return: bool — True when the `$unique` parameter may be passed.
publicstatic reset_action_scheduler_unique_cache()
public static function reset_action_scheduler_unique_cache(): voidReset the memoized Action Scheduler unique-support probes.
Return: void.
publicstatic enqueue_unique_async_action()
public static function enqueue_unique_async_action(string $hook, array=array() $args, string=\'\' $group, array=array() $extra_groups): intEnqueue an async Action Scheduler job with atomic dedup when available. Parameter Type Default Description $hookstring— Action hook. $argsarray=array()— Action arguments. $groupstring=\'\'— Action group. $extra_groupsarray=array()— Additional groups probed by the legacy fallback guard (e.g. the CCSS legacy group).
Return: int — Action ID, or 0 when deduped, unavailable, or on failure.
publicstatic schedule_unique_single_action()
public static function schedule_unique_single_action(int $timestamp, string $hook, array=array() $args, string=\'\' $group, array=array() $extra_groups): intSchedule a one-off Action Scheduler job with atomic dedup when available. Parameter Type Default Description $timestampint— When the job will run. $hookstring— Action hook. $argsarray=array()— Action arguments. $groupstring=\'\'— Action group. $extra_groupsarray=array()— Additional groups probed by the legacy fallback guard (e.g. the CCSS legacy group).
Return: int — Action ID, or 0 when deduped, unavailable, or on failure.
publicstatic is_stampede_guard_enabled()
public static function is_stampede_guard_enabled(): boolWhether the stampede guard is enabled.
Return: bool — True when coalescing is active.
publicstatic stampede_lock_ttl()
public static function stampede_lock_ttl(): intEffective stampede lock TTL in seconds, clamped to 2-5s.
Return: int — Lock TTL clamped to 2-5 seconds.
publicstatic generate_stampede_owner()
public static function generate_stampede_owner(): stringGenerate a unique stampede lock owner token.
Return: string — Unique owner token (never empty).
publicstatic acquire_stampede_lock()
public static function acquire_stampede_lock(string $lock_key, string $owner, int=5 $ttl, string=\'wppo\' $group): boolAtomically acquire a named stampede lock. Parameter Type Default Description $lock_keystring— Blog-aware lock key (use transient_key()). $ownerstring— Unique owner token from generate_stampede_owner(). $ttlint=5— Lock TTL in seconds (clamped to 2-5s; best-effort bound — rebuilds slower than the TTL, e.g. a slow- origin telemetry fetch, may let the lock expire mid-rebuild and duplicate work). $groupstring=\'wppo\'— Object-cache group for the lock.
Return: bool — True when this worker owns the lock.
publicstatic release_stampede_lock()
public static function release_stampede_lock(string $lock_key, string $owner, string=\'wppo\' $group): voidRelease a stampede lock only when this worker still owns it. Parameter Type Default Description $lock_keystring— Blog-aware lock key. $ownerstring— Owner token that acquired the lock. $groupstring=\'wppo\'— Object-cache group for the lock.
Return: void.
publicstatic stampede_stale_key()
public static function stampede_stale_key(string $key): stringDerive the stale-copy transient key for a guarded value key. Parameter Type Default Description $keystring— Value cache key as passed to get_with_stampede_lock().
Return: string — Stale-copy key.
publicstatic register_transient_index_key()
public static function register_transient_index_key(string $key, int $ttl): voidBest-effort registration of a stale-copy key in `wppo_transient_index`. Parameter Type Default Description $keystring— Stale-copy transient key. $ttlint— Stale TTL in seconds (converted to an absolute expiry).
Return: void.
publicstatic get_with_stampede_lock()
public static function get_with_stampede_lock(string $key, callable $rebuild, array=array() $args): mixedGet a cached value or rebuild it under an atomic owner lock. Parameter Type Default Description $keystring— Value cache key as read/written by $args get/set (caller-qualified). $rebuildcallable— Zero-arg rebuild callback. Returning false or WP_Error means \”not cacheable\” (stale served when available). $argsarray=array()— Optional arguments accepting `ttl`, `stale_ttl`, `lock_ttl`, `retries`, `retry_delay_us`, `group`, `force`, `get_cached`, and `set_cached` keys.
Return: mixed — Fresh value, stale fallback, rebuild result, or false on total miss failure.
publicstatic get_alloptions_with_stampede_lock()
public static function get_alloptions_with_stampede_lock(callable $rebuild, array=array() $args): mixedCoalesce concurrent alloptions loads behind a stampede lock. Parameter Type Default Description $rebuildcallable— Zero-arg rebuild callback performing the single database query. Returning false or WP_Error means \”not cacheable\” (stale served when available). $argsarray=array()— Optional overrides for `ttl`, `stale_ttl`, `lock_ttl`, `retries`, `retry_delay_us`, and `group` (see get_with_stampede_lock()).
Return: mixed — Fresh value, stale fallback, rebuild result, or false on total miss failure.
publicstatic get_role_hash()
public static function get_role_hash(\\WP_User $user): stringCompute a stable 12-char hex hash of a user\’s sorted roles, salted with the site\’s secret to prevent cookie forgery. Parameter Type Default Description $user\\WP_User— The user whose roles to hash.
Return: string — 12-char hex hash, or empty string if the user has no roles.
publicstatic is_cache_eligible_for_current_user()
public static function is_cache_eligible_for_current_user(array $cache_settings): boolWhether the current user is eligible for logged-in caching based on the cache settings (enableLoggedInCache + loggedInCacheRoles). Parameter Type Default Description $cache_settingsarray— The cache_settings sub-array from wppo_settings.
Return: bool — True if the current user may receive cached pages / optimisations.
publicstatic is_auto_sizes_available()
public static function is_auto_sizes_available(): boolWhether the current WordPress version supports auto-sizes for lazy-loaded images.
Return: bool — True when auto-sizes is available.
publicstatic content_has_block()
public static function content_has_block(string $content, string $block_name): boolWhether content contains a block type via streaming processor. Parameter Type Default Description $contentstring— Post content. $block_namestring— Block name e.g. \’core/image\’.
Return: bool — True when the block type is present.
publicstatic count_blocks_by_type()
public static function count_blocks_by_type(string $content, string $block_name): intCount blocks of a given type in post content. Parameter Type Default Description $contentstring— Post content. $block_namestring— Block name e.g. \’core/gallery\’.
Return: int — Number of matching blocks.
privatestatic blocks_contain_type()
private static function blocks_contain_type(array $blocks, string $block_name): boolWhether a parsed block tree contains a block type (recursive). Parameter Type Default Description $blocksarray— Parsed blocks from parse_blocks(). $block_namestring— Block name.
Return: bool.
privatestatic count_blocks_recursive()
private static function count_blocks_recursive(array $blocks, string $block_name): intCount blocks of type in a parsed block tree (recursive). Parameter Type Default Description $blocksarray— Parsed blocks. $block_namestring— Block name.
Return: int.
publicstatic wildcard2regex()
public static function wildcard2regex(string $pattern): stringConvert wildcard pattern to regex fragment (mirrors CDN::wildcard2regex / LSCWP cdn.cls.php:188). Parameter Type Default Description $patternstring— Wildcard pattern.
Return: string — Regex fragment.
publicstatic sanitize_mode_value()
public static function sanitize_mode_value($value): stringSanitize the LiteSpeed integration `mode` value against its allowlist. Parameter Type Default Description $valuemixed— Raw value.
Return: string — Allowlisted mode (\’auto\’ fallback).
publicstatic sanitize_ttl_overrides()
public static function sanitize_ttl_overrides($value): arraySanitize per-post-type cache TTL overrides. Parameter Type Default Description $valuearray— Raw overrides.
Return: array — Sanitized overrides.
publicstatic sanitize_cdn_mapping()
public static function sanitize_cdn_mapping($value): arraySanitize the one-to-many CDN mapping list. Parameter Type Default Description $valuearray— Raw mapping entries.
Return: array — Sanitized mapping.
publicstatic sanitize_scalar_setting()
public static function sanitize_scalar_setting(string $safe_key, $value)Sanitize a scalar settings value with the generic fallback rules. Parameter Type Default Description $safe_keystring— Sanitized key. $valuemixed— Raw value.
Return: mixed — Sanitized value.
publicstatic get_settings_sanitizer_map()
public static function get_settings_sanitizer_map(): arrayMap of setting-tab slugs to their dedicated sanitizer methods.
Return: array<string,string> — Tab slug => sanitizer method name.
publicstatic sanitize_cache_settings()
public static function sanitize_cache_settings($settings): arraySanitize the `cache_settings` tab. Parameter Type Default Description $settingsarray— Raw tab settings.
Return: array — Sanitized tab settings.
publicstatic sanitize_file_optimisation()
public static function sanitize_file_optimisation($settings): arraySanitize the `file_optimisation` tab. Parameter Type Default Description $settingsarray— Raw tab settings.
Return: array — Sanitized tab settings.
publicstatic sanitize_settings_recursively()
public static function sanitize_settings_recursively($settings)Sanitizes the settings array recursively. Parameter Type Default Description $settingsarray— The settings array.
Return: array — The sanitized settings array.
publicstatic remove_sensitive_settings_from_response()
public static function remove_sensitive_settings_from_response(array& $settings): voidStrips sensitive values from a settings array before it leaves the server. Parameter Type Default Description $settingsarray&— The settings array passed by reference.
Return: void.
publicstatic cache_salt()
public static function cache_salt(string $option): stringCurrent value of a salted-cache salt (option-backed). Parameter Type Default Description $optionstring— Option key holding the salt.
Return: string — Current salt value (\’0\’ until the first bump).
publicstatic should_use_html_processor()
public static function should_use_html_processor(): boolWhether the WP 6.9+ HTML API token serializer is available.
Return: bool — True when `WP_HTML_Processor::serialize_token()` is public.
publicstatic reset_html_processor_memo()
public static function reset_html_processor_memo(): voidReset the memoized HTML-processor availability probe.
Return: void.
publicstatic create_html_processor()
public static function create_html_processor(string $html): ?\\WP_HTML_ProcessorCreate a WP_HTML_Processor for full-buffer rewrites. Parameter Type Default Description $htmlstring— HTML document or fragment.
Return: \\WP_HTML_Processor|null — Processor instance, or null on failure.
publicstatic safe_css_fallback_enabled()
public static function safe_css_fallback_enabled(): boolWhether the safe CSS combine/used-CSS fallback is enabled.
Return: bool — True when fallback guards are active.
publicstatic is_purge_fallback_enabled()
public static function is_purge_fallback_enabled(): boolWhether the post-purge last-good fallback is enabled.
Return: bool — True when purge-fallback retention/serving is active.
publicstatic get_purge_fallback_path_for()
public static function get_purge_fallback_path_for(string $file_path): stringMap a derived asset path to its sibling last-good fallback path. Parameter Type Default Description $file_pathstring— Absolute derived-asset path.
Return: string — Sibling fallback path, or \’\’ when not applicable.
publicstatic retain_purge_fallback_file()
public static function retain_purge_fallback_file($fs, callable $is_allowed, string $file_path): voidRetain a last-good fallback copy before a derived file is purged. Parameter Type Default Description $fsobject— Filesystem exposing exists()/size()/copy()/get_contents()/put_contents(). $is_allowedcallable— Containment validator: fn( string $path ): bool. $file_pathstring— The derived file about to be deleted.
Return: void.
publicstatic is_purge_fallback_payload_valid()
public static function is_purge_fallback_payload_valid($fs, string $fallback): boolWhether a retained fallback file holds a servable payload. Parameter Type Default Description $fsobject— Filesystem exposing size()/get_contents(). $fallbackstring— Absolute fallback path.
Return: bool — True when the fallback exists with non-empty content.
publicstatic get_staged_path_for()
public static function get_staged_path_for(string $file_path): stringMap a derived CSS/JS file to its sibling staged-rollout path. Parameter Type Default Description $file_pathstring— Absolute live derived-file path.
Return: string — Sibling staged path, or \’\’ when not applicable.
publicstatic promote_staged_file()
public static function promote_staged_file($fs, callable $is_allowed, string $live_path): boolPromote a staged-rollout file over its live sibling (issue #1348). Parameter Type Default Description $fsobject— Filesystem exposing exists()/size()/get_contents()/move()/copy()/delete(). $is_allowedcallable— Containment validator: fn( string $path ): bool. $live_pathstring— Absolute live derived-file path.
Return: bool — True when the staged file replaced the live file.
publicstatic restore_fallback_file()
public static function restore_fallback_file($fs, callable $is_allowed, string $live_path): boolRestore a derived file from its retained last-good fallback (issue #1348). Parameter Type Default Description $fsobject— Filesystem exposing copy()/delete() plus the fallback-validity surface. $is_allowedcallable— Containment validator: fn( string $path ): bool. $live_pathstring— Absolute live derived-file path.
Return: bool — True when the fallback payload replaced the live file.
publicstatic describe_rollout_slot()
public static function describe_rollout_slot($fs, string $live_path): arrayDescribe the safe-rollout slot triple for a live file (issue #1348). Parameter Type Default Description $fsobject— Filesystem exposing exists()/size()/get_contents(). $live_pathstring— Absolute live derived-file path.
Return: array{live_bytes: — int, live_checksum: string, staged: bool, staged_bytes: int, staged_checksum: string, staged_changed: bool, fallback: bool} Slot description.
publicstatic purge_fallback_should_log()
public static function purge_fallback_should_log(): boolA single blog-prefixed transient (`wppo_purge_fallback_served`) gates all fallback-serve log rows (both Cache and used-CSS share it) so a post-purge miss storm writes one row per day instead of one per directory.
Return: bool — True when the caller should write its log row.
publicstatic css_file_valid()
public static function css_file_valid(string $path): boolWhether a generated CSS file is valid (exists, readable, non-empty). Parameter Type Default Description $pathstring— Absolute path to the CSS file.
Return: bool — True when the file is usable.
publicstatic log_css_fallback()
public static function log_css_fallback(string $reason, array $handles, string $context): voidLog a guarded CSS fallback (combine or used-CSS) event with throttling. Parameter Type Default Description $reasonstring— Machine-readable reason code (empty_payload, write_failure, head_match_failure, …). $handlesarray— Handles preserved by the fallback. $contextstring— \’combine\’ or \’usedcss\’ — selects the log-key prefix and message.
Return: void.
publicstatic is_php85_or_greater()
public static function is_php85_or_greater(?string=null $php_version): boolWhether the current runtime deprecates explicit handle-close calls (PHP 8.5+). Parameter Type Default Description $php_version?string=null— Optional version string for testing; defaults to PHP_VERSION.
Return: bool — True on PHP 8.5+, false below.
publicstatic close_curl_handle()
public static function close_curl_handle(& $ch, ?string=null $php_version): voidRelease a cURL handle without triggering the PHP 8.5 deprecation. Parameter Type Default Description $ch&— cURL handle to release (nulled in the caller scope). $php_version?string=null— Optional version override for testing; defaults to PHP_VERSION.
Return: void.
publicstatic close_curl_multi_handle()
public static function close_curl_multi_handle(& $mh, ?string=null $php_version): voidRelease a cURL multi handle without triggering the PHP 8.5 deprecation. Parameter Type Default Description $mh&— cURL multi handle to release (nulled in the caller scope). $php_version?string=null— Optional version override for testing; defaults to PHP_VERSION.
Return: void.
publicstatic destroy_gd_image()
public static function destroy_gd_image(& $image, ?string=null $php_version): voidRelease a GD image without triggering the PHP 8.5 deprecation. Parameter Type Default Description $image&— GD image to release (nulled in the caller scope). $php_version?string=null— Optional version override for testing; defaults to PHP_VERSION.
Return: void.
publicstatic close_curl_share_handle()
public static function close_curl_share_handle(& $sh, ?string=null $php_version): voidRelease a cURL share handle without triggering the PHP 8.5 deprecation. Parameter Type Default Description $sh&— cURL share handle to release (nulled in the caller scope). $php_version?string=null— Optional version override for testing; defaults to PHP_VERSION.
Return: void.
publicstatic close_finfo_handle()
public static function close_finfo_handle(& $finfo, ?string=null $php_version): voidRelease a finfo handle without triggering the PHP 8.5 deprecation. Parameter Type Default Description $finfo&— Finfo handle to release (nulled in the caller scope). $php_version?string=null— Optional version override for testing; defaults to PHP_VERSION.
Return: void.
publicstatic free_xml_parser()
public static function free_xml_parser(& $parser, ?string=null $php_version): voidRelease an XML parser without triggering the PHP 8.5 deprecation. Parameter Type Default Description $parser&— XML parser to release (nulled in the caller scope). $php_version?string=null— Optional version override for testing; defaults to PHP_VERSION.
Return: void.
publicstatic get_last_response_headers()
public static function get_last_response_headers(?array=null $legacy_source): arrayReturn the last HTTP response headers without touching the deprecated global. Parameter Type Default Description $legacy_source?array=null— Optional explicit header lines for the legacy path (string-filtered).
Return: string[] — List of response header lines, or empty array when unavailable.
publicstatic get_styles_inline_limit()
public static function get_styles_inline_limit(): intRead core\’s `styles_inline_size_limit` budget.
Return: int — The inline size limit in bytes.
publicstatic get_styles_inline_default()
public static function get_styles_inline_default(): intUnfiltered core inline default for the invalid-limit fallback (issue #1462).
Return: int — The default inline size limit in bytes.
publicstatic add_committed_inline_bytes()
public static function add_committed_inline_bytes(int $bytes): voidRecord bytes just inlined on this request (issue #1462). Parameter Type Default Description $bytesint— Bytes just committed to inline output.
Return: void.
publicstatic get_committed_inline_bytes()
public static function get_committed_inline_bytes(): intBytes committed to inline output so far on this request (issue #1462).
Return: int — Committed inline bytes (>= 0).
publicstatic reset_committed_inline_bytes()
public static function reset_committed_inline_bytes(): voidReset the request-global committed-bytes ledger (unit tests).
Return: void.
publicstatic get_remaining_inline_budget()
public static function get_remaining_inline_budget(int=0 $already_inlined, ?int=null $limit): intRemaining inline budget after bytes already committed (issue #1462). Parameter Type Default Description $already_inlinedint=0— Bytes already committed to inline output on this request. $limit?int=null— Optional budget override (defaults to get_styles_inline_limit()).
Return: int — Remaining bytes available for inline output (>= 0).
publicstatic split_css_for_inline_budget()
public static function split_css_for_inline_budget(string $css, ?int=null $limit): arraySplit CSS into an inline prefix and a deferred remainder (issue #1462). Parameter Type Default Description $cssstring— CSS content to split. $limit?int=null— Optional budget override (defaults to get_styles_inline_limit()).
Return: array{inline: — string, deferred: string} Inline prefix and deferred remainder.
privatestatic find_top_level_css_cut()
private static function find_top_level_css_cut(string $css, int $budget): ?intOffset of the last top-level `}` at or under the budget (issue #1462). Parameter Type Default Description $cssstring— CSS content. $budgetint— Maximum bytes for the inline prefix.
Return: int|null — Offset of the cut brace, or null when nothing fits.
Hooks
Hooks referenced in includes/class-util.php: Hook Type Line Notes wppo_cache_query_allowlistfilter 2271 — wppo_safe_css_combine_fallbackfilter 4122 @param ×1