[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> blocks.php (source)

   1  <?php
   2  /**
   3   * Functions related to registering and parsing blocks.
   4   *
   5   * @package WordPress
   6   * @subpackage Blocks
   7   * @since 5.0.0
   8   */
   9  
  10  /**
  11   * Removes the block asset's path prefix if provided.
  12   *
  13   * @since 5.5.0
  14   *
  15   * @param string $asset_handle_or_path Asset handle or prefixed path.
  16   * @return string Path without the prefix or the original value.
  17   */
  18  function remove_block_asset_path_prefix( $asset_handle_or_path ) {
  19      $path_prefix = 'file:';
  20      if ( ! str_starts_with( $asset_handle_or_path, $path_prefix ) ) {
  21          return $asset_handle_or_path;
  22      }
  23      $path = substr(
  24          $asset_handle_or_path,
  25          strlen( $path_prefix )
  26      );
  27      if ( str_starts_with( $path, './' ) ) {
  28          $path = substr( $path, 2 );
  29      }
  30      return $path;
  31  }
  32  
  33  /**
  34   * Generates the name for an asset based on the name of the block
  35   * and the field name provided.
  36   *
  37   * @since 5.5.0
  38   * @since 6.1.0 Added `$index` parameter.
  39   * @since 6.5.0 Added support for `viewScriptModule` field.
  40   *
  41   * @param string $block_name Name of the block.
  42   * @param string $field_name Name of the metadata field.
  43   * @param int    $index      Optional. Index of the asset when multiple items passed.
  44   *                           Default 0.
  45   * @return string Generated asset name for the block's field.
  46   */
  47  function generate_block_asset_handle( $block_name, $field_name, $index = 0 ) {
  48      if ( str_starts_with( $block_name, 'core/' ) ) {
  49          $asset_handle = str_replace( 'core/', 'wp-block-', $block_name );
  50          if ( str_starts_with( $field_name, 'editor' ) ) {
  51              $asset_handle .= '-editor';
  52          }
  53          if ( str_starts_with( $field_name, 'view' ) ) {
  54              $asset_handle .= '-view';
  55          }
  56          if ( str_ends_with( strtolower( $field_name ), 'scriptmodule' ) ) {
  57              $asset_handle .= '-script-module';
  58          }
  59          if ( $index > 0 ) {
  60              $asset_handle .= '-' . ( $index + 1 );
  61          }
  62          return $asset_handle;
  63      }
  64  
  65      $field_mappings = array(
  66          'editorScript'     => 'editor-script',
  67          'editorStyle'      => 'editor-style',
  68          'script'           => 'script',
  69          'style'            => 'style',
  70          'viewScript'       => 'view-script',
  71          'viewScriptModule' => 'view-script-module',
  72          'viewStyle'        => 'view-style',
  73      );
  74      $asset_handle   = str_replace( '/', '-', $block_name ) .
  75          '-' . $field_mappings[ $field_name ];
  76      if ( $index > 0 ) {
  77          $asset_handle .= '-' . ( $index + 1 );
  78      }
  79      return $asset_handle;
  80  }
  81  
  82  /**
  83   * Gets the URL to a block asset.
  84   *
  85   * @since 6.4.0
  86   *
  87   * @param string $path A normalized path to a block asset.
  88   * @return string|false The URL to the block asset or false on failure.
  89   */
  90  function get_block_asset_url( $path ) {
  91      if ( empty( $path ) ) {
  92          return false;
  93      }
  94  
  95      // Path needs to be normalized to work in Windows env.
  96      static $wpinc_path_norm = '';
  97      if ( ! $wpinc_path_norm ) {
  98          $wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) );
  99      }
 100  
 101      if ( str_starts_with( $path, $wpinc_path_norm ) ) {
 102          return includes_url( str_replace( $wpinc_path_norm, '', $path ) );
 103      }
 104  
 105      static $template_paths_norm = array();
 106  
 107      $template = get_template();
 108      if ( ! isset( $template_paths_norm[ $template ] ) ) {
 109          $template_paths_norm[ $template ] = wp_normalize_path( realpath( get_template_directory() ) );
 110      }
 111  
 112      if ( str_starts_with( $path, trailingslashit( $template_paths_norm[ $template ] ) ) ) {
 113          return get_theme_file_uri( str_replace( $template_paths_norm[ $template ], '', $path ) );
 114      }
 115  
 116      if ( is_child_theme() ) {
 117          $stylesheet = get_stylesheet();
 118          if ( ! isset( $template_paths_norm[ $stylesheet ] ) ) {
 119              $template_paths_norm[ $stylesheet ] = wp_normalize_path( realpath( get_stylesheet_directory() ) );
 120          }
 121  
 122          if ( str_starts_with( $path, trailingslashit( $template_paths_norm[ $stylesheet ] ) ) ) {
 123              return get_theme_file_uri( str_replace( $template_paths_norm[ $stylesheet ], '', $path ) );
 124          }
 125      }
 126  
 127      return plugins_url( basename( $path ), $path );
 128  }
 129  
 130  /**
 131   * Finds a script module ID for the selected block metadata field. It detects
 132   * when a path to file was provided and optionally finds a corresponding asset
 133   * file with details necessary to register the script module under with an
 134   * automatically generated module ID. It returns unprocessed script module
 135   * ID otherwise.
 136   *
 137   * @since 6.5.0
 138   *
 139   * @param array  $metadata   Block metadata.
 140   * @param string $field_name Field name to pick from metadata.
 141   * @param int    $index      Optional. Index of the script module ID to register when multiple
 142   *                           items passed. Default 0.
 143   * @return string|false Script module ID or false on failure.
 144   */
 145  function register_block_script_module_id( $metadata, $field_name, $index = 0 ) {
 146      if ( empty( $metadata[ $field_name ] ) ) {
 147          return false;
 148      }
 149  
 150      $module_id = $metadata[ $field_name ];
 151      if ( is_array( $module_id ) ) {
 152          if ( empty( $module_id[ $index ] ) ) {
 153              return false;
 154          }
 155          $module_id = $module_id[ $index ];
 156      }
 157  
 158      $module_path = remove_block_asset_path_prefix( $module_id );
 159      if ( $module_id === $module_path ) {
 160          return $module_id;
 161      }
 162  
 163      $path                  = dirname( $metadata['file'] );
 164      $module_asset_raw_path = $path . '/' . substr_replace( $module_path, '.asset.php', - strlen( '.js' ) );
 165      $module_id             = generate_block_asset_handle( $metadata['name'], $field_name, $index );
 166      $module_asset_path     = wp_normalize_path(
 167          realpath( $module_asset_raw_path )
 168      );
 169  
 170      $module_path_norm = wp_normalize_path( realpath( $path . '/' . $module_path ) );
 171      $module_uri       = get_block_asset_url( $module_path_norm );
 172  
 173      $module_asset        = ! empty( $module_asset_path ) ? require $module_asset_path : array();
 174      $module_dependencies = isset( $module_asset['dependencies'] ) ? $module_asset['dependencies'] : array();
 175      $block_version       = isset( $metadata['version'] ) ? $metadata['version'] : false;
 176      $module_version      = isset( $module_asset['version'] ) ? $module_asset['version'] : $block_version;
 177  
 178      wp_register_script_module(
 179          $module_id,
 180          $module_uri,
 181          $module_dependencies,
 182          $module_version
 183      );
 184  
 185      return $module_id;
 186  }
 187  
 188  /**
 189   * Finds a script handle for the selected block metadata field. It detects
 190   * when a path to file was provided and optionally finds a corresponding asset
 191   * file with details necessary to register the script under automatically
 192   * generated handle name. It returns unprocessed script handle otherwise.
 193   *
 194   * @since 5.5.0
 195   * @since 6.1.0 Added `$index` parameter.
 196   * @since 6.5.0 The asset file is optional. Added script handle support in the asset file.
 197   *
 198   * @param array  $metadata   Block metadata.
 199   * @param string $field_name Field name to pick from metadata.
 200   * @param int    $index      Optional. Index of the script to register when multiple items passed.
 201   *                           Default 0.
 202   * @return string|false Script handle provided directly or created through
 203   *                      script's registration, or false on failure.
 204   */
 205  function register_block_script_handle( $metadata, $field_name, $index = 0 ) {
 206      if ( empty( $metadata[ $field_name ] ) ) {
 207          return false;
 208      }
 209  
 210      $script_handle_or_path = $metadata[ $field_name ];
 211      if ( is_array( $script_handle_or_path ) ) {
 212          if ( empty( $script_handle_or_path[ $index ] ) ) {
 213              return false;
 214          }
 215          $script_handle_or_path = $script_handle_or_path[ $index ];
 216      }
 217  
 218      $script_path = remove_block_asset_path_prefix( $script_handle_or_path );
 219      if ( $script_handle_or_path === $script_path ) {
 220          return $script_handle_or_path;
 221      }
 222  
 223      $path                  = dirname( $metadata['file'] );
 224      $script_asset_raw_path = $path . '/' . substr_replace( $script_path, '.asset.php', - strlen( '.js' ) );
 225      $script_asset_path     = wp_normalize_path(
 226          realpath( $script_asset_raw_path )
 227      );
 228  
 229      // Asset file for blocks is optional. See https://core.trac.wordpress.org/ticket/60460.
 230      $script_asset  = ! empty( $script_asset_path ) ? require $script_asset_path : array();
 231      $script_handle = isset( $script_asset['handle'] ) ?
 232          $script_asset['handle'] :
 233          generate_block_asset_handle( $metadata['name'], $field_name, $index );
 234      if ( wp_script_is( $script_handle, 'registered' ) ) {
 235          return $script_handle;
 236      }
 237  
 238      $script_path_norm    = wp_normalize_path( realpath( $path . '/' . $script_path ) );
 239      $script_uri          = get_block_asset_url( $script_path_norm );
 240      $script_dependencies = isset( $script_asset['dependencies'] ) ? $script_asset['dependencies'] : array();
 241      $block_version       = isset( $metadata['version'] ) ? $metadata['version'] : false;
 242      $script_version      = isset( $script_asset['version'] ) ? $script_asset['version'] : $block_version;
 243      $script_args         = array();
 244      if ( 'viewScript' === $field_name && $script_uri ) {
 245          $script_args['strategy'] = 'defer';
 246      }
 247  
 248      $result = wp_register_script(
 249          $script_handle,
 250          $script_uri,
 251          $script_dependencies,
 252          $script_version,
 253          $script_args
 254      );
 255      if ( ! $result ) {
 256          return false;
 257      }
 258  
 259      if ( ! empty( $metadata['textdomain'] ) && in_array( 'wp-i18n', $script_dependencies, true ) ) {
 260          wp_set_script_translations( $script_handle, $metadata['textdomain'] );
 261      }
 262  
 263      return $script_handle;
 264  }
 265  
 266  /**
 267   * Finds a style handle for the block metadata field. It detects when a path
 268   * to file was provided and registers the style under automatically
 269   * generated handle name. It returns unprocessed style handle otherwise.
 270   *
 271   * @since 5.5.0
 272   * @since 6.1.0 Added `$index` parameter.
 273   *
 274   * @param array  $metadata   Block metadata.
 275   * @param string $field_name Field name to pick from metadata.
 276   * @param int    $index      Optional. Index of the style to register when multiple items passed.
 277   *                           Default 0.
 278   * @return string|false Style handle provided directly or created through
 279   *                      style's registration, or false on failure.
 280   */
 281  function register_block_style_handle( $metadata, $field_name, $index = 0 ) {
 282      if ( empty( $metadata[ $field_name ] ) ) {
 283          return false;
 284      }
 285  
 286      $style_handle = $metadata[ $field_name ];
 287      if ( is_array( $style_handle ) ) {
 288          if ( empty( $style_handle[ $index ] ) ) {
 289              return false;
 290          }
 291          $style_handle = $style_handle[ $index ];
 292      }
 293  
 294      $style_handle_name = generate_block_asset_handle( $metadata['name'], $field_name, $index );
 295      // If the style handle is already registered, skip re-registering.
 296      if ( wp_style_is( $style_handle_name, 'registered' ) ) {
 297          return $style_handle_name;
 298      }
 299  
 300      static $wpinc_path_norm = '';
 301      if ( ! $wpinc_path_norm ) {
 302          $wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) );
 303      }
 304  
 305      $is_core_block = isset( $metadata['file'] ) && str_starts_with( $metadata['file'], $wpinc_path_norm );
 306      // Skip registering individual styles for each core block when a bundled version provided.
 307      if ( $is_core_block && ! wp_should_load_separate_core_block_assets() ) {
 308          return false;
 309      }
 310  
 311      $style_path      = remove_block_asset_path_prefix( $style_handle );
 312      $is_style_handle = $style_handle === $style_path;
 313      // Allow only passing style handles for core blocks.
 314      if ( $is_core_block && ! $is_style_handle ) {
 315          return false;
 316      }
 317      // Return the style handle unless it's the first item for every core block that requires special treatment.
 318      if ( $is_style_handle && ! ( $is_core_block && 0 === $index ) ) {
 319          return $style_handle;
 320      }
 321  
 322      // Check whether styles should have a ".min" suffix or not.
 323      $suffix = SCRIPT_DEBUG ? '' : '.min';
 324      if ( $is_core_block ) {
 325          $style_path = ( 'editorStyle' === $field_name ) ? "editor{$suffix}.css" : "style{$suffix}.css";
 326      }
 327  
 328      $style_path_norm = wp_normalize_path( realpath( dirname( $metadata['file'] ) . '/' . $style_path ) );
 329      $style_uri       = get_block_asset_url( $style_path_norm );
 330  
 331      $version = ! $is_core_block && isset( $metadata['version'] ) ? $metadata['version'] : false;
 332      $result  = wp_register_style(
 333          $style_handle_name,
 334          $style_uri,
 335          array(),
 336          $version
 337      );
 338      if ( ! $result ) {
 339          return false;
 340      }
 341  
 342      if ( $style_uri ) {
 343          wp_style_add_data( $style_handle_name, 'path', $style_path_norm );
 344  
 345          if ( $is_core_block ) {
 346              $rtl_file = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $style_path_norm );
 347          } else {
 348              $rtl_file = str_replace( '.css', '-rtl.css', $style_path_norm );
 349          }
 350  
 351          if ( is_rtl() && file_exists( $rtl_file ) ) {
 352              wp_style_add_data( $style_handle_name, 'rtl', 'replace' );
 353              wp_style_add_data( $style_handle_name, 'suffix', $suffix );
 354              wp_style_add_data( $style_handle_name, 'path', $rtl_file );
 355          }
 356      }
 357  
 358      return $style_handle_name;
 359  }
 360  
 361  /**
 362   * Gets i18n schema for block's metadata read from `block.json` file.
 363   *
 364   * @since 5.9.0
 365   *
 366   * @return object The schema for block's metadata.
 367   */
 368  function get_block_metadata_i18n_schema() {
 369      static $i18n_block_schema;
 370  
 371      if ( ! isset( $i18n_block_schema ) ) {
 372          $i18n_block_schema = wp_json_file_decode( __DIR__ . '/block-i18n.json' );
 373      }
 374  
 375      return $i18n_block_schema;
 376  }
 377  
 378  /**
 379   * Registers all block types from a block metadata collection.
 380   *
 381   * This can either reference a previously registered metadata collection or, if the `$manifest` parameter is provided,
 382   * register the metadata collection directly within the same function call.
 383   *
 384   * @since 6.8.0
 385   * @see wp_register_block_metadata_collection()
 386   * @see register_block_type_from_metadata()
 387   *
 388   * @param string $path     The absolute base path for the collection ( e.g., WP_PLUGIN_DIR . '/my-plugin/blocks/' ).
 389   * @param string $manifest Optional. The absolute path to the manifest file containing the metadata collection, in
 390   *                         order to register the collection. If this parameter is not provided, the `$path` parameter
 391   *                         must reference a previously registered block metadata collection.
 392   */
 393  function wp_register_block_types_from_metadata_collection( $path, $manifest = '' ) {
 394      if ( $manifest ) {
 395          wp_register_block_metadata_collection( $path, $manifest );
 396      }
 397  
 398      $block_metadata_files = WP_Block_Metadata_Registry::get_collection_block_metadata_files( $path );
 399      foreach ( $block_metadata_files as $block_metadata_file ) {
 400          register_block_type_from_metadata( $block_metadata_file );
 401      }
 402  }
 403  
 404  /**
 405   * Registers a block metadata collection.
 406   *
 407   * This function allows core and third-party plugins to register their block metadata
 408   * collections in a centralized location. Registering collections can improve performance
 409   * by avoiding multiple reads from the filesystem and parsing JSON.
 410   *
 411   * @since 6.7.0
 412   *
 413   * @param string $path     The base path in which block files for the collection reside.
 414   * @param string $manifest The path to the manifest file for the collection.
 415   */
 416  function wp_register_block_metadata_collection( $path, $manifest ) {
 417      WP_Block_Metadata_Registry::register_collection( $path, $manifest );
 418  }
 419  
 420  /**
 421   * Registers a block type from the metadata stored in the `block.json` file.
 422   *
 423   * @since 5.5.0
 424   * @since 5.7.0 Added support for `textdomain` field and i18n handling for all translatable fields.
 425   * @since 5.9.0 Added support for `variations` and `viewScript` fields.
 426   * @since 6.1.0 Added support for `render` field.
 427   * @since 6.3.0 Added `selectors` field.
 428   * @since 6.4.0 Added support for `blockHooks` field.
 429   * @since 6.5.0 Added support for `allowedBlocks`, `viewScriptModule`, and `viewStyle` fields.
 430   * @since 6.7.0 Allow PHP filename as `variations` argument.
 431   *
 432   * @param string $file_or_folder Path to the JSON file with metadata definition for
 433   *                               the block or path to the folder where the `block.json` file is located.
 434   *                               If providing the path to a JSON file, the filename must end with `block.json`.
 435   * @param array  $args           Optional. Array of block type arguments. Accepts any public property
 436   *                               of `WP_Block_Type`. See WP_Block_Type::__construct() for information
 437   *                               on accepted arguments. Default empty array.
 438   * @return WP_Block_Type|false The registered block type on success, or false on failure.
 439   */
 440  function register_block_type_from_metadata( $file_or_folder, $args = array() ) {
 441      /*
 442       * Get an array of metadata from a PHP file.
 443       * This improves performance for core blocks as it's only necessary to read a single PHP file
 444       * instead of reading a JSON file per-block, and then decoding from JSON to PHP.
 445       * Using a static variable ensures that the metadata is only read once per request.
 446       */
 447  
 448      $file_or_folder = wp_normalize_path( $file_or_folder );
 449  
 450      $metadata_file = ( ! str_ends_with( $file_or_folder, 'block.json' ) ) ?
 451          trailingslashit( $file_or_folder ) . 'block.json' :
 452          $file_or_folder;
 453  
 454      $is_core_block        = str_starts_with( $file_or_folder, wp_normalize_path( ABSPATH . WPINC ) );
 455      $metadata_file_exists = $is_core_block || file_exists( $metadata_file );
 456      $registry_metadata    = WP_Block_Metadata_Registry::get_metadata( $file_or_folder );
 457  
 458      if ( $registry_metadata ) {
 459          $metadata = $registry_metadata;
 460      } elseif ( $metadata_file_exists ) {
 461          $metadata = wp_json_file_decode( $metadata_file, array( 'associative' => true ) );
 462      } else {
 463          $metadata = array();
 464      }
 465  
 466      if ( ! is_array( $metadata ) || ( empty( $metadata['name'] ) && empty( $args['name'] ) ) ) {
 467          return false;
 468      }
 469  
 470      $metadata['file'] = $metadata_file_exists ? wp_normalize_path( realpath( $metadata_file ) ) : null;
 471  
 472      /**
 473       * Filters the metadata provided for registering a block type.
 474       *
 475       * @since 5.7.0
 476       *
 477       * @param array $metadata Metadata for registering a block type.
 478       */
 479      $metadata = apply_filters( 'block_type_metadata', $metadata );
 480  
 481      // Add `style` and `editor_style` for core blocks if missing.
 482      if ( ! empty( $metadata['name'] ) && str_starts_with( $metadata['name'], 'core/' ) ) {
 483          $block_name = str_replace( 'core/', '', $metadata['name'] );
 484  
 485          if ( ! isset( $metadata['style'] ) ) {
 486              $metadata['style'] = "wp-block-$block_name";
 487          }
 488          if ( current_theme_supports( 'wp-block-styles' ) && wp_should_load_separate_core_block_assets() ) {
 489              $metadata['style']   = (array) $metadata['style'];
 490              $metadata['style'][] = "wp-block-{$block_name}-theme";
 491          }
 492          if ( ! isset( $metadata['editorStyle'] ) ) {
 493              $metadata['editorStyle'] = "wp-block-{$block_name}-editor";
 494          }
 495      }
 496  
 497      $settings          = array();
 498      $property_mappings = array(
 499          'apiVersion'      => 'api_version',
 500          'name'            => 'name',
 501          'title'           => 'title',
 502          'category'        => 'category',
 503          'parent'          => 'parent',
 504          'ancestor'        => 'ancestor',
 505          'icon'            => 'icon',
 506          'description'     => 'description',
 507          'keywords'        => 'keywords',
 508          'attributes'      => 'attributes',
 509          'providesContext' => 'provides_context',
 510          'usesContext'     => 'uses_context',
 511          'selectors'       => 'selectors',
 512          'supports'        => 'supports',
 513          'styles'          => 'styles',
 514          'variations'      => 'variations',
 515          'example'         => 'example',
 516          'allowedBlocks'   => 'allowed_blocks',
 517      );
 518      $textdomain        = ! empty( $metadata['textdomain'] ) ? $metadata['textdomain'] : null;
 519      $i18n_schema       = get_block_metadata_i18n_schema();
 520  
 521      foreach ( $property_mappings as $key => $mapped_key ) {
 522          if ( isset( $metadata[ $key ] ) ) {
 523              $settings[ $mapped_key ] = $metadata[ $key ];
 524              if ( $metadata_file_exists && $textdomain && isset( $i18n_schema->$key ) ) {
 525                  $settings[ $mapped_key ] = translate_settings_using_i18n_schema( $i18n_schema->$key, $settings[ $key ], $textdomain );
 526              }
 527          }
 528      }
 529  
 530      if ( ! empty( $metadata['render'] ) ) {
 531          $template_path = wp_normalize_path(
 532              realpath(
 533                  dirname( $metadata['file'] ) . '/' .
 534                  remove_block_asset_path_prefix( $metadata['render'] )
 535              )
 536          );
 537          if ( $template_path ) {
 538              /**
 539               * Renders the block on the server.
 540               *
 541               * @since 6.1.0
 542               *
 543               * @param array    $attributes Block attributes.
 544               * @param string   $content    Block default content.
 545               * @param WP_Block $block      Block instance.
 546               *
 547               * @return string Returns the block content.
 548               */
 549              $settings['render_callback'] = static function ( $attributes, $content, $block ) use ( $template_path ) {
 550                  ob_start();
 551                  require $template_path;
 552                  return ob_get_clean();
 553              };
 554          }
 555      }
 556  
 557      // If `variations` is a string, it's the name of a PHP file that
 558      // generates the variations.
 559      if ( ! empty( $metadata['variations'] ) && is_string( $metadata['variations'] ) ) {
 560          $variations_path = wp_normalize_path(
 561              realpath(
 562                  dirname( $metadata['file'] ) . '/' .
 563                  remove_block_asset_path_prefix( $metadata['variations'] )
 564              )
 565          );
 566          if ( $variations_path ) {
 567              /**
 568               * Generates the list of block variations.
 569               *
 570               * @since 6.7.0
 571               *
 572               * @return string Returns the list of block variations.
 573               */
 574              $settings['variation_callback'] = static function () use ( $variations_path ) {
 575                  $variations = require $variations_path;
 576                  return $variations;
 577              };
 578              // The block instance's `variations` field is only allowed to be an array
 579              // (of known block variations). We unset it so that the block instance will
 580              // provide a getter that returns the result of the `variation_callback` instead.
 581              unset( $settings['variations'] );
 582          }
 583      }
 584  
 585      $settings = array_merge( $settings, $args );
 586  
 587      $script_fields = array(
 588          'editorScript' => 'editor_script_handles',
 589          'script'       => 'script_handles',
 590          'viewScript'   => 'view_script_handles',
 591      );
 592      foreach ( $script_fields as $metadata_field_name => $settings_field_name ) {
 593          if ( ! empty( $settings[ $metadata_field_name ] ) ) {
 594              $metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ];
 595          }
 596          if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
 597              $scripts           = $metadata[ $metadata_field_name ];
 598              $processed_scripts = array();
 599              if ( is_array( $scripts ) ) {
 600                  for ( $index = 0; $index < count( $scripts ); $index++ ) {
 601                      $result = register_block_script_handle(
 602                          $metadata,
 603                          $metadata_field_name,
 604                          $index
 605                      );
 606                      if ( $result ) {
 607                          $processed_scripts[] = $result;
 608                      }
 609                  }
 610              } else {
 611                  $result = register_block_script_handle(
 612                      $metadata,
 613                      $metadata_field_name
 614                  );
 615                  if ( $result ) {
 616                      $processed_scripts[] = $result;
 617                  }
 618              }
 619              $settings[ $settings_field_name ] = $processed_scripts;
 620          }
 621      }
 622  
 623      $module_fields = array(
 624          'viewScriptModule' => 'view_script_module_ids',
 625      );
 626      foreach ( $module_fields as $metadata_field_name => $settings_field_name ) {
 627          if ( ! empty( $settings[ $metadata_field_name ] ) ) {
 628              $metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ];
 629          }
 630          if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
 631              $modules           = $metadata[ $metadata_field_name ];
 632              $processed_modules = array();
 633              if ( is_array( $modules ) ) {
 634                  for ( $index = 0; $index < count( $modules ); $index++ ) {
 635                      $result = register_block_script_module_id(
 636                          $metadata,
 637                          $metadata_field_name,
 638                          $index
 639                      );
 640                      if ( $result ) {
 641                          $processed_modules[] = $result;
 642                      }
 643                  }
 644              } else {
 645                  $result = register_block_script_module_id(
 646                      $metadata,
 647                      $metadata_field_name
 648                  );
 649                  if ( $result ) {
 650                      $processed_modules[] = $result;
 651                  }
 652              }
 653              $settings[ $settings_field_name ] = $processed_modules;
 654          }
 655      }
 656  
 657      $style_fields = array(
 658          'editorStyle' => 'editor_style_handles',
 659          'style'       => 'style_handles',
 660          'viewStyle'   => 'view_style_handles',
 661      );
 662      foreach ( $style_fields as $metadata_field_name => $settings_field_name ) {
 663          if ( ! empty( $settings[ $metadata_field_name ] ) ) {
 664              $metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ];
 665          }
 666          if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
 667              $styles           = $metadata[ $metadata_field_name ];
 668              $processed_styles = array();
 669              if ( is_array( $styles ) ) {
 670                  for ( $index = 0; $index < count( $styles ); $index++ ) {
 671                      $result = register_block_style_handle(
 672                          $metadata,
 673                          $metadata_field_name,
 674                          $index
 675                      );
 676                      if ( $result ) {
 677                          $processed_styles[] = $result;
 678                      }
 679                  }
 680              } else {
 681                  $result = register_block_style_handle(
 682                      $metadata,
 683                      $metadata_field_name
 684                  );
 685                  if ( $result ) {
 686                      $processed_styles[] = $result;
 687                  }
 688              }
 689              $settings[ $settings_field_name ] = $processed_styles;
 690          }
 691      }
 692  
 693      if ( ! empty( $metadata['blockHooks'] ) ) {
 694          /**
 695           * Map camelCased position string (from block.json) to snake_cased block type position.
 696           *
 697           * @var array
 698           */
 699          $position_mappings = array(
 700              'before'     => 'before',
 701              'after'      => 'after',
 702              'firstChild' => 'first_child',
 703              'lastChild'  => 'last_child',
 704          );
 705  
 706          $settings['block_hooks'] = array();
 707          foreach ( $metadata['blockHooks'] as $anchor_block_name => $position ) {
 708              // Avoid infinite recursion (hooking to itself).
 709              if ( $metadata['name'] === $anchor_block_name ) {
 710                  _doing_it_wrong(
 711                      __METHOD__,
 712                      __( 'Cannot hook block to itself.' ),
 713                      '6.4.0'
 714                  );
 715                  continue;
 716              }
 717  
 718              if ( ! isset( $position_mappings[ $position ] ) ) {
 719                  continue;
 720              }
 721  
 722              $settings['block_hooks'][ $anchor_block_name ] = $position_mappings[ $position ];
 723          }
 724      }
 725  
 726      /**
 727       * Filters the settings determined from the block type metadata.
 728       *
 729       * @since 5.7.0
 730       *
 731       * @param array $settings Array of determined settings for registering a block type.
 732       * @param array $metadata Metadata provided for registering a block type.
 733       */
 734      $settings = apply_filters( 'block_type_metadata_settings', $settings, $metadata );
 735  
 736      $metadata['name'] = ! empty( $settings['name'] ) ? $settings['name'] : $metadata['name'];
 737  
 738      return WP_Block_Type_Registry::get_instance()->register(
 739          $metadata['name'],
 740          $settings
 741      );
 742  }
 743  
 744  /**
 745   * Registers a block type. The recommended way is to register a block type using
 746   * the metadata stored in the `block.json` file.
 747   *
 748   * @since 5.0.0
 749   * @since 5.8.0 First parameter now accepts a path to the `block.json` file.
 750   *
 751   * @param string|WP_Block_Type $block_type Block type name including namespace, or alternatively
 752   *                                         a path to the JSON file with metadata definition for the block,
 753   *                                         or a path to the folder where the `block.json` file is located,
 754   *                                         or a complete WP_Block_Type instance.
 755   *                                         In case a WP_Block_Type is provided, the $args parameter will be ignored.
 756   * @param array                $args       Optional. Array of block type arguments. Accepts any public property
 757   *                                         of `WP_Block_Type`. See WP_Block_Type::__construct() for information
 758   *                                         on accepted arguments. Default empty array.
 759   *
 760   * @return WP_Block_Type|false The registered block type on success, or false on failure.
 761   */
 762  function register_block_type( $block_type, $args = array() ) {
 763      if ( is_string( $block_type ) && file_exists( $block_type ) ) {
 764          return register_block_type_from_metadata( $block_type, $args );
 765      }
 766  
 767      return WP_Block_Type_Registry::get_instance()->register( $block_type, $args );
 768  }
 769  
 770  /**
 771   * Unregisters a block type.
 772   *
 773   * @since 5.0.0
 774   *
 775   * @param string|WP_Block_Type $name Block type name including namespace, or alternatively
 776   *                                   a complete WP_Block_Type instance.
 777   * @return WP_Block_Type|false The unregistered block type on success, or false on failure.
 778   */
 779  function unregister_block_type( $name ) {
 780      return WP_Block_Type_Registry::get_instance()->unregister( $name );
 781  }
 782  
 783  /**
 784   * Determines whether a post or content string has blocks.
 785   *
 786   * This test optimizes for performance rather than strict accuracy, detecting
 787   * the pattern of a block but not validating its structure. For strict accuracy,
 788   * you should use the block parser on post content.
 789   *
 790   * @since 5.0.0
 791   *
 792   * @see parse_blocks()
 793   *
 794   * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object.
 795   *                                      Defaults to global $post.
 796   * @return bool Whether the post has blocks.
 797   */
 798  function has_blocks( $post = null ) {
 799      if ( ! is_string( $post ) ) {
 800          $wp_post = get_post( $post );
 801  
 802          if ( ! $wp_post instanceof WP_Post ) {
 803              return false;
 804          }
 805  
 806          $post = $wp_post->post_content;
 807      }
 808  
 809      return str_contains( (string) $post, '<!-- wp:' );
 810  }
 811  
 812  /**
 813   * Determines whether a $post or a string contains a specific block type.
 814   *
 815   * This test optimizes for performance rather than strict accuracy, detecting
 816   * whether the block type exists but not validating its structure and not checking
 817   * synced patterns (formerly called reusable blocks). For strict accuracy,
 818   * you should use the block parser on post content.
 819   *
 820   * @since 5.0.0
 821   *
 822   * @see parse_blocks()
 823   *
 824   * @param string                  $block_name Full block type to look for.
 825   * @param int|string|WP_Post|null $post       Optional. Post content, post ID, or post object.
 826   *                                            Defaults to global $post.
 827   * @return bool Whether the post content contains the specified block.
 828   */
 829  function has_block( $block_name, $post = null ) {
 830      if ( ! has_blocks( $post ) ) {
 831          return false;
 832      }
 833  
 834      if ( ! is_string( $post ) ) {
 835          $wp_post = get_post( $post );
 836          if ( $wp_post instanceof WP_Post ) {
 837              $post = $wp_post->post_content;
 838          }
 839      }
 840  
 841      /*
 842       * Normalize block name to include namespace, if provided as non-namespaced.
 843       * This matches behavior for WordPress 5.0.0 - 5.3.0 in matching blocks by
 844       * their serialized names.
 845       */
 846      if ( ! str_contains( $block_name, '/' ) ) {
 847          $block_name = 'core/' . $block_name;
 848      }
 849  
 850      // Test for existence of block by its fully qualified name.
 851      $has_block = str_contains( $post, '<!-- wp:' . $block_name . ' ' );
 852  
 853      if ( ! $has_block ) {
 854          /*
 855           * If the given block name would serialize to a different name, test for
 856           * existence by the serialized form.
 857           */
 858          $serialized_block_name = strip_core_block_namespace( $block_name );
 859          if ( $serialized_block_name !== $block_name ) {
 860              $has_block = str_contains( $post, '<!-- wp:' . $serialized_block_name . ' ' );
 861          }
 862      }
 863  
 864      return $has_block;
 865  }
 866  
 867  /**
 868   * Returns an array of the names of all registered dynamic block types.
 869   *
 870   * @since 5.0.0
 871   *
 872   * @return string[] Array of dynamic block names.
 873   */
 874  function get_dynamic_block_names() {
 875      $dynamic_block_names = array();
 876  
 877      $block_types = WP_Block_Type_Registry::get_instance()->get_all_registered();
 878      foreach ( $block_types as $block_type ) {
 879          if ( $block_type->is_dynamic() ) {
 880              $dynamic_block_names[] = $block_type->name;
 881          }
 882      }
 883  
 884      return $dynamic_block_names;
 885  }
 886  
 887  /**
 888   * Retrieves block types hooked into the given block, grouped by anchor block type and the relative position.
 889   *
 890   * @since 6.4.0
 891   *
 892   * @return array[] Array of block types grouped by anchor block type and the relative position.
 893   */
 894  function get_hooked_blocks() {
 895      $block_types   = WP_Block_Type_Registry::get_instance()->get_all_registered();
 896      $hooked_blocks = array();
 897      foreach ( $block_types as $block_type ) {
 898          if ( ! ( $block_type instanceof WP_Block_Type ) || ! is_array( $block_type->block_hooks ) ) {
 899              continue;
 900          }
 901          foreach ( $block_type->block_hooks as $anchor_block_type => $relative_position ) {
 902              if ( ! isset( $hooked_blocks[ $anchor_block_type ] ) ) {
 903                  $hooked_blocks[ $anchor_block_type ] = array();
 904              }
 905              if ( ! isset( $hooked_blocks[ $anchor_block_type ][ $relative_position ] ) ) {
 906                  $hooked_blocks[ $anchor_block_type ][ $relative_position ] = array();
 907              }
 908              $hooked_blocks[ $anchor_block_type ][ $relative_position ][] = $block_type->name;
 909          }
 910      }
 911  
 912      return $hooked_blocks;
 913  }
 914  
 915  /**
 916   * Returns the markup for blocks hooked to the given anchor block in a specific relative position.
 917   *
 918   * @since 6.5.0
 919   * @access private
 920   *
 921   * @param array                           $parsed_anchor_block The anchor block, in parsed block array format.
 922   * @param string                          $relative_position   The relative position of the hooked blocks.
 923   *                                                             Can be one of 'before', 'after', 'first_child', or 'last_child'.
 924   * @param array                           $hooked_blocks       An array of hooked block types, grouped by anchor block and relative position.
 925   * @param WP_Block_Template|WP_Post|array $context             The block template, template part, or pattern that the anchor block belongs to.
 926   * @return string
 927   */
 928  function insert_hooked_blocks( &$parsed_anchor_block, $relative_position, $hooked_blocks, $context ) {
 929      $anchor_block_type  = $parsed_anchor_block['blockName'];
 930      $hooked_block_types = isset( $hooked_blocks[ $anchor_block_type ][ $relative_position ] )
 931          ? $hooked_blocks[ $anchor_block_type ][ $relative_position ]
 932          : array();
 933  
 934      /**
 935       * Filters the list of hooked block types for a given anchor block type and relative position.
 936       *
 937       * @since 6.4.0
 938       *
 939       * @param string[]                        $hooked_block_types The list of hooked block types.
 940       * @param string                          $relative_position  The relative position of the hooked blocks.
 941       *                                                            Can be one of 'before', 'after', 'first_child', or 'last_child'.
 942       * @param string                          $anchor_block_type  The anchor block type.
 943       * @param WP_Block_Template|WP_Post|array $context            The block template, template part, post object,
 944       *                                                            or pattern that the anchor block belongs to.
 945       */
 946      $hooked_block_types = apply_filters( 'hooked_block_types', $hooked_block_types, $relative_position, $anchor_block_type, $context );
 947  
 948      $markup = '';
 949      foreach ( $hooked_block_types as $hooked_block_type ) {
 950          $parsed_hooked_block = array(
 951              'blockName'    => $hooked_block_type,
 952              'attrs'        => array(),
 953              'innerBlocks'  => array(),
 954              'innerContent' => array(),
 955          );
 956  
 957          /**
 958           * Filters the parsed block array for a given hooked block.
 959           *
 960           * @since 6.5.0
 961           *
 962           * @param array|null                      $parsed_hooked_block The parsed block array for the given hooked block type, or null to suppress the block.
 963           * @param string                          $hooked_block_type   The hooked block type name.
 964           * @param string                          $relative_position   The relative position of the hooked block.
 965           * @param array                           $parsed_anchor_block The anchor block, in parsed block array format.
 966           * @param WP_Block_Template|WP_Post|array $context             The block template, template part, post object,
 967           *                                                             or pattern that the anchor block belongs to.
 968           */
 969          $parsed_hooked_block = apply_filters( 'hooked_block', $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context );
 970  
 971          /**
 972           * Filters the parsed block array for a given hooked block.
 973           *
 974           * The dynamic portion of the hook name, `$hooked_block_type`, refers to the block type name of the specific hooked block.
 975           *
 976           * @since 6.5.0
 977           *
 978           * @param array|null                      $parsed_hooked_block The parsed block array for the given hooked block type, or null to suppress the block.
 979           * @param string                          $hooked_block_type   The hooked block type name.
 980           * @param string                          $relative_position   The relative position of the hooked block.
 981           * @param array                           $parsed_anchor_block The anchor block, in parsed block array format.
 982           * @param WP_Block_Template|WP_Post|array $context             The block template, template part, post object,
 983           *                                                             or pattern that the anchor block belongs to.
 984           */
 985          $parsed_hooked_block = apply_filters( "hooked_block_{$hooked_block_type}", $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context );
 986  
 987          if ( null === $parsed_hooked_block ) {
 988              continue;
 989          }
 990  
 991          // It's possible that the filter returned a block of a different type, so we explicitly
 992          // look for the original `$hooked_block_type` in the `ignoredHookedBlocks` metadata.
 993          if (
 994              ! isset( $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] ) ||
 995              ! in_array( $hooked_block_type, $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'], true )
 996          ) {
 997              $markup .= serialize_block( $parsed_hooked_block );
 998          }
 999      }
1000  
1001      return $markup;
1002  }
1003  
1004  /**
1005   * Adds a list of hooked block types to an anchor block's ignored hooked block types.
1006   *
1007   * This function is meant for internal use only.
1008   *
1009   * @since 6.5.0
1010   * @access private
1011   *
1012   * @param array                           $parsed_anchor_block The anchor block, in parsed block array format.
1013   * @param string                          $relative_position   The relative position of the hooked blocks.
1014   *                                                             Can be one of 'before', 'after', 'first_child', or 'last_child'.
1015   * @param array                           $hooked_blocks       An array of hooked block types, grouped by anchor block and relative position.
1016   * @param WP_Block_Template|WP_Post|array $context             The block template, template part, or pattern that the anchor block belongs to.
1017   * @return string Empty string.
1018   */
1019  function set_ignored_hooked_blocks_metadata( &$parsed_anchor_block, $relative_position, $hooked_blocks, $context ) {
1020      $anchor_block_type  = $parsed_anchor_block['blockName'];
1021      $hooked_block_types = isset( $hooked_blocks[ $anchor_block_type ][ $relative_position ] )
1022          ? $hooked_blocks[ $anchor_block_type ][ $relative_position ]
1023          : array();
1024  
1025      /** This filter is documented in wp-includes/blocks.php */
1026      $hooked_block_types = apply_filters( 'hooked_block_types', $hooked_block_types, $relative_position, $anchor_block_type, $context );
1027      if ( empty( $hooked_block_types ) ) {
1028          return '';
1029      }
1030  
1031      foreach ( $hooked_block_types as $index => $hooked_block_type ) {
1032          $parsed_hooked_block = array(
1033              'blockName'    => $hooked_block_type,
1034              'attrs'        => array(),
1035              'innerBlocks'  => array(),
1036              'innerContent' => array(),
1037          );
1038  
1039          /** This filter is documented in wp-includes/blocks.php */
1040          $parsed_hooked_block = apply_filters( 'hooked_block', $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context );
1041  
1042          /** This filter is documented in wp-includes/blocks.php */
1043          $parsed_hooked_block = apply_filters( "hooked_block_{$hooked_block_type}", $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context );
1044  
1045          if ( null === $parsed_hooked_block ) {
1046              unset( $hooked_block_types[ $index ] );
1047          }
1048      }
1049  
1050      $previously_ignored_hooked_blocks = isset( $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] )
1051          ? $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks']
1052          : array();
1053  
1054      $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] = array_unique(
1055          array_merge(
1056              $previously_ignored_hooked_blocks,
1057              $hooked_block_types
1058          )
1059      );
1060  
1061      // Markup for the hooked blocks has already been created (in `insert_hooked_blocks`).
1062      return '';
1063  }
1064  
1065  /**
1066   * Runs the hooked blocks algorithm on the given content.
1067   *
1068   * @since 6.6.0
1069   * @since 6.7.0 Injects the `theme` attribute into Template Part blocks, even if no hooked blocks are registered.
1070   * @since 6.8.0 Have the `$context` parameter default to `null`, in which case `get_post()` will be called to use the current post as context.
1071   * @access private
1072   *
1073   * @param string                               $content  Serialized content.
1074   * @param WP_Block_Template|WP_Post|array|null $context  A block template, template part, post object, or pattern
1075   *                                                       that the blocks belong to. If set to `null`, `get_post()`
1076   *                                                       will be called to use the current post as context.
1077   *                                                       Default: `null`.
1078   * @param callable                             $callback A function that will be called for each block to generate
1079   *                                                       the markup for a given list of blocks that are hooked to it.
1080   *                                                       Default: 'insert_hooked_blocks'.
1081   * @return string The serialized markup.
1082   */
1083  function apply_block_hooks_to_content( $content, $context = null, $callback = 'insert_hooked_blocks' ) {
1084      // Default to the current post if no context is provided.
1085      if ( null === $context ) {
1086          $context = get_post();
1087      }
1088  
1089      $hooked_blocks = get_hooked_blocks();
1090  
1091      $before_block_visitor = '_inject_theme_attribute_in_template_part_block';
1092      $after_block_visitor  = null;
1093      if ( ! empty( $hooked_blocks ) || has_filter( 'hooked_block_types' ) ) {
1094          $before_block_visitor = make_before_block_visitor( $hooked_blocks, $context, $callback );
1095          $after_block_visitor  = make_after_block_visitor( $hooked_blocks, $context, $callback );
1096      }
1097  
1098      $block_allows_multiple_instances = array();
1099      /*
1100       * Remove hooked blocks from `$hooked_block_types` if they have `multiple` set to false and
1101       * are already present in `$content`.
1102       */
1103      foreach ( $hooked_blocks as $anchor_block_type => $relative_positions ) {
1104          foreach ( $relative_positions as $relative_position => $hooked_block_types ) {
1105              foreach ( $hooked_block_types as $index => $hooked_block_type ) {
1106                  $hooked_block_type_definition =
1107                      WP_Block_Type_Registry::get_instance()->get_registered( $hooked_block_type );
1108  
1109                  $block_allows_multiple_instances[ $hooked_block_type ] =
1110                      block_has_support( $hooked_block_type_definition, 'multiple', true );
1111  
1112                  if (
1113                      ! $block_allows_multiple_instances[ $hooked_block_type ] &&
1114                      has_block( $hooked_block_type, $content )
1115                  ) {
1116                      unset( $hooked_blocks[ $anchor_block_type ][ $relative_position ][ $index ] );
1117                  }
1118              }
1119              if ( empty( $hooked_blocks[ $anchor_block_type ][ $relative_position ] ) ) {
1120                  unset( $hooked_blocks[ $anchor_block_type ][ $relative_position ] );
1121              }
1122          }
1123          if ( empty( $hooked_blocks[ $anchor_block_type ] ) ) {
1124              unset( $hooked_blocks[ $anchor_block_type ] );
1125          }
1126      }
1127  
1128      /*
1129       * We also need to cover the case where the hooked block is not present in
1130       * `$content` at first and we're allowed to insert it once -- but not again.
1131       */
1132      $suppress_single_instance_blocks = static function ( $hooked_block_types ) use ( &$block_allows_multiple_instances, $content ) {
1133          static $single_instance_blocks_present_in_content = array();
1134          foreach ( $hooked_block_types as $index => $hooked_block_type ) {
1135              if ( ! isset( $block_allows_multiple_instances[ $hooked_block_type ] ) ) {
1136                  $hooked_block_type_definition =
1137                      WP_Block_Type_Registry::get_instance()->get_registered( $hooked_block_type );
1138  
1139                  $block_allows_multiple_instances[ $hooked_block_type ] =
1140                      block_has_support( $hooked_block_type_definition, 'multiple', true );
1141              }
1142  
1143              if ( $block_allows_multiple_instances[ $hooked_block_type ] ) {
1144                  continue;
1145              }
1146  
1147              // The block doesn't allow multiple instances, so we need to check if it's already present.
1148              if (
1149                  in_array( $hooked_block_type, $single_instance_blocks_present_in_content, true ) ||
1150                  has_block( $hooked_block_type, $content )
1151              ) {
1152                  unset( $hooked_block_types[ $index ] );
1153              } else {
1154                  // We can insert the block once, but need to remember not to insert it again.
1155                  $single_instance_blocks_present_in_content[] = $hooked_block_type;
1156              }
1157          }
1158          return $hooked_block_types;
1159      };
1160      add_filter( 'hooked_block_types', $suppress_single_instance_blocks, PHP_INT_MAX );
1161      $content = traverse_and_serialize_blocks(
1162          parse_blocks( $content ),
1163          $before_block_visitor,
1164          $after_block_visitor
1165      );
1166      remove_filter( 'hooked_block_types', $suppress_single_instance_blocks, PHP_INT_MAX );
1167  
1168      return $content;
1169  }
1170  
1171  /**
1172   * Run the Block Hooks algorithm on a post object's content.
1173   *
1174   * This function is different from `apply_block_hooks_to_content` in that
1175   * it takes ignored hooked block information from the post's metadata into
1176   * account. This ensures that any blocks hooked as first or last child
1177   * of the block that corresponds to the post type are handled correctly.
1178   *
1179   * @since 6.8.0
1180   * @access private
1181   *
1182   * @param string       $content  Serialized content.
1183   * @param WP_Post|null $post     A post object that the content belongs to. If set to `null`,
1184   *                               `get_post()` will be called to use the current post as context.
1185   *                               Default: `null`.
1186   * @param callable     $callback A function that will be called for each block to generate
1187   *                               the markup for a given list of blocks that are hooked to it.
1188   *                               Default: 'insert_hooked_blocks'.
1189   * @return string The serialized markup.
1190   */
1191  function apply_block_hooks_to_content_from_post_object( $content, $post = null, $callback = 'insert_hooked_blocks' ) {
1192      // Default to the current post if no context is provided.
1193      if ( null === $post ) {
1194          $post = get_post();
1195      }
1196  
1197      if ( ! $post instanceof WP_Post ) {
1198          return apply_block_hooks_to_content( $content, $post, $callback );
1199      }
1200  
1201      /*
1202       * If the content was created using the classic editor or using a single Classic block
1203       * (`core/freeform`), it might not contain any block markup at all.
1204       * However, we still might need to inject hooked blocks in the first child or last child
1205       * positions of the parent block. To be able to apply the Block Hooks algorithm, we wrap
1206       * the content in a `core/freeform` wrapper block.
1207       */
1208      if ( ! has_blocks( $content ) ) {
1209          $original_content = $content;
1210  
1211          $content_wrapped_in_classic_block = get_comment_delimited_block_content(
1212              'core/freeform',
1213              array(),
1214              $content
1215          );
1216  
1217          $content = $content_wrapped_in_classic_block;
1218      }
1219  
1220      $attributes = array();
1221  
1222      // If context is a post object, `ignoredHookedBlocks` information is stored in its post meta.
1223      $ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true );
1224      if ( ! empty( $ignored_hooked_blocks ) ) {
1225          $ignored_hooked_blocks  = json_decode( $ignored_hooked_blocks, true );
1226          $attributes['metadata'] = array(
1227              'ignoredHookedBlocks' => $ignored_hooked_blocks,
1228          );
1229      }
1230  
1231      /*
1232       * We need to wrap the content in a temporary wrapper block with that metadata
1233       * so the Block Hooks algorithm can insert blocks that are hooked as first or last child
1234       * of the wrapper block.
1235       * To that end, we need to determine the wrapper block type based on the post type.
1236       */
1237      if ( 'wp_navigation' === $post->post_type ) {
1238          $wrapper_block_type = 'core/navigation';
1239      } elseif ( 'wp_block' === $post->post_type ) {
1240          $wrapper_block_type = 'core/block';
1241      } else {
1242          $wrapper_block_type = 'core/post-content';
1243      }
1244  
1245      $content = get_comment_delimited_block_content(
1246          $wrapper_block_type,
1247          $attributes,
1248          $content
1249      );
1250  
1251      /*
1252       * We need to avoid inserting any blocks hooked into the `before` and `after` positions
1253       * of the temporary wrapper block that we create to wrap the content.
1254       * See https://core.trac.wordpress.org/ticket/63287 for more details.
1255       */
1256      $suppress_blocks_from_insertion_before_and_after_wrapper_block = static function ( $hooked_block_types, $relative_position, $anchor_block_type ) use ( $wrapper_block_type ) {
1257          if (
1258              $wrapper_block_type === $anchor_block_type &&
1259              in_array( $relative_position, array( 'before', 'after' ), true )
1260          ) {
1261              return array();
1262          }
1263          return $hooked_block_types;
1264      };
1265  
1266      // Apply Block Hooks.
1267      add_filter( 'hooked_block_types', $suppress_blocks_from_insertion_before_and_after_wrapper_block, PHP_INT_MAX, 3 );
1268      $content = apply_block_hooks_to_content( $content, $post, $callback );
1269      remove_filter( 'hooked_block_types', $suppress_blocks_from_insertion_before_and_after_wrapper_block, PHP_INT_MAX );
1270  
1271      // Finally, we need to remove the temporary wrapper block.
1272      $content = remove_serialized_parent_block( $content );
1273  
1274      // If we wrapped the content in a `core/freeform` block, we also need to remove that.
1275      if ( ! empty( $content_wrapped_in_classic_block ) ) {
1276          /*
1277           * We cannot simply use remove_serialized_parent_block() here,
1278           * as that function assumes that the block wrapper is at the top level.
1279           * However, there might now be a hooked block inserted next to it
1280           * (as first or last child of the parent).
1281           */
1282          $content = str_replace( $content_wrapped_in_classic_block, $original_content, $content );
1283      }
1284  
1285      return $content;
1286  }
1287  
1288  /**
1289   * Accepts the serialized markup of a block and its inner blocks, and returns serialized markup of the inner blocks.
1290   *
1291   * @since 6.6.0
1292   * @access private
1293   *
1294   * @param string $serialized_block The serialized markup of a block and its inner blocks.
1295   * @return string The serialized markup of the inner blocks.
1296   */
1297  function remove_serialized_parent_block( $serialized_block ) {
1298      $start = strpos( $serialized_block, '-->' ) + strlen( '-->' );
1299      $end   = strrpos( $serialized_block, '<!--' );
1300      return substr( $serialized_block, $start, $end - $start );
1301  }
1302  
1303  /**
1304   * Accepts the serialized markup of a block and its inner blocks, and returns serialized markup of the wrapper block.
1305   *
1306   * @since 6.7.0
1307   * @access private
1308   *
1309   * @see remove_serialized_parent_block()
1310   *
1311   * @param string $serialized_block The serialized markup of a block and its inner blocks.
1312   * @return string The serialized markup of the wrapper block.
1313   */
1314  function extract_serialized_parent_block( $serialized_block ) {
1315      $start = strpos( $serialized_block, '-->' ) + strlen( '-->' );
1316      $end   = strrpos( $serialized_block, '<!--' );
1317      return substr( $serialized_block, 0, $start ) . substr( $serialized_block, $end );
1318  }
1319  
1320  /**
1321   * Updates the wp_postmeta with the list of ignored hooked blocks
1322   * where the inner blocks are stored as post content.
1323   *
1324   * @since 6.6.0
1325   * @since 6.8.0 Support non-`wp_navigation` post types.
1326   * @access private
1327   *
1328   * @param stdClass $post Post object.
1329   * @return stdClass The updated post object.
1330   */
1331  function update_ignored_hooked_blocks_postmeta( $post ) {
1332      /*
1333       * In this scenario the user has likely tried to create a new post object via the REST API.
1334       * In which case we won't have a post ID to work with and store meta against.
1335       */
1336      if ( empty( $post->ID ) ) {
1337          return $post;
1338      }
1339  
1340      /*
1341       * Skip meta generation when consumers intentionally update specific fields
1342       * and omit the content update.
1343       */
1344      if ( ! isset( $post->post_content ) ) {
1345          return $post;
1346      }
1347  
1348      /*
1349       * Skip meta generation if post type is not set.
1350       */
1351      if ( ! isset( $post->post_type ) ) {
1352          return $post;
1353      }
1354  
1355      $attributes = array();
1356  
1357      $ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true );
1358      if ( ! empty( $ignored_hooked_blocks ) ) {
1359          $ignored_hooked_blocks  = json_decode( $ignored_hooked_blocks, true );
1360          $attributes['metadata'] = array(
1361              'ignoredHookedBlocks' => $ignored_hooked_blocks,
1362          );
1363      }
1364  
1365      if ( 'wp_navigation' === $post->post_type ) {
1366          $wrapper_block_type = 'core/navigation';
1367      } elseif ( 'wp_block' === $post->post_type ) {
1368          $wrapper_block_type = 'core/block';
1369      } else {
1370          $wrapper_block_type = 'core/post-content';
1371      }
1372  
1373      $markup = get_comment_delimited_block_content(
1374          $wrapper_block_type,
1375          $attributes,
1376          $post->post_content
1377      );
1378  
1379      $existing_post = get_post( $post->ID );
1380      // Merge the existing post object with the updated post object to pass to the block hooks algorithm for context.
1381      $context          = (object) array_merge( (array) $existing_post, (array) $post );
1382      $context          = new WP_Post( $context ); // Convert to WP_Post object.
1383      $serialized_block = apply_block_hooks_to_content( $markup, $context, 'set_ignored_hooked_blocks_metadata' );
1384      $root_block       = parse_blocks( $serialized_block )[0];
1385  
1386      $ignored_hooked_blocks = isset( $root_block['attrs']['metadata']['ignoredHookedBlocks'] )
1387          ? $root_block['attrs']['metadata']['ignoredHookedBlocks']
1388          : array();
1389  
1390      if ( ! empty( $ignored_hooked_blocks ) ) {
1391          $existing_ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true );
1392          if ( ! empty( $existing_ignored_hooked_blocks ) ) {
1393              $existing_ignored_hooked_blocks = json_decode( $existing_ignored_hooked_blocks, true );
1394              $ignored_hooked_blocks          = array_unique( array_merge( $ignored_hooked_blocks, $existing_ignored_hooked_blocks ) );
1395          }
1396  
1397          if ( ! isset( $post->meta_input ) ) {
1398              $post->meta_input = array();
1399          }
1400          $post->meta_input['_wp_ignored_hooked_blocks'] = json_encode( $ignored_hooked_blocks );
1401      }
1402  
1403      $post->post_content = remove_serialized_parent_block( $serialized_block );
1404      return $post;
1405  }
1406  
1407  /**
1408   * Returns the markup for blocks hooked to the given anchor block in a specific relative position and then
1409   * adds a list of hooked block types to an anchor block's ignored hooked block types.
1410   *
1411   * This function is meant for internal use only.
1412   *
1413   * @since 6.6.0
1414   * @access private
1415   *
1416   * @param array                           $parsed_anchor_block The anchor block, in parsed block array format.
1417   * @param string                          $relative_position   The relative position of the hooked blocks.
1418   *                                                             Can be one of 'before', 'after', 'first_child', or 'last_child'.
1419   * @param array                           $hooked_blocks       An array of hooked block types, grouped by anchor block and relative position.
1420   * @param WP_Block_Template|WP_Post|array $context             The block template, template part, or pattern that the anchor block belongs to.
1421   * @return string
1422   */
1423  function insert_hooked_blocks_and_set_ignored_hooked_blocks_metadata( &$parsed_anchor_block, $relative_position, $hooked_blocks, $context ) {
1424      $markup  = insert_hooked_blocks( $parsed_anchor_block, $relative_position, $hooked_blocks, $context );
1425      $markup .= set_ignored_hooked_blocks_metadata( $parsed_anchor_block, $relative_position, $hooked_blocks, $context );
1426  
1427      return $markup;
1428  }
1429  
1430  /**
1431   * Hooks into the REST API response for the Posts endpoint and adds the first and last inner blocks.
1432   *
1433   * @since 6.6.0
1434   * @since 6.8.0 Support non-`wp_navigation` post types.
1435   *
1436   * @param WP_REST_Response $response The response object.
1437   * @param WP_Post          $post     Post object.
1438   * @return WP_REST_Response The response object.
1439   */
1440  function insert_hooked_blocks_into_rest_response( $response, $post ) {
1441      if ( empty( $response->data['content']['raw'] ) ) {
1442          return $response;
1443      }
1444  
1445      $response->data['content']['raw'] = apply_block_hooks_to_content_from_post_object(
1446          $response->data['content']['raw'],
1447          $post,
1448          'insert_hooked_blocks_and_set_ignored_hooked_blocks_metadata'
1449      );
1450  
1451      // If the rendered content was previously empty, we leave it like that.
1452      if ( empty( $response->data['content']['rendered'] ) ) {
1453          return $response;
1454      }
1455  
1456      // `apply_block_hooks_to_content` is called above. Ensure it is not called again as a filter.
1457      $priority = has_filter( 'the_content', 'apply_block_hooks_to_content_from_post_object' );
1458      if ( false !== $priority ) {
1459          remove_filter( 'the_content', 'apply_block_hooks_to_content_from_post_object', $priority );
1460      }
1461  
1462      /** This filter is documented in wp-includes/post-template.php */
1463      $response->data['content']['rendered'] = apply_filters(
1464          'the_content',
1465          $response->data['content']['raw']
1466      );
1467  
1468      // Restore the filter if it was set initially.
1469      if ( false !== $priority ) {
1470          add_filter( 'the_content', 'apply_block_hooks_to_content_from_post_object', $priority );
1471      }
1472  
1473      return $response;
1474  }
1475  
1476  /**
1477   * Returns a function that injects the theme attribute into, and hooked blocks before, a given block.
1478   *
1479   * The returned function can be used as `$pre_callback` argument to `traverse_and_serialize_block(s)`,
1480   * where it will inject the `theme` attribute into all Template Part blocks, and prepend the markup for
1481   * any blocks hooked `before` the given block and as its parent's `first_child`, respectively.
1482   *
1483   * This function is meant for internal use only.
1484   *
1485   * @since 6.4.0
1486   * @since 6.5.0 Added $callback argument.
1487   * @access private
1488   *
1489   * @param array                           $hooked_blocks An array of blocks hooked to another given block.
1490   * @param WP_Block_Template|WP_Post|array $context       A block template, template part, post object,
1491   *                                                       or pattern that the blocks belong to.
1492   * @param callable                        $callback      A function that will be called for each block to generate
1493   *                                                       the markup for a given list of blocks that are hooked to it.
1494   *                                                       Default: 'insert_hooked_blocks'.
1495   * @return callable A function that returns the serialized markup for the given block,
1496   *                  including the markup for any hooked blocks before it.
1497   */
1498  function make_before_block_visitor( $hooked_blocks, $context, $callback = 'insert_hooked_blocks' ) {
1499      /**
1500       * Injects hooked blocks before the given block, injects the `theme` attribute into Template Part blocks, and returns the serialized markup.
1501       *
1502       * If the current block is a Template Part block, inject the `theme` attribute.
1503       * Furthermore, prepend the markup for any blocks hooked `before` the given block and as its parent's
1504       * `first_child`, respectively, to the serialized markup for the given block.
1505       *
1506       * @param array $block        The block to inject the theme attribute into, and hooked blocks before. Passed by reference.
1507       * @param array $parent_block The parent block of the given block. Passed by reference. Default null.
1508       * @param array $prev         The previous sibling block of the given block. Default null.
1509       * @return string The serialized markup for the given block, with the markup for any hooked blocks prepended to it.
1510       */
1511      return function ( &$block, &$parent_block = null, $prev = null ) use ( $hooked_blocks, $context, $callback ) {
1512          _inject_theme_attribute_in_template_part_block( $block );
1513  
1514          $markup = '';
1515  
1516          if ( $parent_block && ! $prev ) {
1517              // Candidate for first-child insertion.
1518              $markup .= call_user_func_array(
1519                  $callback,
1520                  array( &$parent_block, 'first_child', $hooked_blocks, $context )
1521              );
1522          }
1523  
1524          $markup .= call_user_func_array(
1525              $callback,
1526              array( &$block, 'before', $hooked_blocks, $context )
1527          );
1528  
1529          return $markup;
1530      };
1531  }
1532  
1533  /**
1534   * Returns a function that injects the hooked blocks after a given block.
1535   *
1536   * The returned function can be used as `$post_callback` argument to `traverse_and_serialize_block(s)`,
1537   * where it will append the markup for any blocks hooked `after` the given block and as its parent's
1538   * `last_child`, respectively.
1539   *
1540   * This function is meant for internal use only.
1541   *
1542   * @since 6.4.0
1543   * @since 6.5.0 Added $callback argument.
1544   * @access private
1545   *
1546   * @param array                           $hooked_blocks An array of blocks hooked to another block.
1547   * @param WP_Block_Template|WP_Post|array $context       A block template, template part, post object,
1548   *                                                       or pattern that the blocks belong to.
1549   * @param callable                        $callback      A function that will be called for each block to generate
1550   *                                                       the markup for a given list of blocks that are hooked to it.
1551   *                                                       Default: 'insert_hooked_blocks'.
1552   * @return callable A function that returns the serialized markup for the given block,
1553   *                  including the markup for any hooked blocks after it.
1554   */
1555  function make_after_block_visitor( $hooked_blocks, $context, $callback = 'insert_hooked_blocks' ) {
1556      /**
1557       * Injects hooked blocks after the given block, and returns the serialized markup.
1558       *
1559       * Append the markup for any blocks hooked `after` the given block and as its parent's
1560       * `last_child`, respectively, to the serialized markup for the given block.
1561       *
1562       * @param array $block        The block to inject the hooked blocks after. Passed by reference.
1563       * @param array $parent_block The parent block of the given block. Passed by reference. Default null.
1564       * @param array $next         The next sibling block of the given block. Default null.
1565       * @return string The serialized markup for the given block, with the markup for any hooked blocks appended to it.
1566       */
1567      return function ( &$block, &$parent_block = null, $next = null ) use ( $hooked_blocks, $context, $callback ) {
1568          $markup = call_user_func_array(
1569              $callback,
1570              array( &$block, 'after', $hooked_blocks, $context )
1571          );
1572  
1573          if ( $parent_block && ! $next ) {
1574              // Candidate for last-child insertion.
1575              $markup .= call_user_func_array(
1576                  $callback,
1577                  array( &$parent_block, 'last_child', $hooked_blocks, $context )
1578              );
1579          }
1580  
1581          return $markup;
1582      };
1583  }
1584  
1585  /**
1586   * Given an array of attributes, returns a string in the serialized attributes
1587   * format prepared for post content.
1588   *
1589   * The serialized result is a JSON-encoded string, with unicode escape sequence
1590   * substitution for characters which might otherwise interfere with embedding
1591   * the result in an HTML comment.
1592   *
1593   * This function must produce output that remains in sync with the output of
1594   * the serializeAttributes JavaScript function in the block editor in order
1595   * to ensure consistent operation between PHP and JavaScript.
1596   *
1597   * @since 5.3.1
1598   *
1599   * @param array $block_attributes Attributes object.
1600   * @return string Serialized attributes.
1601   */
1602  function serialize_block_attributes( $block_attributes ) {
1603      $encoded_attributes = wp_json_encode( $block_attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
1604      $encoded_attributes = preg_replace( '/--/', '\\u002d\\u002d', $encoded_attributes );
1605      $encoded_attributes = preg_replace( '/</', '\\u003c', $encoded_attributes );
1606      $encoded_attributes = preg_replace( '/>/', '\\u003e', $encoded_attributes );
1607      $encoded_attributes = preg_replace( '/&/', '\\u0026', $encoded_attributes );
1608      // Regex: /\\"/
1609      $encoded_attributes = preg_replace( '/\\\\"/', '\\u0022', $encoded_attributes );
1610  
1611      return $encoded_attributes;
1612  }
1613  
1614  /**
1615   * Returns the block name to use for serialization. This will remove the default
1616   * "core/" namespace from a block name.
1617   *
1618   * @since 5.3.1
1619   *
1620   * @param string|null $block_name Optional. Original block name. Null if the block name is unknown,
1621   *                                e.g. Classic blocks have their name set to null. Default null.
1622   * @return string Block name to use for serialization.
1623   */
1624  function strip_core_block_namespace( $block_name = null ) {
1625      if ( is_string( $block_name ) && str_starts_with( $block_name, 'core/' ) ) {
1626          return substr( $block_name, 5 );
1627      }
1628  
1629      return $block_name;
1630  }
1631  
1632  /**
1633   * Returns the content of a block, including comment delimiters.
1634   *
1635   * @since 5.3.1
1636   *
1637   * @param string|null $block_name       Block name. Null if the block name is unknown,
1638   *                                      e.g. Classic blocks have their name set to null.
1639   * @param array       $block_attributes Block attributes.
1640   * @param string      $block_content    Block save content.
1641   * @return string Comment-delimited block content.
1642   */
1643  function get_comment_delimited_block_content( $block_name, $block_attributes, $block_content ) {
1644      if ( is_null( $block_name ) ) {
1645          return $block_content;
1646      }
1647  
1648      $serialized_block_name = strip_core_block_namespace( $block_name );
1649      $serialized_attributes = empty( $block_attributes ) ? '' : serialize_block_attributes( $block_attributes ) . ' ';
1650  
1651      if ( empty( $block_content ) ) {
1652          return sprintf( '<!-- wp:%s %s/-->', $serialized_block_name, $serialized_attributes );
1653      }
1654  
1655      return sprintf(
1656          '<!-- wp:%s %s-->%s<!-- /wp:%s -->',
1657          $serialized_block_name,
1658          $serialized_attributes,
1659          $block_content,
1660          $serialized_block_name
1661      );
1662  }
1663  
1664  /**
1665   * Returns the content of a block, including comment delimiters, serializing all
1666   * attributes from the given parsed block.
1667   *
1668   * This should be used when preparing a block to be saved to post content.
1669   * Prefer `render_block` when preparing a block for display. Unlike
1670   * `render_block`, this does not evaluate a block's `render_callback`, and will
1671   * instead preserve the markup as parsed.
1672   *
1673   * @since 5.3.1
1674   *
1675   * @param array $block {
1676   *     An associative array of a single parsed block object. See WP_Block_Parser_Block.
1677   *
1678   *     @type string   $blockName    Name of block.
1679   *     @type array    $attrs        Attributes from block comment delimiters.
1680   *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
1681   *                                  have the same structure as this one.
1682   *     @type string   $innerHTML    HTML from inside block comment delimiters.
1683   *     @type array    $innerContent List of string fragments and null markers where
1684   *                                  inner blocks were found.
1685   * }
1686   * @return string String of rendered HTML.
1687   */
1688  function serialize_block( $block ) {
1689      $block_content = '';
1690  
1691      $index = 0;
1692      foreach ( $block['innerContent'] as $chunk ) {
1693          $block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ] );
1694      }
1695  
1696      if ( ! is_array( $block['attrs'] ) ) {
1697          $block['attrs'] = array();
1698      }
1699  
1700      return get_comment_delimited_block_content(
1701          $block['blockName'],
1702          $block['attrs'],
1703          $block_content
1704      );
1705  }
1706  
1707  /**
1708   * Returns a joined string of the aggregate serialization of the given
1709   * parsed blocks.
1710   *
1711   * @since 5.3.1
1712   *
1713   * @param array[] $blocks {
1714   *     Array of block structures.
1715   *
1716   *     @type array ...$0 {
1717   *         An associative array of a single parsed block object. See WP_Block_Parser_Block.
1718   *
1719   *         @type string   $blockName    Name of block.
1720   *         @type array    $attrs        Attributes from block comment delimiters.
1721   *         @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
1722   *                                      have the same structure as this one.
1723   *         @type string   $innerHTML    HTML from inside block comment delimiters.
1724   *         @type array    $innerContent List of string fragments and null markers where
1725   *                                      inner blocks were found.
1726   *     }
1727   * }
1728   * @return string String of rendered HTML.
1729   */
1730  function serialize_blocks( $blocks ) {
1731      return implode( '', array_map( 'serialize_block', $blocks ) );
1732  }
1733  
1734  /**
1735   * Traverses a parsed block tree and applies callbacks before and after serializing it.
1736   *
1737   * Recursively traverses the block and its inner blocks and applies the two callbacks provided as
1738   * arguments, the first one before serializing the block, and the second one after serializing it.
1739   * If either callback returns a string value, it will be prepended and appended to the serialized
1740   * block markup, respectively.
1741   *
1742   * The callbacks will receive a reference to the current block as their first argument, so that they
1743   * can also modify it, and the current block's parent block as second argument. Finally, the
1744   * `$pre_callback` receives the previous block, whereas the `$post_callback` receives
1745   * the next block as third argument.
1746   *
1747   * Serialized blocks are returned including comment delimiters, and with all attributes serialized.
1748   *
1749   * This function should be used when there is a need to modify the saved block, or to inject markup
1750   * into the return value. Prefer `serialize_block` when preparing a block to be saved to post content.
1751   *
1752   * This function is meant for internal use only.
1753   *
1754   * @since 6.4.0
1755   * @access private
1756   *
1757   * @see serialize_block()
1758   *
1759   * @param array    $block         An associative array of a single parsed block object. See WP_Block_Parser_Block.
1760   * @param callable $pre_callback  Callback to run on each block in the tree before it is traversed and serialized.
1761   *                                It is called with the following arguments: &$block, $parent_block, $previous_block.
1762   *                                Its string return value will be prepended to the serialized block markup.
1763   * @param callable $post_callback Callback to run on each block in the tree after it is traversed and serialized.
1764   *                                It is called with the following arguments: &$block, $parent_block, $next_block.
1765   *                                Its string return value will be appended to the serialized block markup.
1766   * @return string Serialized block markup.
1767   */
1768  function traverse_and_serialize_block( $block, $pre_callback = null, $post_callback = null ) {
1769      $block_content = '';
1770      $block_index   = 0;
1771  
1772      foreach ( $block['innerContent'] as $chunk ) {
1773          if ( is_string( $chunk ) ) {
1774              $block_content .= $chunk;
1775          } else {
1776              $inner_block = $block['innerBlocks'][ $block_index ];
1777  
1778              if ( is_callable( $pre_callback ) ) {
1779                  $prev = 0 === $block_index
1780                      ? null
1781                      : $block['innerBlocks'][ $block_index - 1 ];
1782  
1783                  $block_content .= call_user_func_array(
1784                      $pre_callback,
1785                      array( &$inner_block, &$block, $prev )
1786                  );
1787              }
1788  
1789              if ( is_callable( $post_callback ) ) {
1790                  $next = count( $block['innerBlocks'] ) - 1 === $block_index
1791                      ? null
1792                      : $block['innerBlocks'][ $block_index + 1 ];
1793  
1794                  $post_markup = call_user_func_array(
1795                      $post_callback,
1796                      array( &$inner_block, &$block, $next )
1797                  );
1798              }
1799  
1800              $block_content .= traverse_and_serialize_block( $inner_block, $pre_callback, $post_callback );
1801              $block_content .= isset( $post_markup ) ? $post_markup : '';
1802  
1803              ++$block_index;
1804          }
1805      }
1806  
1807      if ( ! is_array( $block['attrs'] ) ) {
1808          $block['attrs'] = array();
1809      }
1810  
1811      return get_comment_delimited_block_content(
1812          $block['blockName'],
1813          $block['attrs'],
1814          $block_content
1815      );
1816  }
1817  
1818  /**
1819   * Replaces patterns in a block tree with their content.
1820   *
1821   * @since 6.6.0
1822   *
1823   * @param array $blocks An array blocks.
1824   *
1825   * @return array An array of blocks with patterns replaced by their content.
1826   */
1827  function resolve_pattern_blocks( $blocks ) {
1828      static $inner_content;
1829      // Keep track of seen references to avoid infinite loops.
1830      static $seen_refs = array();
1831      $i                = 0;
1832      while ( $i < count( $blocks ) ) {
1833          if ( 'core/pattern' === $blocks[ $i ]['blockName'] ) {
1834              $attrs = $blocks[ $i ]['attrs'];
1835  
1836              if ( empty( $attrs['slug'] ) ) {
1837                  ++$i;
1838                  continue;
1839              }
1840  
1841              $slug = $attrs['slug'];
1842  
1843              if ( isset( $seen_refs[ $slug ] ) ) {
1844                  // Skip recursive patterns.
1845                  array_splice( $blocks, $i, 1 );
1846                  continue;
1847              }
1848  
1849              $registry = WP_Block_Patterns_Registry::get_instance();
1850              $pattern  = $registry->get_registered( $slug );
1851  
1852              // Skip unknown patterns.
1853              if ( ! $pattern ) {
1854                  ++$i;
1855                  continue;
1856              }
1857  
1858              $blocks_to_insert   = parse_blocks( $pattern['content'] );
1859              $seen_refs[ $slug ] = true;
1860              $prev_inner_content = $inner_content;
1861              $inner_content      = null;
1862              $blocks_to_insert   = resolve_pattern_blocks( $blocks_to_insert );
1863              $inner_content      = $prev_inner_content;
1864              unset( $seen_refs[ $slug ] );
1865              array_splice( $blocks, $i, 1, $blocks_to_insert );
1866  
1867              // If we have inner content, we need to insert nulls in the
1868              // inner content array, otherwise serialize_blocks will skip
1869              // blocks.
1870              if ( $inner_content ) {
1871                  $null_indices  = array_keys( $inner_content, null, true );
1872                  $content_index = $null_indices[ $i ];
1873                  $nulls         = array_fill( 0, count( $blocks_to_insert ), null );
1874                  array_splice( $inner_content, $content_index, 1, $nulls );
1875              }
1876  
1877              // Skip inserted blocks.
1878              $i += count( $blocks_to_insert );
1879          } else {
1880              if ( ! empty( $blocks[ $i ]['innerBlocks'] ) ) {
1881                  $prev_inner_content           = $inner_content;
1882                  $inner_content                = $blocks[ $i ]['innerContent'];
1883                  $blocks[ $i ]['innerBlocks']  = resolve_pattern_blocks(
1884                      $blocks[ $i ]['innerBlocks']
1885                  );
1886                  $blocks[ $i ]['innerContent'] = $inner_content;
1887                  $inner_content                = $prev_inner_content;
1888              }
1889              ++$i;
1890          }
1891      }
1892      return $blocks;
1893  }
1894  
1895  /**
1896   * Given an array of parsed block trees, applies callbacks before and after serializing them and
1897   * returns their concatenated output.
1898   *
1899   * Recursively traverses the blocks and their inner blocks and applies the two callbacks provided as
1900   * arguments, the first one before serializing a block, and the second one after serializing.
1901   * If either callback returns a string value, it will be prepended and appended to the serialized
1902   * block markup, respectively.
1903   *
1904   * The callbacks will receive a reference to the current block as their first argument, so that they
1905   * can also modify it, and the current block's parent block as second argument. Finally, the
1906   * `$pre_callback` receives the previous block, whereas the `$post_callback` receives
1907   * the next block as third argument.
1908   *
1909   * Serialized blocks are returned including comment delimiters, and with all attributes serialized.
1910   *
1911   * This function should be used when there is a need to modify the saved blocks, or to inject markup
1912   * into the return value. Prefer `serialize_blocks` when preparing blocks to be saved to post content.
1913   *
1914   * This function is meant for internal use only.
1915   *
1916   * @since 6.4.0
1917   * @access private
1918   *
1919   * @see serialize_blocks()
1920   *
1921   * @param array[]  $blocks        An array of parsed blocks. See WP_Block_Parser_Block.
1922   * @param callable $pre_callback  Callback to run on each block in the tree before it is traversed and serialized.
1923   *                                It is called with the following arguments: &$block, $parent_block, $previous_block.
1924   *                                Its string return value will be prepended to the serialized block markup.
1925   * @param callable $post_callback Callback to run on each block in the tree after it is traversed and serialized.
1926   *                                It is called with the following arguments: &$block, $parent_block, $next_block.
1927   *                                Its string return value will be appended to the serialized block markup.
1928   * @return string Serialized block markup.
1929   */
1930  function traverse_and_serialize_blocks( $blocks, $pre_callback = null, $post_callback = null ) {
1931      $result       = '';
1932      $parent_block = null; // At the top level, there is no parent block to pass to the callbacks; yet the callbacks expect a reference.
1933  
1934      $pre_callback_is_callable  = is_callable( $pre_callback );
1935      $post_callback_is_callable = is_callable( $post_callback );
1936  
1937      foreach ( $blocks as $index => $block ) {
1938          if ( $pre_callback_is_callable ) {
1939              $prev = 0 === $index
1940                  ? null
1941                  : $blocks[ $index - 1 ];
1942  
1943              $result .= call_user_func_array(
1944                  $pre_callback,
1945                  array( &$block, &$parent_block, $prev )
1946              );
1947          }
1948  
1949          if ( $post_callback_is_callable ) {
1950              $next = count( $blocks ) - 1 === $index
1951                  ? null
1952                  : $blocks[ $index + 1 ];
1953  
1954              $post_markup = call_user_func_array(
1955                  $post_callback,
1956                  array( &$block, &$parent_block, $next )
1957              );
1958          }
1959  
1960          $result .= traverse_and_serialize_block( $block, $pre_callback, $post_callback );
1961          $result .= isset( $post_markup ) ? $post_markup : '';
1962      }
1963  
1964      return $result;
1965  }
1966  
1967  /**
1968   * Filters and sanitizes block content to remove non-allowable HTML
1969   * from parsed block attribute values.
1970   *
1971   * @since 5.3.1
1972   *
1973   * @param string         $text              Text that may contain block content.
1974   * @param array[]|string $allowed_html      Optional. An array of allowed HTML elements and attributes,
1975   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
1976   *                                          for the list of accepted context names. Default 'post'.
1977   * @param string[]       $allowed_protocols Optional. Array of allowed URL protocols.
1978   *                                          Defaults to the result of wp_allowed_protocols().
1979   * @return string The filtered and sanitized content result.
1980   */
1981  function filter_block_content( $text, $allowed_html = 'post', $allowed_protocols = array() ) {
1982      $result = '';
1983  
1984      if ( str_contains( $text, '<!--' ) && str_contains( $text, '--->' ) ) {
1985          $text = preg_replace_callback( '%<!--(.*?)--->%', '_filter_block_content_callback', $text );
1986      }
1987  
1988      $blocks = parse_blocks( $text );
1989      foreach ( $blocks as $block ) {
1990          $block   = filter_block_kses( $block, $allowed_html, $allowed_protocols );
1991          $result .= serialize_block( $block );
1992      }
1993  
1994      return $result;
1995  }
1996  
1997  /**
1998   * Callback used for regular expression replacement in filter_block_content().
1999   *
2000   * @since 6.2.1
2001   * @access private
2002   *
2003   * @param array $matches Array of preg_replace_callback matches.
2004   * @return string Replacement string.
2005   */
2006  function _filter_block_content_callback( $matches ) {
2007      return '<!--' . rtrim( $matches[1], '-' ) . '-->';
2008  }
2009  
2010  /**
2011   * Filters and sanitizes a parsed block to remove non-allowable HTML
2012   * from block attribute values.
2013   *
2014   * @since 5.3.1
2015   *
2016   * @param WP_Block_Parser_Block $block             The parsed block object.
2017   * @param array[]|string        $allowed_html      An array of allowed HTML elements and attributes,
2018   *                                                 or a context name such as 'post'. See wp_kses_allowed_html()
2019   *                                                 for the list of accepted context names.
2020   * @param string[]              $allowed_protocols Optional. Array of allowed URL protocols.
2021   *                                                 Defaults to the result of wp_allowed_protocols().
2022   * @return array The filtered and sanitized block object result.
2023   */
2024  function filter_block_kses( $block, $allowed_html, $allowed_protocols = array() ) {
2025      $block['attrs'] = filter_block_kses_value( $block['attrs'], $allowed_html, $allowed_protocols, $block );
2026  
2027      if ( is_array( $block['innerBlocks'] ) ) {
2028          foreach ( $block['innerBlocks'] as $i => $inner_block ) {
2029              $block['innerBlocks'][ $i ] = filter_block_kses( $inner_block, $allowed_html, $allowed_protocols );
2030          }
2031      }
2032  
2033      return $block;
2034  }
2035  
2036  /**
2037   * Filters and sanitizes a parsed block attribute value to remove
2038   * non-allowable HTML.
2039   *
2040   * @since 5.3.1
2041   * @since 6.5.5 Added the `$block_context` parameter.
2042   *
2043   * @param string[]|string $value             The attribute value to filter.
2044   * @param array[]|string  $allowed_html      An array of allowed HTML elements and attributes,
2045   *                                           or a context name such as 'post'. See wp_kses_allowed_html()
2046   *                                           for the list of accepted context names.
2047   * @param string[]        $allowed_protocols Optional. Array of allowed URL protocols.
2048   *                                           Defaults to the result of wp_allowed_protocols().
2049   * @param array           $block_context     Optional. The block the attribute belongs to, in parsed block array format.
2050   * @return string[]|string The filtered and sanitized result.
2051   */
2052  function filter_block_kses_value( $value, $allowed_html, $allowed_protocols = array(), $block_context = null ) {
2053      if ( is_array( $value ) ) {
2054          foreach ( $value as $key => $inner_value ) {
2055              $filtered_key   = filter_block_kses_value( $key, $allowed_html, $allowed_protocols, $block_context );
2056              $filtered_value = filter_block_kses_value( $inner_value, $allowed_html, $allowed_protocols, $block_context );
2057  
2058              if ( isset( $block_context['blockName'] ) && 'core/template-part' === $block_context['blockName'] ) {
2059                  $filtered_value = filter_block_core_template_part_attributes( $filtered_value, $filtered_key, $allowed_html );
2060              }
2061              if ( $filtered_key !== $key ) {
2062                  unset( $value[ $key ] );
2063              }
2064  
2065              $value[ $filtered_key ] = $filtered_value;
2066          }
2067      } elseif ( is_string( $value ) ) {
2068          return wp_kses( $value, $allowed_html, $allowed_protocols );
2069      }
2070  
2071      return $value;
2072  }
2073  
2074  /**
2075   * Sanitizes the value of the Template Part block's `tagName` attribute.
2076   *
2077   * @since 6.5.5
2078   *
2079   * @param string         $attribute_value The attribute value to filter.
2080   * @param string         $attribute_name  The attribute name.
2081   * @param array[]|string $allowed_html    An array of allowed HTML elements and attributes,
2082   *                                        or a context name such as 'post'. See wp_kses_allowed_html()
2083   *                                        for the list of accepted context names.
2084   * @return string The sanitized attribute value.
2085   */
2086  function filter_block_core_template_part_attributes( $attribute_value, $attribute_name, $allowed_html ) {
2087      if ( empty( $attribute_value ) || 'tagName' !== $attribute_name ) {
2088          return $attribute_value;
2089      }
2090      if ( ! is_array( $allowed_html ) ) {
2091          $allowed_html = wp_kses_allowed_html( $allowed_html );
2092      }
2093      return isset( $allowed_html[ $attribute_value ] ) ? $attribute_value : '';
2094  }
2095  
2096  /**
2097   * Parses blocks out of a content string, and renders those appropriate for the excerpt.
2098   *
2099   * As the excerpt should be a small string of text relevant to the full post content,
2100   * this function renders the blocks that are most likely to contain such text.
2101   *
2102   * @since 5.0.0
2103   *
2104   * @param string $content The content to parse.
2105   * @return string The parsed and filtered content.
2106   */
2107  function excerpt_remove_blocks( $content ) {
2108      if ( ! has_blocks( $content ) ) {
2109          return $content;
2110      }
2111  
2112      $allowed_inner_blocks = array(
2113          // Classic blocks have their blockName set to null.
2114          null,
2115          'core/freeform',
2116          'core/heading',
2117          'core/html',
2118          'core/list',
2119          'core/media-text',
2120          'core/paragraph',
2121          'core/preformatted',
2122          'core/pullquote',
2123          'core/quote',
2124          'core/table',
2125          'core/verse',
2126      );
2127  
2128      $allowed_wrapper_blocks = array(
2129          'core/columns',
2130          'core/column',
2131          'core/group',
2132      );
2133  
2134      /**
2135       * Filters the list of blocks that can be used as wrapper blocks, allowing
2136       * excerpts to be generated from the `innerBlocks` of these wrappers.
2137       *
2138       * @since 5.8.0
2139       *
2140       * @param string[] $allowed_wrapper_blocks The list of names of allowed wrapper blocks.
2141       */
2142      $allowed_wrapper_blocks = apply_filters( 'excerpt_allowed_wrapper_blocks', $allowed_wrapper_blocks );
2143  
2144      $allowed_blocks = array_merge( $allowed_inner_blocks, $allowed_wrapper_blocks );
2145  
2146      /**
2147       * Filters the list of blocks that can contribute to the excerpt.
2148       *
2149       * If a dynamic block is added to this list, it must not generate another
2150       * excerpt, as this will cause an infinite loop to occur.
2151       *
2152       * @since 5.0.0
2153       *
2154       * @param string[] $allowed_blocks The list of names of allowed blocks.
2155       */
2156      $allowed_blocks = apply_filters( 'excerpt_allowed_blocks', $allowed_blocks );
2157      $blocks         = parse_blocks( $content );
2158      $output         = '';
2159  
2160      foreach ( $blocks as $block ) {
2161          if ( in_array( $block['blockName'], $allowed_blocks, true ) ) {
2162              if ( ! empty( $block['innerBlocks'] ) ) {
2163                  if ( in_array( $block['blockName'], $allowed_wrapper_blocks, true ) ) {
2164                      $output .= _excerpt_render_inner_blocks( $block, $allowed_blocks );
2165                      continue;
2166                  }
2167  
2168                  // Skip the block if it has disallowed or nested inner blocks.
2169                  foreach ( $block['innerBlocks'] as $inner_block ) {
2170                      if (
2171                          ! in_array( $inner_block['blockName'], $allowed_inner_blocks, true ) ||
2172                          ! empty( $inner_block['innerBlocks'] )
2173                      ) {
2174                          continue 2;
2175                      }
2176                  }
2177              }
2178  
2179              $output .= render_block( $block );
2180          }
2181      }
2182  
2183      return $output;
2184  }
2185  
2186  /**
2187   * Parses footnotes markup out of a content string,
2188   * and renders those appropriate for the excerpt.
2189   *
2190   * @since 6.3.0
2191   *
2192   * @param string $content The content to parse.
2193   * @return string The parsed and filtered content.
2194   */
2195  function excerpt_remove_footnotes( $content ) {
2196      if ( ! str_contains( $content, 'data-fn=' ) ) {
2197          return $content;
2198      }
2199  
2200      return preg_replace(
2201          '_<sup data-fn="[^"]+" class="[^"]+">\s*<a href="[^"]+" id="[^"]+">\d+</a>\s*</sup>_',
2202          '',
2203          $content
2204      );
2205  }
2206  
2207  /**
2208   * Renders inner blocks from the allowed wrapper blocks
2209   * for generating an excerpt.
2210   *
2211   * @since 5.8.0
2212   * @access private
2213   *
2214   * @param array $parsed_block   The parsed block.
2215   * @param array $allowed_blocks The list of allowed inner blocks.
2216   * @return string The rendered inner blocks.
2217   */
2218  function _excerpt_render_inner_blocks( $parsed_block, $allowed_blocks ) {
2219      $output = '';
2220  
2221      foreach ( $parsed_block['innerBlocks'] as $inner_block ) {
2222          if ( ! in_array( $inner_block['blockName'], $allowed_blocks, true ) ) {
2223              continue;
2224          }
2225  
2226          if ( empty( $inner_block['innerBlocks'] ) ) {
2227              $output .= render_block( $inner_block );
2228          } else {
2229              $output .= _excerpt_render_inner_blocks( $inner_block, $allowed_blocks );
2230          }
2231      }
2232  
2233      return $output;
2234  }
2235  
2236  /**
2237   * Renders a single block into a HTML string.
2238   *
2239   * @since 5.0.0
2240   *
2241   * @global WP_Post $post The post to edit.
2242   *
2243   * @param array $parsed_block {
2244   *     An associative array of the block being rendered. See WP_Block_Parser_Block.
2245   *
2246   *     @type string   $blockName    Name of block.
2247   *     @type array    $attrs        Attributes from block comment delimiters.
2248   *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
2249   *                                  have the same structure as this one.
2250   *     @type string   $innerHTML    HTML from inside block comment delimiters.
2251   *     @type array    $innerContent List of string fragments and null markers where
2252   *                                  inner blocks were found.
2253   * }
2254   * @return string String of rendered HTML.
2255   */
2256  function render_block( $parsed_block ) {
2257      global $post;
2258      $parent_block = null;
2259  
2260      /**
2261       * Allows render_block() to be short-circuited, by returning a non-null value.
2262       *
2263       * @since 5.1.0
2264       * @since 5.9.0 The `$parent_block` parameter was added.
2265       *
2266       * @param string|null   $pre_render   The pre-rendered content. Default null.
2267       * @param array         $parsed_block {
2268       *     An associative array of the block being rendered. See WP_Block_Parser_Block.
2269       *
2270       *     @type string   $blockName    Name of block.
2271       *     @type array    $attrs        Attributes from block comment delimiters.
2272       *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
2273       *                                  have the same structure as this one.
2274       *     @type string   $innerHTML    HTML from inside block comment delimiters.
2275       *     @type array    $innerContent List of string fragments and null markers where
2276       *                                  inner blocks were found.
2277       * }
2278       * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block.
2279       */
2280      $pre_render = apply_filters( 'pre_render_block', null, $parsed_block, $parent_block );
2281      if ( ! is_null( $pre_render ) ) {
2282          return $pre_render;
2283      }
2284  
2285      $source_block = $parsed_block;
2286  
2287      /**
2288       * Filters the block being rendered in render_block(), before it's processed.
2289       *
2290       * @since 5.1.0
2291       * @since 5.9.0 The `$parent_block` parameter was added.
2292       *
2293       * @param array         $parsed_block {
2294       *     An associative array of the block being rendered. See WP_Block_Parser_Block.
2295       *
2296       *     @type string   $blockName    Name of block.
2297       *     @type array    $attrs        Attributes from block comment delimiters.
2298       *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
2299       *                                  have the same structure as this one.
2300       *     @type string   $innerHTML    HTML from inside block comment delimiters.
2301       *     @type array    $innerContent List of string fragments and null markers where
2302       *                                  inner blocks were found.
2303       * }
2304       * @param array         $source_block {
2305       *     An un-modified copy of `$parsed_block`, as it appeared in the source content.
2306       *     See WP_Block_Parser_Block.
2307       *
2308       *     @type string   $blockName    Name of block.
2309       *     @type array    $attrs        Attributes from block comment delimiters.
2310       *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
2311       *                                  have the same structure as this one.
2312       *     @type string   $innerHTML    HTML from inside block comment delimiters.
2313       *     @type array    $innerContent List of string fragments and null markers where
2314       *                                  inner blocks were found.
2315       * }
2316       * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block.
2317       */
2318      $parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block, $parent_block );
2319  
2320      $context = array();
2321  
2322      if ( $post instanceof WP_Post ) {
2323          $context['postId'] = $post->ID;
2324  
2325          /*
2326           * The `postType` context is largely unnecessary server-side, since the ID
2327           * is usually sufficient on its own. That being said, since a block's
2328           * manifest is expected to be shared between the server and the client,
2329           * it should be included to consistently fulfill the expectation.
2330           */
2331          $context['postType'] = $post->post_type;
2332      }
2333  
2334      /**
2335       * Filters the default context provided to a rendered block.
2336       *
2337       * @since 5.5.0
2338       * @since 5.9.0 The `$parent_block` parameter was added.
2339       *
2340       * @param array         $context      Default context.
2341       * @param array         $parsed_block {
2342       *     An associative array of the block being rendered. See WP_Block_Parser_Block.
2343       *
2344       *     @type string   $blockName    Name of block.
2345       *     @type array    $attrs        Attributes from block comment delimiters.
2346       *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
2347       *                                  have the same structure as this one.
2348       *     @type string   $innerHTML    HTML from inside block comment delimiters.
2349       *     @type array    $innerContent List of string fragments and null markers where
2350       *                                  inner blocks were found.
2351       * }
2352       * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block.
2353       */
2354      $context = apply_filters( 'render_block_context', $context, $parsed_block, $parent_block );
2355  
2356      $block = new WP_Block( $parsed_block, $context );
2357  
2358      return $block->render();
2359  }
2360  
2361  /**
2362   * Parses blocks out of a content string.
2363   *
2364   * @since 5.0.0
2365   *
2366   * @param string $content Post content.
2367   * @return array[] {
2368   *     Array of block structures.
2369   *
2370   *     @type array ...$0 {
2371   *         An associative array of a single parsed block object. See WP_Block_Parser_Block.
2372   *
2373   *         @type string   $blockName    Name of block.
2374   *         @type array    $attrs        Attributes from block comment delimiters.
2375   *         @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
2376   *                                      have the same structure as this one.
2377   *         @type string   $innerHTML    HTML from inside block comment delimiters.
2378   *         @type array    $innerContent List of string fragments and null markers where
2379   *                                      inner blocks were found.
2380   *     }
2381   * }
2382   */
2383  function parse_blocks( $content ) {
2384      /**
2385       * Filter to allow plugins to replace the server-side block parser.
2386       *
2387       * @since 5.0.0
2388       *
2389       * @param string $parser_class Name of block parser class.
2390       */
2391      $parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' );
2392  
2393      $parser = new $parser_class();
2394      return $parser->parse( $content );
2395  }
2396  
2397  /**
2398   * Parses dynamic blocks out of `post_content` and re-renders them.
2399   *
2400   * @since 5.0.0
2401   *
2402   * @param string $content Post content.
2403   * @return string Updated post content.
2404   */
2405  function do_blocks( $content ) {
2406      $blocks = parse_blocks( $content );
2407      $output = '';
2408  
2409      foreach ( $blocks as $block ) {
2410          $output .= render_block( $block );
2411      }
2412  
2413      // If there are blocks in this content, we shouldn't run wpautop() on it later.
2414      $priority = has_filter( 'the_content', 'wpautop' );
2415      if ( false !== $priority && doing_filter( 'the_content' ) && has_blocks( $content ) ) {
2416          remove_filter( 'the_content', 'wpautop', $priority );
2417          add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
2418      }
2419  
2420      return $output;
2421  }
2422  
2423  /**
2424   * If do_blocks() needs to remove wpautop() from the `the_content` filter, this re-adds it afterwards,
2425   * for subsequent `the_content` usage.
2426   *
2427   * @since 5.0.0
2428   * @access private
2429   *
2430   * @param string $content The post content running through this filter.
2431   * @return string The unmodified content.
2432   */
2433  function _restore_wpautop_hook( $content ) {
2434      $current_priority = has_filter( 'the_content', '_restore_wpautop_hook' );
2435  
2436      add_filter( 'the_content', 'wpautop', $current_priority - 1 );
2437      remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority );
2438  
2439      return $content;
2440  }
2441  
2442  /**
2443   * Returns the current version of the block format that the content string is using.
2444   *
2445   * If the string doesn't contain blocks, it returns 0.
2446   *
2447   * @since 5.0.0
2448   *
2449   * @param string $content Content to test.
2450   * @return int The block format version is 1 if the content contains one or more blocks, 0 otherwise.
2451   */
2452  function block_version( $content ) {
2453      return has_blocks( $content ) ? 1 : 0;
2454  }
2455  
2456  /**
2457   * Registers a new block style.
2458   *
2459   * @since 5.3.0
2460   * @since 6.6.0 Added support for registering styles for multiple block types.
2461   *
2462   * @link https://developer.wordpress.org/block-editor/reference-guides/block-api/block-styles/
2463   *
2464   * @param string|string[] $block_name       Block type name including namespace or array of namespaced block type names.
2465   * @param array           $style_properties Array containing the properties of the style name, label,
2466   *                                          style_handle (name of the stylesheet to be enqueued),
2467   *                                          inline_style (string containing the CSS to be added),
2468   *                                          style_data (theme.json-like array to generate CSS from).
2469   *                                          See WP_Block_Styles_Registry::register().
2470   * @return bool True if the block style was registered with success and false otherwise.
2471   */
2472  function register_block_style( $block_name, $style_properties ) {
2473      return WP_Block_Styles_Registry::get_instance()->register( $block_name, $style_properties );
2474  }
2475  
2476  /**
2477   * Unregisters a block style.
2478   *
2479   * @since 5.3.0
2480   *
2481   * @param string $block_name       Block type name including namespace.
2482   * @param string $block_style_name Block style name.
2483   * @return bool True if the block style was unregistered with success and false otherwise.
2484   */
2485  function unregister_block_style( $block_name, $block_style_name ) {
2486      return WP_Block_Styles_Registry::get_instance()->unregister( $block_name, $block_style_name );
2487  }
2488  
2489  /**
2490   * Checks whether the current block type supports the feature requested.
2491   *
2492   * @since 5.8.0
2493   * @since 6.4.0 The `$feature` parameter now supports a string.
2494   *
2495   * @param WP_Block_Type $block_type    Block type to check for support.
2496   * @param string|array  $feature       Feature slug, or path to a specific feature to check support for.
2497   * @param mixed         $default_value Optional. Fallback value for feature support. Default false.
2498   * @return bool Whether the feature is supported.
2499   */
2500  function block_has_support( $block_type, $feature, $default_value = false ) {
2501      $block_support = $default_value;
2502      if ( $block_type instanceof WP_Block_Type ) {
2503          if ( is_array( $feature ) && count( $feature ) === 1 ) {
2504              $feature = $feature[0];
2505          }
2506  
2507          if ( is_array( $feature ) ) {
2508              $block_support = _wp_array_get( $block_type->supports, $feature, $default_value );
2509          } elseif ( isset( $block_type->supports[ $feature ] ) ) {
2510              $block_support = $block_type->supports[ $feature ];
2511          }
2512      }
2513  
2514      return true === $block_support || is_array( $block_support );
2515  }
2516  
2517  /**
2518   * Converts typography keys declared under `supports.*` to `supports.typography.*`.
2519   *
2520   * Displays a `_doing_it_wrong()` notice when a block using the older format is detected.
2521   *
2522   * @since 5.8.0
2523   *
2524   * @param array $metadata Metadata for registering a block type.
2525   * @return array Filtered metadata for registering a block type.
2526   */
2527  function wp_migrate_old_typography_shape( $metadata ) {
2528      if ( ! isset( $metadata['supports'] ) ) {
2529          return $metadata;
2530      }
2531  
2532      $typography_keys = array(
2533          '__experimentalFontFamily',
2534          '__experimentalFontStyle',
2535          '__experimentalFontWeight',
2536          '__experimentalLetterSpacing',
2537          '__experimentalTextDecoration',
2538          '__experimentalTextTransform',
2539          'fontSize',
2540          'lineHeight',
2541      );
2542  
2543      foreach ( $typography_keys as $typography_key ) {
2544          $support_for_key = isset( $metadata['supports'][ $typography_key ] ) ? $metadata['supports'][ $typography_key ] : null;
2545  
2546          if ( null !== $support_for_key ) {
2547              _doing_it_wrong(
2548                  'register_block_type_from_metadata()',
2549                  sprintf(
2550                      /* translators: 1: Block type, 2: Typography supports key, e.g: fontSize, lineHeight, etc. 3: block.json, 4: Old metadata key, 5: New metadata key. */
2551                      __( 'Block "%1$s" is declaring %2$s support in %3$s file under %4$s. %2$s support is now declared under %5$s.' ),
2552                      $metadata['name'],
2553                      "<code>$typography_key</code>",
2554                      '<code>block.json</code>',
2555                      "<code>supports.$typography_key</code>",
2556                      "<code>supports.typography.$typography_key</code>"
2557                  ),
2558                  '5.8.0'
2559              );
2560  
2561              _wp_array_set( $metadata['supports'], array( 'typography', $typography_key ), $support_for_key );
2562              unset( $metadata['supports'][ $typography_key ] );
2563          }
2564      }
2565  
2566      return $metadata;
2567  }
2568  
2569  /**
2570   * Helper function that constructs a WP_Query args array from
2571   * a `Query` block properties.
2572   *
2573   * It's used in Query Loop, Query Pagination Numbers and Query Pagination Next blocks.
2574   *
2575   * @since 5.8.0
2576   * @since 6.1.0 Added `query_loop_block_query_vars` filter and `parents` support in query.
2577   * @since 6.7.0 Added support for the `format` property in query.
2578   *
2579   * @param WP_Block $block Block instance.
2580   * @param int      $page  Current query's page.
2581   *
2582   * @return array Returns the constructed WP_Query arguments.
2583   */
2584  function build_query_vars_from_query_block( $block, $page ) {
2585      $query = array(
2586          'post_type'    => 'post',
2587          'order'        => 'DESC',
2588          'orderby'      => 'date',
2589          'post__not_in' => array(),
2590          'tax_query'    => array(),
2591      );
2592  
2593      if ( isset( $block->context['query'] ) ) {
2594          if ( ! empty( $block->context['query']['postType'] ) ) {
2595              $post_type_param = $block->context['query']['postType'];
2596              if ( is_post_type_viewable( $post_type_param ) ) {
2597                  $query['post_type'] = $post_type_param;
2598              }
2599          }
2600          if ( isset( $block->context['query']['sticky'] ) && ! empty( $block->context['query']['sticky'] ) ) {
2601              $sticky = get_option( 'sticky_posts' );
2602              if ( 'only' === $block->context['query']['sticky'] ) {
2603                  /*
2604                   * Passing an empty array to post__in will return have_posts() as true (and all posts will be returned).
2605                   * Logic should be used before hand to determine if WP_Query should be used in the event that the array
2606                   * being passed to post__in is empty.
2607                   *
2608                   * @see https://core.trac.wordpress.org/ticket/28099
2609                   */
2610                  $query['post__in']            = ! empty( $sticky ) ? $sticky : array( 0 );
2611                  $query['ignore_sticky_posts'] = 1;
2612              } elseif ( 'exclude' === $block->context['query']['sticky'] ) {
2613                  $query['post__not_in'] = array_merge( $query['post__not_in'], $sticky );
2614              } elseif ( 'ignore' === $block->context['query']['sticky'] ) {
2615                  $query['ignore_sticky_posts'] = 1;
2616              }
2617          }
2618          if ( ! empty( $block->context['query']['exclude'] ) ) {
2619              $excluded_post_ids     = array_map( 'intval', $block->context['query']['exclude'] );
2620              $excluded_post_ids     = array_filter( $excluded_post_ids );
2621              $query['post__not_in'] = array_merge( $query['post__not_in'], $excluded_post_ids );
2622          }
2623          if (
2624              isset( $block->context['query']['perPage'] ) &&
2625              is_numeric( $block->context['query']['perPage'] )
2626          ) {
2627              $per_page = absint( $block->context['query']['perPage'] );
2628              $offset   = 0;
2629  
2630              if (
2631                  isset( $block->context['query']['offset'] ) &&
2632                  is_numeric( $block->context['query']['offset'] )
2633              ) {
2634                  $offset = absint( $block->context['query']['offset'] );
2635              }
2636  
2637              $query['offset']         = ( $per_page * ( $page - 1 ) ) + $offset;
2638              $query['posts_per_page'] = $per_page;
2639          }
2640          // Migrate `categoryIds` and `tagIds` to `tax_query` for backwards compatibility.
2641          if ( ! empty( $block->context['query']['categoryIds'] ) || ! empty( $block->context['query']['tagIds'] ) ) {
2642              $tax_query_back_compat = array();
2643              if ( ! empty( $block->context['query']['categoryIds'] ) ) {
2644                  $tax_query_back_compat[] = array(
2645                      'taxonomy'         => 'category',
2646                      'terms'            => array_filter( array_map( 'intval', $block->context['query']['categoryIds'] ) ),
2647                      'include_children' => false,
2648                  );
2649              }
2650              if ( ! empty( $block->context['query']['tagIds'] ) ) {
2651                  $tax_query_back_compat[] = array(
2652                      'taxonomy'         => 'post_tag',
2653                      'terms'            => array_filter( array_map( 'intval', $block->context['query']['tagIds'] ) ),
2654                      'include_children' => false,
2655                  );
2656              }
2657              $query['tax_query'] = array_merge( $query['tax_query'], $tax_query_back_compat );
2658          }
2659          if ( ! empty( $block->context['query']['taxQuery'] ) ) {
2660              $tax_query = array();
2661              foreach ( $block->context['query']['taxQuery'] as $taxonomy => $terms ) {
2662                  if ( is_taxonomy_viewable( $taxonomy ) && ! empty( $terms ) ) {
2663                      $tax_query[] = array(
2664                          'taxonomy'         => $taxonomy,
2665                          'terms'            => array_filter( array_map( 'intval', $terms ) ),
2666                          'include_children' => false,
2667                      );
2668                  }
2669              }
2670              $query['tax_query'] = array_merge( $query['tax_query'], $tax_query );
2671          }
2672          if ( ! empty( $block->context['query']['format'] ) && is_array( $block->context['query']['format'] ) ) {
2673              $formats = $block->context['query']['format'];
2674              /*
2675               * Validate that the format is either `standard` or a supported post format.
2676               * - First, add `standard` to the array of valid formats.
2677               * - Then, remove any invalid formats.
2678               */
2679              $valid_formats = array_merge( array( 'standard' ), get_post_format_slugs() );
2680              $formats       = array_intersect( $formats, $valid_formats );
2681  
2682              /*
2683               * The relation needs to be set to `OR` since the request can contain
2684               * two separate conditions. The user may be querying for items that have
2685               * either the `standard` format or a specific format.
2686               */
2687              $formats_query = array( 'relation' => 'OR' );
2688  
2689              /*
2690               * The default post format, `standard`, is not stored in the database.
2691               * If `standard` is part of the request, the query needs to exclude all post items that
2692               * have a format assigned.
2693               */
2694              if ( in_array( 'standard', $formats, true ) ) {
2695                  $formats_query[] = array(
2696                      'taxonomy' => 'post_format',
2697                      'field'    => 'slug',
2698                      'operator' => 'NOT EXISTS',
2699                  );
2700                  // Remove the `standard` format, since it cannot be queried.
2701                  unset( $formats[ array_search( 'standard', $formats, true ) ] );
2702              }
2703              // Add any remaining formats to the formats query.
2704              if ( ! empty( $formats ) ) {
2705                  // Add the `post-format-` prefix.
2706                  $terms           = array_map(
2707                      static function ( $format ) {
2708                          return "post-format-$format";
2709                      },
2710                      $formats
2711                  );
2712                  $formats_query[] = array(
2713                      'taxonomy' => 'post_format',
2714                      'field'    => 'slug',
2715                      'terms'    => $terms,
2716                      'operator' => 'IN',
2717                  );
2718              }
2719  
2720              /*
2721               * Add `$formats_query` to `$query`, as long as it contains more than one key:
2722               * If `$formats_query` only contains the initial `relation` key, there are no valid formats to query,
2723               * and the query should not be modified.
2724               */
2725              if ( count( $formats_query ) > 1 ) {
2726                  // Enable filtering by both post formats and other taxonomies by combining them with `AND`.
2727                  if ( empty( $query['tax_query'] ) ) {
2728                      $query['tax_query'] = $formats_query;
2729                  } else {
2730                      $query['tax_query'] = array(
2731                          'relation' => 'AND',
2732                          $query['tax_query'],
2733                          $formats_query,
2734                      );
2735                  }
2736              }
2737          }
2738  
2739          if (
2740              isset( $block->context['query']['order'] ) &&
2741                  in_array( strtoupper( $block->context['query']['order'] ), array( 'ASC', 'DESC' ), true )
2742          ) {
2743              $query['order'] = strtoupper( $block->context['query']['order'] );
2744          }
2745          if ( isset( $block->context['query']['orderBy'] ) ) {
2746              $query['orderby'] = $block->context['query']['orderBy'];
2747          }
2748          if (
2749              isset( $block->context['query']['author'] )
2750          ) {
2751              if ( is_array( $block->context['query']['author'] ) ) {
2752                  $query['author__in'] = array_filter( array_map( 'intval', $block->context['query']['author'] ) );
2753              } elseif ( is_string( $block->context['query']['author'] ) ) {
2754                  $query['author__in'] = array_filter( array_map( 'intval', explode( ',', $block->context['query']['author'] ) ) );
2755              } elseif ( is_int( $block->context['query']['author'] ) && $block->context['query']['author'] > 0 ) {
2756                  $query['author'] = $block->context['query']['author'];
2757              }
2758          }
2759          if ( ! empty( $block->context['query']['search'] ) ) {
2760              $query['s'] = $block->context['query']['search'];
2761          }
2762          if ( ! empty( $block->context['query']['parents'] ) && is_post_type_hierarchical( $query['post_type'] ) ) {
2763              $query['post_parent__in'] = array_unique( array_map( 'intval', $block->context['query']['parents'] ) );
2764          }
2765      }
2766  
2767      /**
2768       * Filters the arguments which will be passed to `WP_Query` for the Query Loop Block.
2769       *
2770       * Anything to this filter should be compatible with the `WP_Query` API to form
2771       * the query context which will be passed down to the Query Loop Block's children.
2772       * This can help, for example, to include additional settings or meta queries not
2773       * directly supported by the core Query Loop Block, and extend its capabilities.
2774       *
2775       * Please note that this will only influence the query that will be rendered on the
2776       * front-end. The editor preview is not affected by this filter. Also, worth noting
2777       * that the editor preview uses the REST API, so, ideally, one should aim to provide
2778       * attributes which are also compatible with the REST API, in order to be able to
2779       * implement identical queries on both sides.
2780       *
2781       * @since 6.1.0
2782       *
2783       * @param array    $query Array containing parameters for `WP_Query` as parsed by the block context.
2784       * @param WP_Block $block Block instance.
2785       * @param int      $page  Current query's page.
2786       */
2787      return apply_filters( 'query_loop_block_query_vars', $query, $block, $page );
2788  }
2789  
2790  /**
2791   * Helper function that returns the proper pagination arrow HTML for
2792   * `QueryPaginationNext` and `QueryPaginationPrevious` blocks based
2793   * on the provided `paginationArrow` from `QueryPagination` context.
2794   *
2795   * It's used in QueryPaginationNext and QueryPaginationPrevious blocks.
2796   *
2797   * @since 5.9.0
2798   *
2799   * @param WP_Block $block   Block instance.
2800   * @param bool     $is_next Flag for handling `next/previous` blocks.
2801   * @return string|null The pagination arrow HTML or null if there is none.
2802   */
2803  function get_query_pagination_arrow( $block, $is_next ) {
2804      $arrow_map = array(
2805          'none'    => '',
2806          'arrow'   => array(
2807              'next'     => '→',
2808              'previous' => '←',
2809          ),
2810          'chevron' => array(
2811              'next'     => '»',
2812              'previous' => '«',
2813          ),
2814      );
2815      if ( ! empty( $block->context['paginationArrow'] ) && array_key_exists( $block->context['paginationArrow'], $arrow_map ) && ! empty( $arrow_map[ $block->context['paginationArrow'] ] ) ) {
2816          $pagination_type = $is_next ? 'next' : 'previous';
2817          $arrow_attribute = $block->context['paginationArrow'];
2818          $arrow           = $arrow_map[ $block->context['paginationArrow'] ][ $pagination_type ];
2819          $arrow_classes   = "wp-block-query-pagination-$pagination_type-arrow is-arrow-$arrow_attribute";
2820          return "<span class='$arrow_classes' aria-hidden='true'>$arrow</span>";
2821      }
2822      return null;
2823  }
2824  
2825  /**
2826   * Helper function that constructs a comment query vars array from the passed
2827   * block properties.
2828   *
2829   * It's used with the Comment Query Loop inner blocks.
2830   *
2831   * @since 6.0.0
2832   *
2833   * @param WP_Block $block Block instance.
2834   * @return array Returns the comment query parameters to use with the
2835   *               WP_Comment_Query constructor.
2836   */
2837  function build_comment_query_vars_from_block( $block ) {
2838  
2839      $comment_args = array(
2840          'orderby'       => 'comment_date_gmt',
2841          'order'         => 'ASC',
2842          'status'        => 'approve',
2843          'no_found_rows' => false,
2844      );
2845  
2846      if ( is_user_logged_in() ) {
2847          $comment_args['include_unapproved'] = array( get_current_user_id() );
2848      } else {
2849          $unapproved_email = wp_get_unapproved_comment_author_email();
2850  
2851          if ( $unapproved_email ) {
2852              $comment_args['include_unapproved'] = array( $unapproved_email );
2853          }
2854      }
2855  
2856      if ( ! empty( $block->context['postId'] ) ) {
2857          $comment_args['post_id'] = (int) $block->context['postId'];
2858      }
2859  
2860      if ( get_option( 'thread_comments' ) ) {
2861          $comment_args['hierarchical'] = 'threaded';
2862      } else {
2863          $comment_args['hierarchical'] = false;
2864      }
2865  
2866      if ( get_option( 'page_comments' ) === '1' || get_option( 'page_comments' ) === true ) {
2867          $per_page     = get_option( 'comments_per_page' );
2868          $default_page = get_option( 'default_comments_page' );
2869          if ( $per_page > 0 ) {
2870              $comment_args['number'] = $per_page;
2871  
2872              $page = (int) get_query_var( 'cpage' );
2873              if ( $page ) {
2874                  $comment_args['paged'] = $page;
2875              } elseif ( 'oldest' === $default_page ) {
2876                  $comment_args['paged'] = 1;
2877              } elseif ( 'newest' === $default_page ) {
2878                  $max_num_pages = (int) ( new WP_Comment_Query( $comment_args ) )->max_num_pages;
2879                  if ( 0 !== $max_num_pages ) {
2880                      $comment_args['paged'] = $max_num_pages;
2881                  }
2882              }
2883          }
2884      }
2885  
2886      return $comment_args;
2887  }
2888  
2889  /**
2890   * Helper function that returns the proper pagination arrow HTML for
2891   * `CommentsPaginationNext` and `CommentsPaginationPrevious` blocks based on the
2892   * provided `paginationArrow` from `CommentsPagination` context.
2893   *
2894   * It's used in CommentsPaginationNext and CommentsPaginationPrevious blocks.
2895   *
2896   * @since 6.0.0
2897   *
2898   * @param WP_Block $block           Block instance.
2899   * @param string   $pagination_type Optional. Type of the arrow we will be rendering.
2900   *                                  Accepts 'next' or 'previous'. Default 'next'.
2901   * @return string|null The pagination arrow HTML or null if there is none.
2902   */
2903  function get_comments_pagination_arrow( $block, $pagination_type = 'next' ) {
2904      $arrow_map = array(
2905          'none'    => '',
2906          'arrow'   => array(
2907              'next'     => '→',
2908              'previous' => '←',
2909          ),
2910          'chevron' => array(
2911              'next'     => '»',
2912              'previous' => '«',
2913          ),
2914      );
2915      if ( ! empty( $block->context['comments/paginationArrow'] ) && ! empty( $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ] ) ) {
2916          $arrow_attribute = $block->context['comments/paginationArrow'];
2917          $arrow           = $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ];
2918          $arrow_classes   = "wp-block-comments-pagination-$pagination_type-arrow is-arrow-$arrow_attribute";
2919          return "<span class='$arrow_classes' aria-hidden='true'>$arrow</span>";
2920      }
2921      return null;
2922  }
2923  
2924  /**
2925   * Strips all HTML from the content of footnotes, and sanitizes the ID.
2926   *
2927   * This function expects slashed data on the footnotes content.
2928   *
2929   * @access private
2930   * @since 6.3.2
2931   *
2932   * @param string $footnotes JSON-encoded string of an array containing the content and ID of each footnote.
2933   * @return string Filtered content without any HTML on the footnote content and with the sanitized ID.
2934   */
2935  function _wp_filter_post_meta_footnotes( $footnotes ) {
2936      $footnotes_decoded = json_decode( $footnotes, true );
2937      if ( ! is_array( $footnotes_decoded ) ) {
2938          return '';
2939      }
2940      $footnotes_sanitized = array();
2941      foreach ( $footnotes_decoded as $footnote ) {
2942          if ( ! empty( $footnote['content'] ) && ! empty( $footnote['id'] ) ) {
2943              $footnotes_sanitized[] = array(
2944                  'id'      => sanitize_key( $footnote['id'] ),
2945                  'content' => wp_unslash( wp_filter_post_kses( wp_slash( $footnote['content'] ) ) ),
2946              );
2947          }
2948      }
2949      return wp_json_encode( $footnotes_sanitized );
2950  }
2951  
2952  /**
2953   * Adds the filters for footnotes meta field.
2954   *
2955   * @access private
2956   * @since 6.3.2
2957   */
2958  function _wp_footnotes_kses_init_filters() {
2959      add_filter( 'sanitize_post_meta_footnotes', '_wp_filter_post_meta_footnotes' );
2960  }
2961  
2962  /**
2963   * Removes the filters for footnotes meta field.
2964   *
2965   * @access private
2966   * @since 6.3.2
2967   */
2968  function _wp_footnotes_remove_filters() {
2969      remove_filter( 'sanitize_post_meta_footnotes', '_wp_filter_post_meta_footnotes' );
2970  }
2971  
2972  /**
2973   * Registers the filter of footnotes meta field if the user does not have `unfiltered_html` capability.
2974   *
2975   * @access private
2976   * @since 6.3.2
2977   */
2978  function _wp_footnotes_kses_init() {
2979      _wp_footnotes_remove_filters();
2980      if ( ! current_user_can( 'unfiltered_html' ) ) {
2981          _wp_footnotes_kses_init_filters();
2982      }
2983  }
2984  
2985  /**
2986   * Initializes the filters for footnotes meta field when imported data should be filtered.
2987   *
2988   * This filter is the last one being executed on {@see 'force_filtered_html_on_import'}.
2989   * If the input of the filter is true, it means we are in an import situation and should
2990   * enable kses, independently of the user capabilities. So in that case we call
2991   * _wp_footnotes_kses_init_filters().
2992   *
2993   * @access private
2994   * @since 6.3.2
2995   *
2996   * @param string $arg Input argument of the filter.
2997   * @return string Input argument of the filter.
2998   */
2999  function _wp_footnotes_force_filtered_html_on_import_filter( $arg ) {
3000      // If `force_filtered_html_on_import` is true, we need to init the global styles kses filters.
3001      if ( $arg ) {
3002          _wp_footnotes_kses_init_filters();
3003      }
3004      return $arg;
3005  }


Generated : Thu Apr 24 08:20:01 2025 Cross-referenced by PHPXref