[ 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 a block type from the metadata stored in the `block.json` file.
 380   *
 381   * @since 5.5.0
 382   * @since 5.7.0 Added support for `textdomain` field and i18n handling for all translatable fields.
 383   * @since 5.9.0 Added support for `variations` and `viewScript` fields.
 384   * @since 6.1.0 Added support for `render` field.
 385   * @since 6.3.0 Added `selectors` field.
 386   * @since 6.4.0 Added support for `blockHooks` field.
 387   * @since 6.5.0 Added support for `allowedBlocks`, `viewScriptModule`, and `viewStyle` fields.
 388   *
 389   * @param string $file_or_folder Path to the JSON file with metadata definition for
 390   *                               the block or path to the folder where the `block.json` file is located.
 391   *                               If providing the path to a JSON file, the filename must end with `block.json`.
 392   * @param array  $args           Optional. Array of block type arguments. Accepts any public property
 393   *                               of `WP_Block_Type`. See WP_Block_Type::__construct() for information
 394   *                               on accepted arguments. Default empty array.
 395   * @return WP_Block_Type|false The registered block type on success, or false on failure.
 396   */
 397  function register_block_type_from_metadata( $file_or_folder, $args = array() ) {
 398      /*
 399       * Get an array of metadata from a PHP file.
 400       * This improves performance for core blocks as it's only necessary to read a single PHP file
 401       * instead of reading a JSON file per-block, and then decoding from JSON to PHP.
 402       * Using a static variable ensures that the metadata is only read once per request.
 403       */
 404      static $core_blocks_meta;
 405      if ( ! $core_blocks_meta ) {
 406          $core_blocks_meta = require  ABSPATH . WPINC . '/blocks/blocks-json.php';
 407      }
 408  
 409      $metadata_file = ( ! str_ends_with( $file_or_folder, 'block.json' ) ) ?
 410          trailingslashit( $file_or_folder ) . 'block.json' :
 411          $file_or_folder;
 412  
 413      $is_core_block = str_starts_with( $file_or_folder, ABSPATH . WPINC );
 414      // If the block is not a core block, the metadata file must exist.
 415      $metadata_file_exists = $is_core_block || file_exists( $metadata_file );
 416      if ( ! $metadata_file_exists && empty( $args['name'] ) ) {
 417          return false;
 418      }
 419  
 420      // Try to get metadata from the static cache for core blocks.
 421      $metadata = array();
 422      if ( $is_core_block ) {
 423          $core_block_name = str_replace( ABSPATH . WPINC . '/blocks/', '', $file_or_folder );
 424          if ( ! empty( $core_blocks_meta[ $core_block_name ] ) ) {
 425              $metadata = $core_blocks_meta[ $core_block_name ];
 426          }
 427      }
 428  
 429      // If metadata is not found in the static cache, read it from the file.
 430      if ( $metadata_file_exists && empty( $metadata ) ) {
 431          $metadata = wp_json_file_decode( $metadata_file, array( 'associative' => true ) );
 432      }
 433  
 434      if ( ! is_array( $metadata ) || ( empty( $metadata['name'] ) && empty( $args['name'] ) ) ) {
 435          return false;
 436      }
 437  
 438      $metadata['file'] = $metadata_file_exists ? wp_normalize_path( realpath( $metadata_file ) ) : null;
 439  
 440      /**
 441       * Filters the metadata provided for registering a block type.
 442       *
 443       * @since 5.7.0
 444       *
 445       * @param array $metadata Metadata for registering a block type.
 446       */
 447      $metadata = apply_filters( 'block_type_metadata', $metadata );
 448  
 449      // Add `style` and `editor_style` for core blocks if missing.
 450      if ( ! empty( $metadata['name'] ) && str_starts_with( $metadata['name'], 'core/' ) ) {
 451          $block_name = str_replace( 'core/', '', $metadata['name'] );
 452  
 453          if ( ! isset( $metadata['style'] ) ) {
 454              $metadata['style'] = "wp-block-$block_name";
 455          }
 456          if ( current_theme_supports( 'wp-block-styles' ) && wp_should_load_separate_core_block_assets() ) {
 457              $metadata['style']   = (array) $metadata['style'];
 458              $metadata['style'][] = "wp-block-{$block_name}-theme";
 459          }
 460          if ( ! isset( $metadata['editorStyle'] ) ) {
 461              $metadata['editorStyle'] = "wp-block-{$block_name}-editor";
 462          }
 463      }
 464  
 465      $settings          = array();
 466      $property_mappings = array(
 467          'apiVersion'      => 'api_version',
 468          'name'            => 'name',
 469          'title'           => 'title',
 470          'category'        => 'category',
 471          'parent'          => 'parent',
 472          'ancestor'        => 'ancestor',
 473          'icon'            => 'icon',
 474          'description'     => 'description',
 475          'keywords'        => 'keywords',
 476          'attributes'      => 'attributes',
 477          'providesContext' => 'provides_context',
 478          'usesContext'     => 'uses_context',
 479          'selectors'       => 'selectors',
 480          'supports'        => 'supports',
 481          'styles'          => 'styles',
 482          'variations'      => 'variations',
 483          'example'         => 'example',
 484          'allowedBlocks'   => 'allowed_blocks',
 485      );
 486      $textdomain        = ! empty( $metadata['textdomain'] ) ? $metadata['textdomain'] : null;
 487      $i18n_schema       = get_block_metadata_i18n_schema();
 488  
 489      foreach ( $property_mappings as $key => $mapped_key ) {
 490          if ( isset( $metadata[ $key ] ) ) {
 491              $settings[ $mapped_key ] = $metadata[ $key ];
 492              if ( $metadata_file_exists && $textdomain && isset( $i18n_schema->$key ) ) {
 493                  $settings[ $mapped_key ] = translate_settings_using_i18n_schema( $i18n_schema->$key, $settings[ $key ], $textdomain );
 494              }
 495          }
 496      }
 497  
 498      if ( ! empty( $metadata['render'] ) ) {
 499          $template_path = wp_normalize_path(
 500              realpath(
 501                  dirname( $metadata['file'] ) . '/' .
 502                  remove_block_asset_path_prefix( $metadata['render'] )
 503              )
 504          );
 505          if ( $template_path ) {
 506              /**
 507               * Renders the block on the server.
 508               *
 509               * @since 6.1.0
 510               *
 511               * @param array    $attributes Block attributes.
 512               * @param string   $content    Block default content.
 513               * @param WP_Block $block      Block instance.
 514               *
 515               * @return string Returns the block content.
 516               */
 517              $settings['render_callback'] = static function ( $attributes, $content, $block ) use ( $template_path ) {
 518                  ob_start();
 519                  require $template_path;
 520                  return ob_get_clean();
 521              };
 522          }
 523      }
 524  
 525      $settings = array_merge( $settings, $args );
 526  
 527      $script_fields = array(
 528          'editorScript' => 'editor_script_handles',
 529          'script'       => 'script_handles',
 530          'viewScript'   => 'view_script_handles',
 531      );
 532      foreach ( $script_fields as $metadata_field_name => $settings_field_name ) {
 533          if ( ! empty( $settings[ $metadata_field_name ] ) ) {
 534              $metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ];
 535          }
 536          if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
 537              $scripts           = $metadata[ $metadata_field_name ];
 538              $processed_scripts = array();
 539              if ( is_array( $scripts ) ) {
 540                  for ( $index = 0; $index < count( $scripts ); $index++ ) {
 541                      $result = register_block_script_handle(
 542                          $metadata,
 543                          $metadata_field_name,
 544                          $index
 545                      );
 546                      if ( $result ) {
 547                          $processed_scripts[] = $result;
 548                      }
 549                  }
 550              } else {
 551                  $result = register_block_script_handle(
 552                      $metadata,
 553                      $metadata_field_name
 554                  );
 555                  if ( $result ) {
 556                      $processed_scripts[] = $result;
 557                  }
 558              }
 559              $settings[ $settings_field_name ] = $processed_scripts;
 560          }
 561      }
 562  
 563      $module_fields = array(
 564          'viewScriptModule' => 'view_script_module_ids',
 565      );
 566      foreach ( $module_fields as $metadata_field_name => $settings_field_name ) {
 567          if ( ! empty( $settings[ $metadata_field_name ] ) ) {
 568              $metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ];
 569          }
 570          if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
 571              $modules           = $metadata[ $metadata_field_name ];
 572              $processed_modules = array();
 573              if ( is_array( $modules ) ) {
 574                  for ( $index = 0; $index < count( $modules ); $index++ ) {
 575                      $result = register_block_script_module_id(
 576                          $metadata,
 577                          $metadata_field_name,
 578                          $index
 579                      );
 580                      if ( $result ) {
 581                          $processed_modules[] = $result;
 582                      }
 583                  }
 584              } else {
 585                  $result = register_block_script_module_id(
 586                      $metadata,
 587                      $metadata_field_name
 588                  );
 589                  if ( $result ) {
 590                      $processed_modules[] = $result;
 591                  }
 592              }
 593              $settings[ $settings_field_name ] = $processed_modules;
 594          }
 595      }
 596  
 597      $style_fields = array(
 598          'editorStyle' => 'editor_style_handles',
 599          'style'       => 'style_handles',
 600          'viewStyle'   => 'view_style_handles',
 601      );
 602      foreach ( $style_fields as $metadata_field_name => $settings_field_name ) {
 603          if ( ! empty( $settings[ $metadata_field_name ] ) ) {
 604              $metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ];
 605          }
 606          if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
 607              $styles           = $metadata[ $metadata_field_name ];
 608              $processed_styles = array();
 609              if ( is_array( $styles ) ) {
 610                  for ( $index = 0; $index < count( $styles ); $index++ ) {
 611                      $result = register_block_style_handle(
 612                          $metadata,
 613                          $metadata_field_name,
 614                          $index
 615                      );
 616                      if ( $result ) {
 617                          $processed_styles[] = $result;
 618                      }
 619                  }
 620              } else {
 621                  $result = register_block_style_handle(
 622                      $metadata,
 623                      $metadata_field_name
 624                  );
 625                  if ( $result ) {
 626                      $processed_styles[] = $result;
 627                  }
 628              }
 629              $settings[ $settings_field_name ] = $processed_styles;
 630          }
 631      }
 632  
 633      if ( ! empty( $metadata['blockHooks'] ) ) {
 634          /**
 635           * Map camelCased position string (from block.json) to snake_cased block type position.
 636           *
 637           * @var array
 638           */
 639          $position_mappings = array(
 640              'before'     => 'before',
 641              'after'      => 'after',
 642              'firstChild' => 'first_child',
 643              'lastChild'  => 'last_child',
 644          );
 645  
 646          $settings['block_hooks'] = array();
 647          foreach ( $metadata['blockHooks'] as $anchor_block_name => $position ) {
 648              // Avoid infinite recursion (hooking to itself).
 649              if ( $metadata['name'] === $anchor_block_name ) {
 650                  _doing_it_wrong(
 651                      __METHOD__,
 652                      __( 'Cannot hook block to itself.' ),
 653                      '6.4.0'
 654                  );
 655                  continue;
 656              }
 657  
 658              if ( ! isset( $position_mappings[ $position ] ) ) {
 659                  continue;
 660              }
 661  
 662              $settings['block_hooks'][ $anchor_block_name ] = $position_mappings[ $position ];
 663          }
 664      }
 665  
 666      /**
 667       * Filters the settings determined from the block type metadata.
 668       *
 669       * @since 5.7.0
 670       *
 671       * @param array $settings Array of determined settings for registering a block type.
 672       * @param array $metadata Metadata provided for registering a block type.
 673       */
 674      $settings = apply_filters( 'block_type_metadata_settings', $settings, $metadata );
 675  
 676      $metadata['name'] = ! empty( $settings['name'] ) ? $settings['name'] : $metadata['name'];
 677  
 678      return WP_Block_Type_Registry::get_instance()->register(
 679          $metadata['name'],
 680          $settings
 681      );
 682  }
 683  
 684  /**
 685   * Registers a block type. The recommended way is to register a block type using
 686   * the metadata stored in the `block.json` file.
 687   *
 688   * @since 5.0.0
 689   * @since 5.8.0 First parameter now accepts a path to the `block.json` file.
 690   *
 691   * @param string|WP_Block_Type $block_type Block type name including namespace, or alternatively
 692   *                                         a path to the JSON file with metadata definition for the block,
 693   *                                         or a path to the folder where the `block.json` file is located,
 694   *                                         or a complete WP_Block_Type instance.
 695   *                                         In case a WP_Block_Type is provided, the $args parameter will be ignored.
 696   * @param array                $args       Optional. Array of block type arguments. Accepts any public property
 697   *                                         of `WP_Block_Type`. See WP_Block_Type::__construct() for information
 698   *                                         on accepted arguments. Default empty array.
 699   *
 700   * @return WP_Block_Type|false The registered block type on success, or false on failure.
 701   */
 702  function register_block_type( $block_type, $args = array() ) {
 703      if ( is_string( $block_type ) && file_exists( $block_type ) ) {
 704          return register_block_type_from_metadata( $block_type, $args );
 705      }
 706  
 707      return WP_Block_Type_Registry::get_instance()->register( $block_type, $args );
 708  }
 709  
 710  /**
 711   * Unregisters a block type.
 712   *
 713   * @since 5.0.0
 714   *
 715   * @param string|WP_Block_Type $name Block type name including namespace, or alternatively
 716   *                                   a complete WP_Block_Type instance.
 717   * @return WP_Block_Type|false The unregistered block type on success, or false on failure.
 718   */
 719  function unregister_block_type( $name ) {
 720      return WP_Block_Type_Registry::get_instance()->unregister( $name );
 721  }
 722  
 723  /**
 724   * Determines whether a post or content string has blocks.
 725   *
 726   * This test optimizes for performance rather than strict accuracy, detecting
 727   * the pattern of a block but not validating its structure. For strict accuracy,
 728   * you should use the block parser on post content.
 729   *
 730   * @since 5.0.0
 731   *
 732   * @see parse_blocks()
 733   *
 734   * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object.
 735   *                                      Defaults to global $post.
 736   * @return bool Whether the post has blocks.
 737   */
 738  function has_blocks( $post = null ) {
 739      if ( ! is_string( $post ) ) {
 740          $wp_post = get_post( $post );
 741  
 742          if ( ! $wp_post instanceof WP_Post ) {
 743              return false;
 744          }
 745  
 746          $post = $wp_post->post_content;
 747      }
 748  
 749      return str_contains( (string) $post, '<!-- wp:' );
 750  }
 751  
 752  /**
 753   * Determines whether a $post or a string contains a specific block type.
 754   *
 755   * This test optimizes for performance rather than strict accuracy, detecting
 756   * whether the block type exists but not validating its structure and not checking
 757   * synced patterns (formerly called reusable blocks). For strict accuracy,
 758   * you should use the block parser on post content.
 759   *
 760   * @since 5.0.0
 761   *
 762   * @see parse_blocks()
 763   *
 764   * @param string                  $block_name Full block type to look for.
 765   * @param int|string|WP_Post|null $post       Optional. Post content, post ID, or post object.
 766   *                                            Defaults to global $post.
 767   * @return bool Whether the post content contains the specified block.
 768   */
 769  function has_block( $block_name, $post = null ) {
 770      if ( ! has_blocks( $post ) ) {
 771          return false;
 772      }
 773  
 774      if ( ! is_string( $post ) ) {
 775          $wp_post = get_post( $post );
 776          if ( $wp_post instanceof WP_Post ) {
 777              $post = $wp_post->post_content;
 778          }
 779      }
 780  
 781      /*
 782       * Normalize block name to include namespace, if provided as non-namespaced.
 783       * This matches behavior for WordPress 5.0.0 - 5.3.0 in matching blocks by
 784       * their serialized names.
 785       */
 786      if ( ! str_contains( $block_name, '/' ) ) {
 787          $block_name = 'core/' . $block_name;
 788      }
 789  
 790      // Test for existence of block by its fully qualified name.
 791      $has_block = str_contains( $post, '<!-- wp:' . $block_name . ' ' );
 792  
 793      if ( ! $has_block ) {
 794          /*
 795           * If the given block name would serialize to a different name, test for
 796           * existence by the serialized form.
 797           */
 798          $serialized_block_name = strip_core_block_namespace( $block_name );
 799          if ( $serialized_block_name !== $block_name ) {
 800              $has_block = str_contains( $post, '<!-- wp:' . $serialized_block_name . ' ' );
 801          }
 802      }
 803  
 804      return $has_block;
 805  }
 806  
 807  /**
 808   * Returns an array of the names of all registered dynamic block types.
 809   *
 810   * @since 5.0.0
 811   *
 812   * @return string[] Array of dynamic block names.
 813   */
 814  function get_dynamic_block_names() {
 815      $dynamic_block_names = array();
 816  
 817      $block_types = WP_Block_Type_Registry::get_instance()->get_all_registered();
 818      foreach ( $block_types as $block_type ) {
 819          if ( $block_type->is_dynamic() ) {
 820              $dynamic_block_names[] = $block_type->name;
 821          }
 822      }
 823  
 824      return $dynamic_block_names;
 825  }
 826  
 827  /**
 828   * Retrieves block types hooked into the given block, grouped by anchor block type and the relative position.
 829   *
 830   * @since 6.4.0
 831   *
 832   * @return array[] Array of block types grouped by anchor block type and the relative position.
 833   */
 834  function get_hooked_blocks() {
 835      $block_types   = WP_Block_Type_Registry::get_instance()->get_all_registered();
 836      $hooked_blocks = array();
 837      foreach ( $block_types as $block_type ) {
 838          if ( ! ( $block_type instanceof WP_Block_Type ) || ! is_array( $block_type->block_hooks ) ) {
 839              continue;
 840          }
 841          foreach ( $block_type->block_hooks as $anchor_block_type => $relative_position ) {
 842              if ( ! isset( $hooked_blocks[ $anchor_block_type ] ) ) {
 843                  $hooked_blocks[ $anchor_block_type ] = array();
 844              }
 845              if ( ! isset( $hooked_blocks[ $anchor_block_type ][ $relative_position ] ) ) {
 846                  $hooked_blocks[ $anchor_block_type ][ $relative_position ] = array();
 847              }
 848              $hooked_blocks[ $anchor_block_type ][ $relative_position ][] = $block_type->name;
 849          }
 850      }
 851  
 852      return $hooked_blocks;
 853  }
 854  
 855  /**
 856   * Returns the markup for blocks hooked to the given anchor block in a specific relative position.
 857   *
 858   * @since 6.5.0
 859   * @access private
 860   *
 861   * @param array                           $parsed_anchor_block The anchor block, in parsed block array format.
 862   * @param string                          $relative_position   The relative position of the hooked blocks.
 863   *                                                             Can be one of 'before', 'after', 'first_child', or 'last_child'.
 864   * @param array                           $hooked_blocks       An array of hooked block types, grouped by anchor block and relative position.
 865   * @param WP_Block_Template|WP_Post|array $context             The block template, template part, or pattern that the anchor block belongs to.
 866   * @return string
 867   */
 868  function insert_hooked_blocks( &$parsed_anchor_block, $relative_position, $hooked_blocks, $context ) {
 869      $anchor_block_type  = $parsed_anchor_block['blockName'];
 870      $hooked_block_types = isset( $hooked_blocks[ $anchor_block_type ][ $relative_position ] )
 871          ? $hooked_blocks[ $anchor_block_type ][ $relative_position ]
 872          : array();
 873  
 874      /**
 875       * Filters the list of hooked block types for a given anchor block type and relative position.
 876       *
 877       * @since 6.4.0
 878       *
 879       * @param string[]                        $hooked_block_types The list of hooked block types.
 880       * @param string                          $relative_position  The relative position of the hooked blocks.
 881       *                                                            Can be one of 'before', 'after', 'first_child', or 'last_child'.
 882       * @param string                          $anchor_block_type  The anchor block type.
 883       * @param WP_Block_Template|WP_Post|array $context            The block template, template part, `wp_navigation` post type,
 884       *                                                            or pattern that the anchor block belongs to.
 885       */
 886      $hooked_block_types = apply_filters( 'hooked_block_types', $hooked_block_types, $relative_position, $anchor_block_type, $context );
 887  
 888      $markup = '';
 889      foreach ( $hooked_block_types as $hooked_block_type ) {
 890          $parsed_hooked_block = array(
 891              'blockName'    => $hooked_block_type,
 892              'attrs'        => array(),
 893              'innerBlocks'  => array(),
 894              'innerContent' => array(),
 895          );
 896  
 897          /**
 898           * Filters the parsed block array for a given hooked block.
 899           *
 900           * @since 6.5.0
 901           *
 902           * @param array|null                      $parsed_hooked_block The parsed block array for the given hooked block type, or null to suppress the block.
 903           * @param string                          $hooked_block_type   The hooked block type name.
 904           * @param string                          $relative_position   The relative position of the hooked block.
 905           * @param array                           $parsed_anchor_block The anchor block, in parsed block array format.
 906           * @param WP_Block_Template|WP_Post|array $context             The block template, template part, `wp_navigation` post type,
 907           *                                                             or pattern that the anchor block belongs to.
 908           */
 909          $parsed_hooked_block = apply_filters( 'hooked_block', $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context );
 910  
 911          /**
 912           * Filters the parsed block array for a given hooked block.
 913           *
 914           * The dynamic portion of the hook name, `$hooked_block_type`, refers to the block type name of the specific hooked block.
 915           *
 916           * @since 6.5.0
 917           *
 918           * @param array|null                      $parsed_hooked_block The parsed block array for the given hooked block type, or null to suppress the block.
 919           * @param string                          $hooked_block_type   The hooked block type name.
 920           * @param string                          $relative_position   The relative position of the hooked block.
 921           * @param array                           $parsed_anchor_block The anchor block, in parsed block array format.
 922           * @param WP_Block_Template|WP_Post|array $context             The block template, template part, `wp_navigation` post type,
 923           *                                                             or pattern that the anchor block belongs to.
 924           */
 925          $parsed_hooked_block = apply_filters( "hooked_block_{$hooked_block_type}", $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context );
 926  
 927          if ( null === $parsed_hooked_block ) {
 928              continue;
 929          }
 930  
 931          // It's possible that the filter returned a block of a different type, so we explicitly
 932          // look for the original `$hooked_block_type` in the `ignoredHookedBlocks` metadata.
 933          if (
 934              ! isset( $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] ) ||
 935              ! in_array( $hooked_block_type, $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'], true )
 936          ) {
 937              $markup .= serialize_block( $parsed_hooked_block );
 938          }
 939      }
 940  
 941      return $markup;
 942  }
 943  
 944  /**
 945   * Adds a list of hooked block types to an anchor block's ignored hooked block types.
 946   *
 947   * This function is meant for internal use only.
 948   *
 949   * @since 6.5.0
 950   * @access private
 951   *
 952   * @param array                           $parsed_anchor_block The anchor block, in parsed block array format.
 953   * @param string                          $relative_position   The relative position of the hooked blocks.
 954   *                                                             Can be one of 'before', 'after', 'first_child', or 'last_child'.
 955   * @param array                           $hooked_blocks       An array of hooked block types, grouped by anchor block and relative position.
 956   * @param WP_Block_Template|WP_Post|array $context             The block template, template part, or pattern that the anchor block belongs to.
 957   * @return string Empty string.
 958   */
 959  function set_ignored_hooked_blocks_metadata( &$parsed_anchor_block, $relative_position, $hooked_blocks, $context ) {
 960      $anchor_block_type  = $parsed_anchor_block['blockName'];
 961      $hooked_block_types = isset( $hooked_blocks[ $anchor_block_type ][ $relative_position ] )
 962          ? $hooked_blocks[ $anchor_block_type ][ $relative_position ]
 963          : array();
 964  
 965      /** This filter is documented in wp-includes/blocks.php */
 966      $hooked_block_types = apply_filters( 'hooked_block_types', $hooked_block_types, $relative_position, $anchor_block_type, $context );
 967      if ( empty( $hooked_block_types ) ) {
 968          return '';
 969      }
 970  
 971      foreach ( $hooked_block_types as $index => $hooked_block_type ) {
 972          $parsed_hooked_block = array(
 973              'blockName'    => $hooked_block_type,
 974              'attrs'        => array(),
 975              'innerBlocks'  => array(),
 976              'innerContent' => array(),
 977          );
 978  
 979          /** This filter is documented in wp-includes/blocks.php */
 980          $parsed_hooked_block = apply_filters( 'hooked_block', $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context );
 981  
 982          /** This filter is documented in wp-includes/blocks.php */
 983          $parsed_hooked_block = apply_filters( "hooked_block_{$hooked_block_type}", $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context );
 984  
 985          if ( null === $parsed_hooked_block ) {
 986              unset( $hooked_block_types[ $index ] );
 987          }
 988      }
 989  
 990      $previously_ignored_hooked_blocks = isset( $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] )
 991          ? $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks']
 992          : array();
 993  
 994      $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] = array_unique(
 995          array_merge(
 996              $previously_ignored_hooked_blocks,
 997              $hooked_block_types
 998          )
 999      );
