purge_scheduled = true; if ( $reason !== '' ) { $this->purge_reasons[] = $reason; } } /** * Check whether the given setting key affects frontend output. * * @param string $key The setting/field name. * @return bool */ public static function is_frontend_setting( string $key ): bool { $frontend_keys = [ // App properties 'app_name', 'app_name_show', 'app_logo', 'app_description', 'app_disclaimer', 'response_message', 'response_header', 'submit_button_txt', 'title_color', 'font_color', 'bg_color', 'btn_color', 'btn_font_color', 'response_bg_color', 'app_corner', 'app_height', 'short_code_genrated', 'email_only_enabled', 'output_preview_word_count', 'email_field_notice', // Plugin settings (frontend-relevant) 'app_selector', 'banned_words', 'banned_words_csv', // Field selector 'field_id', 'field_type', 'field_label', 'field_maxchar', 'field_dropdown_options', 'field_sample_text', 'field_require_field_status', 'field_include_in_export_email', 'field_position', 'field_tag', 'app_width', // Prompt 'prompt', 'prompt_html', 'ai_response_style', 'ai_response_tone', // Model (affects response) 'model', 'temperature', 'f_penalty', 'p_penalty', 'max_tokens', 'top_p', // Style settings 'titleColors', 'fontColor', 'bgColor', 'btnColors', 'btnFontColors', 'responseBgColors', 'app-corner', 'app-height', 'app-width', ]; return in_array( $key, $frontend_keys, true ); } /** * Detect whether any values in $new_data differ from $old_data. * Only compares keys that affect frontend output. * * @param array $old_data Previous values. * @param array $new_data New values. * @return bool True if frontend-affecting changes detected. */ public static function has_frontend_changes( array $old_data, array $new_data ): bool { foreach ( $new_data as $key => $new_value ) { if ( ! self::is_frontend_setting( $key ) ) { continue; } $old_value = $old_data[ $key ] ?? null; // Normalize for comparison $old_normalized = self::normalize_value( $old_value ); $new_normalized = self::normalize_value( $new_value ); if ( $old_normalized !== $new_normalized ) { return true; } } return false; } /** * Get IDs of posts/pages containing the plugin shortcode. * * Uses a cached mapping that is refreshed periodically or on post save. * * @return array Array of post IDs. */ public function get_shortcode_pages(): array { $pages = get_option( self::SHORTCODE_PAGES_OPTION, null ); if ( $pages === null || ! is_array( $pages ) ) { $pages = $this->scan_shortcode_pages(); } return $pages; } /** * Rebuild the shortcode page mapping by scanning post_content. * * Throttled to prevent excessive DB queries. * * @param bool $force Skip throttle check. * @return array Array of post IDs. */ public function scan_shortcode_pages( bool $force = false ): array { // Throttle: don't scan more than once per 5 minutes unless forced if ( ! $force && get_transient( self::SCAN_THROTTLE_TRANSIENT ) ) { $cached = get_option( self::SHORTCODE_PAGES_OPTION, [] ); return is_array( $cached ) ? $cached : []; } global $wpdb; // Get the shortcode name from the app_properties table $shortcode_name = $wpdb->get_var( "SELECT short_code_genrated FROM {$wpdb->prefix}ai_app_onsite_app_properties WHERE app_id = 1 LIMIT 1" ); $post_ids = []; if ( ! empty( $shortcode_name ) && $shortcode_name !== 'NO' ) { // Search for [shortcode_name] in post_content $like_pattern = '%[' . $wpdb->esc_like( $shortcode_name ) . ']%'; $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_status = 'publish' AND (post_type = 'post' OR post_type = 'page') AND post_content LIKE %s", $like_pattern ) ); // Also search for the Gutenberg block $block_pattern = '%ai-app-onsite-form-block%'; $block_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_status = 'publish' AND (post_type = 'post' OR post_type = 'page') AND post_content LIKE %s", $block_pattern ) ); $post_ids = array_unique( array_merge( array_map( 'intval', $post_ids ), array_map( 'intval', $block_ids ) ) ); } // Also search generically for _aiao shortcode pattern if ( empty( $post_ids ) ) { $generic_pattern = '%_aiao]%'; $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_status = 'publish' AND (post_type = 'post' OR post_type = 'page') AND post_content LIKE %s", $generic_pattern ) ); $post_ids = array_map( 'intval', $post_ids ); } // Store mapping update_option( self::SHORTCODE_PAGES_OPTION, $post_ids, false ); set_transient( self::SCAN_THROTTLE_TRANSIENT, 1, 5 * MINUTE_IN_SECONDS ); return $post_ids; } // ------------------------------------------------------------------ // EXECUTION // ------------------------------------------------------------------ /** * Execute the batched purge at shutdown (if scheduled). */ public function execute_purge(): void { if ( ! $this->purge_scheduled ) { return; } $page_ids = $this->get_shortcode_pages(); if ( ! empty( $page_ids ) ) { $this->purge_pages( $page_ids ); } else { // Fallback: if no pages tracked, do a full purge $this->purge_all(); } $this->log_purge(); } /** * Purge cache for specific page IDs only. * * @param array $page_ids Array of post IDs. */ private function purge_pages( array $page_ids ): void { $urls = []; foreach ( $page_ids as $id ) { $url = get_permalink( $id ); if ( $url ) { $urls[] = $url; } } // --- LiteSpeed Cache (per-URL purge) --- if ( class_exists( 'LiteSpeed_Cache_API' ) ) { foreach ( $urls as $url ) { if ( method_exists( 'LiteSpeed_Cache_API', 'purge_url' ) ) { LiteSpeed_Cache_API::purge_url( $url ); } } // Fallback if per-URL purge not available if ( ! method_exists( 'LiteSpeed_Cache_API', 'purge_url' ) ) { LiteSpeed_Cache_API::purge_all(); } } // --- WP Rocket (per-URL purge) --- if ( function_exists( 'rocket_clean_post' ) ) { foreach ( $page_ids as $id ) { rocket_clean_post( $id ); } } elseif ( function_exists( 'rocket_clean_files' ) && ! empty( $urls ) ) { rocket_clean_files( $urls ); } // --- W3 Total Cache (per-URL purge) --- if ( function_exists( 'w3tc_pgcache_flush_url' ) ) { foreach ( $urls as $url ) { w3tc_pgcache_flush_url( $url ); } } elseif ( function_exists( 'w3tc_pgcache_flush_post' ) ) { foreach ( $page_ids as $id ) { w3tc_pgcache_flush_post( $id ); } } elseif ( function_exists( 'w3tc_pgcache_flush' ) ) { w3tc_pgcache_flush(); } // --- WP Super Cache (per-URL purge) --- if ( function_exists( 'wpsc_delete_url_cache' ) ) { foreach ( $urls as $url ) { wpsc_delete_url_cache( $url ); } } elseif ( function_exists( 'wp_cache_post_change' ) ) { foreach ( $page_ids as $id ) { wp_cache_post_change( $id ); } } elseif ( function_exists( 'wp_cache_clear_cache' ) ) { wp_cache_clear_cache(); } // --- WP Fastest Cache --- if ( class_exists( 'WpFastestCache' ) ) { $wfc = new WpFastestCache(); if ( method_exists( $wfc, 'singleDeleteCache' ) ) { foreach ( $urls as $url ) { $path = wp_parse_url( $url, PHP_URL_PATH ); if ( $path ) { $wfc->singleDeleteCache( false, $path ); } } } elseif ( method_exists( $wfc, 'deleteCache' ) ) { $wfc->deleteCache(); } } // --- SiteGround Optimizer --- if ( function_exists( 'sg_cachepress_purge_cache' ) ) { // SiteGround doesn't have per-URL purge in older versions if ( function_exists( 'sg_cachepress_purge_url' ) ) { foreach ( $urls as $url ) { sg_cachepress_purge_url( $url ); } } else { sg_cachepress_purge_cache(); } } // --- Breeze (Cloudways) --- if ( function_exists( 'breeze_cache_clean' ) ) { // Breeze doesn't have per-URL API in most versions breeze_cache_clean(); } // --- FlyingPress --- if ( class_exists( 'FlyingPress\Purge' ) && method_exists( 'FlyingPress\Purge', 'purge_urls' ) ) { \FlyingPress\Purge::purge_urls( $urls ); } elseif ( class_exists( 'FlyingPress\Purge' ) && method_exists( 'FlyingPress\Purge', 'purge_url' ) ) { foreach ( $urls as $url ) { \FlyingPress\Purge::purge_url( $url ); } } // --- Autoptimize --- if ( function_exists( 'autoptimize_clearall' ) ) { autoptimize_clearall(); } // Clear WP object cache for the relevant posts foreach ( $page_ids as $id ) { clean_post_cache( $id ); } } /** * Full cache purge fallback. * Used only when shortcode pages cannot be determined. */ private function purge_all(): void { if ( function_exists( 'aiapp_clear_page_cache' ) ) { aiapp_clear_page_cache(); } } // ------------------------------------------------------------------ // POST SAVE HOOK // ------------------------------------------------------------------ /** * When a post is saved, check if it contains our shortcode * and update the page mapping. * * @param int $post_id Post ID. * @param \WP_Post $post Post object. */ public function on_post_save( int $post_id, $post ): void { // Skip revisions and autosaves if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) { return; } if ( ! in_array( $post->post_type, [ 'post', 'page' ], true ) ) { return; } $current_pages = get_option( self::SHORTCODE_PAGES_OPTION, [] ); if ( ! is_array( $current_pages ) ) { $current_pages = []; } $contains_shortcode = $this->post_contains_shortcode( $post->post_content ); $is_tracked = in_array( $post_id, $current_pages, true ); if ( $contains_shortcode && ! $is_tracked ) { // Add to tracked pages $current_pages[] = $post_id; update_option( self::SHORTCODE_PAGES_OPTION, array_unique( $current_pages ), false ); } elseif ( ! $contains_shortcode && $is_tracked ) { // Remove from tracked pages $current_pages = array_diff( $current_pages, [ $post_id ] ); update_option( self::SHORTCODE_PAGES_OPTION, array_values( $current_pages ), false ); } } // ------------------------------------------------------------------ // HELPERS // ------------------------------------------------------------------ /** * Check if post content contains the AI App shortcode or block. * * @param string $content Post content. * @return bool */ private function post_contains_shortcode( string $content ): bool { // Check for _aiao] shortcode pattern if ( strpos( $content, '_aiao]' ) !== false ) { return true; } // Check for Gutenberg block if ( strpos( $content, 'ai-app-onsite-form-block' ) !== false ) { return true; } return false; } /** * Normalize a value for comparison. * * @param mixed $value The value to normalize. * @return string Normalized string representation. */ private static function normalize_value( $value ): string { if ( is_null( $value ) ) { return ''; } if ( is_array( $value ) || is_object( $value ) ) { return wp_json_encode( $value ); } // Trim whitespace and normalize line endings return trim( (string) $value ); } /** * Log purge action if WP_DEBUG is enabled. */ private function log_purge(): void { if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) { return; } $page_ids = $this->get_shortcode_pages(); $reasons = implode( ', ', $this->purge_reasons ); if ( ! empty( $page_ids ) ) { error_log( sprintf( '[AI App Onsite] Frontend cache invalidated for page IDs: %s. Reason: %s', implode( ', ', $page_ids ), $reasons ?: 'unspecified' ) ); } else { error_log( sprintf( '[AI App Onsite] Full cache purge (no shortcode pages tracked). Reason: %s', $reasons ?: 'unspecified' ) ); } } } }