Plugin Directory

Changeset 3840577


Ignore:
Timestamp:
12/02/2026 04:13:55 PM (less than one hour ago)
Author:
blizhost
Message:

Release version 5.0.3

Location:
blizhost-cache-purge
Files:
12 edited
1 copied

Legend:

Unmodified
Added
Removed
  • blizhost-cache-purge/tags/5.0.3/blizhost-cache-purge.php

    r3183932 r3840577  
    44Plugin URI: https://www.blizhost.com
    55Description: Automatic Cache Clearing and CloudCache Integration to Boost Speed and Protect Your Site with Enhanced Security.
    6 Version: 5.0.2
     6Version: 5.0.3
    77Author: Blizhost
    88Author URI: https://www.blizhost.com
    … …  
    1515
    1616*/
     17
     18// Exit if accessed directly
     19if ( ! defined( 'ABSPATH' ) ) {
     20        exit;
     21}
    1722
    1823/**
    … …  
    2429        protected $purgeUrls = array();                 // URLs to be purged
    2530        protected $processedPosts = array();    // Posts that have been processed
    26         public $p_version = '5.0.2';                    // Plugin version
     31        public $p_version = '5.0.3';                    // Plugin version
    2732        public $do_full_purge = false;                  // Flag to trigger a full cache purge
    2833       
    … …  
    3035        protected $is_ssl;
    3136
     37        // Declared to avoid dynamic properties (deprecated since PHP 8.2)
     38        public $server_hostname = '';           // Server hostname (CloudCache features only run on Blizhost servers)
     39        public $server_sapi = '';                       // PHP SAPI (cli, fpm-fcgi, litespeed...)
     40
     41        protected static $instance = null;      // Main instance (used by WP-CLI)
     42        protected $skipPostPurge = array();     // Posts whose next edit_post comes from a comment recount that changed nothing visible
     43
    3244        /**
    3345         * Constructor: Initializes the plugin
    … …  
    3749         */
    3850        public function __construct() {
     51
     52                // Keep the first instance as the main one (WP-CLI uses it instead of creating another)
     53                if ( null === self::$instance ) {
     54                        self::$instance = $this;
     55                }
    3956
    4057                // Gets the hostname, more reliable than obtaining the server name through headers, compatible with PHP via CLI
    … …  
    118135                // AJAX action handler for cache purging
    119136                add_action( 'wp_ajax_bliz_purge_all', array( $this, 'bliz_purge_all_ajax_handler' ) );
     137        }
     138
     139        /**
     140         * Main instance of the plugin
     141         *
     142         * @since 5.0.3
     143         * @return BlizCloudCachePurger
     144         */
     145        public static function get_instance() {
     146                if ( null === self::$instance ) {
     147                        self::$instance = new self();
     148                }
     149                return self::$instance;
     150        }
     151
     152        /**
     153         * Queue a URL to be purged (a path containing ".*" is purged as a regex)
     154         *
     155         * @since 5.0.3
     156         * @param string $url Full URL to purge.
     157         */
     158        public function blizqueuePurgeUrl( $url ) {
     159                $this->purgeUrls[] = $url;
    120160        }
    121161
    … …  
    172212         */
    173213        public function init() {
    174                 global $blog_id;
     214
     215                // Up to 5.0.2 the purge key was also saved in the "bliz_hash" option (plain text, never read): remove it once.
     216                // wp_load_alloptions() is already in memory, so this check costs nothing on the following requests.
     217                $alloptions = wp_load_alloptions();
     218                if ( isset( $alloptions['bliz_hash'] ) ) {
     219                        delete_option( 'bliz_hash' );
     220                }
    175221
    176222                // Load plugin textdomain for translations
    … …  
    192238
    193239                // Get registered events that trigger cache purging
    194                 $events  = $this->blizgetRegisterEvents();
    195                 $noIDevents = $this->getNoIDEvents();
    196 
    197                 // Ensure events are arrays
    198                 if ( ! empty( $events ) && ! empty( $noIDevents ) ) {
    199 
    200                         // Convert to arrays if necessary
    201                         $events  = (array) $events;
    202                         $noIDevents = (array) $noIDevents;
    203 
    204                         // Add the action for each event
    205                         foreach ( $events as $event ) {
    206                                 if ( in_array( $event, $noIDevents ) ) {
    207                                         // Events that require a full cache purge
    208                                         add_action( $event, array( $this, 'purgeNoID' ) );
    209                                 } else {
    210                                         // Events that require purging specific posts
    211                                         add_action( $event, array( $this, 'blizpurgePost' ), 10, 2 );
    212                                 }
    213                         }
    214                 }
     240                $events  = (array) $this->blizgetRegisterEvents();
     241                $noIDevents = (array) $this->getNoIDEvents();
     242
     243                // Register the events of both lists: the "no ID" events purge the whole site, the others purge the post.
     244                // (Up to 5.0.2 only the first list was registered, so the "no ID" events that were not in it never ran.)
     245                foreach ( array_unique( array_merge( $events, $noIDevents ) ) as $event ) {
     246                        if ( in_array( $event, $noIDevents, true ) ) {
     247                                // Events that require a full cache purge
     248                                add_action( $event, array( $this, 'purgeNoID' ) );
     249                        } else {
     250                                // Events that require purging specific posts
     251                                add_action( $event, array( $this, 'blizpurgePost' ), 10, 2 );
     252                        }
     253                }
     254
     255                // Advanced Custom Fields: the post, or the whole site for options pages, terms and widgets
     256                add_action( 'acf/save_post', array( $this, 'blizpurgeAcf' ), 20 );
     257
     258                // WP Offload Media: the attachment URL changed; purge the post it belongs to
     259                add_action( 'as3cf_post_upload_item', array( $this, 'blizpurgeOffloadItem' ) );                 // 2.6 and newer
     260                add_action( 'as3cf_post_upload_attachment', array( $this, 'blizpurgeAttachment' ) );    // Before 2.6
     261
     262                // Comments: purge the post when a visible comment is added, edited, approved or removed
     263                add_action( 'comment_post', array( $this, 'blizpurgeNewComment' ), 10, 2 );
     264                add_action( 'edit_comment', array( $this, 'blizpurgeComment' ) );
     265                add_action( 'transition_comment_status', array( $this, 'blizpurgeCommentStatus' ), 10, 3 );
     266                // WordPress fires edit_post after every comment recount, even when the count did not change
     267                add_action( 'wp_update_comment_count', array( $this, 'blizcommentCountUpdated' ), 10, 3 );
     268                add_action( 'edit_post', array( $this, 'blizclearSkipPostPurge' ), PHP_INT_MAX );
     269
     270                // Widgets saved outside the Customizer (widgets screen, block widgets editor)
     271                add_action( 'updated_option', array( $this, 'blizpurgeWidgetOption' ) );
     272
     273                // Menu locations saved in Appearance > Menus (outside the Customizer)
     274                add_filter( 'pre_set_theme_mod_nav_menu_locations', array( $this, 'blizpurgeMenuLocations' ), 10, 2 );
    215275
    216276                // Add actions for events that trigger a full cache purge
    … …  
    226286
    227287                // Check user permissions to add admin bar button
    228                 if (
    229                         // SingleSite - admins can always purge
    230                         ( ! is_multisite() && current_user_can( 'activate_plugins' ) ) ||
    231                         // Multisite - Network Admin can always purge
    232                         current_user_can( 'manage_network' ) ||
    233                         // Multisite - Site admins can purge unless it's a subfolder install and we're on site #1
    234                         ( is_multisite() && current_user_can( 'activate_plugins' ) && ( SUBDOMAIN_INSTALL || ( ! SUBDOMAIN_INSTALL && ( BLOG_ID_CURRENT_SITE != $blog_id ) ) ) )
    235                 ) {
     288                if ( $this->bliz_user_can_purge_all() ) {
    236289                        // Add the cache purge button to the admin bar
    237290                        add_action( 'admin_bar_menu', array( $this, 'blizccache_rightnow_adminbar' ), 100 );
    … …  
    243296         */
    244297        public function enqueue_bliz_purge_scripts() {
    245                 if ( is_user_logged_in() && current_user_can( 'manage_options' ) ) {
     298                if ( is_user_logged_in() && $this->bliz_user_can_purge_all() ) {
    246299                        if ( ! wp_script_is( 'bliz-purge-script', 'enqueued' ) ) {
    247300                                wp_enqueue_script( 'bliz-purge-script', plugin_dir_url( __FILE__ ) . 'js/bliz-purge.js', array( 'jquery' ), '1.6', true );
    … …  
    249302                                        'ajax_url'         => admin_url( 'admin-ajax.php' ),
    250303                                        'nonce'           => wp_create_nonce( 'bliz_purge_all_nonce' ),
    251                                         'dismiss_notice' => __( 'Dismiss this notice.', 'blizhost-cache-purge' ),
    252                                         'error_message'  => __( 'An error occurred while purging the cache.', 'blizhost-cache-purge' ),
     304                                        // Escaped: the script inserts these texts as HTML
     305                                        'dismiss_notice' => esc_html__( 'Dismiss this notice.', 'blizhost-cache-purge' ),
     306                                        'error_message'  => esc_html__( 'An error occurred while purging the cache.', 'blizhost-cache-purge' ),
    253307                                ) );
    254308                        }
    … …  
    372426                $admin_bar->add_menu( array(
    373427                        'id'    => 'bliz-purge-ccache-cache',
    374                         'title' => '<span class="ab-icon blizicon-symbol_16px" style="font-size: 18px; margin-top: 3px; font-family: \'blizhost_logo\'!important; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;"></span>' . __( 'Blizhost CloudCache', 'blizhost-cache-purge' ),
     428                        'title' => '<span class="ab-icon blizicon-symbol_16px" style="font-size: 18px; margin-top: 3px; font-family: \'blizhost_logo\'!important; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;"></span>' . esc_html__( 'Blizhost CloudCache', 'blizhost-cache-purge' ),
    375429                ) );
    376430
    … …  
    406460                        'parent' => 'bliz-purge-ccache-cache',
    407461                        'id'     => 'bliz-cloudcache-status',
    408                         'title'  => '<span style="display: flex; align-items: center; width: auto;">' . __( 'CloudCache Status - Speed and Security', 'blizhost-cache-purge' ) . '<span style="margin-left: auto;">' . $cloudcache_status_dot . '</span></span>',
     462                        'title'  => '<span style="display: flex; align-items: center; width: auto;">' . esc_html__( 'CloudCache Status - Speed and Security', 'blizhost-cache-purge' ) . '<span style="margin-left: auto;">' . $cloudcache_status_dot . '</span></span>',
    409463                        'meta'   => array(
    410464                                'title' => $cloudcache_tooltip, // Add tooltip if inactive
    … …  
    416470                        'parent' => 'bliz-purge-ccache-cache',
    417471                        'id'     => 'bliz-cdn-status',
    418                         'title'  => '<span style="display: flex; align-items: center; width: auto;">' . __( 'CDN and Image Optimization Status', 'blizhost-cache-purge' ) . '<span style="margin-left: auto;">' . $cdn_status_dot . '</span></span>',
     472                        'title'  => '<span style="display: flex; align-items: center; width: auto;">' . esc_html__( 'CDN and Image Optimization Status', 'blizhost-cache-purge' ) . '<span style="margin-left: auto;">' . $cdn_status_dot . '</span></span>',
    419473                        'meta'   => array(
    420474                                'title' => $cdn_tooltip, // Add tooltip if inactive
    … …  
    426480                        'parent' => 'bliz-purge-ccache-cache',
    427481                        'id'     => 'bliz-purge-ccache-cache-all',
    428                         'title'  => '<span style="display: flex; align-items: center; width: auto; border-top: 1px solid rgba(255, 255, 255, 0.4); margin-top: 10px;">' . __( 'Purge Entire Cache', 'blizhost-cache-purge' ) . '</span>',
     482                        'title'  => '<span style="display: flex; align-items: center; width: auto; border-top: 1px solid rgba(255, 255, 255, 0.4); margin-top: 10px;">' . esc_html__( 'Purge Entire Cache', 'blizhost-cache-purge' ) . '</span>',
    429483                        'href'   => $fallback_url, // Fallback URL
    430484                        'meta'   => array(
    … …  
    441495         */
    442496        public function blizccache_rightnow() {
    443                 global $blog_id;
    444497                $fallback_url = wp_nonce_url( add_query_arg( 'bliz_purge_cache', 1 ), 'bliz_purge_cache_action' );
    445498
    … …  
    466519
    467520                $button  = esc_html__( 'Press the button below to force a cleanup of the entire cache:', 'blizhost-cache-purge' );
    468                 $button .= '</p><p><span class="button bliz-purge-all-cache"><a href="' . $fallback_url . '" style="text-decoration:none;"><strong>';
     521                $button .= '</p><p><span class="button bliz-purge-all-cache"><a href="' . esc_url( $fallback_url ) . '" style="text-decoration:none;"><strong>';
    469522                $button .= esc_html__( 'Purge CloudCache', 'blizhost-cache-purge' );
    470523                $button .= '</strong></a></span>';
    … …  
    472525                $nobutton = esc_html__( 'You do not have permission to purge the cache for the whole site. Please contact your administrator.', 'blizhost-cache-purge' );
    473526
    474                 if (
    475                         ( ! is_multisite() && current_user_can( 'activate_plugins' ) ) ||
    476                         current_user_can( 'manage_network' ) ||
    477                         ( is_multisite() && ! current_user_can( 'manage_network' ) && ( SUBDOMAIN_INSTALL || ( ! SUBDOMAIN_INSTALL && ( BLOG_ID_CURRENT_SITE != $blog_id ) ) ) )
    478                 ) {
     527                if ( $this->bliz_user_can_purge_all() ) {
    479528                        $text = $intro . ' ' . $button;
    480529                } else {
    … …  
    726775                }
    727776
     777                // Keep <script>, <style> and <textarea> blocks out of the parser and put them back untouched afterwards.
     778                // The libxml HTML parser ends these blocks at the first "</" (a browser only at "</script>"), which broke
     779                // inline scripts with tags inside strings (part of the code was shown as text), and it turned their
     780                // non-ASCII characters into entities. Their URLs are not images, so nothing in them is rewritten.
     781                $raw_blocks = array();
     782                $protected  = preg_replace_callback(
     783                        '#<(script|style|textarea)\b[^>]*>.*?</\1\s*>#is',
     784                        function ( $m ) use ( &$raw_blocks ) {
     785                                $key                = '<!--bliz-raw-' . count( $raw_blocks ) . '-->';
     786                                $raw_blocks[ $key ] = $m[0];
     787                                return $key;
     788                        },
     789                        $content
     790                );
     791                if ( null === $protected ) {
     792                        // The regular expression failed (for example, the backtrack limit on a huge page): change nothing
     793                        return $content;
     794                }
     795                $original_content = $content;
     796                $content          = $protected;
     797
    728798                libxml_use_internal_errors( true );
    729799                $doc = new DOMDocument();
    730800
    731                 // Convert encoding to HTML-ENTITIES for proper parsing
    732                 if ( function_exists( 'mb_convert_encoding' ) ) {
    733                         $content = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' );
     801                // Convert non-ASCII characters to numeric HTML entities for proper parsing
     802                // (same result as the old mb_convert_encoding( ..., 'HTML-ENTITIES' ), deprecated since PHP 8.2)
     803                // Invalid UTF-8 bytes are dropped first, as the old conversion did. Output tested identical on PHP 7.4 and 8.4.
     804                if ( function_exists( 'mb_encode_numericentity' ) ) {
     805                        $previous_substitute = mb_substitute_character();
     806                        mb_substitute_character( 'none' );
     807                        $content = mb_convert_encoding( $content, 'UTF-8', 'UTF-8' );
     808                        mb_substitute_character( $previous_substitute );
     809                        $content = mb_encode_numericentity( $content, array( 0x80, 0x10FFFF, 0, 0x1FFFFF ), 'UTF-8' );
    734810                } else {
    735811                        return $content;
    … …  
    775851                if ( substr( $newContent, 0, 5 ) === '<div>' && substr( $newContent, -6 ) === '</div>' ) {
    776852                        $newContent = substr( $newContent, 5, -6 );
     853                }
     854
     855                // Put the <script>, <style> and <textarea> blocks back; if a placeholder was lost, change nothing
     856                if ( $raw_blocks ) {
     857                        foreach ( array_keys( $raw_blocks ) as $key ) {
     858                                if ( false === strpos( $newContent, $key ) ) {
     859                                        return $original_content;
     860                                }
     861                        }
     862                        $newContent = strtr( $newContent, $raw_blocks );
    777863                }
    778864
    … …  
    11361222                        'autoptimize_action_cachepurged',       // Compatibility with Autoptimize plugin
    11371223                        'customize_save_after',                         // After saving changes in the Customizer
    1138                         'acf/save_post',                                        // Advanced Custom Fields
    1139                         'gform_after_save_form',                        // Gravity Forms
    1140                         'rank_math/after_save_settings',        // Rank Math SEO
    1141                         'as3cf_after_upload_attachment',        // WP Offload Media
     1224                        'gform_after_save_form',                        // Gravity Forms: a form was saved (forms can be embedded in any page)
     1225                        'rank_math/settings/after_save',        // Rank Math SEO: settings saved (titles and meta of every page)
     1226                        'wp_update_nav_menu',                           // A navigation menu was saved (menus appear on every page)
     1227                        'wp_delete_nav_menu',                           // A navigation menu was deleted
    11421228                );
    11431229
    … …  
    11561242        public function blizexecutePurge() {
    11571243                $purgeUrls = array_unique( $this->purgeUrls );
     1244                $result = null;
    11581245
    11591246                // Get correct HTTP protocol from Blizhost CloudCache
    … …  
    11611248
    11621249                if ( $this->do_full_purge ) {
    1163                         // Send the full purge URL in an array
    1164                         $this->blizpurgeUrl( array( $http_proto . $this->site_host . '/.*' ) ); // Clears the main domain
     1250                        // Send the full purge URL in an array: the host plus the site path (only this subsite in a subdirectory multisite)
     1251                        $result = $this->blizpurgeUrl( array( $http_proto . $this->site_host . $this->bliz_home_path() . '/.*' ) );
    11651252                } else {
    11661253                        if ( ! empty( $purgeUrls ) ) {
    11671254                                // Send all URLs in a single request
    1168                                 $this->blizpurgeUrl( $purgeUrls );
    1169                         }
    1170                 }
     1255                                $result = $this->blizpurgeUrl( $purgeUrls );
     1256                        }
     1257                }
     1258
     1259                // Clear the queue, so the same URLs are not sent again (WP-CLI runs it before the shutdown hook)
     1260                $this->purgeUrls = array();
     1261                $this->do_full_purge = false;
     1262
     1263                return $result;
    11711264        }
    11721265
    … …  
    12451338                        'method' => 'POST',
    12461339                        'timeout' => 15,
     1340                        // Not verified, as up to 5.0.2: WordPress checks certificates against its own bundle
     1341                        // (wp-includes/certificates/ca-bundle.crt), and the bundle of WordPress 4.4 to 5.2 lacks the
     1342                        // ISRG Root X1 (Let's Encrypt) root of the API certificate, so verifying would silently stop
     1343                        // the purge on those sites. The request is only sent from Blizhost servers, where the API runs.
    12471344                        'sslverify' => false,
    12481345                        'body' => array(
    … …  
    12581355
    12591356                do_action( 'after_purge_url', $urls, $blizpurgeme_list, $response );
     1357
     1358                return $response;
    12601359        }
    12611360
    … …  
    13031402        public function blizpurgePost( $postId ) {
    13041403
     1404                // The edit_post that follows a comment recount with no visible change: the comment handlers decide
     1405                if ( isset( $this->skipPostPurge[ (int) $postId ] ) ) {
     1406                        unset( $this->skipPostPurge[ (int) $postId ] );
     1407                        return;
     1408                }
     1409
    13051410                // Checks if the post has already been processed
    13061411                if ( in_array( $postId, $this->processedPosts ) ) {
    … …  
    13091414                // Marks the post as processed
    13101415                $this->processedPosts[] = $postId;
     1416
     1417                // Block theme templates, template parts, global styles, navigation menus and synced patterns
     1418                // can change every page of the site
     1419                $full_purge_types = apply_filters( 'bliz_full_purge_post_types', array( 'wp_template', 'wp_template_part', 'wp_global_styles', 'wp_navigation', 'wp_block' ) );
     1420                if ( in_array( get_post_type( $postId ), (array) $full_purge_types, true ) ) {
     1421                        $this->purgeNoID();
     1422                        return;
     1423                }
    13111424
    13121425                // If this is a valid post we want to purge the post,
    … …  
    14181531
    14191532        /**
     1533         * Advanced Custom Fields: purge after the fields are saved
     1534         *
     1535         * @since 5.0.3
     1536         * @param int|string $post_id A post ID, or "options"/a custom ID (options pages), "term_5", "user_1", "comment_3", "block_..."
     1537         */
     1538        public function blizpurgeAcf( $post_id ) {
     1539                if ( is_numeric( $post_id ) ) {
     1540                        $this->blizpurgePost( (int) $post_id );
     1541                } elseif ( is_string( $post_id ) && ! preg_match( '/^(user|comment|block)_/', $post_id ) ) {
     1542                        // Options pages, terms and widgets can be shown on any page
     1543                        $this->purgeNoID();
     1544                }
     1545        }
     1546
     1547        /**
     1548         * Purge the post an attachment belongs to (its URL changed, for example after WP Offload Media copied it)
     1549         *
     1550         * @since 5.0.3
     1551         * @param int $attachment_id Attachment ID.
     1552         */
     1553        public function blizpurgeAttachment( $attachment_id ) {
     1554                $parent_id = wp_get_post_parent_id( (int) $attachment_id );
     1555                if ( $parent_id ) {
     1556                        $this->blizpurgePost( $parent_id );
     1557                }
     1558        }
     1559
     1560        /**
     1561         * WP Offload Media 2.6+: an item was copied to the bucket
     1562         *
     1563         * @since 5.0.3
     1564         * @param object $as3cf_item The uploaded item.
     1565         */
     1566        public function blizpurgeOffloadItem( $as3cf_item ) {
     1567                if ( ! is_object( $as3cf_item ) || ! method_exists( $as3cf_item, 'source_id' ) ) {
     1568                        return;
     1569                }
     1570                if ( method_exists( $as3cf_item, 'source_type' ) && 'media-library' !== $as3cf_item->source_type() ) {
     1571                        return;
     1572                }
     1573                $this->blizpurgeAttachment( $as3cf_item->source_id() );
     1574        }
     1575
     1576        /**
     1577         * A new comment was posted: purge the post if the comment is already visible
     1578         *
     1579         * @since 5.0.3
     1580         * @param int        $comment_id       Comment ID.
     1581         * @param int|string $comment_approved 1 if approved, 0 if pending, "spam" or "trash".
     1582         */
     1583        public function blizpurgeNewComment( $comment_id, $comment_approved ) {
     1584                if ( 1 === (int) $comment_approved ) {
     1585                        $this->blizpurgeComment( $comment_id );
     1586                }
     1587        }
     1588
     1589        /**
     1590         * A comment was edited: purge the post if the comment is visible
     1591         *
     1592         * @since 5.0.3
     1593         * @param int $comment_id Comment ID.
     1594         */
     1595        public function blizpurgeComment( $comment_id ) {
     1596                $comment = get_comment( $comment_id );
     1597                if ( $comment && 1 === (int) $comment->comment_approved && $comment->comment_post_ID && $this->bliz_is_public_comment( $comment ) ) {
     1598                        $this->blizpurgePost( (int) $comment->comment_post_ID );
     1599                }
     1600        }
     1601
     1602        /**
     1603         * A comment changed status: purge the post when it becomes visible or stops being visible
     1604         *
     1605         * @since 5.0.3
     1606         * @param string     $new_status New status (approved, unapproved, spam, trash, delete).
     1607         * @param string     $old_status Old status.
     1608         * @param WP_Comment $comment    The comment.
     1609         */
     1610        public function blizpurgeCommentStatus( $new_status, $old_status, $comment ) {
     1611                if ( ( 'approved' === $new_status || 'approved' === $old_status ) && ! empty( $comment->comment_post_ID ) && $this->bliz_is_public_comment( $comment ) ) {
     1612                        $this->blizpurgePost( (int) $comment->comment_post_ID );
     1613                }
     1614        }
     1615
     1616        /**
     1617         * The comments of a post were recounted (WordPress fires edit_post right after, even when nothing changed)
     1618         *
     1619         * When the number of visible comments did not change (a block editor note was resolved, a pending comment
     1620         * was edited, a comment text was edited), that edit_post must not purge the post: blizpurgeComment and
     1621         * blizpurgeCommentStatus already purge it when a visible comment changed.
     1622         *
     1623         * @since 5.0.3
     1624         * @param int $post_id Post ID.
     1625         * @param int $new     New comment count.
     1626         * @param int $old     Old comment count.
     1627         */
     1628        public function blizcommentCountUpdated( $post_id, $new, $old ) {
     1629                if ( (int) $new === (int) $old ) {
     1630                        $this->skipPostPurge[ (int) $post_id ] = true;
     1631                }
     1632        }
     1633
     1634        /**
     1635         * Clear the skip flag after edit_post ran (in case edit_post was removed from the purge events)
     1636         *
     1637         * @since 5.0.3
     1638         * @param int $post_id Post ID.
     1639         */
     1640        public function blizclearSkipPostPurge( $post_id ) {
     1641                unset( $this->skipPostPurge[ (int) $post_id ] );
     1642        }
     1643
     1644        /**
     1645         * Is the comment shown to visitors? Private comment types (block editor notes, WooCommerce order notes...)
     1646         * never appear on the site, so resolving or editing them must not purge the post.
     1647         *
     1648         * @since 5.0.3
     1649         * @param WP_Comment|object $comment The comment.
     1650         * @return bool
     1651         */
     1652        protected function bliz_is_public_comment( $comment ) {
     1653                $type = isset( $comment->comment_type ) ? (string) $comment->comment_type : '';
     1654                // note: block editor notes (WordPress 6.9+); order_note, webhook_delivery and action_log: WooCommerce
     1655                $private_types = apply_filters( 'bliz_private_comment_types', array( 'note', 'order_note', 'webhook_delivery', 'action_log' ) );
     1656                return ! in_array( $type, (array) $private_types, true );
     1657        }
     1658
     1659        /**
     1660         * Widgets were saved outside the Customizer: purge the whole site
     1661         *
     1662         * @since 5.0.3
     1663         * @param string $option Name of the updated option (only called when the value changed).
     1664         */
     1665        public function blizpurgeWidgetOption( $option ) {
     1666                if ( 'sidebars_widgets' === $option || 0 === strpos( $option, 'widget_' ) ) {
     1667                        $this->purgeNoID();
     1668                }
     1669        }
     1670
     1671        /**
     1672         * Menu locations were saved: purge the whole site
     1673         *
     1674         * @since 5.0.3
     1675         * @param array $value     New menu locations.
     1676         * @param array $old_value Current menu locations.
     1677         * @return array The new value, unchanged.
     1678         */
     1679        public function blizpurgeMenuLocations( $value, $old_value ) {
     1680                if ( $value !== $old_value ) {
     1681                        $this->purgeNoID();
     1682                }
     1683                return $value;
     1684        }
     1685
     1686        /**
     1687         * Can the current user purge the entire cache of this site?
     1688         *
     1689         * The same rule for every purge action (admin bar, dashboard, AJAX and fallback URL), based on
     1690         * manage_options: site administrators. Up to 5.0.2 the buttons used activate_plugins and the actions
     1691         * used manage_options, and in multisite the dashboard button appeared to users without permission.
     1692         * In a subdirectory multisite, only network admins can purge the main site, because its purge
     1693         * (example.com/.*) also reaches every subsite (example.com/site1/...).
     1694         *
     1695         * @since 5.0.3
     1696         * @return bool
     1697         */
     1698        public function bliz_user_can_purge_all() {
     1699                if ( ! is_multisite() ) {
     1700                        return current_user_can( 'manage_options' );
     1701                }
     1702                if ( current_user_can( 'manage_network' ) ) {
     1703                        return true;
     1704                }
     1705                return current_user_can( 'manage_options' ) && ( is_subdomain_install() || ! is_main_site() );
     1706        }
     1707
     1708        /**
     1709         * Path of the site's home URL, without the trailing slash ("" for a site at the domain root)
     1710         *
     1711         * In a subdirectory multisite (or a site installed in a subdirectory), a full purge must be limited
     1712         * to this path, or it would purge every site of the domain.
     1713         *
     1714         * @since 5.0.3
     1715         * @return string
     1716         */
     1717        protected function bliz_home_path() {
     1718                $home = wp_parse_url( self::the_home_url() );
     1719                return isset( $home['path'] ) ? rtrim( $home['path'], '/' ) : '';
     1720        }
     1721
     1722        /**
    14201723        * Handle the cache purge request via URL
    14211724        */
    14221725        public function handle_fallback_purge_cache_request() {
    1423                 if ( current_user_can( 'manage_options' ) ) {
     1726                if ( $this->bliz_user_can_purge_all() ) {
    14241727                        $this->do_full_purge = true;
    14251728                }
    … …  
    14341737
    14351738                // Check user permissions
    1436                 if ( ! current_user_can( 'manage_options' ) ) {
    1437                         wp_send_json_error( __( 'You do not have sufficient permissions to access this action.', 'blizhost-cache-purge' ) );
     1739                if ( ! $this->bliz_user_can_purge_all() ) {
     1740                        // Escaped: the script inserts this text as HTML
     1741                        wp_send_json_error( esc_html__( 'You do not have sufficient permissions to access this action.', 'blizhost-cache-purge' ) );
    14381742                }
    14391743
    … …  
    14421746
    14431747                // Prepare the notice HTML
    1444                 $message = __( 'All CloudCache has been purged!', 'blizhost-cache-purge' );
     1748                $message = esc_html__( 'All CloudCache has been purged!', 'blizhost-cache-purge' );
    14451749                $notice  = '<div id="message" class="notice notice-success is-dismissible"><p><strong>' . $message . '</strong></p></div>';
    14461750
    … …  
    14731777                                $nonce = wp_create_nonce( 'generate_hash_action' );
    14741778
     1779                                // Loopback request to the site itself (no secret is sent). Like WordPress core does for its own
     1780                                // loopback requests, the certificate is only verified if the https_local_ssl_verify filter says so.
    14751781                                $response = wp_remote_post( $request_url, array(
    14761782                                        'body' => array(
    … …  
    14791785                                        ),
    14801786                                        'timeout' => 15,
    1481                                         'sslverify' => false,
     1787                                        'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
    14821788                                ) );
    14831789
    … …  
    14871793                                }
    14881794
    1489                                 // Now attempt to get the hash from the transient again
     1795                                // Now attempt to get the hash from the transient again. The first get_transient() above left the
     1796                                // option marked as missing in this process's cache ('notoptions'), and the value was written by
     1797                                // the loopback request (another process): without clearing that cache, the first WP-CLI purge
     1798                                // always failed.
     1799                                wp_cache_delete( 'notoptions', 'options' );
     1800                                wp_cache_delete( '_transient_bliz_hash_transient', 'options' );
     1801                                wp_cache_delete( '_transient_timeout_bliz_hash_transient', 'options' );
    14901802                                $hash = get_transient( 'bliz_hash_transient' );
    14911803                        }
    … …  
    15191831                                $nonce = wp_create_nonce( 'generate_cdn_domain_action' );
    15201832
     1833                                // Loopback request to the site itself (see get_hash)
    15211834                                $response = wp_remote_post( $request_url, array(
    15221835                                        'body' => array(
    … …  
    15251838                                        ),
    15261839                                        'timeout' => 15,
    1527                                         'sslverify' => false,
     1840                                        'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
    15281841                                ) );
    15291842
    … …  
    15421855
    15431856        /**
    1544          * Handle the generate_hash request to store the hash in transient and database.
     1857         * Handle the generate_hash request to store the hash in a transient (used by WP-CLI).
    15451858         */
    15461859        public function handle_generate_hash() {
    … …  
    15481861                        // Verify nonce
    15491862                        if ( isset( $_POST['nonce'] ) && wp_verify_nonce( sanitize_key( $_POST['nonce'] ), 'generate_hash_action' ) ) {
    1550                                 $current_domain = parse_url( home_url(), PHP_URL_HOST );
    1551 
    15521863                                // Fetch the hash value from $_SERVER
    15531864                                if ( isset( $_SERVER['HTTP_X_PURGE_KEY'] ) ) {
    15541865                                        $hash = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_PURGE_KEY'] ) );
    1555                                         // Store in transient and options table
     1866                                        // Store in a transient only (up to 5.0.2 it was also saved, never read, in the "bliz_hash" option)
    15561867                                        set_transient( 'bliz_hash_transient', $hash, DAY_IN_SECONDS );
    1557                                         update_option( 'bliz_hash', array( 'hash' => $hash, 'domain' => $current_domain, 'timestamp' => time() ) );
    15581868                                }
    15591869                        }
    … …  
    15971907 */
    15981908if ( defined( 'WP_CLI' ) && WP_CLI ) {
    1599         include( 'wp-cli.php' );
     1909        include __DIR__ . '/wp-cli.php';
    16001910}
  • blizhost-cache-purge/tags/5.0.3/font/index.php

    r1904994 r3840577  
     1<?php
     2// Silence is golden.
  • blizhost-cache-purge/tags/5.0.3/js/index.php

    r3180199 r3840577  
     1<?php
     2// Silence is golden.
  • blizhost-cache-purge/tags/5.0.3/lang/index.php

    r1904994 r3840577  
     1<?php
     2// Silence is golden.
  • blizhost-cache-purge/tags/5.0.3/readme.txt

    r3183932 r3840577  
    33Tags: cache, performance, security, nginx, redis
    44Requires at least: 4.4
    5 Tested up to: 6.7
     5Tested up to: 7.1
    66Requires PHP: 5.6
    7 Stable tag: 5.0.2
     7Stable tag: 5.0.3
    88License: GPLv3
    99License URI: https://www.gnu.org/licenses/gpl-3.0.html
    … …  
    7878* Portuguese-BR
    7979
     80== External services ==
     81
     82This plugin connects to the external services below. They are only used when the site is hosted on a <strong>Blizhost</strong> server (the server hostname contains "blizhost"); on other hosts, nothing is sent.
     83
     84= Blizhost CloudCache purge API =
     85
     86Used to clear the CloudCache (the server cache in front of the site) when the content changes: when a post, page, comment, menu or widget is saved, when settings that affect every page change, or when an administrator clicks "Purge CloudCache" or runs `wp ccache purge`.
     87
     88The plugin sends a POST request to `https://cloudcache-api.blizhost.com/purge/` with: the list of URLs (paths) to purge, the hosting account username, the site domain, the site purge key (provided by the Blizhost server), the server hostname, the PHP SAPI and the plugin version. No visitor data is sent.
     89
     90This service is provided by Blizhost: [Terms of Service](https://www.blizhost.com.br/termos-de-servico/), [Privacy Policy](https://www.blizhost.com.br/politica-de-privacidade/).
     91
     92= WordPress.com image CDN (Photon) =
     93
     94Used to serve the site images faster. Unless the Jetpack image CDN is already active or the `DISABLE_WP_CDN` constant is set to `true`, the plugin rewrites the URLs of the site's own images (JPG, PNG, GIF and WebP) to the WordPress.com image CDN (`i0.wp.com` to `i3.wp.com`), operated by Automattic. The visitor's browser then loads those images from the CDN, which receives the image URL and, like any website, the visitor's IP address and browser information.
     95
     96This service is provided by Automattic: [Terms of Service](https://wordpress.com/tos/), [Privacy Policy](https://automattic.com/privacy/).
     97
    8098== Frequently Asked Questions ==
    8199
    … …  
    102120
    103121== Changelog ==
     122
     123= 5.0.3 =
     124* Fixed the WP-CLI command (`wp ccache purge`), broken since 5.0.1; it now reports when the purge fails
     125* Fixed deprecation notices on PHP 8.2 and newer (dynamic properties and HTML-ENTITIES conversion)
     126* Fixed purge events that were never registered (Customizer, Gravity Forms, Rank Math SEO) and the hook names for Rank Math SEO and WP Offload Media
     127* New purge triggers: comments, navigation menus and menu locations, widgets, block theme templates, template parts, global styles and synced patterns
     128* Private comment types (block editor notes, WooCommerce order notes) no longer purge the cache
     129* Advanced Custom Fields and WP Offload Media now purge only the affected post instead of the whole site
     130* Multisite: a full purge of a subdirectory site now clears only that site
     131* The same permission (manage_options) is required for every purge action
     132* The purge key is no longer stored in the database (the old option is removed)
     133* Escaped admin texts and added protection against direct file access
     134* Added the "External services" section to the readme
     135* Tested up to WordPress 7.1
    104136
    105137= 5.0.2 =
  • blizhost-cache-purge/tags/5.0.3/wp-cli.php

    r3180223 r3840577  
    11<?php
    22
    3 if (!defined('ABSPATH')) {
    4     die();
     3if ( ! defined( 'ABSPATH' ) ) {
     4        die();
    55}
    66
    77// Bail if WP-CLI is not present
    8 if ( !defined( 'WP_CLI' ) ) return;
     8if ( ! defined( 'WP_CLI' ) ) {
     9        return;
     10}
    911
    1012/**
    11  * Purges CloudCache
     13 * Purges CloudCache using WP-CLI commands.
    1214 */
    13 class WP_CLI_BlizCCache_Purge_Command extends WP_CLI_Command {
     15class WP_CLI_BlizCloudCache_Purge_Command extends WP_CLI_Command {
    1416
    15         private $wildcard = false;
     17        /**
     18         * Instance of the BlizCloudCachePurger class.
     19         *
     20         * @var BlizCloudCachePurger
     21         */
     22        private $ccache_purge;
    1623
     24        /**
     25         * Constructor.
     26         */
    1727        public function __construct() {
    18                 $this->ccache_purge = new BlizCCachePurger();
     28                // Use the plugin's main instance instead of creating another one (which would register every hook again)
     29                $this->ccache_purge = BlizCloudCachePurger::get_instance();
    1930        }
    20        
    21     /**
    22      * Forces a full CloudCache Purge of the entire site (provided
    23      * regex is supported).
    24      *
    25      * ## EXAMPLES
    26      *
    27      *          wp ccache purge
    28      *
    29      *          wp ccache purge http://example.com/wp-content/themes/twentyeleventy/style.css
    30      *
    31          *              wp ccache purge "/wp-content/themes/twentysixty/style.css"
     31
     32        /**
     33         * Forces a CloudCache purge of the specified URL or the entire site.
    3234         *
    33      *          wp ccache purge http://example.com/wp-content/themes/ --wildcard
    34      *
    35      *          wp ccache purge "/wp-content/themes/" --wildcard
    36      *
    37      */
    38        
    39         function purge( $args , $assoc_args ) {
    40                
    41                 $wp_version = get_bloginfo( 'version' );
    42                 $cli_version = WP_CLI_VERSION;
    43                
     35         * ## OPTIONS
     36         *
     37         * [<url>]
     38         * : The URL to purge from the cache. If omitted, the entire cache will be purged.
     39         *
     40         * [--wildcard]
     41         * : Purge using a wildcard, purging all URLs under the specified path.
     42         *
     43         * ## EXAMPLES
     44         *
     45         *    wp ccache purge
     46         *
     47         *    wp ccache purge http://example.com/wp-content/themes/twentyeleventy/style.css
     48         *
     49         *    wp ccache purge "/wp-content/themes/twentysixty/style.css"
     50         *
     51         *    wp ccache purge http://example.com/wp-content/themes/ --wildcard
     52         *
     53         *    wp ccache purge "/wp-content/themes/" --wildcard
     54         *
     55         * @synopsis [<url>] [--wildcard]
     56         *
     57         * @param array $args        The URL argument.
     58         * @param array $assoc_args  The associative arguments.
     59         */
     60        public function purge( $args, $assoc_args ) {
    4461                // Set the URL/path
    45                 if ( !empty($args) ) { list( $url ) = $args; }
    46 
    47                 // If wildcard is set, or the URL argument is empty
    48                 // then treat this as a full purge
    49                 $wild = '';
    50                 if ( isset( $assoc_args['wildcard'] ) || empty($url) ) {
    51                         $wild = ".*";
     62                $url = '';
     63                if ( ! empty( $args ) ) {
     64                        $url = $args[0];
    5265                }
    5366
    54                 wp_create_nonce('ccache-purge-cli');
     67                // If the URL argument is empty, treat this as a full purge
     68                if ( empty( $url ) ) {
     69                        $this->ccache_purge->do_full_purge = true;
     70                } else {
     71                        // Make sure the URL is a full URL
     72                        if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
     73                                $url = home_url( '/' . ltrim( $url, '/' ) );
     74                        }
    5575
    56                 // Make sure the URL is a URL:
    57                 if ( !empty($url) ) {
    58                         $url = $this->ccache_purge->the_home_url() . esc_url( $url );
    59                 } else {
    60                         $url = $this->ccache_purge->the_home_url();
    61                 }
    62                
    63                 if ( version_compare( $wp_version, '4.6', '>=' ) && ( version_compare( $cli_version, '0.25.0', '<' ) || version_compare( $cli_version, '0.25.0-alpha', 'eq' ) ) ) {
    64                        
    65                         WP_CLI::log( sprintf( 'This plugin does not work on WP 4.6 and up, unless WP-CLI is version 0.25.0 or greater. You\'re using WP-CLI %s and WordPress %s.', $cli_version, $wp_version ) );
    66                         WP_CLI::log( 'To flush your cache, please run the following command:');
    67                         WP_CLI::log( sprintf( '$ curl -X PURGE "%s"' , $url.$wild ) );
    68                         WP_CLI::error( 'CloudCache must be purged manually.' );
     76                        // If wildcard is set, append '.*' to the path
     77                        if ( isset( $assoc_args['wildcard'] ) ) {
     78                                // Parse the URL to manipulate the path
     79                                $parsed_url = wp_parse_url( $url );
     80                                $path = isset( $parsed_url['path'] ) ? $parsed_url['path'] : '';
     81
     82                                // Ensure the path ends with '/' before appending '.*'
     83                                if ( substr( $path, -1 ) !== '/' ) {
     84                                        $path .= '/';
     85                                }
     86                                $path .= '.*';
     87
     88                                // Reconstruct the URL with the modified path
     89                                $url = ( isset( $parsed_url['scheme'] ) ? $parsed_url['scheme'] . '://' : '' )
     90                                         . ( isset( $parsed_url['host'] ) ? $parsed_url['host'] : '' )
     91                                         . $path;
     92                        }
     93
     94                        // Add the URL to the purge list
     95                        $this->ccache_purge->blizqueuePurgeUrl( $url );
    6996                }
    7097
    71                 $this->ccache_purge->purgeUrl( $url.$wild );
     98                // Execute the purge and report the real result
     99                $result = $this->ccache_purge->blizexecutePurge();
     100
     101                if ( false === $result || null === $result ) {
     102                        WP_CLI::error( 'CloudCache was not purged: the site is not hosted at Blizhost or the purge key is not available.' );
     103                }
     104                if ( is_wp_error( $result ) ) {
     105                        WP_CLI::error( 'CloudCache was not purged: ' . $result->get_error_message() );
     106                }
     107                $code = (int) wp_remote_retrieve_response_code( $result );
     108                if ( 200 !== $code ) {
     109                        WP_CLI::error( sprintf( 'CloudCache was not purged: the purge API answered HTTP %d.', $code ) );
     110                }
    72111
    73112                WP_CLI::success( 'The CloudCache was purged.' );
    74113        }
    75 
    76114}
    77115
    78 WP_CLI::add_command( 'ccache', 'WP_CLI_BlizCCache_Purge_Command' );
     116WP_CLI::add_command( 'ccache', 'WP_CLI_BlizCloudCache_Purge_Command' );
  • blizhost-cache-purge/trunk/blizhost-cache-purge.php

    r3183932 r3840577  
    44Plugin URI: https://www.blizhost.com
    55Description: Automatic Cache Clearing and CloudCache Integration to Boost Speed and Protect Your Site with Enhanced Security.
    6 Version: 5.0.2
     6Version: 5.0.3
    77Author: Blizhost
    88Author URI: https://www.blizhost.com
    … …  
    1515
    1616*/
     17
     18// Exit if accessed directly
     19if ( ! defined( 'ABSPATH' ) ) {
     20        exit;
     21}
    1722
    1823/**
    … …  
    2429        protected $purgeUrls = array();                 // URLs to be purged
    2530        protected $processedPosts = array();    // Posts that have been processed
    26         public $p_version = '5.0.2';                    // Plugin version
     31        public $p_version = '5.0.3';                    // Plugin version
    2732        public $do_full_purge = false;                  // Flag to trigger a full cache purge
    2833       
    … …  
    3035        protected $is_ssl;
    3136
     37        // Declared to avoid dynamic properties (deprecated since PHP 8.2)
     38        public $server_hostname = '';           // Server hostname (CloudCache features only run on Blizhost servers)
     39        public $server_sapi = '';                       // PHP SAPI (cli, fpm-fcgi, litespeed...)
     40
     41        protected static $instance = null;      // Main instance (used by WP-CLI)
     42        protected $skipPostPurge = array();     // Posts whose next edit_post comes from a comment recount that changed nothing visible
     43
    3244        /**
    3345         * Constructor: Initializes the plugin
    … …  
    3749         */
    3850        public function __construct() {
     51
     52                // Keep the first instance as the main one (WP-CLI uses it instead of creating another)
     53                if ( null === self::$instance ) {
     54                        self::$instance = $this;
     55                }
    3956
    4057                // Gets the hostname, more reliable than obtaining the server name through headers, compatible with PHP via CLI
    … …  
    118135                // AJAX action handler for cache purging
    119136                add_action( 'wp_ajax_bliz_purge_all', array( $this, 'bliz_purge_all_ajax_handler' ) );
     137        }
     138
     139        /**
     140         * Main instance of the plugin
     141         *
     142         * @since 5.0.3
     143         * @return BlizCloudCachePurger
     144         */
     145        public static function get_instance() {
     146                if ( null === self::$instance ) {
     147                        self::$instance = new self();
     148                }
     149                return self::$instance;
     150        }
     151
     152        /**
     153         * Queue a URL to be purged (a path containing ".*" is purged as a regex)
     154         *
     155         * @since 5.0.3
     156         * @param string $url Full URL to purge.
     157         */
     158        public function blizqueuePurgeUrl( $url ) {
     159                $this->purgeUrls[] = $url;
    120160        }
    121161
    … …  
    172212         */
    173213        public function init() {
    174                 global $blog_id;
     214
     215                // Up to 5.0.2 the purge key was also saved in the "bliz_hash" option (plain text, never read): remove it once.
     216                // wp_load_alloptions() is already in memory, so this check costs nothing on the following requests.
     217                $alloptions = wp_load_alloptions();
     218                if ( isset( $alloptions['bliz_hash'] ) ) {
     219                        delete_option( 'bliz_hash' );
     220                }
    175221
    176222                // Load plugin textdomain for translations
    … …  
    192238
    193239                // Get registered events that trigger cache purging
    194                 $events  = $this->blizgetRegisterEvents();
    195                 $noIDevents = $this->getNoIDEvents();
    196 
    197                 // Ensure events are arrays
    198                 if ( ! empty( $events ) && ! empty( $noIDevents ) ) {
    199 
    200                         // Convert to arrays if necessary
    201                         $events  = (array) $events;
    202                         $noIDevents = (array) $noIDevents;
    203 
    204                         // Add the action for each event
    205                         foreach ( $events as $event ) {
    206                                 if ( in_array( $event, $noIDevents ) ) {
    207                                         // Events that require a full cache purge
    208                                         add_action( $event, array( $this, 'purgeNoID' ) );
    209                                 } else {
    210                                         // Events that require purging specific posts
    211                                         add_action( $event, array( $this, 'blizpurgePost' ), 10, 2 );
    212                                 }
    213                         }
    214                 }
     240                $events  = (array) $this->blizgetRegisterEvents();
     241                $noIDevents = (array) $this->getNoIDEvents();
     242
     243                // Register the events of both lists: the "no ID" events purge the whole site, the others purge the post.
     244                // (Up to 5.0.2 only the first list was registered, so the "no ID" events that were not in it never ran.)
     245                foreach ( array_unique( array_merge( $events, $noIDevents ) ) as $event ) {
     246                        if ( in_array( $event, $noIDevents, true ) ) {
     247                                // Events that require a full cache purge
     248                                add_action( $event, array( $this, 'purgeNoID' ) );
     249                        } else {
     250                                // Events that require purging specific posts
     251                                add_action( $event, array( $this, 'blizpurgePost' ), 10, 2 );
     252                        }
     253                }
     254
     255                // Advanced Custom Fields: the post, or the whole site for options pages, terms and widgets
     256                add_action( 'acf/save_post', array( $this, 'blizpurgeAcf' ), 20 );
     257
     258                // WP Offload Media: the attachment URL changed; purge the post it belongs to
     259                add_action( 'as3cf_post_upload_item', array( $this, 'blizpurgeOffloadItem' ) );                 // 2.6 and newer
     260                add_action( 'as3cf_post_upload_attachment', array( $this, 'blizpurgeAttachment' ) );    // Before 2.6
     261
     262                // Comments: purge the post when a visible comment is added, edited, approved or removed
     263                add_action( 'comment_post', array( $this, 'blizpurgeNewComment' ), 10, 2 );
     264                add_action( 'edit_comment', array( $this, 'blizpurgeComment' ) );
     265                add_action( 'transition_comment_status', array( $this, 'blizpurgeCommentStatus' ), 10, 3 );
     266                // WordPress fires edit_post after every comment recount, even when the count did not change
     267                add_action( 'wp_update_comment_count', array( $this, 'blizcommentCountUpdated' ), 10, 3 );
     268                add_action( 'edit_post', array( $this, 'blizclearSkipPostPurge' ), PHP_INT_MAX );
     269
     270                // Widgets saved outside the Customizer (widgets screen, block widgets editor)
     271                add_action( 'updated_option', array( $this, 'blizpurgeWidgetOption' ) );
     272
     273                // Menu locations saved in Appearance > Menus (outside the Customizer)
     274                add_filter( 'pre_set_theme_mod_nav_menu_locations', array( $this, 'blizpurgeMenuLocations' ), 10, 2 );
    215275
    216276                // Add actions for events that trigger a full cache purge
    … …  
    226286
    227287                // Check user permissions to add admin bar button
    228                 if (
    229                         // SingleSite - admins can always purge
    230                         ( ! is_multisite() && current_user_can( 'activate_plugins' ) ) ||
    231                         // Multisite - Network Admin can always purge
    232                         current_user_can( 'manage_network' ) ||
    233                         // Multisite - Site admins can purge unless it's a subfolder install and we're on site #1
    234                         ( is_multisite() && current_user_can( 'activate_plugins' ) && ( SUBDOMAIN_INSTALL || ( ! SUBDOMAIN_INSTALL && ( BLOG_ID_CURRENT_SITE != $blog_id ) ) ) )
    235                 ) {
     288                if ( $this->bliz_user_can_purge_all() ) {
    236289                        // Add the cache purge button to the admin bar
    237290                        add_action( 'admin_bar_menu', array( $this, 'blizccache_rightnow_adminbar' ), 100 );
    … …  
    243296         */
    244297        public function enqueue_bliz_purge_scripts() {
    245                 if ( is_user_logged_in() && current_user_can( 'manage_options' ) ) {
     298                if ( is_user_logged_in() && $this->bliz_user_can_purge_all() ) {
    246299                        if ( ! wp_script_is( 'bliz-purge-script', 'enqueued' ) ) {
    247300                                wp_enqueue_script( 'bliz-purge-script', plugin_dir_url( __FILE__ ) . 'js/bliz-purge.js', array( 'jquery' ), '1.6', true );
    … …  
    249302                                        'ajax_url'         => admin_url( 'admin-ajax.php' ),
    250303                                        'nonce'           => wp_create_nonce( 'bliz_purge_all_nonce' ),
    251                                         'dismiss_notice' => __( 'Dismiss this notice.', 'blizhost-cache-purge' ),
    252                                         'error_message'  => __( 'An error occurred while purging the cache.', 'blizhost-cache-purge' ),
     304                                        // Escaped: the script inserts these texts as HTML
     305                                        'dismiss_notice' => esc_html__( 'Dismiss this notice.', 'blizhost-cache-purge' ),
     306                                        'error_message'  => esc_html__( 'An error occurred while purging the cache.', 'blizhost-cache-purge' ),
    253307                                ) );
    254308                        }
    … …  
    372426                $admin_bar->add_menu( array(
    373427                        'id'    => 'bliz-purge-ccache-cache',
    374                         'title' => '<span class="ab-icon blizicon-symbol_16px" style="font-size: 18px; margin-top: 3px; font-family: \'blizhost_logo\'!important; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;"></span>' . __( 'Blizhost CloudCache', 'blizhost-cache-purge' ),
     428                        'title' => '<span class="ab-icon blizicon-symbol_16px" style="font-size: 18px; margin-top: 3px; font-family: \'blizhost_logo\'!important; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;"></span>' . esc_html__( 'Blizhost CloudCache', 'blizhost-cache-purge' ),
    375429                ) );
    376430
    … …  
    406460                        'parent' => 'bliz-purge-ccache-cache',
    407461                        'id'     => 'bliz-cloudcache-status',
    408                         'title'  => '<span style="display: flex; align-items: center; width: auto;">' . __( 'CloudCache Status - Speed and Security', 'blizhost-cache-purge' ) . '<span style="margin-left: auto;">' . $cloudcache_status_dot . '</span></span>',
     462                        'title'  => '<span style="display: flex; align-items: center; width: auto;">' . esc_html__( 'CloudCache Status - Speed and Security', 'blizhost-cache-purge' ) . '<span style="margin-left: auto;">' . $cloudcache_status_dot . '</span></span>',
    409463                        'meta'   => array(
    410464                                'title' => $cloudcache_tooltip, // Add tooltip if inactive
    … …  
    416470                        'parent' => 'bliz-purge-ccache-cache',
    417471                        'id'     => 'bliz-cdn-status',
    418                         'title'  => '<span style="display: flex; align-items: center; width: auto;">' . __( 'CDN and Image Optimization Status', 'blizhost-cache-purge' ) . '<span style="margin-left: auto;">' . $cdn_status_dot . '</span></span>',
     472                        'title'  => '<span style="display: flex; align-items: center; width: auto;">' . esc_html__( 'CDN and Image Optimization Status', 'blizhost-cache-purge' ) . '<span style="margin-left: auto;">' . $cdn_status_dot . '</span></span>',
    419473                        'meta'   => array(
    420474                                'title' => $cdn_tooltip, // Add tooltip if inactive
    … …  
    426480                        'parent' => 'bliz-purge-ccache-cache',
    427481                        'id'     => 'bliz-purge-ccache-cache-all',
    428                         'title'  => '<span style="display: flex; align-items: center; width: auto; border-top: 1px solid rgba(255, 255, 255, 0.4); margin-top: 10px;">' . __( 'Purge Entire Cache', 'blizhost-cache-purge' ) . '</span>',
     482                        'title'  => '<span style="display: flex; align-items: center; width: auto; border-top: 1px solid rgba(255, 255, 255, 0.4); margin-top: 10px;">' . esc_html__( 'Purge Entire Cache', 'blizhost-cache-purge' ) . '</span>',
    429483                        'href'   => $fallback_url, // Fallback URL
    430484                        'meta'   => array(
    … …  
    441495         */
    442496        public function blizccache_rightnow() {
    443                 global $blog_id;
    444497                $fallback_url = wp_nonce_url( add_query_arg( 'bliz_purge_cache', 1 ), 'bliz_purge_cache_action' );
    445498
    … …  
    466519
    467520                $button  = esc_html__( 'Press the button below to force a cleanup of the entire cache:', 'blizhost-cache-purge' );
    468                 $button .= '</p><p><span class="button bliz-purge-all-cache"><a href="' . $fallback_url . '" style="text-decoration:none;"><strong>';
     521                $button .= '</p><p><span class="button bliz-purge-all-cache"><a href="' . esc_url( $fallback_url ) . '" style="text-decoration:none;"><strong>';
    469522                $button .= esc_html__( 'Purge CloudCache', 'blizhost-cache-purge' );
    470523                $button .= '</strong></a></span>';
    … …  
    472525                $nobutton = esc_html__( 'You do not have permission to purge the cache for the whole site. Please contact your administrator.', 'blizhost-cache-purge' );
    473526
    474                 if (
    475                         ( ! is_multisite() && current_user_can( 'activate_plugins' ) ) ||
    476                         current_user_can( 'manage_network' ) ||
    477                         ( is_multisite() && ! current_user_can( 'manage_network' ) && ( SUBDOMAIN_INSTALL || ( ! SUBDOMAIN_INSTALL && ( BLOG_ID_CURRENT_SITE != $blog_id ) ) ) )
    478                 ) {
     527                if ( $this->bliz_user_can_purge_all() ) {
    479528                        $text = $intro . ' ' . $button;
    480529                } else {
    … …  
    726775                }
    727776
     777                // Keep <script>, <style> and <textarea> blocks out of the parser and put them back untouched afterwards.
     778                // The libxml HTML parser ends these blocks at the first "</" (a browser only at "</script>"), which broke
     779                // inline scripts with tags inside strings (part of the code was shown as text), and it turned their
     780                // non-ASCII characters into entities. Their URLs are not images, so nothing in them is rewritten.
     781                $raw_blocks = array();
     782                $protected  = preg_replace_callback(
     783                        '#<(script|style|textarea)\b[^>]*>.*?</\1\s*>#is',
     784                        function ( $m ) use ( &$raw_blocks ) {
     785                                $key                = '<!--bliz-raw-' . count( $raw_blocks ) . '-->';
     786                                $raw_blocks[ $key ] = $m[0];
     787                                return $key;
     788                        },
     789                        $content
     790                );
     791                if ( null === $protected ) {
     792                        // The regular expression failed (for example, the backtrack limit on a huge page): change nothing
     793                        return $content;
     794                }
     795                $original_content = $content;
     796                $content          = $protected;
     797
    728798                libxml_use_internal_errors( true );
    729799                $doc = new DOMDocument();
    730800
    731                 // Convert encoding to HTML-ENTITIES for proper parsing
    732                 if ( function_exists( 'mb_convert_encoding' ) ) {
    733                         $content = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' );
     801                // Convert non-ASCII characters to numeric HTML entities for proper parsing
     802                // (same result as the old mb_convert_encoding( ..., 'HTML-ENTITIES' ), deprecated since PHP 8.2)
     803                // Invalid UTF-8 bytes are dropped first, as the old conversion did. Output tested identical on PHP 7.4 and 8.4.
     804                if ( function_exists( 'mb_encode_numericentity' ) ) {
     805                        $previous_substitute = mb_substitute_character();
     806                        mb_substitute_character( 'none' );
     807                        $content = mb_convert_encoding( $content, 'UTF-8', 'UTF-8' );
     808                        mb_substitute_character( $previous_substitute );
     809                        $content = mb_encode_numericentity( $content, array( 0x80, 0x10FFFF, 0, 0x1FFFFF ), 'UTF-8' );
    734810                } else {
    735811                        return $content;
    … …  
    775851                if ( substr( $newContent, 0, 5 ) === '<div>' && substr( $newContent, -6 ) === '</div>' ) {
    776852                        $newContent = substr( $newContent, 5, -6 );
     853                }
     854
     855                // Put the <script>, <style> and <textarea> blocks back; if a placeholder was lost, change nothing
     856                if ( $raw_blocks ) {
     857                        foreach ( array_keys( $raw_blocks ) as $key ) {
     858                                if ( false === strpos( $newContent, $key ) ) {
     859                                        return $original_content;
     860                                }
     861                        }
     862                        $newContent = strtr( $newContent, $raw_blocks );
    777863                }
    778864
    … …  
    11361222                        'autoptimize_action_cachepurged',       // Compatibility with Autoptimize plugin
    11371223                        'customize_save_after',                         // After saving changes in the Customizer
    1138                         'acf/save_post',                                        // Advanced Custom Fields
    1139                         'gform_after_save_form',                        // Gravity Forms
    1140                         'rank_math/after_save_settings',        // Rank Math SEO
    1141                         'as3cf_after_upload_attachment',        // WP Offload Media
     1224                        'gform_after_save_form',                        // Gravity Forms: a form was saved (forms can be embedded in any page)
     1225                        'rank_math/settings/after_save',        // Rank Math SEO: settings saved (titles and meta of every page)
     1226                        'wp_update_nav_menu',                           // A navigation menu was saved (menus appear on every page)
     1227                        'wp_delete_nav_menu',                           // A navigation menu was deleted
    11421228                );
    11431229
    … …  
    11561242        public function blizexecutePurge() {
    11571243                $purgeUrls = array_unique( $this->purgeUrls );
     1244                $result = null;
    11581245
    11591246                // Get correct HTTP protocol from Blizhost CloudCache
    … …  
    11611248
    11621249                if ( $this->do_full_purge ) {
    1163                         // Send the full purge URL in an array
    1164                         $this->blizpurgeUrl( array( $http_proto . $this->site_host . '/.*' ) ); // Clears the main domain
     1250                        // Send the full purge URL in an array: the host plus the site path (only this subsite in a subdirectory multisite)
     1251                        $result = $this->blizpurgeUrl( array( $http_proto . $this->site_host . $this->bliz_home_path() . '/.*' ) );
    11651252                } else {
    11661253                        if ( ! empty( $purgeUrls ) ) {
    11671254                                // Send all URLs in a single request
    1168                                 $this->blizpurgeUrl( $purgeUrls );
    1169                         }
    1170                 }
     1255                                $result = $this->blizpurgeUrl( $purgeUrls );
     1256                        }
     1257                }
     1258
     1259                // Clear the queue, so the same URLs are not sent again (WP-CLI runs it before the shutdown hook)
     1260                $this->purgeUrls = array();
     1261                $this->do_full_purge = false;
     1262
     1263                return $result;
    11711264        }
    11721265
    … …  
    12451338                        'method' => 'POST',
    12461339                        'timeout' => 15,
     1340                        // Not verified, as up to 5.0.2: WordPress checks certificates against its own bundle
     1341                        // (wp-includes/certificates/ca-bundle.crt), and the bundle of WordPress 4.4 to 5.2 lacks the
     1342                        // ISRG Root X1 (Let's Encrypt) root of the API certificate, so verifying would silently stop
     1343                        // the purge on those sites. The request is only sent from Blizhost servers, where the API runs.
    12471344                        'sslverify' => false,
    12481345                        'body' => array(
    … …  
    12581355
    12591356                do_action( 'after_purge_url', $urls, $blizpurgeme_list, $response );
     1357
     1358                return $response;
    12601359        }
    12611360
    … …  
    13031402        public function blizpurgePost( $postId ) {
    13041403
     1404                // The edit_post that follows a comment recount with no visible change: the comment handlers decide
     1405                if ( isset( $this->skipPostPurge[ (int) $postId ] ) ) {
     1406                        unset( $this->skipPostPurge[ (int) $postId ] );
     1407                        return;
     1408                }
     1409
    13051410                // Checks if the post has already been processed
    13061411                if ( in_array( $postId, $this->processedPosts ) ) {
    … …  
    13091414                // Marks the post as processed
    13101415                $this->processedPosts[] = $postId;
     1416
     1417                // Block theme templates, template parts, global styles, navigation menus and synced patterns
     1418                // can change every page of the site
     1419                $full_purge_types = apply_filters( 'bliz_full_purge_post_types', array( 'wp_template', 'wp_template_part', 'wp_global_styles', 'wp_navigation', 'wp_block' ) );
     1420                if ( in_array( get_post_type( $postId ), (array) $full_purge_types, true ) ) {
     1421                        $this->purgeNoID();
     1422                        return;
     1423                }
    13111424
    13121425                // If this is a valid post we want to purge the post,
    … …  
    14181531
    14191532        /**
     1533         * Advanced Custom Fields: purge after the fields are saved
     1534         *
     1535         * @since 5.0.3
     1536         * @param int|string $post_id A post ID, or "options"/a custom ID (options pages), "term_5", "user_1", "comment_3", "block_..."
     1537         */
     1538        public function blizpurgeAcf( $post_id ) {
     1539                if ( is_numeric( $post_id ) ) {
     1540                        $this->blizpurgePost( (int) $post_id );
     1541                } elseif ( is_string( $post_id ) && ! preg_match( '/^(user|comment|block)_/', $post_id ) ) {
     1542                        // Options pages, terms and widgets can be shown on any page
     1543                        $this->purgeNoID();
     1544                }
     1545        }
     1546
     1547        /**
     1548         * Purge the post an attachment belongs to (its URL changed, for example after WP Offload Media copied it)
     1549         *
     1550         * @since 5.0.3
     1551         * @param int $attachment_id Attachment ID.
     1552         */
     1553        public function blizpurgeAttachment( $attachment_id ) {
     1554                $parent_id = wp_get_post_parent_id( (int) $attachment_id );
     1555                if ( $parent_id ) {
     1556                        $this->blizpurgePost( $parent_id );
     1557                }
     1558        }
     1559
     1560        /**
     1561         * WP Offload Media 2.6+: an item was copied to the bucket
     1562         *
     1563         * @since 5.0.3
     1564         * @param object $as3cf_item The uploaded item.
     1565         */
     1566        public function blizpurgeOffloadItem( $as3cf_item ) {
     1567                if ( ! is_object( $as3cf_item ) || ! method_exists( $as3cf_item, 'source_id' ) ) {
     1568                        return;
     1569                }
     1570                if ( method_exists( $as3cf_item, 'source_type' ) && 'media-library' !== $as3cf_item->source_type() ) {
     1571                        return;
     1572                }
     1573                $this->blizpurgeAttachment( $as3cf_item->source_id() );
     1574        }
     1575
     1576        /**
     1577         * A new comment was posted: purge the post if the comment is already visible
     1578         *
     1579         * @since 5.0.3
     1580         * @param int        $comment_id       Comment ID.
     1581         * @param int|string $comment_approved 1 if approved, 0 if pending, "spam" or "trash".
     1582         */
     1583        public function blizpurgeNewComment( $comment_id, $comment_approved ) {
     1584                if ( 1 === (int) $comment_approved ) {
     1585                        $this->blizpurgeComment( $comment_id );
     1586                }
     1587        }
     1588
     1589        /**
     1590         * A comment was edited: purge the post if the comment is visible
     1591         *
     1592         * @since 5.0.3
     1593         * @param int $comment_id Comment ID.
     1594         */
     1595        public function blizpurgeComment( $comment_id ) {
     1596                $comment = get_comment( $comment_id );
     1597                if ( $comment && 1 === (int) $comment->comment_approved && $comment->comment_post_ID && $this->bliz_is_public_comment( $comment ) ) {
     1598                        $this->blizpurgePost( (int) $comment->comment_post_ID );
     1599                }
     1600        }
     1601
     1602        /**
     1603         * A comment changed status: purge the post when it becomes visible or stops being visible
     1604         *
     1605         * @since 5.0.3
     1606         * @param string     $new_status New status (approved, unapproved, spam, trash, delete).
     1607         * @param string     $old_status Old status.
     1608         * @param WP_Comment $comment    The comment.
     1609         */
     1610        public function blizpurgeCommentStatus( $new_status, $old_status, $comment ) {
     1611                if ( ( 'approved' === $new_status || 'approved' === $old_status ) && ! empty( $comment->comment_post_ID ) && $this->bliz_is_public_comment( $comment ) ) {
     1612                        $this->blizpurgePost( (int) $comment->comment_post_ID );
     1613                }
     1614        }
     1615
     1616        /**
     1617         * The comments of a post were recounted (WordPress fires edit_post right after, even when nothing changed)
     1618         *
     1619         * When the number of visible comments did not change (a block editor note was resolved, a pending comment
     1620         * was edited, a comment text was edited), that edit_post must not purge the post: blizpurgeComment and
     1621         * blizpurgeCommentStatus already purge it when a visible comment changed.
     1622         *
     1623         * @since 5.0.3
     1624         * @param int $post_id Post ID.
     1625         * @param int $new     New comment count.
     1626         * @param int $old     Old comment count.
     1627         */
     1628        public function blizcommentCountUpdated( $post_id, $new, $old ) {
     1629                if ( (int) $new === (int) $old ) {
     1630                        $this->skipPostPurge[ (int) $post_id ] = true;
     1631                }
     1632        }
     1633
     1634        /**
     1635         * Clear the skip flag after edit_post ran (in case edit_post was removed from the purge events)
     1636         *
     1637         * @since 5.0.3
     1638         * @param int $post_id Post ID.
     1639         */
     1640        public function blizclearSkipPostPurge( $post_id ) {
     1641                unset( $this->skipPostPurge[ (int) $post_id ] );
     1642        }
     1643
     1644        /**
     1645         * Is the comment shown to visitors? Private comment types (block editor notes, WooCommerce order notes...)
     1646         * never appear on the site, so resolving or editing them must not purge the post.
     1647         *
     1648         * @since 5.0.3
     1649         * @param WP_Comment|object $comment The comment.
     1650         * @return bool
     1651         */
     1652        protected function bliz_is_public_comment( $comment ) {
     1653                $type = isset( $comment->comment_type ) ? (string) $comment->comment_type : '';
     1654                // note: block editor notes (WordPress 6.9+); order_note, webhook_delivery and action_log: WooCommerce
     1655                $private_types = apply_filters( 'bliz_private_comment_types', array( 'note', 'order_note', 'webhook_delivery', 'action_log' ) );
     1656                return ! in_array( $type, (array) $private_types, true );
     1657        }
     1658
     1659        /**
     1660         * Widgets were saved outside the Customizer: purge the whole site
     1661         *
     1662         * @since 5.0.3
     1663         * @param string $option Name of the updated option (only called when the value changed).
     1664         */
     1665        public function blizpurgeWidgetOption( $option ) {
     1666                if ( 'sidebars_widgets' === $option || 0 === strpos( $option, 'widget_' ) ) {
     1667                        $this->purgeNoID();
     1668                }
     1669        }
     1670
     1671        /**
     1672         * Menu locations were saved: purge the whole site
     1673         *
     1674         * @since 5.0.3
     1675         * @param array $value     New menu locations.
     1676         * @param array $old_value Current menu locations.
     1677         * @return array The new value, unchanged.
     1678         */
     1679        public function blizpurgeMenuLocations( $value, $old_value ) {
     1680                if ( $value !== $old_value ) {
     1681                        $this->purgeNoID();
     1682                }
     1683                return $value;
     1684        }
     1685
     1686        /**
     1687         * Can the current user purge the entire cache of this site?
     1688         *
     1689         * The same rule for every purge action (admin bar, dashboard, AJAX and fallback URL), based on
     1690         * manage_options: site administrators. Up to 5.0.2 the buttons used activate_plugins and the actions
     1691         * used manage_options, and in multisite the dashboard button appeared to users without permission.
     1692         * In a subdirectory multisite, only network admins can purge the main site, because its purge
     1693         * (example.com/.*) also reaches every subsite (example.com/site1/...).
     1694         *
     1695         * @since 5.0.3
     1696         * @return bool
     1697         */
     1698        public function bliz_user_can_purge_all() {
     1699                if ( ! is_multisite() ) {
     1700                        return current_user_can( 'manage_options' );
     1701                }
     1702                if ( current_user_can( 'manage_network' ) ) {
     1703                        return true;
     1704                }
     1705                return current_user_can( 'manage_options' ) && ( is_subdomain_install() || ! is_main_site() );
     1706        }
     1707
     1708        /**
     1709         * Path of the site's home URL, without the trailing slash ("" for a site at the domain root)
     1710         *
     1711         * In a subdirectory multisite (or a site installed in a subdirectory), a full purge must be limited
     1712         * to this path, or it would purge every site of the domain.
     1713         *
     1714         * @since 5.0.3
     1715         * @return string
     1716         */
     1717        protected function bliz_home_path() {
     1718                $home = wp_parse_url( self::the_home_url() );
     1719                return isset( $home['path'] ) ? rtrim( $home['path'], '/' ) : '';
     1720        }
     1721
     1722        /**
    14201723        * Handle the cache purge request via URL
    14211724        */
    14221725        public function handle_fallback_purge_cache_request() {
    1423                 if ( current_user_can( 'manage_options' ) ) {
     1726                if ( $this->bliz_user_can_purge_all() ) {
    14241727                        $this->do_full_purge = true;
    14251728                }
    … …  
    14341737
    14351738                // Check user permissions
    1436                 if ( ! current_user_can( 'manage_options' ) ) {
    1437                         wp_send_json_error( __( 'You do not have sufficient permissions to access this action.', 'blizhost-cache-purge' ) );
     1739                if ( ! $this->bliz_user_can_purge_all() ) {
     1740                        // Escaped: the script inserts this text as HTML
     1741                        wp_send_json_error( esc_html__( 'You do not have sufficient permissions to access this action.', 'blizhost-cache-purge' ) );
    14381742                }
    14391743
    … …  
    14421746
    14431747                // Prepare the notice HTML
    1444                 $message = __( 'All CloudCache has been purged!', 'blizhost-cache-purge' );
     1748                $message = esc_html__( 'All CloudCache has been purged!', 'blizhost-cache-purge' );
    14451749                $notice  = '<div id="message" class="notice notice-success is-dismissible"><p><strong>' . $message . '</strong></p></div>';
    14461750
    … …  
    14731777                                $nonce = wp_create_nonce( 'generate_hash_action' );
    14741778
     1779                                // Loopback request to the site itself (no secret is sent). Like WordPress core does for its own
     1780                                // loopback requests, the certificate is only verified if the https_local_ssl_verify filter says so.
    14751781                                $response = wp_remote_post( $request_url, array(
    14761782                                        'body' => array(
    … …  
    14791785                                        ),
    14801786                                        'timeout' => 15,
    1481                                         'sslverify' => false,
     1787                                        'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
    14821788                                ) );
    14831789
    … …  
    14871793                                }
    14881794
    1489                                 // Now attempt to get the hash from the transient again
     1795                                // Now attempt to get the hash from the transient again. The first get_transient() above left the
     1796                                // option marked as missing in this process's cache ('notoptions'), and the value was written by
     1797                                // the loopback request (another process): without clearing that cache, the first WP-CLI purge
     1798                                // always failed.
     1799                                wp_cache_delete( 'notoptions', 'options' );
     1800                                wp_cache_delete( '_transient_bliz_hash_transient', 'options' );
     1801                                wp_cache_delete( '_transient_timeout_bliz_hash_transient', 'options' );
    14901802                                $hash = get_transient( 'bliz_hash_transient' );
    14911803                        }
    … …  
    15191831                                $nonce = wp_create_nonce( 'generate_cdn_domain_action' );
    15201832
     1833                                // Loopback request to the site itself (see get_hash)
    15211834                                $response = wp_remote_post( $request_url, array(
    15221835                                        'body' => array(
    … …  
    15251838                                        ),
    15261839                                        'timeout' => 15,
    1527                                         'sslverify' => false,
     1840                                        'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
    15281841                                ) );
    15291842
    … …  
    15421855
    15431856        /**
    1544          * Handle the generate_hash request to store the hash in transient and database.
     1857         * Handle the generate_hash request to store the hash in a transient (used by WP-CLI).
    15451858         */
    15461859        public function handle_generate_hash() {
    … …  
    15481861                        // Verify nonce
    15491862                        if ( isset( $_POST['nonce'] ) && wp_verify_nonce( sanitize_key( $_POST['nonce'] ), 'generate_hash_action' ) ) {
    1550                                 $current_domain = parse_url( home_url(), PHP_URL_HOST );
    1551 
    15521863                                // Fetch the hash value from $_SERVER
    15531864                                if ( isset( $_SERVER['HTTP_X_PURGE_KEY'] ) ) {
    15541865                                        $hash = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_PURGE_KEY'] ) );
    1555                                         // Store in transient and options table
     1866                                        // Store in a transient only (up to 5.0.2 it was also saved, never read, in the "bliz_hash" option)
    15561867                                        set_transient( 'bliz_hash_transient', $hash, DAY_IN_SECONDS );
    1557                                         update_option( 'bliz_hash', array( 'hash' => $hash, 'domain' => $current_domain, 'timestamp' => time() ) );
    15581868                                }
    15591869                        }
    … …  
    15971907 */
    15981908if ( defined( 'WP_CLI' ) && WP_CLI ) {
    1599         include( 'wp-cli.php' );
     1909        include __DIR__ . '/wp-cli.php';
    16001910}
  • blizhost-cache-purge/trunk/font/index.php

    r1904994 r3840577  
     1<?php
     2// Silence is golden.
  • blizhost-cache-purge/trunk/js/index.php

    r3180199 r3840577  
     1<?php
     2// Silence is golden.
  • blizhost-cache-purge/trunk/lang/index.php

    r1904994 r3840577  
     1<?php
     2// Silence is golden.
  • blizhost-cache-purge/trunk/readme.txt

    r3183932 r3840577  
    33Tags: cache, performance, security, nginx, redis
    44Requires at least: 4.4
    5 Tested up to: 6.7
     5Tested up to: 7.1
    66Requires PHP: 5.6
    7 Stable tag: 5.0.2
     7Stable tag: 5.0.3
    88License: GPLv3
    99License URI: https://www.gnu.org/licenses/gpl-3.0.html
    … …  
    7878* Portuguese-BR
    7979
     80== External services ==
     81
     82This plugin connects to the external services below. They are only used when the site is hosted on a <strong>Blizhost</strong> server (the server hostname contains "blizhost"); on other hosts, nothing is sent.
     83
     84= Blizhost CloudCache purge API =
     85
     86Used to clear the CloudCache (the server cache in front of the site) when the content changes: when a post, page, comment, menu or widget is saved, when settings that affect every page change, or when an administrator clicks "Purge CloudCache" or runs `wp ccache purge`.
     87
     88The plugin sends a POST request to `https://cloudcache-api.blizhost.com/purge/` with: the list of URLs (paths) to purge, the hosting account username, the site domain, the site purge key (provided by the Blizhost server), the server hostname, the PHP SAPI and the plugin version. No visitor data is sent.
     89
     90This service is provided by Blizhost: [Terms of Service](https://www.blizhost.com.br/termos-de-servico/), [Privacy Policy](https://www.blizhost.com.br/politica-de-privacidade/).
     91
     92= WordPress.com image CDN (Photon) =
     93
     94Used to serve the site images faster. Unless the Jetpack image CDN is already active or the `DISABLE_WP_CDN` constant is set to `true`, the plugin rewrites the URLs of the site's own images (JPG, PNG, GIF and WebP) to the WordPress.com image CDN (`i0.wp.com` to `i3.wp.com`), operated by Automattic. The visitor's browser then loads those images from the CDN, which receives the image URL and, like any website, the visitor's IP address and browser information.
     95
     96This service is provided by Automattic: [Terms of Service](https://wordpress.com/tos/), [Privacy Policy](https://automattic.com/privacy/).
     97
    8098== Frequently Asked Questions ==
    8199
    … …  
    102120
    103121== Changelog ==
     122
     123= 5.0.3 =
     124* Fixed the WP-CLI command (`wp ccache purge`), broken since 5.0.1; it now reports when the purge fails
     125* Fixed deprecation notices on PHP 8.2 and newer (dynamic properties and HTML-ENTITIES conversion)
     126* Fixed purge events that were never registered (Customizer, Gravity Forms, Rank Math SEO) and the hook names for Rank Math SEO and WP Offload Media
     127* New purge triggers: comments, navigation menus and menu locations, widgets, block theme templates, template parts, global styles and synced patterns
     128* Private comment types (block editor notes, WooCommerce order notes) no longer purge the cache
     129* Advanced Custom Fields and WP Offload Media now purge only the affected post instead of the whole site
     130* Multisite: a full purge of a subdirectory site now clears only that site
     131* The same permission (manage_options) is required for every purge action
     132* The purge key is no longer stored in the database (the old option is removed)
     133* Escaped admin texts and added protection against direct file access
     134* Added the "External services" section to the readme
     135* Tested up to WordPress 7.1
    104136
    105137= 5.0.2 =
  • blizhost-cache-purge/trunk/wp-cli.php

    r3180223 r3840577  
    11<?php
    22
    3 if (!defined('ABSPATH')) {
    4     die();
     3if ( ! defined( 'ABSPATH' ) ) {
     4        die();
    55}
    66
    77// Bail if WP-CLI is not present
    8 if ( !defined( 'WP_CLI' ) ) return;
     8if ( ! defined( 'WP_CLI' ) ) {
     9        return;
     10}
    911
    1012/**
    11  * Purges CloudCache
     13 * Purges CloudCache using WP-CLI commands.
    1214 */
    13 class WP_CLI_BlizCCache_Purge_Command extends WP_CLI_Command {
     15class WP_CLI_BlizCloudCache_Purge_Command extends WP_CLI_Command {
    1416
    15         private $wildcard = false;
     17        /**
     18         * Instance of the BlizCloudCachePurger class.
     19         *
     20         * @var BlizCloudCachePurger
     21         */
     22        private $ccache_purge;
    1623
     24        /**
     25         * Constructor.
     26         */
    1727        public function __construct() {
    18                 $this->ccache_purge = new BlizCCachePurger();
     28                // Use the plugin's main instance instead of creating another one (which would register every hook again)
     29                $this->ccache_purge = BlizCloudCachePurger::get_instance();
    1930        }
    20        
    21     /**
    22      * Forces a full CloudCache Purge of the entire site (provided
    23      * regex is supported).
    24      *
    25      * ## EXAMPLES
    26      *
    27      *          wp ccache purge
    28      *
    29      *          wp ccache purge http://example.com/wp-content/themes/twentyeleventy/style.css
    30      *
    31          *              wp ccache purge "/wp-content/themes/twentysixty/style.css"
     31
     32        /**
     33         * Forces a CloudCache purge of the specified URL or the entire site.
    3234         *
    33      *          wp ccache purge http://example.com/wp-content/themes/ --wildcard
    34      *
    35      *          wp ccache purge "/wp-content/themes/" --wildcard
    36      *
    37      */
    38        
    39         function purge( $args , $assoc_args ) {
    40                
    41                 $wp_version = get_bloginfo( 'version' );
    42                 $cli_version = WP_CLI_VERSION;
    43                
     35         * ## OPTIONS
     36         *
     37         * [<url>]
     38         * : The URL to purge from the cache. If omitted, the entire cache will be purged.
     39         *
     40         * [--wildcard]
     41         * : Purge using a wildcard, purging all URLs under the specified path.
     42         *
     43         * ## EXAMPLES
     44         *
     45         *    wp ccache purge
     46         *
     47         *    wp ccache purge http://example.com/wp-content/themes/twentyeleventy/style.css
     48         *
     49         *    wp ccache purge "/wp-content/themes/twentysixty/style.css"
     50         *
     51         *    wp ccache purge http://example.com/wp-content/themes/ --wildcard
     52         *
     53         *    wp ccache purge "/wp-content/themes/" --wildcard
     54         *
     55         * @synopsis [<url>] [--wildcard]
     56         *
     57         * @param array $args        The URL argument.
     58         * @param array $assoc_args  The associative arguments.
     59         */
     60        public function purge( $args, $assoc_args ) {
    4461                // Set the URL/path
    45                 if ( !empty($args) ) { list( $url ) = $args; }
    46 
    47                 // If wildcard is set, or the URL argument is empty
    48                 // then treat this as a full purge
    49                 $wild = '';
    50                 if ( isset( $assoc_args['wildcard'] ) || empty($url) ) {
    51                         $wild = ".*";
     62                $url = '';
     63                if ( ! empty( $args ) ) {
     64                        $url = $args[0];
    5265                }
    5366
    54                 wp_create_nonce('ccache-purge-cli');
     67                // If the URL argument is empty, treat this as a full purge
     68                if ( empty( $url ) ) {
     69                        $this->ccache_purge->do_full_purge = true;
     70                } else {
     71                        // Make sure the URL is a full URL
     72                        if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
     73                                $url = home_url( '/' . ltrim( $url, '/' ) );
     74                        }
    5575
    56                 // Make sure the URL is a URL:
    57                 if ( !empty($url) ) {
    58                         $url = $this->ccache_purge->the_home_url() . esc_url( $url );
    59                 } else {
    60                         $url = $this->ccache_purge->the_home_url();
    61                 }
    62                
    63                 if ( version_compare( $wp_version, '4.6', '>=' ) && ( version_compare( $cli_version, '0.25.0', '<' ) || version_compare( $cli_version, '0.25.0-alpha', 'eq' ) ) ) {
    64                        
    65                         WP_CLI::log( sprintf( 'This plugin does not work on WP 4.6 and up, unless WP-CLI is version 0.25.0 or greater. You\'re using WP-CLI %s and WordPress %s.', $cli_version, $wp_version ) );
    66                         WP_CLI::log( 'To flush your cache, please run the following command:');
    67                         WP_CLI::log( sprintf( '$ curl -X PURGE "%s"' , $url.$wild ) );
    68                         WP_CLI::error( 'CloudCache must be purged manually.' );
     76                        // If wildcard is set, append '.*' to the path
     77                        if ( isset( $assoc_args['wildcard'] ) ) {
     78                                // Parse the URL to manipulate the path
     79                                $parsed_url = wp_parse_url( $url );
     80                                $path = isset( $parsed_url['path'] ) ? $parsed_url['path'] : '';
     81
     82                                // Ensure the path ends with '/' before appending '.*'
     83                                if ( substr( $path, -1 ) !== '/' ) {
     84                                        $path .= '/';
     85                                }
     86                                $path .= '.*';
     87
     88                                // Reconstruct the URL with the modified path
     89                                $url = ( isset( $parsed_url['scheme'] ) ? $parsed_url['scheme'] . '://' : '' )
     90                                         . ( isset( $parsed_url['host'] ) ? $parsed_url['host'] : '' )
     91                                         . $path;
     92                        }
     93
     94                        // Add the URL to the purge list
     95                        $this->ccache_purge->blizqueuePurgeUrl( $url );
    6996                }
    7097
    71                 $this->ccache_purge->purgeUrl( $url.$wild );
     98                // Execute the purge and report the real result
     99                $result = $this->ccache_purge->blizexecutePurge();
     100
     101                if ( false === $result || null === $result ) {
     102                        WP_CLI::error( 'CloudCache was not purged: the site is not hosted at Blizhost or the purge key is not available.' );
     103                }
     104                if ( is_wp_error( $result ) ) {
     105                        WP_CLI::error( 'CloudCache was not purged: ' . $result->get_error_message() );
     106                }
     107                $code = (int) wp_remote_retrieve_response_code( $result );
     108                if ( 200 !== $code ) {
     109                        WP_CLI::error( sprintf( 'CloudCache was not purged: the purge API answered HTTP %d.', $code ) );
     110                }
    72111
    73112                WP_CLI::success( 'The CloudCache was purged.' );
    74113        }
    75 
    76114}
    77115
    78 WP_CLI::add_command( 'ccache', 'WP_CLI_BlizCCache_Purge_Command' );
     116WP_CLI::add_command( 'ccache', 'WP_CLI_BlizCloudCache_Purge_Command' );
Note: See TracChangeset for help on using the changeset viewer.