1000  
1001      // Markup for the hooked blocks has already been created (in `insert_hooked_blocks`).
1002      return '';
1003  }
1004  
1005  /**
1006   * Runs the hooked blocks algorithm on the given content.
1007   *
1008   * @since 6.6.0
1009   * @access private
1010   *
1011   * @param string                          $content  Serialized content.
1012   * @param WP_Block_Template|WP_Post|array $context  A block template, template part, `wp_navigation` post object,
1013   *                                                  or pattern that the blocks belong to.
1014   * @param callable                        $callback A function that will be called for each block to generate
1015   *                                                  the markup for a given list of blocks that are hooked to it.
1016   *                                                  Default: 'insert_hooked_blocks'.
1017   * @return string The serialized markup.
1018   */
1019  function apply_block_hooks_to_content( $content, $context, $callback = 'insert_hooked_blocks' ) {
1020      $hooked_blocks = get_hooked_blocks();
1021      if ( empty( $hooked_blocks ) && ! has_filter( 'hooked_block_types' ) ) {
1022          return $content;
1023      }
1024  
1025      $blocks = parse_blocks( $content );
1026  
1027      $before_block_visitor = make_before_block_visitor( $hooked_blocks, $context, $callback );
1028      $after_block_visitor  = make_after_block_visitor( $hooked_blocks, $context, $callback );
1029  
1030      return traverse_and_serialize_blocks( $blocks, $before_block_visitor, $after_block_visitor );
1031  }
1032  
1033  /**
1034   * Accepts the serialized markup of a block and its inner blocks, and returns serialized markup of the inner blocks.
1035   *
1036   * @since 6.6.0
1037   * @access private
1038   *
1039   * @param string $serialized_block The serialized markup of a block and its inner blocks.
1040   * @return string The serialized markup of the inner blocks.
1041   */
1042  function remove_serialized_parent_block( $serialized_block ) {
1043      $start = strpos( $serialized_block, '-->' ) + strlen( '-->' );
1044      $end   = strrpos( $serialized_block, '<!--' );
1045      return substr( $serialized_block, $start, $end - $start );
1046  }
1047  
1048  /**
1049   * Accepts the serialized markup of a block and its inner blocks, and returns serialized markup of the wrapper block.
1050   *
1051   * @since 6.7.0
1052   * @access private
1053   *
1054   * @see remove_serialized_parent_block()
1055   *
1056   * @param string $serialized_block The serialized markup of a block and its inner blocks.
1057   * @return string The serialized markup of the wrapper block.
1058   */
1059  function extract_serialized_parent_block( $serialized_block ) {
1060      $start = strpos( $serialized_block, '-->' ) + strlen( '-->' );
1061      $end   = strrpos( $serialized_block, '<!--' );
1062      return substr( $serialized_block, 0, $start ) . substr( $serialized_block, $end );
1063  }
1064  
1065  /**
1066   * Updates the wp_postmeta with the list of ignored hooked blocks where the inner blocks are stored as post content.
1067   * Currently only supports `wp_navigation` post types.
1068   *
1069   * @since 6.6.0
1070   * @access private
1071   *
1072   * @param stdClass $post Post object.
1073   * @return stdClass The updated post object.
1074   */
1075  function update_ignored_hooked_blocks_postmeta( $post ) {
1076      /*
1077       * In this scenario the user has likely tried to create a navigation via the REST API.
1078       * In which case we won't have a post ID to work with and store meta against.
1079       */
1080      if ( empty( $post->ID ) ) {
1081          return $post;
1082      }
1083  
1084      /*
1085       * Skip meta generation when consumers intentionally update specific Navigation fields
1086       * and omit the content update.
1087       */
1088      if ( ! isset( $post->post_content ) ) {
1089          return $post;
1090      }
1091  
1092      /*
1093       * Skip meta generation when the post content is not a navigation block.
1094       */
1095      if ( ! isset( $post->post_type ) || 'wp_navigation' !== $post->post_type ) {
1096          return $post;
1097      }
1098  
1099      $attributes = array();
1100  
1101      $ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true );
1102      if ( ! empty( $ignored_hooked_blocks ) ) {
1103          $ignored_hooked_blocks  = json_decode( $ignored_hooked_blocks, true );
1104          $attributes['metadata'] = array(
1105              'ignoredHookedBlocks' => $ignored_hooked_blocks,
1106          );
1107      }
1108  
1109      $markup = get_comment_delimited_block_content(
1110          'core/navigation',
1111          $attributes,
1112          $post->post_content
1113      );
1114  
1115      $existing_post = get_post( $post->ID );
1116      // Merge the existing post object with the updated post object to pass to the block hooks algorithm for context.
1117      $context          = (object) array_merge( (array) $existing_post, (array) $post );
1118      $serialized_block = apply_block_hooks_to_content( $markup, $context, 'set_ignored_hooked_blocks_metadata' );
1119      $root_block       = parse_blocks( $serialized_block )[0];
1120  
1121      $ignored_hooked_blocks = isset( $root_block['attrs']['metadata']['ignoredHookedBlocks'] )
1122          ? $root_block['attrs']['metadata']['ignoredHookedBlocks']
1123          : array();
1124  
1125      if ( ! empty( $ignored_hooked_blocks ) ) {
1126          $existing_ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true );
1127          if ( ! empty( $existing_ignored_hooked_blocks ) ) {
1128              $existing_ignored_hooked_blocks = json_decode( $existing_ignored_hooked_blocks, true );
1129              $ignored_hooked_blocks          = array_unique( array_merge( $ignored_hooked_blocks, $existing_ignored_hooked_blocks ) );
1130          }
1131  
1132          if ( ! isset( $post->meta_input ) ) {
1133              $post->meta_input = array();
1134          }
1135          $post->meta_input['_wp_ignored_hooked_blocks'] = json_encode( $ignored_hooked_blocks );
1136      }
1137  
1138      $post->post_content = remove_serialized_parent_block( $serialized_block );
1139      return $post;
1140  }
1141  
1142  /**
1143   * Returns the markup for blocks hooked to the given anchor block in a specific relative position and then
1144   * adds a list of hooked block types to an anchor block's ignored hooked block types.
1145   *
1146   * This function is meant for internal use only.
1147   *
1148   * @since 6.6.0
1149   * @access private
1150   *
1151   * @param array                           $parsed_anchor_block The anchor block, in parsed block array format.
1152   * @param string                          $relative_position   The relative position of the hooked blocks.
1153   *                                                             Can be one of 'before', 'after', 'first_child', or 'last_child'.
1154   * @param array                           $hooked_blocks       An array of hooked block types, grouped by anchor block and relative position.
1155   * @param WP_Block_Template|WP_Post|array $context             The block template, template part, or pattern that the anchor block belongs to.
1156   * @return string
1157   */
1158  function insert_hooked_blocks_and_set_ignored_hooked_blocks_metadata( &$parsed_anchor_block, $relative_position, $hooked_blocks, $context ) {
1159      $markup  = insert_hooked_blocks( $parsed_anchor_block, $relative_position, $hooked_blocks, $context );
1160      $markup .= set_ignored_hooked_blocks_metadata( $parsed_anchor_block, $relative_position, $hooked_blocks, $context );
1161  
1162      return $markup;
1163  }
1164  
1165  /**
1166   * Hooks into the REST API response for the core/navigation block and adds the first and last inner blocks.
1167   *
1168   * @since 6.6.0
1169   *
1170   * @param WP_REST_Response $response The response object.
1171   * @param WP_Post          $post     Post object.
1172   * @return WP_REST_Response The response object.
1173   */
1174  function insert_hooked_blocks_into_rest_response( $response, $post ) {
1175      if ( ! isset( $response->data['content']['raw'] ) || ! isset( $response->data['content']['rendered'] ) ) {
1176          return $response;
1177      }
1178  
1179      $attributes            = array();
1180      $ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true );
1181      if ( ! empty( $ignored_hooked_blocks ) ) {
1182          $ignored_hooked_blocks  = json_decode( $ignored_hooked_blocks, true );
1183          $attributes['metadata'] = array(
1184              'ignoredHookedBlocks' => $ignored_hooked_blocks,
1185          );
1186      }
1187      $content = get_comment_delimited_block_content(
1188          'core/navigation',
1189          $attributes,
1190          $response->data['content']['raw']
1191      );
1192  
1193      $content = apply_block_hooks_to_content( $content, $post );
1194  
1195      // Remove mock Navigation block wrapper.
1196      $content = remove_serialized_parent_block( $content );
1197  
1198      $response->data['content']['raw'] = $content;
1199  
1200      /** This filter is documented in wp-includes/post-template.php */
1201      $response->data['content']['rendered'] = apply_filters( 'the_content', $content );
1202  
1203      return $response;
1204  }
1205  
1206  /**
1207   * Returns a function that injects the theme attribute into, and hooked blocks before, a given block.
1208   *
1209   * The returned function can be used as `$pre_callback` argument to `traverse_and_serialize_block(s)`,
1210   * where it will inject the `theme` attribute into all Template Part blocks, and prepend the markup for
1211   * any blocks hooked `before` the given block and as its parent's `first_child`, respectively.
1212   *
1213   * This function is meant for internal use only.
1214   *
1215   * @since 6.4.0
1216   * @since 6.5.0 Added $callback argument.
1217   * @access private
1218   *
1219   * @param array                           $hooked_blocks An array of blocks hooked to another given block.
1220   * @param WP_Block_Template|WP_Post|array $context       A block template, template part, `wp_navigation` post object,
1221   *                                                       or pattern that the blocks belong to.
1222   * @param callable                        $callback      A function that will be called for each block to generate
1223   *                                                       the markup for a given list of blocks that are hooked to it.
1224   *                                                       Default: 'insert_hooked_blocks'.
1225   * @return callable A function that returns the serialized markup for the given block,
1226   *                  including the markup for any hooked blocks before it.
1227   */
1228  function make_before_block_visitor( $hooked_blocks, $context, $callback = 'insert_hooked_blocks' ) {
1229      /**
1230       * Injects hooked blocks before the given block, injects the `theme` attribute into Template Part blocks, and returns the serialized markup.
1231       *
1232       * If the current block is a Template Part block, inject the `theme` attribute.
1233       * Furthermore, prepend the markup for any blocks hooked `before` the given block and as its parent's
1234       * `first_child`, respectively, to the serialized markup for the given block.
1235       *
1236       * @param array $block        The block to inject the theme attribute into, and hooked blocks before. Passed by reference.
1237       * @param array $parent_block The parent block of the given block. Passed by reference. Default null.
1238       * @param array $prev         The previous sibling block of the given block. Default null.
1239       * @return string The serialized markup for the given block, with the markup for any hooked blocks prepended to it.
1240       */
1241      return function ( &$block, &$parent_block = null, $prev = null ) use ( $hooked_blocks, $context, $callback ) {
1242          _inject_theme_attribute_in_template_part_block( $block );
1243  
1244          $markup = '';
1245  
1246          if ( $parent_block && ! $prev ) {
1247              // Candidate for first-child insertion.
1248              $markup .= call_user_func_array(
1249                  $callback,
1250                  array( &$parent_block, 'first_child', $hooked_blocks, $context )
1251              );
1252          }
1253  
1254          $markup .= call_user_func_array(
1255              $callback,
1256              array( &$block, 'before', $hooked_blocks, $context )
1257          );
1258  
1259          return $markup;
1260      };
1261  }
1262  
1263  /**
1264   * Returns a function that injects the hooked blocks after a given block.
1265   *
1266   * The returned function can be used as `$post_callback` argument to `traverse_and_serialize_block(s)`,
1267   * where it will append the markup for any blocks hooked `after` the given block and as its parent's
1268   * `last_child`, respectively.
1269   *
1270   * This function is meant for internal use only.
1271   *
1272   * @since 6.4.0
1273   * @since 6.5.0 Added $callback argument.
1274   * @access private
1275   *
1276   * @param array                           $hooked_blocks An array of blocks hooked to another block.
1277   * @param WP_Block_Template|WP_Post|array $context       A block template, template part, `wp_navigation` post object,
1278   *                                                       or pattern that the blocks belong to.
1279   * @param callable                        $callback      A function that will be called for each block to generate
1280   *                                                       the markup for a given list of blocks that are hooked to it.
1281   *                                                       Default: 'insert_hooked_blocks'.
1282   * @return callable A function that returns the serialized markup for the given block,
1283   *                  including the markup for any hooked blocks after it.
1284   */
1285  function make_after_block_visitor( $hooked_blocks, $context, $callback = 'insert_hooked_blocks' ) {
1286      /**
1287       * Injects hooked blocks after the given block, and returns the serialized markup.
1288       *
1289       * Append the markup for any blocks hooked `after` the given block and as its parent's
1290       * `last_child`, respectively, to the serialized markup for the given block.
1291       *
1292       * @param array $block        The block to inject the hooked blocks after. Passed by reference.
1293       * @param array $parent_block The parent block of the given block. Passed by reference. Default null.
1294       * @param array $next         The next sibling block of the given block. Default null.
1295       * @return string The serialized markup for the given block, with the markup for any hooked blocks appended to it.
1296       */
1297      return function ( &$block, &$parent_block = null, $next = null ) use ( $hooked_blocks, $context, $callback ) {
1298          $markup = call_user_func_array(
1299              $callback,
1300              array( &$block, 'after', $hooked_blocks, $context )
1301          );
1302  
1303          if ( $parent_block && ! $next ) {
1304              // Candidate for last-child insertion.
1305              $markup .= call_user_func_array(
1306                  $callback,
1307                  array( &$parent_block, 'last_child', $hooked_blocks, $context )
1308              );
1309          }
1310  
1311          return $markup;
1312      };
1313  }
1314  
1315  /**
1316   * Given an array of attributes, returns a string in the serialized attributes
1317   * format prepared for post content.
1318   *
1319   * The serialized result is a JSON-encoded string, with unicode escape sequence
1320   * substitution for characters which might otherwise interfere with embedding
1321   * the result in an HTML comment.
1322   *
1323   * This function must produce output that remains in sync with the output of
1324   * the serializeAttributes JavaScript function in the block editor in order
1325   * to ensure consistent operation between PHP and JavaScript.
1326   *
1327   * @since 5.3.1
1328   *
1329   * @param array $block_attributes Attributes object.
1330   * @return string Serialized attributes.
1331   */
1332  function serialize_block_attributes( $block_attributes ) {
1333      $encoded_attributes = wp_json_encode( $block_attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
1334      $encoded_attributes = preg_replace( '/--/', '\\u002d\\u002d', $encoded_attributes );
1335      $encoded_attributes = preg_replace( '/</', '\\u003c', $encoded_attributes );
1336      $encoded_attributes = preg_replace( '/>/', '\\u003e', $encoded_attributes );
1337      $encoded_attributes = preg_replace( '/&/', '\\u0026', $encoded_attributes );
1338      // Regex: /\\"/
1339      $encoded_attributes = preg_replace( '/\\\\"/', '\\u0022', $encoded_attributes );
1340  
1341      return $encoded_attributes;
1342  }
1343  
1344  /**
1345   * Returns the block name to use for serialization. This will remove the default
1346   * "core/" namespace from a block name.
1347   *
1348   * @since 5.3.1
1349   *
1350   * @param string|null $block_name Optional. Original block name. Null if the block name is unknown,
1351   *                                e.g. Classic blocks have their name set to null. Default null.
1352   * @return string Block name to use for serialization.
1353   */
1354  function strip_core_block_namespace( $block_name = null ) {
1355      if ( is_string( $block_name ) && str_starts_with( $block_name, 'core/' ) ) {
1356          return substr( $block_name, 5 );
1357      }
1358  
1359      return $block_name;
1360  }
1361  
1362  /**
1363   * Returns the content of a block, including comment delimiters.
1364   *
1365   * @since 5.3.1
1366   *
1367   * @param string|null $block_name       Block name. Null if the block name is unknown,
1368   *                                      e.g. Classic blocks have their name set to null.
1369   * @param array       $block_attributes Block attributes.
1370   * @param string      $block_content    Block save content.
1371   * @return string Comment-delimited block content.
1372   */
1373  function get_comment_delimited_block_content( $block_name, $block_attributes, $block_content ) {
1374      if ( is_null( $block_name ) ) {
1375          return $block_content;
1376      }
1377  
1378      $serialized_block_name = strip_core_block_namespace( $block_name );
1379      $serialized_attributes = empty( $block_attributes ) ? '' : serialize_block_attributes( $block_attributes ) . ' ';
1380  
1381      if ( empty( $block_content ) ) {
1382          return sprintf( '<!-- wp:%s %s/-->', $serialized_block_name, $serialized_attributes );
1383      }
1384  
1385      return sprintf(
1386          '<!-- wp:%s %s-->%s<!-- /wp:%s -->',
1387          $serialized_block_name,
1388          $serialized_attributes,
1389          $block_content,
1390          $serialized_block_name
1391      );
1392  }
1393  
1394  /**
1395   * Returns the content of a block, including comment delimiters, serializing all
1396   * attributes from the given parsed block.
1397   *
1398   * This should be used when preparing a block to be saved to post content.
1399   * Prefer `render_block` when preparing a block for display. Unlike
1400   * `render_block`, this does not evaluate a block's `render_callback`, and will
1401   * instead preserve the markup as parsed.
1402   *
1403   * @since 5.3.1
1404   *
1405   * @param array $block {
1406   *     A representative array of a single parsed block object. See WP_Block_Parser_Block.
1407   *
1408   *     @type string   $blockName    Name of block.
1409   *     @type array    $attrs        Attributes from block comment delimiters.
1410   *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
1411   *                                  have the same structure as this one.
1412   *     @type string   $innerHTML    HTML from inside block comment delimiters.
1413   *     @type array    $innerContent List of string fragments and null markers where
1414   *                                  inner blocks were found.
1415   * }
1416   * @return string String of rendered HTML.
1417   */
1418  function serialize_block( $block ) {
1419      $block_content = '';
1420  
1421      $index = 0;
1422      foreach ( $block['innerContent'] as $chunk ) {
1423          $block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ] );
1424      }
1425  
1426      if ( ! is_array( $block['attrs'] ) ) {
1427          $block['attrs'] = array();
1428      }
1429  
1430      return get_comment_delimited_block_content(
1431          $block['blockName'],
1432          $block['attrs'],
1433          $block_content
1434      );
1435  }
1436  
1437  /**
1438   * Returns a joined string of the aggregate serialization of the given
1439   * parsed blocks.
1440   *
1441   * @since 5.3.1
1442   *
1443   * @param array[] $blocks {
1444   *     Array of block structures.
1445   *
1446   *     @type array ...$0 {
1447   *         A representative array of a single parsed block object. See WP_Block_Parser_Block.
1448   *
1449   *         @type string   $blockName    Name of block.
1450   *         @type array    $attrs        Attributes from block comment delimiters.
1451   *         @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
1452   *                                      have the same structure as this one.
1453   *         @type string   $innerHTML    HTML from inside block comment delimiters.
1454   *         @type array    $innerContent List of string fragments and null markers where
1455   *                                      inner blocks were found.
1456   *     }
1457   * }
1458   * @return string String of rendered HTML.
1459   */
1460  function serialize_blocks( $blocks ) {
1461      return implode( '', array_map( 'serialize_block', $blocks ) );
1462  }
1463  
1464  /**
1465   * Traverses a parsed block tree and applies callbacks before and after serializing it.
1466   *
1467   * Recursively traverses the block and its inner blocks and applies the two callbacks provided as
1468   * arguments, the first one before serializing the block, and the second one after serializing it.
1469   * If either callback returns a string value, it will be prepended and appended to the serialized
1470   * block markup, respectively.
1471   *
1472   * The callbacks will receive a reference to the current block as their first argument, so that they
1473   * can also modify it, and the current block's parent block as second argument. Finally, the
1474   * `$pre_callback` receives the previous block, whereas the `$post_callback` receives
1475   * the next block as third argument.
1476   *
1477   * Serialized blocks are returned including comment delimiters, and with all attributes serialized.
1478   *
1479   * This function should be used when there is a need to modify the saved block, or to inject markup
1480   * into the return value. Prefer `serialize_block` when preparing a block to be saved to post content.
1481   *
1482   * This function is meant for internal use only.
1483   *
1484   * @since 6.4.0
1485   * @access private
1486   *
1487   * @see serialize_block()
1488   *
1489   * @param array    $block         A representative array of a single parsed block object. See WP_Block_Parser_Block.
1490   * @param callable $pre_callback  Callback to run on each block in the tree before it is traversed and serialized.
1491   *                                It is called with the following arguments: &$block, $parent_block, $previous_block.
1492   *                                Its string return value will be prepended to the serialized block markup.
1493   * @param callable $post_callback Callback to run on each block in the tree after it is traversed and serialized.
1494   *                                It is called with the following arguments: &$block, $parent_block, $next_block.
1495   *                                Its string return value will be appended to the serialized block markup.
1496   * @return string Serialized block markup.
1497   */
1498  function traverse_and_serialize_block( $block, $pre_callback = null, $post_callback = null ) {
1499      $block_content = '';
1500      $block_index   = 0;
1501  
1502      foreach ( $block['innerContent'] as $chunk ) {
1503          if ( is_string( $chunk ) ) {
1504              $block_content .= $chunk;
1505          } else {
1506              $inner_block = $block['innerBlocks'][ $block_index ];
1507  
1508              if ( is_callable( $pre_callback ) ) {
1509                  $prev = 0 === $block_index
1510                      ? null
1511                      : $block['innerBlocks'][ $block_index - 1 ];
1512  
1513                  $block_content .= call_user_func_array(
1514                      $pre_callback,
1515                      array( &$inner_block, &$block, $prev )
1516                  );
1517              }
1518  
1519              if ( is_callable( $post_callback ) ) {
1520                  $next = count( $block['innerBlocks'] ) - 1 === $block_index
1521                      ? null
1522                      : $block['innerBlocks'][ $block_index + 1 ];
1523  
1524                  $post_markup = call_user_func_array(
1525                      $post_callback,
1526                      array( &$inner_block, &$block, $next )
1527                  );
1528              }
1529  
1530              $block_content .= traverse_and_serialize_block( $inner_block, $pre_callback, $post_callback );
1531              $block_content .= isset( $post_markup ) ? $post_markup : '';
1532  
1533              ++$block_index;
1534          }
1535      }
1536  
1537      if ( ! is_array( $block['attrs'] ) ) {
1538          $block['attrs'] = array();
1539      }
1540  
1541      return get_comment_delimited_block_content(
1542          $block['blockName'],
1543          $block['attrs'],
1544          $block_content
1545      );
1546  }
1547  
1548  /**
1549   * Replaces patterns in a block tree with their content.
1550   *
1551   * @since 6.6.0
1552   *
1553   * @param array $blocks An array blocks.
1554   *
1555   * @return array An array of blocks with patterns replaced by their content.
1556   */
1557  function resolve_pattern_blocks( $blocks ) {
1558      static $inner_content;
1559      // Keep track of seen references to avoid infinite loops.
1560      static $seen_refs = array();
1561      $i                = 0;
1562      while ( $i < count( $blocks ) ) {
1563          if ( 'core/pattern' === $blocks[ $i ]['blockName'] ) {
1564              $attrs = $blocks[ $i ]['attrs'];
1565  
1566              if ( empty( $attrs['slug'] ) ) {
1567                  ++$i;
1568                  continue;
1569              }
1570  
1571              $slug = $attrs['slug'];
1572  
1573              if ( isset( $seen_refs[ $slug ] ) ) {
1574                  // Skip recursive patterns.
1575                  array_splice( $blocks, $i, 1 );
1576                  continue;
1577              }
1578  
1579              $registry = WP_Block_Patterns_Registry::get_instance();
1580              $pattern  = $registry->get_registered( $slug );
1581  
1582              // Skip unknown patterns.
1583              if ( ! $pattern ) {
1584                  ++$i;
1585                  continue;
1586              }
1587  
1588              $blocks_to_insert   = parse_blocks( $pattern['content'] );
1589              $seen_refs[ $slug ] = true;
1590              $prev_inner_content = $inner_content;
1591              $inner_content      = null;
1592              $blocks_to_insert   = resolve_pattern_blocks( $blocks_to_insert );
1593              $inner_content      = $prev_inner_content;
1594              unset( $seen_refs[ $slug ] );
1595              array_splice( $blocks, $i, 1, $blocks_to_insert );
1596  
1597              // If we have inner content, we need to insert nulls in the
1598              // inner content array, otherwise serialize_blocks will skip
1599              // blocks.
1600              if ( $inner_content ) {
1601                  $null_indices  = array_keys( $inner_content, null, true );
1602                  $content_index = $null_indices[ $i ];
1603                  $nulls         = array_fill( 0, count( $blocks_to_insert ), null );
1604                  array_splice( $inner_content, $content_index, 1, $nulls );
1605              }
1606  
1607              // Skip inserted blocks.
1608              $i += count( $blocks_to_insert );
1609          } else {
1610              if ( ! empty( $blocks[ $i ]['innerBlocks'] ) ) {
1611                  $prev_inner_content           = $inner_content;
1612                  $inner_content                = $blocks[ $i ]['innerContent'];
1613                  $blocks[ $i ]['innerBlocks']  = resolve_pattern_blocks(
1614                      $blocks[ $i ]['innerBlocks']
1615                  );
1616                  $blocks[ $i ]['innerContent'] = $inner_content;
1617                  $inner_content                = $prev_inner_content;
1618              }
1619              ++$i;
1620          }
1621      }
1622      return $blocks;
1623  }
1624  
1625  /**
1626   * Given an array of parsed block trees, applies callbacks before and after serializing them and
1627   * returns their concatenated output.
1628   *
1629   * Recursively traverses the blocks and their inner blocks and applies the two callbacks provided as
1630   * arguments, the first one before serializing a block, and the second one after serializing.
1631   * If either callback returns a string value, it will be prepended and appended to the serialized
1632   * block markup, respectively.
1633   *
1634   * The callbacks will receive a reference to the current block as their first argument, so that they
1635   * can also modify it, and the current block's parent block as second argument. Finally, the
1636   * `$pre_callback` receives the previous block, whereas the `$post_callback` receives
1637   * the next block as third argument.
1638   *
1639   * Serialized blocks are returned including comment delimiters, and with all attributes serialized.
1640   *
1641   * This function should be used when there is a need to modify the saved blocks, or to inject markup
1642   * into the return value. Prefer `serialize_blocks` when preparing blocks to be saved to post content.
1643   *
1644   * This function is meant for internal use only.
1645   *
1646   * @since 6.4.0
1647   * @access private
1648   *
1649   * @see serialize_blocks()
1650   *
1651   * @param array[]  $blocks        An array of parsed blocks. See WP_Block_Parser_Block.
1652   * @param callable $pre_callback  Callback to run on each block in the tree before it is traversed and serialized.
1653   *                                It is called with the following arguments: &$block, $parent_block, $previous_block.
1654   *                                Its string return value will be prepended to the serialized block markup.
1655   * @param callable $post_callback Callback to run on each block in the tree after it is traversed and serialized.
1656   *                                It is called with the following arguments: &$block, $parent_block, $next_block.
1657   *                                Its string return value will be appended to the serialized block markup.
1658   * @return string Serialized block markup.
1659   */
1660  function traverse_and_serialize_blocks( $blocks, $pre_callback = null, $post_callback = null ) {
1661      $result       = '';
1662      $parent_block = null; // At the top level, there is no parent block to pass to the callbacks; yet the callbacks expect a reference.
1663  
1664      foreach ( $blocks as $index => $block ) {
1665          if ( is_callable( $pre_callback ) ) {
1666              $prev = 0 === $index
1667                  ? null
1668                  : $blocks[ $index - 1 ];
1669  
1670              $result .= call_user_func_array(
1671                  $pre_callback,
1672                  array( &$block, &$parent_block, $prev )
1673              );
1674          }
1675  
1676          if ( is_callable( $post_callback ) ) {
1677              $next = count( $blocks ) - 1 === $index
1678                  ? null
1679                  : $blocks[ $index + 1 ];
1680  
1681              $post_markup = call_user_func_array(
1682                  $post_callback,
1683                  array( &$block, &$parent_block, $next )
1684              );
1685          }
1686  
1687          $result .= traverse_and_serialize_block( $block, $pre_callback, $post_callback );
1688          $result .= isset( $post_markup ) ? $post_markup : '';
1689      }
1690  
1691      return $result;
1692  }
1693  
1694  /**
1695   * Filters and sanitizes block content to remove non-allowable HTML
1696   * from parsed block attribute values.
1697   *
1698   * @since 5.3.1
1699   *
1700   * @param string         $text              Text that may contain block content.
1701   * @param array[]|string $allowed_html      Optional. An array of allowed HTML elements and attributes,
1702   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
1703   *                                          for the list of accepted context names. Default 'post'.
1704   * @param string[]       $allowed_protocols Optional. Array of allowed URL protocols.
1705   *                                          Defaults to the result of wp_allowed_protocols().
1706   * @return string The filtered and sanitized content result.
1707   */
1708  function filter_block_content( $text, $allowed_html = 'post', $allowed_protocols = array() ) {
1709      $result = '';
1710  
1711      if ( str_contains( $text, '<!--' ) && str_contains( $text, '--->' ) ) {
1712          $text = preg_replace_callback( '%<!--(.*?)--->%', '_filter_block_content_callback', $text );
1713      }
1714  
1715      $blocks = parse_blocks( $text );
1716      foreach ( $blocks as $block ) {
1717          $block   = filter_block_kses( $block, $allowed_html, $allowed_protocols );
1718          $result .= serialize_block( $block );
1719      }
1720  
1721      return $result;
1722  }
1723  
1724  /**
1725   * Callback used for regular expression replacement in filter_block_content().
1726   *
1727   * @since 6.2.1
1728   * @access private
1729   *
1730   * @param array $matches Array of preg_replace_callback matches.
1731   * @return string Replacement string.
1732   */
1733  function _filter_block_content_callback( $matches ) {
1734      return '<!--' . rtrim( $matches[1], '-' ) . '-->';
1735  }
1736  
1737  /**
1738   * Filters and sanitizes a parsed block to remove non-allowable HTML
1739   * from block attribute values.
1740   *
1741   * @since 5.3.1
1742   *
1743   * @param WP_Block_Parser_Block $block             The parsed block object.
1744   * @param array[]|string        $allowed_html      An array of allowed HTML elements and attributes,
1745   *                                                 or a context name such as 'post'. See wp_kses_allowed_html()
1746   *                                                 for the list of accepted context names.
1747   * @param string[]              $allowed_protocols Optional. Array of allowed URL protocols.
1748   *                                                 Defaults to the result of wp_allowed_protocols().
1749   * @return array The filtered and sanitized block object result.
1750   */
1751  function filter_block_kses( $block, $allowed_html, $allowed_protocols = array() ) {
1752      $block['attrs'] = filter_block_kses_value( $block['attrs'], $allowed_html, $allowed_protocols, $block );
1753  
1754      if ( is_array( $block['innerBlocks'] ) ) {
1755          foreach ( $block['innerBlocks'] as $i => $inner_block ) {
1756              $block['innerBlocks'][ $i ] = filter_block_kses( $inner_block, $allowed_html, $allowed_protocols );
1757          }
1758      }
1759  
1760      return $block;
1761  }
1762  
1763  /**
1764   * Filters and sanitizes a parsed block attribute value to remove
1765   * non-allowable HTML.
1766   *
1767   * @since 5.3.1
1768   * @since 6.5.5 Added the `$block_context` parameter.
1769   *
1770   * @param string[]|string $value             The attribute value to filter.
1771   * @param array[]|string  $allowed_html      An array of allowed HTML elements and attributes,
1772   *                                           or a context name such as 'post'. See wp_kses_allowed_html()
1773   *                                           for the list of accepted context names.
1774   * @param string[]        $allowed_protocols Optional. Array of allowed URL protocols.
1775   *                                           Defaults to the result of wp_allowed_protocols().
1776   * @param array           $block_context     Optional. The block the attribute belongs to, in parsed block array format.
1777   * @return string[]|string The filtered and sanitized result.
1778   */
1779  function filter_block_kses_value( $value, $allowed_html, $allowed_protocols = array(), $block_context = null ) {
1780      if ( is_array( $value ) ) {
1781          foreach ( $value as $key => $inner_value ) {
1782              $filtered_key   = filter_block_kses_value( $key, $allowed_html, $allowed_protocols, $block_context );
1783              $filtered_value = filter_block_kses_value( $inner_value, $allowed_html, $allowed_protocols, $block_context );
1784  
1785              if ( isset( $block_context['blockName'] ) && 'core/template-part' === $block_context['blockName'] ) {
1786                  $filtered_value = filter_block_core_template_part_attributes( $filtered_value, $filtered_key, $allowed_html );
1787              }
1788              if ( $filtered_key !== $key ) {
1789                  unset( $value[ $key ] );
1790              }
1791  
1792              $value[ $filtered_key ] = $filtered_value;
1793          }
1794      } elseif ( is_string( $value ) ) {
1795          return wp_kses( $value, $allowed_html, $allowed_protocols );
1796      }
1797  
1798      return $value;
1799  }
1800  
1801  /**
1802   * Sanitizes the value of the Template Part block's `tagName` attribute.
1803   *
1804   * @since 6.5.5
1805   *
1806   * @param string         $attribute_value The attribute value to filter.
1807   * @param string         $attribute_name  The attribute name.
1808   * @param array[]|string $allowed_html    An array of allowed HTML elements and attributes,
1809   *                                        or a context name such as 'post'. See wp_kses_allowed_html()
1810   *                                        for the list of accepted context names.
1811   * @return string The sanitized attribute value.
1812   */
1813  function filter_block_core_template_part_attributes( $attribute_value, $attribute_name, $allowed_html ) {
1814      if ( empty( $attribute_value ) || 'tagName' !== $attribute_name ) {
1815          return $attribute_value;
1816      }
1817      if ( ! is_array( $allowed_html ) ) {
1818          $allowed_html = wp_kses_allowed_html( $allowed_html );
1819      }
1820      return isset( $allowed_html[ $attribute_value ] ) ? $attribute_value : '';
1821  }
1822  
1823  /**
1824   * Parses blocks out of a content string, and renders those appropriate for the excerpt.
1825   *
1826   * As the excerpt should be a small string of text relevant to the full post content,
1827   * this function renders the blocks that are most likely to contain such text.
1828   *
1829   * @since 5.0.0
1830   *
1831   * @param string $content The content to parse.
1832   * @return string The parsed and filtered content.
1833   */
1834  function excerpt_remove_blocks( $content ) {
1835      if ( ! has_blocks( $content ) ) {
1836          return $content;
1837      }
1838  
1839      $allowed_inner_blocks = array(
1840          // Classic blocks have their blockName set to null.
1841          null,
1842          'core/freeform',
1843          'core/heading',
1844          'core/html',
1845          'core/list',
1846          'core/media-text',
1847          'core/paragraph',
1848          'core/preformatted',
1849          'core/pullquote',
1850          'core/quote',
1851          'core/table',
1852          'core/verse',
1853      );
1854  
1855      $allowed_wrapper_blocks = array(
1856          'core/columns',
1857          'core/column',
1858          'core/group',
1859      );
1860  
1861      /**
1862       * Filters the list of blocks that can be used as wrapper blocks, allowing
1863       * excerpts to be generated from the `innerBlocks` of these wrappers.
1864       *
1865       * @since 5.8.0
1866       *
1867       * @param string[] $allowed_wrapper_blocks The list of names of allowed wrapper blocks.
1868       */
1869      $allowed_wrapper_blocks = apply_filters( 'excerpt_allowed_wrapper_blocks', $allowed_wrapper_blocks );
1870  
1871      $allowed_blocks = array_merge( $allowed_inner_blocks, $allowed_wrapper_blocks );
1872  
1873      /**
1874       * Filters the list of blocks that can contribute to the excerpt.
1875       *
1876       * If a dynamic block is added to this list, it must not generate another
1877       * excerpt, as this will cause an infinite loop to occur.
1878       *
1879       * @since 5.0.0
1880       *
1881       * @param string[] $allowed_blocks The list of names of allowed blocks.
1882       */
1883      $allowed_blocks = apply_filters( 'excerpt_allowed_blocks', $allowed_blocks );
1884      $blocks         = parse_blocks( $content );
1885      $output         = '';
1886  
1887      foreach ( $blocks as $block ) {
1888          if ( in_array( $block['blockName'], $allowed_blocks, true ) ) {
1889              if ( ! empty( $block['innerBlocks'] ) ) {
1890                  if ( in_array( $block['blockName'], $allowed_wrapper_blocks, true ) ) {
1891                      $output .= _excerpt_render_inner_blocks( $block, $allowed_blocks );
1892                      continue;
1893                  }
1894  
1895                  // Skip the block if it has disallowed or nested inner blocks.
1896                  foreach ( $block['innerBlocks'] as $inner_block ) {
1897                      if (
1898                          ! in_array( $inner_block['blockName'], $allowed_inner_blocks, true ) ||
1899                          ! empty( $inner_block['innerBlocks'] )
1900                      ) {
1901                          continue 2;
1902                      }
1903                  }
1904              }
1905  
1906              $output .= render_block( $block );
1907          }
1908      }
1909  
1910      return $output;
1911  }
1912  
1913  /**
1914   * Parses footnotes markup out of a content string,
1915   * and renders those appropriate for the excerpt.
1916   *
1917   * @since 6.3.0
1918   *
1919   * @param string $content The content to parse.
1920   * @return string The parsed and filtered content.
1921   */
1922  function excerpt_remove_footnotes( $content ) {
1923      if ( ! str_contains( $content, 'data-fn=' ) ) {
1924          return $content;
1925      }
1926  
1927      return preg_replace(
1928          '_<sup data-fn="[^"]+" class="[^"]+">\s*<a href="[^"]+" id="[^"]+">\d+</a>\s*</sup>_',
1929          '',
1930          $content
1931      );
1932  }
1933  
1934  /**
1935   * Renders inner blocks from the allowed wrapper blocks
1936   * for generating an excerpt.
1937   *
1938   * @since 5.8.0
1939   * @access private
1940   *
1941   * @param array $parsed_block   The parsed block.
1942   * @param array $allowed_blocks The list of allowed inner blocks.
1943   * @return string The rendered inner blocks.
1944   */
1945  function _excerpt_render_inner_blocks( $parsed_block, $allowed_blocks ) {
1946      $output = '';
1947  
1948      foreach ( $parsed_block['innerBlocks'] as $inner_block ) {
1949          if ( ! in_array( $inner_block['blockName'], $allowed_blocks, true ) ) {
1950              continue;
1951          }
1952  
1953          if ( empty( $inner_block['innerBlocks'] ) ) {
1954              $output .= render_block( $inner_block );
1955          } else {
1956              $output .= _excerpt_render_inner_blocks( $inner_block, $allowed_blocks );
1957          }
1958      }
1959  
1960      return $output;
1961  }
1962  
1963  /**
1964   * Renders a single block into a HTML string.
1965   *
1966   * @since 5.0.0
1967   *
1968   * @global WP_Post $post The post to edit.
1969   *
1970   * @param array $parsed_block {
1971   *     A representative array of the block being rendered. See WP_Block_Parser_Block.
1972   *
1973   *     @type string   $blockName    Name of block.
1974   *     @type array    $attrs        Attributes from block comment delimiters.
1975   *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
1976   *                                  have the same structure as this one.
1977   *     @type string   $innerHTML    HTML from inside block comment delimiters.
1978   *     @type array    $innerContent List of string fragments and null markers where
1979   *                                  inner blocks were found.
1980   * }
1981   * @return string String of rendered HTML.
1982   */
1983  function render_block( $parsed_block ) {
1984      global $post;
1985      $parent_block = null;
1986  
1987      /**
1988       * Allows render_block() to be short-circuited, by returning a non-null value.
1989       *
1990       * @since 5.1.0
1991       * @since 5.9.0 The `$parent_block` parameter was added.
1992       *
1993       * @param string|null   $pre_render   The pre-rendered content. Default null.
1994       * @param array         $parsed_block {
1995       *     A representative array of the block being rendered. See WP_Block_Parser_Block.
1996       *
1997       *     @type string   $blockName    Name of block.
1998       *     @type array    $attrs        Attributes from block comment delimiters.
1999       *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
2000       *                                  have the same structure as this one.
2001       *     @type string   $innerHTML    HTML from inside block comment delimiters.
2002       *     @type array    $innerContent List of string fragments and null markers where
2003       *                                  inner blocks were found.
2004       * }
2005       * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block.
2006       */
2007      $pre_render = apply_filters( 'pre_render_block', null, $parsed_block, $parent_block );
2008      if ( ! is_null( $pre_render ) ) {
2009          return $pre_render;
2010      }
2011  
2012      $source_block = $parsed_block;
2013  
2014      /**
2015       * Filters the block being rendered in render_block(), before it's processed.
2016       *
2017       * @since 5.1.0
2018       * @since 5.9.0 The `$parent_block` parameter was added.
2019       *
2020       * @param array         $parsed_block {
2021       *     A representative array of the block being rendered. See WP_Block_Parser_Block.
2022       *
2023       *     @type string   $blockName    Name of block.
2024       *     @type array    $attrs        Attributes from block comment delimiters.
2025       *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
2026       *                                  have the same structure as this one.
2027       *     @type string   $innerHTML    HTML from inside block comment delimiters.
2028       *     @type array    $innerContent List of string fragments and null markers where
2029       *                                  inner blocks were found.
2030       * }
2031       * @param array         $source_block {
2032       *     An un-modified copy of `$parsed_block`, as it appeared in the source content.
2033       *     See WP_Block_Parser_Block.
2034       *
2035       *     @type string   $blockName    Name of block.
2036       *     @type array    $attrs        Attributes from block comment delimiters.
2037       *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
2038       *                                  have the same structure as this one.
2039       *     @type string   $innerHTML    HTML from inside block comment delimiters.
2040       *     @type array    $innerContent List of string fragments and null markers where
2041       *                                  inner blocks were found.
2042       * }
2043       * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block.
2044       */
2045      $parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block, $parent_block );
2046  
2047      $context = array();
2048  
2049      if ( $post instanceof WP_Post ) {
2050          $context['postId'] = $post->ID;
2051  
2052          /*
2053           * The `postType` context is largely unnecessary server-side, since the ID
2054           * is usually sufficient on its own. That being said, since a block's
2055           * manifest is expected to be shared between the server and the client,
2056           * it should be included to consistently fulfill the expectation.
2057           */
2058          $context['postType'] = $post->post_type;
2059      }
2060  
2061      /**
2062       * Filters the default context provided to a rendered block.
2063       *
2064       * @since 5.5.0
2065       * @since 5.9.0 The `$parent_block` parameter was added.
2066       *
2067       * @param array         $context      Default context.
2068       * @param array         $parsed_block {
2069       *     A representative array of the block being rendered. See WP_Block_Parser_Block.
2070       *
2071       *     @type string   $blockName    Name of block.
2072       *     @type array    $attrs        Attributes from block comment delimiters.
2073       *     @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
2074       *                                  have the same structure as this one.
2075       *     @type string   $innerHTML    HTML from inside block comment delimiters.
2076       *     @type array    $innerContent List of string fragments and null markers where
2077       *                                  inner blocks were found.
2078       * }
2079       * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block.
2080       */
2081      $context = apply_filters( 'render_block_context', $context, $parsed_block, $parent_block );
2082  
2083      $block = new WP_Block( $parsed_block, $context );
2084  
2085      return $block->render();
2086  }
2087  
2088  /**
2089   * Parses blocks out of a content string.
2090   *
2091   * @since 5.0.0
2092   *
2093   * @param string $content Post content.
2094   * @return array[] {
2095   *     Array of block structures.
2096   *
2097   *     @type array ...$0 {
2098   *         A representative array of a single parsed block object. See WP_Block_Parser_Block.
2099   *
2100   *         @type string   $blockName    Name of block.
2101   *         @type array    $attrs        Attributes from block comment delimiters.
2102   *         @type array[]  $innerBlocks  List of inner blocks. An array of arrays that
2103   *                                      have the same structure as this one.
2104   *         @type string   $innerHTML    HTML from inside block comment delimiters.
2105   *         @type array    $innerContent List of string fragments and null markers where
2106   *                                      inner blocks were found.
2107   *     }
2108   * }
2109   */
2110  function parse_blocks( $content ) {
2111      /**
2112       * Filter to allow plugins to replace the server-side block parser.
2113       *
2114       * @since 5.0.0
2115       *
2116       * @param string $parser_class Name of block parser class.
2117       */
2118      $parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' );
2119  
2120      $parser = new $parser_class();
2121      return $parser->parse( $content );
2122  }
2123  
2124  /**
2125   * Parses dynamic blocks out of `post_content` and re-renders them.
2126   *
2127   * @since 5.0.0
2128   *
2129   * @param string $content Post content.
2130   * @return string Updated post content.
2131   */
2132  function do_blocks( $content ) {
2133      $blocks = parse_blocks( $content );
2134      $output = '';
2135  
2136      foreach ( $blocks as $block ) {
2137          $output .= render_block( $block );
2138      }
2139  
2140      // If there are blocks in this content, we shouldn't run wpautop() on it later.
2141      $priority = has_filter( 'the_content', 'wpautop' );
2142      if ( false !== $priority && doing_filter( 'the_content' ) && has_blocks( $content ) ) {
2143          remove_filter( 'the_content', 'wpautop', $priority );
2144          add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
2145      }
2146  
2147      return $output;
2148  }
2149  
2150  /**
2151   * If do_blocks() needs to remove wpautop() from the `the_content` filter, this re-adds it afterwards,
2152   * for subsequent `the_content` usage.
2153   *
2154   * @since 5.0.0
2155   * @access private
2156   *
2157   * @param string $content The post content running through this filter.
2158   * @return string The unmodified content.
2159   */
2160  function _restore_wpautop_hook( $content ) {
2161      $current_priority = has_filter( 'the_content', '_restore_wpautop_hook' );
2162  
2163      add_filter( 'the_content', 'wpautop', $current_priority - 1 );
2164      remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority );
2165  
2166      return $content;
2167  }
2168  
2169  /**
2170   * Returns the current version of the block format that the content string is using.
2171   *
2172   * If the string doesn't contain blocks, it returns 0.
2173   *
2174   * @since 5.0.0
2175   *
2176   * @param string $content Content to test.
2177   * @return int The block format version is 1 if the content contains one or more blocks, 0 otherwise.
2178   */
2179  function block_version( $content ) {
2180      return has_blocks( $content ) ? 1 : 0;
2181  }
2182  
2183  /**
2184   * Registers a new block style.
2185   *
2186   * @since 5.3.0
2187   * @since 6.6.0 Added support for registering styles for multiple block types.
2188   *
2189   * @link https://developer.wordpress.org/block-editor/reference-guides/block-api/block-styles/
2190   *
2191   * @param string|string[] $block_name       Block type name including namespace or array of namespaced block type names.
2192   * @param array           $style_properties Array containing the properties of the style name, label,
2193   *                                          style_handle (name of the stylesheet to be enqueued),
2194   *                                          inline_style (string containing the CSS to be added),
2195   *                                          style_data (theme.json-like array to generate CSS from).
2196   *                                          See WP_Block_Styles_Registry::register().
2197   * @return bool True if the block style was registered with success and false otherwise.
2198   */
2199  function register_block_style( $block_name, $style_properties ) {
2200      return WP_Block_Styles_Registry::get_instance()->register( $block_name, $style_properties );
2201  }
2202  
2203  /**
2204   * Unregisters a block style.
2205   *
2206   * @since 5.3.0
2207   *
2208   * @param string $block_name       Block type name including namespace.
2209   * @param string $block_style_name Block style name.
2210   * @return bool True if the block style was unregistered with success and false otherwise.
2211   */
2212  function unregister_block_style( $block_name, $block_style_name ) {
2213      return WP_Block_Styles_Registry::get_instance()->unregister( $block_name, $block_style_name );
2214  }
2215  
2216  /**
2217   * Checks whether the current block type supports the feature requested.
2218   *
2219   * @since 5.8.0
2220   * @since 6.4.0 The `$feature` parameter now supports a string.
2221   *
2222   * @param WP_Block_Type $block_type    Block type to check for support.
2223   * @param string|array  $feature       Feature slug, or path to a specific feature to check support for.
2224   * @param mixed         $default_value Optional. Fallback value for feature support. Default false.
2225   * @return bool Whether the feature is supported.
2226   */
2227  function block_has_support( $block_type, $feature, $default_value = false ) {
2228      $block_support = $default_value;
2229      if ( $block_type instanceof WP_Block_Type ) {
2230          if ( is_array( $feature ) && count( $feature ) === 1 ) {
2231              $feature = $feature[0];
2232          }
2233  
2234          if ( is_array( $feature ) ) {
2235              $block_support = _wp_array_get( $block_type->supports, $feature, $default_value );
2236          } elseif ( isset( $block_type->supports[ $feature ] ) ) {
2237              $block_support = $block_type->supports[ $feature ];
2238          }
2239      }
2240  
2241      return true === $block_support || is_array( $block_support );
2242  }
2243  
2244  /**
2245   * Converts typography keys declared under `supports.*` to `supports.typography.*`.
2246   *
2247   * Displays a `_doing_it_wrong()` notice when a block using the older format is detected.
2248   *
2249   * @since 5.8.0
2250   *
2251   * @param array $metadata Metadata for registering a block type.
2252   * @return array Filtered metadata for registering a block type.
2253   */
2254  function wp_migrate_old_typography_shape( $metadata ) {
2255      if ( ! isset( $metadata['supports'] ) ) {
2256          return $metadata;
2257      }
2258  
2259      $typography_keys = array(
2260          '__experimentalFontFamily',
2261          '__experimentalFontStyle',
2262          '__experimentalFontWeight',
2263          '__experimentalLetterSpacing',
2264          '__experimentalTextDecoration',
2265          '__experimentalTextTransform',
2266          'fontSize',
2267          'lineHeight',
2268      );
2269  
2270      foreach ( $typography_keys as $typography_key ) {
2271          $support_for_key = isset( $metadata['supports'][ $typography_key ] ) ? $metadata['supports'][ $typography_key ] : null;
2272  
2273          if ( null !== $support_for_key ) {
2274              _doing_it_wrong(
2275                  'register_block_type_from_metadata()',
2276                  sprintf(
2277                      /* translators: 1: Block type, 2: Typography supports key, e.g: fontSize, lineHeight, etc. 3: block.json, 4: Old metadata key, 5: New metadata key. */
2278                      __( 'Block "%1$s" is declaring %2$s support in %3$s file under %4$s. %2$s support is now declared under %5$s.' ),
2279                      $metadata['name'],
2280                      "<code>$typography_key</code>",
2281                      '<code>block.json</code>',
2282                      "<code>supports.$typography_key</code>",
2283                      "<code>supports.typography.$typography_key</code>"
2284                  ),
2285                  '5.8.0'
2286              );
2287  
2288              _wp_array_set( $metadata['supports'], array( 'typography', $typography_key ), $support_for_key );
2289              unset( $metadata['supports'][ $typography_key ] );
2290          }
2291      }
2292  
2293      return $metadata;
2294  }
2295  
2296  /**
2297   * Helper function that constructs a WP_Query args array from
2298   * a `Query` block properties.
2299   *
2300   * It's used in Query Loop, Query Pagination Numbers and Query Pagination Next blocks.
2301   *
2302   * @since 5.8.0
2303   * @since 6.1.0 Added `query_loop_block_query_vars` filter and `parents` support in query.
2304   *
2305   * @param WP_Block $block Block instance.
2306   * @param int      $page  Current query's page.
2307   *
2308   * @return array Returns the constructed WP_Query arguments.
2309   */
2310  function build_query_vars_from_query_block( $block, $page ) {
2311      $query = array(
2312          'post_type'    => 'post',
2313          'order'        => 'DESC',
2314          'orderby'      => 'date',
2315          'post__not_in' => array(),
2316      );
2317  
2318      if ( isset( $block->context['query'] ) ) {
2319          if ( ! empty( $block->context['query']['postType'] ) ) {
2320              $post_type_param = $block->context['query']['postType'];
2321              if ( is_post_type_viewable( $post_type_param ) ) {
2322                  $query['post_type'] = $post_type_param;
2323              }
2324          }
2325          if ( isset( $block->context['query']['sticky'] ) && ! empty( $block->context['query']['sticky'] ) ) {
2326              $sticky = get_option( 'sticky_posts' );
2327              if ( 'only' === $block->context['query']['sticky'] ) {
2328                  /*
2329                   * Passing an empty array to post__in will return have_posts() as true (and all posts will be returned).
2330                   * Logic should be used before hand to determine if WP_Query should be used in the event that the array
2331                   * being passed to post__in is empty.
2332                   *
2333                   * @see https://core.trac.wordpress.org/ticket/28099
2334                   */
2335                  $query['post__in']            = ! empty( $sticky ) ? $sticky : array( 0 );
2336                  $query['ignore_sticky_posts'] = 1;
2337              } else {
2338                  $query['post__not_in'] = array_merge( $query['post__not_in'], $sticky );
2339              }
2340          }
2341          if ( ! empty( $block->context['query']['exclude'] ) ) {
2342              $excluded_post_ids     = array_map( 'intval', $block->context['query']['exclude'] );
2343              $excluded_post_ids     = array_filter( $excluded_post_ids );
2344              $query['post__not_in'] = array_merge( $query['post__not_in'], $excluded_post_ids );
2345          }
2346          if (
2347              isset( $block->context['query']['perPage'] ) &&
2348              is_numeric( $block->context['query']['perPage'] )
2349          ) {
2350              $per_page = absint( $block->context['query']['perPage'] );
2351              $offset   = 0;
2352  
2353              if (
2354                  isset( $block->context['query']['offset'] ) &&
2355                  is_numeric( $block->context['query']['offset'] )
2356              ) {
2357                  $offset = absint( $block->context['query']['offset'] );
2358              }
2359  
2360              $query['offset']         = ( $per_page * ( $page - 1 ) ) + $offset;
2361              $query['posts_per_page'] = $per_page;
2362          }
2363          // Migrate `categoryIds` and `tagIds` to `tax_query` for backwards compatibility.
2364          if ( ! empty( $block->context['query']['categoryIds'] ) || ! empty( $block->context['query']['tagIds'] ) ) {
2365              $tax_query = array();
2366              if ( ! empty( $block->context['query']['categoryIds'] ) ) {
2367                  $tax_query[] = array(
2368                      'taxonomy'         => 'category',
2369                      'terms'            => array_filter( array_map( 'intval', $block->context['query']['categoryIds'] ) ),
2370                      'include_children' => false,
2371                  );
2372              }
2373              if ( ! empty( $block->context['query']['tagIds'] ) ) {
2374                  $tax_query[] = array(
2375                      'taxonomy'         => 'post_tag',
2376                      'terms'            => array_filter( array_map( 'intval', $block->context['query']['tagIds'] ) ),
2377                      'include_children' => false,
2378                  );
2379              }
2380              $query['tax_query'] = $tax_query;
2381          }
2382          if ( ! empty( $block->context['query']['taxQuery'] ) ) {
2383              $query['tax_query'] = array();
2384              foreach ( $block->context['query']['taxQuery'] as $taxonomy => $terms ) {
2385                  if ( is_taxonomy_viewable( $taxonomy ) && ! empty( $terms ) ) {
2386                      $query['tax_query'][] = array(
2387                          'taxonomy'         => $taxonomy,
2388                          'terms'            => array_filter( array_map( 'intval', $terms ) ),
2389                          'include_children' => false,
2390                      );
2391                  }
2392              }
2393          }
2394          if (
2395              isset( $block->context['query']['order'] ) &&
2396                  in_array( strtoupper( $block->context['query']['order'] ), array( 'ASC', 'DESC' ), true )
2397          ) {
2398              $query['order'] = strtoupper( $block->context['query']['order'] );
2399          }
2400          if ( isset( $block->context['query']['orderBy'] ) ) {
2401              $query['orderby'] = $block->context['query']['orderBy'];
2402          }
2403          if (
2404              isset( $block->context['query']['author'] )
2405          ) {
2406              if ( is_array( $block->context['query']['author'] ) ) {
2407                  $query['author__in'] = array_filter( array_map( 'intval', $block->context['query']['author'] ) );
2408              } elseif ( is_string( $block->context['query']['author'] ) ) {
2409                  $query['author__in'] = array_filter( array_map( 'intval', explode( ',', $block->context['query']['author'] ) ) );
2410              } elseif ( is_int( $block->context['query']['author'] ) && $block->context['query']['author'] > 0 ) {
2411                  $query['author'] = $block->context['query']['author'];
2412              }
2413          }
2414          if ( ! empty( $block->context['query']['search'] ) ) {
2415              $query['s'] = $block->context['query']['search'];
2416          }
2417          if ( ! empty( $block->context['query']['parents'] ) && is_post_type_hierarchical( $query['post_type'] ) ) {
2418              $query['post_parent__in'] = array_filter( array_map( 'intval', $block->context['query']['parents'] ) );
2419          }
2420      }
2421  
2422      /**
2423       * Filters the arguments which will be passed to `WP_Query` for the Query Loop Block.
2424       *
2425       * Anything to this filter should be compatible with the `WP_Query` API to form
2426       * the query context which will be passed down to the Query Loop Block's children.
2427       * This can help, for example, to include additional settings or meta queries not
2428       * directly supported by the core Query Loop Block, and extend its capabilities.
2429       *
2430       * Please note that this will only influence the query that will be rendered on the
2431       * front-end. The editor preview is not affected by this filter. Also, worth noting
2432       * that the editor preview uses the REST API, so, ideally, one should aim to provide
2433       * attributes which are also compatible with the REST API, in order to be able to
2434       * implement identical queries on both sides.
2435       *
2436       * @since 6.1.0
2437       *
2438       * @param array    $query Array containing parameters for `WP_Query` as parsed by the block context.
2439       * @param WP_Block $block Block instance.
2440       * @param int      $page  Current query's page.
2441       */
2442      return apply_filters( 'query_loop_block_query_vars', $query, $block, $page );
2443  }
2444  
2445  /**
2446   * Helper function that returns the proper pagination arrow HTML for
2447   * `QueryPaginationNext` and `QueryPaginationPrevious` blocks based
2448   * on the provided `paginationArrow` from `QueryPagination` context.
2449   *
2450   * It's used in QueryPaginationNext and QueryPaginationPrevious blocks.
2451   *
2452   * @since 5.9.0
2453   *
2454   * @param WP_Block $block   Block instance.
2455   * @param bool     $is_next Flag for handling `next/previous` blocks.
2456   * @return string|null The pagination arrow HTML or null if there is none.
2457   */
2458  function get_query_pagination_arrow( $block, $is_next ) {
2459      $arrow_map = array(
2460          'none'    => '',
2461          'arrow'   => array(
2462              'next'     => '→',
2463              'previous' => '←',
2464          ),
2465          'chevron' => array(
2466              'next'     => '»',
2467              'previous' => '«',
2468          ),
2469      );
2470      if ( ! empty( $block->context['paginationArrow'] ) && array_key_exists( $block->context['paginationArrow'], $arrow_map ) && ! empty( $arrow_map[ $block->context['paginationArrow'] ] ) ) {
2471          $pagination_type = $is_next ? 'next' : 'previous';
2472          $arrow_attribute = $block->context['paginationArrow'];
2473          $arrow           = $arrow_map[ $block->context['paginationArrow'] ][ $pagination_type ];
2474          $arrow_classes   = "wp-block-query-pagination-$pagination_type-arrow is-arrow-$arrow_attribute";
2475          return "<span class='$arrow_classes' aria-hidden='true'>$arrow</span>";
2476      }
2477      return null;
2478  }
2479  
2480  /**
2481   * Helper function that constructs a comment query vars array from the passed
2482   * block properties.
2483   *
2484   * It's used with the Comment Query Loop inner blocks.
2485   *
2486   * @since 6.0.0
2487   *
2488   * @param WP_Block $block Block instance.
2489   * @return array Returns the comment query parameters to use with the
2490   *               WP_Comment_Query constructor.
2491   */
2492  function build_comment_query_vars_from_block( $block ) {
2493  
2494      $comment_args = array(
2495          'orderby'       => 'comment_date_gmt',
2496          'order'         => 'ASC',
2497          'status'        => 'approve',
2498          'no_found_rows' => false,
2499      );
2500  
2501      if ( is_user_logged_in() ) {
2502          $comment_args['include_unapproved'] = array( get_current_user_id() );
2503      } else {
2504          $unapproved_email = wp_get_unapproved_comment_author_email();
2505  
2506          if ( $unapproved_email ) {
2507              $comment_args['include_unapproved'] = array( $unapproved_email );
2508          }
2509      }
2510  
2511      if ( ! empty( $block->context['postId'] ) ) {
2512          $comment_args['post_id'] = (int) $block->context['postId'];
2513      }
2514  
2515      if ( get_option( 'thread_comments' ) ) {
2516          $comment_args['hierarchical'] = 'threaded';
2517      } else {
2518          $comment_args['hierarchical'] = false;
2519      }
2520  
2521      if ( get_option( 'page_comments' ) === '1' || get_option( 'page_comments' ) === true ) {
2522          $per_page     = get_option( 'comments_per_page' );
2523          $default_page = get_option( 'default_comments_page' );
2524          if ( $per_page > 0 ) {
2525              $comment_args['number'] = $per_page;
2526  
2527              $page = (int) get_query_var( 'cpage' );
2528              if ( $page ) {
2529                  $comment_args['paged'] = $page;
2530              } elseif ( 'oldest' === $default_page ) {
2531                  $comment_args['paged'] = 1;
2532              } elseif ( 'newest' === $default_page ) {
2533                  $max_num_pages = (int) ( new WP_Comment_Query( $comment_args ) )->max_num_pages;
2534                  if ( 0 !== $max_num_pages ) {
2535                      $comment_args['paged'] = $max_num_pages;
2536                  }
2537              }
2538              // Set the `cpage` query var to ensure the previous and next pagination links are correct
2539              // when inheriting the Discussion Settings.
2540              if ( 0 === $page && isset( $comment_args['paged'] ) && $comment_args['paged'] > 0 ) {
2541                  set_query_var( 'cpage', $comment_args['paged'] );
2542              }
2543          }
2544      }
2545  
2546      return $comment_args;
2547  }
2548  
2549  /**
2550   * Helper function that returns the proper pagination arrow HTML for
2551   * `CommentsPaginationNext` and `CommentsPaginationPrevious` blocks based on the
2552   * provided `paginationArrow` from `CommentsPagination` context.
2553   *
2554   * It's used in CommentsPaginationNext and CommentsPaginationPrevious blocks.
2555   *
2556   * @since 6.0.0
2557   *
2558   * @param WP_Block $block           Block instance.
2559   * @param string   $pagination_type Optional. Type of the arrow we will be rendering.
2560   *                                  Accepts 'next' or 'previous'. Default 'next'.
2561   * @return string|null The pagination arrow HTML or null if there is none.
2562   */
2563  function get_comments_pagination_arrow( $block, $pagination_type = 'next' ) {
2564      $arrow_map = array(
2565          'none'    => '',
2566          'arrow'   => array(
2567              'next'     => '→',
2568              'previous' => '←',
2569          ),
2570          'chevron' => array(
2571              'next'     => '»',
2572              'previous' => '«',
2573          ),
2574      );
2575      if ( ! empty( $block->context['comments/paginationArrow'] ) && ! empty( $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ] ) ) {
2576          $arrow_attribute = $block->context['comments/paginationArrow'];
2577          $arrow           = $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ];
2578          $arrow_classes   = "wp-block-comments-pagination-$pagination_type-arrow is-arrow-$arrow_attribute";
2579          return "<span class='$arrow_classes' aria-hidden='true'>$arrow</span>";
2580      }
2581      return null;
2582  }
2583  
2584  /**
2585   * Strips all HTML from the content of footnotes, and sanitizes the ID.
2586   *
2587   * This function expects slashed data on the footnotes content.
2588   *
2589   * @access private
2590   * @since 6.3.2
2591   *
2592   * @param string $footnotes JSON-encoded string of an array containing the content and ID of each footnote.
2593   * @return string Filtered content without any HTML on the footnote content and with the sanitized ID.
2594   */
2595  function _wp_filter_post_meta_footnotes( $footnotes ) {
2596      $footnotes_decoded = json_decode( $footnotes, true );
2597      if ( ! is_array( $footnotes_decoded ) ) {
2598          return '';
2599      }
2600      $footnotes_sanitized = array();
2601      foreach ( $footnotes_decoded as $footnote ) {
2602          if ( ! empty( $footnote['content'] ) && ! empty( $footnote['id'] ) ) {
2603              $footnotes_sanitized[] = array(
2604                  'id'      => sanitize_key( $footnote['id'] ),
2605                  'content' => wp_unslash( wp_filter_post_kses( wp_slash( $footnote['content'] ) ) ),
2606              );
2607          }
2608      }
2609      return wp_json_encode( $footnotes_sanitized );
2610  }
2611  
2612  /**
2613   * Adds the filters for footnotes meta field.
2614   *
2615   * @access private
2616   * @since 6.3.2
2617   */
2618  function _wp_footnotes_kses_init_filters() {
2619      add_filter( 'sanitize_post_meta_footnotes', '_wp_filter_post_meta_footnotes' );
2620  }
2621  
2622  /**
2623   * Removes the filters for footnotes meta field.
2624   *
2625   * @access private
2626   * @since 6.3.2
2627   */
2628  function _wp_footnotes_remove_filters() {
2629      remove_filter( 'sanitize_post_meta_footnotes', '_wp_filter_post_meta_footnotes' );
2630  }
2631  
2632  /**
2633   * Registers the filter of footnotes meta field if the user does not have `unfiltered_html` capability.
2634   *
2635   * @access private
2636   * @since 6.3.2
2637   */
2638  function _wp_footnotes_kses_init() {
2639      _wp_footnotes_remove_filters();
2640      if ( ! current_user_can( 'unfiltered_html' ) ) {
2641          _wp_footnotes_kses_init_filters();
2642      }
2643  }
2644  
2645  /**
2646   * Initializes the filters for footnotes meta field when imported data should be filtered.
2647   *
2648   * This filter is the last one being executed on {@see 'force_filtered_html_on_import'}.
2649   * If the input of the filter is true, it means we are in an import situation and should
2650   * enable kses, independently of the user capabilities. So in that case we call
2651   * _wp_footnotes_kses_init_filters().
2652   *
2653   * @access private
2654   * @since 6.3.2
2655   *
2656   * @param string $arg Input argument of the filter.
2657   * @return string Input argument of the filter.
2658   */
2659  function _wp_footnotes_force_filtered_html_on_import_filter( $arg ) {
2660      // If `force_filtered_html_on_import` is true, we need to init the global styles kses filters.
2661      if ( $arg ) {
2662          _wp_footnotes_kses_init_filters();
2663      }
2664      return $arg;
2665  }


Generated : Tue Jul 16 08:20:02 2024 Cross-referenced by PHPXref