No Description

blocks.php 36KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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. * Removes the block asset's path prefix if provided.
  11. *
  12. * @since 5.5.0
  13. *
  14. * @param string $asset_handle_or_path Asset handle or prefixed path.
  15. * @return string Path without the prefix or the original value.
  16. */
  17. function remove_block_asset_path_prefix( $asset_handle_or_path ) {
  18. $path_prefix = 'file:';
  19. if ( 0 !== strpos( $asset_handle_or_path, $path_prefix ) ) {
  20. return $asset_handle_or_path;
  21. }
  22. return substr(
  23. $asset_handle_or_path,
  24. strlen( $path_prefix )
  25. );
  26. }
  27. /**
  28. * Generates the name for an asset based on the name of the block
  29. * and the field name provided.
  30. *
  31. * @since 5.5.0
  32. *
  33. * @param string $block_name Name of the block.
  34. * @param string $field_name Name of the metadata field.
  35. * @return string Generated asset name for the block's field.
  36. */
  37. function generate_block_asset_handle( $block_name, $field_name ) {
  38. if ( 0 === strpos( $block_name, 'core/' ) ) {
  39. $asset_handle = str_replace( 'core/', 'wp-block-', $block_name );
  40. if ( 0 === strpos( $field_name, 'editor' ) ) {
  41. $asset_handle .= '-editor';
  42. }
  43. return $asset_handle;
  44. }
  45. $field_mappings = array(
  46. 'editorScript' => 'editor-script',
  47. 'script' => 'script',
  48. 'editorStyle' => 'editor-style',
  49. 'style' => 'style',
  50. );
  51. return str_replace( '/', '-', $block_name ) .
  52. '-' . $field_mappings[ $field_name ];
  53. }
  54. /**
  55. * Finds a script handle for the selected block metadata field. It detects
  56. * when a path to file was provided and finds a corresponding asset file
  57. * with details necessary to register the script under automatically
  58. * generated handle name. It returns unprocessed script handle otherwise.
  59. *
  60. * @since 5.5.0
  61. *
  62. * @param array $metadata Block metadata.
  63. * @param string $field_name Field name to pick from metadata.
  64. * @return string|false Script handle provided directly or created through
  65. * script's registration, or false on failure.
  66. */
  67. function register_block_script_handle( $metadata, $field_name ) {
  68. if ( empty( $metadata[ $field_name ] ) ) {
  69. return false;
  70. }
  71. $script_handle = $metadata[ $field_name ];
  72. $script_path = remove_block_asset_path_prefix( $metadata[ $field_name ] );
  73. if ( $script_handle === $script_path ) {
  74. return $script_handle;
  75. }
  76. $script_handle = generate_block_asset_handle( $metadata['name'], $field_name );
  77. $script_asset_path = realpath(
  78. dirname( $metadata['file'] ) . '/' .
  79. substr_replace( $script_path, '.asset.php', - strlen( '.js' ) )
  80. );
  81. if ( ! file_exists( $script_asset_path ) ) {
  82. _doing_it_wrong(
  83. __FUNCTION__,
  84. sprintf(
  85. /* translators: 1: Field name, 2: Block name. */
  86. __( 'The asset file for the "%1$s" defined in "%2$s" block definition is missing.' ),
  87. $field_name,
  88. $metadata['name']
  89. ),
  90. '5.5.0'
  91. );
  92. return false;
  93. }
  94. $script_asset = require $script_asset_path;
  95. $result = wp_register_script(
  96. $script_handle,
  97. plugins_url( $script_path, $metadata['file'] ),
  98. $script_asset['dependencies'],
  99. $script_asset['version']
  100. );
  101. if ( ! $result ) {
  102. return false;
  103. }
  104. if ( ! empty( $metadata['textdomain'] ) ) {
  105. wp_set_script_translations( $script_handle, $metadata['textdomain'] );
  106. }
  107. return $script_handle;
  108. }
  109. /**
  110. * Finds a style handle for the block metadata field. It detects when a path
  111. * to file was provided and registers the style under automatically
  112. * generated handle name. It returns unprocessed style handle otherwise.
  113. *
  114. * @since 5.5.0
  115. *
  116. * @param array $metadata Block metadata.
  117. * @param string $field_name Field name to pick from metadata.
  118. * @return string|false Style handle provided directly or created through
  119. * style's registration, or false on failure.
  120. */
  121. function register_block_style_handle( $metadata, $field_name ) {
  122. if ( empty( $metadata[ $field_name ] ) ) {
  123. return false;
  124. }
  125. $is_core_block = isset( $metadata['file'] ) && 0 === strpos( $metadata['file'], ABSPATH . WPINC );
  126. if ( $is_core_block && ! wp_should_load_separate_core_block_assets() ) {
  127. return false;
  128. }
  129. // Check whether styles should have a ".min" suffix or not.
  130. $suffix = SCRIPT_DEBUG ? '' : '.min';
  131. $style_handle = $metadata[ $field_name ];
  132. $style_path = remove_block_asset_path_prefix( $metadata[ $field_name ] );
  133. if ( $style_handle === $style_path && ! $is_core_block ) {
  134. return $style_handle;
  135. }
  136. $style_uri = plugins_url( $style_path, $metadata['file'] );
  137. if ( $is_core_block ) {
  138. $style_path = "style$suffix.css";
  139. $style_uri = includes_url( 'blocks/' . str_replace( 'core/', '', $metadata['name'] ) . "/style$suffix.css" );
  140. }
  141. $style_handle = generate_block_asset_handle( $metadata['name'], $field_name );
  142. $block_dir = dirname( $metadata['file'] );
  143. $style_file = realpath( "$block_dir/$style_path" );
  144. $has_style_file = false !== $style_file;
  145. $version = ! $is_core_block && isset( $metadata['version'] ) ? $metadata['version'] : false;
  146. $style_uri = $has_style_file ? $style_uri : false;
  147. $result = wp_register_style(
  148. $style_handle,
  149. $style_uri,
  150. array(),
  151. $version
  152. );
  153. if ( file_exists( str_replace( '.css', '-rtl.css', $style_file ) ) ) {
  154. wp_style_add_data( $style_handle, 'rtl', 'replace' );
  155. }
  156. if ( $has_style_file ) {
  157. wp_style_add_data( $style_handle, 'path', $style_file );
  158. }
  159. $rtl_file = str_replace( "$suffix.css", "-rtl$suffix.css", $style_file );
  160. if ( is_rtl() && file_exists( $rtl_file ) ) {
  161. wp_style_add_data( $style_handle, 'path', $rtl_file );
  162. }
  163. return $result ? $style_handle : false;
  164. }
  165. /**
  166. * Registers a block type from the metadata stored in the `block.json` file.
  167. *
  168. * @since 5.5.0
  169. *
  170. * @param string $file_or_folder Path to the JSON file with metadata definition for
  171. * the block or path to the folder where the `block.json` file is located.
  172. * @param array $args Optional. Array of block type arguments. Accepts any public property
  173. * of `WP_Block_Type`. See WP_Block_Type::__construct() for information
  174. * on accepted arguments. Default empty array.
  175. * @return WP_Block_Type|false The registered block type on success, or false on failure.
  176. */
  177. function register_block_type_from_metadata( $file_or_folder, $args = array() ) {
  178. $filename = 'block.json';
  179. $metadata_file = ( substr( $file_or_folder, -strlen( $filename ) ) !== $filename ) ?
  180. trailingslashit( $file_or_folder ) . $filename :
  181. $file_or_folder;
  182. if ( ! file_exists( $metadata_file ) ) {
  183. return false;
  184. }
  185. $metadata = json_decode( file_get_contents( $metadata_file ), true );
  186. if ( ! is_array( $metadata ) || empty( $metadata['name'] ) ) {
  187. return false;
  188. }
  189. $metadata['file'] = $metadata_file;
  190. /**
  191. * Filters the metadata provided for registering a block type.
  192. *
  193. * @since 5.7.0
  194. *
  195. * @param array $metadata Metadata for registering a block type.
  196. */
  197. $metadata = apply_filters( 'block_type_metadata', $metadata );
  198. // Add `style` and `editor_style` for core blocks if missing.
  199. if ( ! empty( $metadata['name'] ) && 0 === strpos( $metadata['name'], 'core/' ) ) {
  200. $block_name = str_replace( 'core/', '', $metadata['name'] );
  201. if ( ! isset( $metadata['style'] ) ) {
  202. $metadata['style'] = "wp-block-$block_name";
  203. }
  204. if ( ! isset( $metadata['editorStyle'] ) ) {
  205. $metadata['editorStyle'] = "wp-block-{$block_name}-editor";
  206. }
  207. }
  208. $settings = array();
  209. $property_mappings = array(
  210. 'title' => 'title',
  211. 'category' => 'category',
  212. 'parent' => 'parent',
  213. 'icon' => 'icon',
  214. 'description' => 'description',
  215. 'keywords' => 'keywords',
  216. 'attributes' => 'attributes',
  217. 'providesContext' => 'provides_context',
  218. 'usesContext' => 'uses_context',
  219. 'supports' => 'supports',
  220. 'styles' => 'styles',
  221. 'example' => 'example',
  222. 'apiVersion' => 'api_version',
  223. );
  224. foreach ( $property_mappings as $key => $mapped_key ) {
  225. if ( isset( $metadata[ $key ] ) ) {
  226. $value = $metadata[ $key ];
  227. if ( empty( $metadata['textdomain'] ) ) {
  228. $settings[ $mapped_key ] = $value;
  229. continue;
  230. }
  231. $textdomain = $metadata['textdomain'];
  232. switch ( $key ) {
  233. case 'title':
  234. case 'description':
  235. // phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText,WordPress.WP.I18n.NonSingularStringLiteralContext,WordPress.WP.I18n.NonSingularStringLiteralDomain
  236. $settings[ $mapped_key ] = translate_with_gettext_context( $value, sprintf( 'block %s', $key ), $textdomain );
  237. break;
  238. case 'keywords':
  239. $settings[ $mapped_key ] = array();
  240. if ( ! is_array( $value ) ) {
  241. continue 2;
  242. }
  243. foreach ( $value as $keyword ) {
  244. // phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText,WordPress.WP.I18n.NonSingularStringLiteralDomain
  245. $settings[ $mapped_key ][] = translate_with_gettext_context( $keyword, 'block keyword', $textdomain );
  246. }
  247. break;
  248. case 'styles':
  249. $settings[ $mapped_key ] = array();
  250. if ( ! is_array( $value ) ) {
  251. continue 2;
  252. }
  253. foreach ( $value as $style ) {
  254. if ( ! empty( $style['label'] ) ) {
  255. // phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText,WordPress.WP.I18n.NonSingularStringLiteralDomain
  256. $style['label'] = translate_with_gettext_context( $style['label'], 'block style label', $textdomain );
  257. }
  258. $settings[ $mapped_key ][] = $style;
  259. }
  260. break;
  261. default:
  262. $settings[ $mapped_key ] = $value;
  263. }
  264. }
  265. }
  266. if ( ! empty( $metadata['editorScript'] ) ) {
  267. $settings['editor_script'] = register_block_script_handle(
  268. $metadata,
  269. 'editorScript'
  270. );
  271. }
  272. if ( ! empty( $metadata['script'] ) ) {
  273. $settings['script'] = register_block_script_handle(
  274. $metadata,
  275. 'script'
  276. );
  277. }
  278. if ( ! empty( $metadata['editorStyle'] ) ) {
  279. $settings['editor_style'] = register_block_style_handle(
  280. $metadata,
  281. 'editorStyle'
  282. );
  283. }
  284. if ( ! empty( $metadata['style'] ) ) {
  285. $settings['style'] = register_block_style_handle(
  286. $metadata,
  287. 'style'
  288. );
  289. }
  290. /**
  291. * Filters the settings determined from the block type metadata.
  292. *
  293. * @since 5.7.0
  294. *
  295. * @param array $settings Array of determined settings for registering a block type.
  296. * @param array $metadata Metadata provided for registering a block type.
  297. */
  298. $settings = apply_filters(
  299. 'block_type_metadata_settings',
  300. array_merge(
  301. $settings,
  302. $args
  303. ),
  304. $metadata
  305. );
  306. return WP_Block_Type_Registry::get_instance()->register(
  307. $metadata['name'],
  308. $settings
  309. );
  310. }
  311. /**
  312. * Registers a block type. The recommended way is to register a block type using
  313. * the metadata stored in the `block.json` file.
  314. *
  315. * @since 5.0.0
  316. * @since 5.8.0 First param accepts a path to the `block.json` file.
  317. *
  318. * @param string|WP_Block_Type $block_type Block type name including namespace, or alternatively
  319. * a path to the JSON file with metadata definition for the block,
  320. * or a path to the folder where the `block.json` file is located,
  321. * or a complete WP_Block_Type instance.
  322. * In case a WP_Block_Type is provided, the $args parameter will be ignored.
  323. * @param array $args Optional. Array of block type arguments. Accepts any public property
  324. * of `WP_Block_Type`. See WP_Block_Type::__construct() for information
  325. * on accepted arguments. Default empty array.
  326. *
  327. * @return WP_Block_Type|false The registered block type on success, or false on failure.
  328. */
  329. function register_block_type( $block_type, $args = array() ) {
  330. if ( is_string( $block_type ) && file_exists( $block_type ) ) {
  331. return register_block_type_from_metadata( $block_type, $args );
  332. }
  333. return WP_Block_Type_Registry::get_instance()->register( $block_type, $args );
  334. }
  335. /**
  336. * Unregisters a block type.
  337. *
  338. * @since 5.0.0
  339. *
  340. * @param string|WP_Block_Type $name Block type name including namespace, or alternatively
  341. * a complete WP_Block_Type instance.
  342. * @return WP_Block_Type|false The unregistered block type on success, or false on failure.
  343. */
  344. function unregister_block_type( $name ) {
  345. return WP_Block_Type_Registry::get_instance()->unregister( $name );
  346. }
  347. /**
  348. * Determine whether a post or content string has blocks.
  349. *
  350. * This test optimizes for performance rather than strict accuracy, detecting
  351. * the pattern of a block but not validating its structure. For strict accuracy,
  352. * you should use the block parser on post content.
  353. *
  354. * @since 5.0.0
  355. *
  356. * @see parse_blocks()
  357. *
  358. * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object.
  359. * Defaults to global $post.
  360. * @return bool Whether the post has blocks.
  361. */
  362. function has_blocks( $post = null ) {
  363. if ( ! is_string( $post ) ) {
  364. $wp_post = get_post( $post );
  365. if ( $wp_post instanceof WP_Post ) {
  366. $post = $wp_post->post_content;
  367. }
  368. }
  369. return false !== strpos( (string) $post, '<!-- wp:' );
  370. }
  371. /**
  372. * Determine whether a $post or a string contains a specific block type.
  373. *
  374. * This test optimizes for performance rather than strict accuracy, detecting
  375. * whether the block type exists but not validating its structure and not checking
  376. * reusable blocks. For strict accuracy, you should use the block parser on post content.
  377. *
  378. * @since 5.0.0
  379. *
  380. * @see parse_blocks()
  381. *
  382. * @param string $block_name Full block type to look for.
  383. * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object.
  384. * Defaults to global $post.
  385. * @return bool Whether the post content contains the specified block.
  386. */
  387. function has_block( $block_name, $post = null ) {
  388. if ( ! has_blocks( $post ) ) {
  389. return false;
  390. }
  391. if ( ! is_string( $post ) ) {
  392. $wp_post = get_post( $post );
  393. if ( $wp_post instanceof WP_Post ) {
  394. $post = $wp_post->post_content;
  395. }
  396. }
  397. /*
  398. * Normalize block name to include namespace, if provided as non-namespaced.
  399. * This matches behavior for WordPress 5.0.0 - 5.3.0 in matching blocks by
  400. * their serialized names.
  401. */
  402. if ( false === strpos( $block_name, '/' ) ) {
  403. $block_name = 'core/' . $block_name;
  404. }
  405. // Test for existence of block by its fully qualified name.
  406. $has_block = false !== strpos( $post, '<!-- wp:' . $block_name . ' ' );
  407. if ( ! $has_block ) {
  408. /*
  409. * If the given block name would serialize to a different name, test for
  410. * existence by the serialized form.
  411. */
  412. $serialized_block_name = strip_core_block_namespace( $block_name );
  413. if ( $serialized_block_name !== $block_name ) {
  414. $has_block = false !== strpos( $post, '<!-- wp:' . $serialized_block_name . ' ' );
  415. }
  416. }
  417. return $has_block;
  418. }
  419. /**
  420. * Returns an array of the names of all registered dynamic block types.
  421. *
  422. * @since 5.0.0
  423. *
  424. * @return string[] Array of dynamic block names.
  425. */
  426. function get_dynamic_block_names() {
  427. $dynamic_block_names = array();
  428. $block_types = WP_Block_Type_Registry::get_instance()->get_all_registered();
  429. foreach ( $block_types as $block_type ) {
  430. if ( $block_type->is_dynamic() ) {
  431. $dynamic_block_names[] = $block_type->name;
  432. }
  433. }
  434. return $dynamic_block_names;
  435. }
  436. /**
  437. * Given an array of attributes, returns a string in the serialized attributes
  438. * format prepared for post content.
  439. *
  440. * The serialized result is a JSON-encoded string, with unicode escape sequence
  441. * substitution for characters which might otherwise interfere with embedding
  442. * the result in an HTML comment.
  443. *
  444. * This function must produce output that remains in sync with the output of
  445. * the serializeAttributes JavaScript function in the block editor in order
  446. * to ensure consistent operation between PHP and JavaScript.
  447. *
  448. * @since 5.3.1
  449. *
  450. * @param array $block_attributes Attributes object.
  451. * @return string Serialized attributes.
  452. */
  453. function serialize_block_attributes( $block_attributes ) {
  454. $encoded_attributes = wp_json_encode( $block_attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
  455. $encoded_attributes = preg_replace( '/--/', '\\u002d\\u002d', $encoded_attributes );
  456. $encoded_attributes = preg_replace( '/</', '\\u003c', $encoded_attributes );
  457. $encoded_attributes = preg_replace( '/>/', '\\u003e', $encoded_attributes );
  458. $encoded_attributes = preg_replace( '/&/', '\\u0026', $encoded_attributes );
  459. // Regex: /\\"/
  460. $encoded_attributes = preg_replace( '/\\\\"/', '\\u0022', $encoded_attributes );
  461. return $encoded_attributes;
  462. }
  463. /**
  464. * Returns the block name to use for serialization. This will remove the default
  465. * "core/" namespace from a block name.
  466. *
  467. * @since 5.3.1
  468. *
  469. * @param string $block_name Original block name.
  470. * @return string Block name to use for serialization.
  471. */
  472. function strip_core_block_namespace( $block_name = null ) {
  473. if ( is_string( $block_name ) && 0 === strpos( $block_name, 'core/' ) ) {
  474. return substr( $block_name, 5 );
  475. }
  476. return $block_name;
  477. }
  478. /**
  479. * Returns the content of a block, including comment delimiters.
  480. *
  481. * @since 5.3.1
  482. *
  483. * @param string|null $block_name Block name. Null if the block name is unknown,
  484. * e.g. Classic blocks have their name set to null.
  485. * @param array $block_attributes Block attributes.
  486. * @param string $block_content Block save content.
  487. * @return string Comment-delimited block content.
  488. */
  489. function get_comment_delimited_block_content( $block_name, $block_attributes, $block_content ) {
  490. if ( is_null( $block_name ) ) {
  491. return $block_content;
  492. }
  493. $serialized_block_name = strip_core_block_namespace( $block_name );
  494. $serialized_attributes = empty( $block_attributes ) ? '' : serialize_block_attributes( $block_attributes ) . ' ';
  495. if ( empty( $block_content ) ) {
  496. return sprintf( '<!-- wp:%s %s/-->', $serialized_block_name, $serialized_attributes );
  497. }
  498. return sprintf(
  499. '<!-- wp:%s %s-->%s<!-- /wp:%s -->',
  500. $serialized_block_name,
  501. $serialized_attributes,
  502. $block_content,
  503. $serialized_block_name
  504. );
  505. }
  506. /**
  507. * Returns the content of a block, including comment delimiters, serializing all
  508. * attributes from the given parsed block.
  509. *
  510. * This should be used when preparing a block to be saved to post content.
  511. * Prefer `render_block` when preparing a block for display. Unlike
  512. * `render_block`, this does not evaluate a block's `render_callback`, and will
  513. * instead preserve the markup as parsed.
  514. *
  515. * @since 5.3.1
  516. *
  517. * @param WP_Block_Parser_Block $block A single parsed block object.
  518. * @return string String of rendered HTML.
  519. */
  520. function serialize_block( $block ) {
  521. $block_content = '';
  522. $index = 0;
  523. foreach ( $block['innerContent'] as $chunk ) {
  524. $block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ] );
  525. }
  526. if ( ! is_array( $block['attrs'] ) ) {
  527. $block['attrs'] = array();
  528. }
  529. return get_comment_delimited_block_content(
  530. $block['blockName'],
  531. $block['attrs'],
  532. $block_content
  533. );
  534. }
  535. /**
  536. * Returns a joined string of the aggregate serialization of the given parsed
  537. * blocks.
  538. *
  539. * @since 5.3.1
  540. *
  541. * @param WP_Block_Parser_Block[] $blocks Parsed block objects.
  542. * @return string String of rendered HTML.
  543. */
  544. function serialize_blocks( $blocks ) {
  545. return implode( '', array_map( 'serialize_block', $blocks ) );
  546. }
  547. /**
  548. * Filters and sanitizes block content to remove non-allowable HTML from
  549. * parsed block attribute values.
  550. *
  551. * @since 5.3.1
  552. *
  553. * @param string $text Text that may contain block content.
  554. * @param array[]|string $allowed_html An array of allowed HTML elements
  555. * and attributes, or a context name
  556. * such as 'post'.
  557. * @param string[] $allowed_protocols Array of allowed URL protocols.
  558. * @return string The filtered and sanitized content result.
  559. */
  560. function filter_block_content( $text, $allowed_html = 'post', $allowed_protocols = array() ) {
  561. $result = '';
  562. $blocks = parse_blocks( $text );
  563. foreach ( $blocks as $block ) {
  564. $block = filter_block_kses( $block, $allowed_html, $allowed_protocols );
  565. $result .= serialize_block( $block );
  566. }
  567. return $result;
  568. }
  569. /**
  570. * Filters and sanitizes a parsed block to remove non-allowable HTML from block
  571. * attribute values.
  572. *
  573. * @since 5.3.1
  574. *
  575. * @param WP_Block_Parser_Block $block The parsed block object.
  576. * @param array[]|string $allowed_html An array of allowed HTML
  577. * elements and attributes, or a
  578. * context name such as 'post'.
  579. * @param string[] $allowed_protocols Allowed URL protocols.
  580. * @return array The filtered and sanitized block object result.
  581. */
  582. function filter_block_kses( $block, $allowed_html, $allowed_protocols = array() ) {
  583. $block['attrs'] = filter_block_kses_value( $block['attrs'], $allowed_html, $allowed_protocols );
  584. if ( is_array( $block['innerBlocks'] ) ) {
  585. foreach ( $block['innerBlocks'] as $i => $inner_block ) {
  586. $block['innerBlocks'][ $i ] = filter_block_kses( $inner_block, $allowed_html, $allowed_protocols );
  587. }
  588. }
  589. return $block;
  590. }
  591. /**
  592. * Filters and sanitizes a parsed block attribute value to remove non-allowable
  593. * HTML.
  594. *
  595. * @since 5.3.1
  596. *
  597. * @param string[]|string $value The attribute value to filter.
  598. * @param array[]|string $allowed_html An array of allowed HTML elements
  599. * and attributes, or a context name
  600. * such as 'post'.
  601. * @param string[] $allowed_protocols Array of allowed URL protocols.
  602. * @return string[]|string The filtered and sanitized result.
  603. */
  604. function filter_block_kses_value( $value, $allowed_html, $allowed_protocols = array() ) {
  605. if ( is_array( $value ) ) {
  606. foreach ( $value as $key => $inner_value ) {
  607. $filtered_key = filter_block_kses_value( $key, $allowed_html, $allowed_protocols );
  608. $filtered_value = filter_block_kses_value( $inner_value, $allowed_html, $allowed_protocols );
  609. if ( $filtered_key !== $key ) {
  610. unset( $value[ $key ] );
  611. }
  612. $value[ $filtered_key ] = $filtered_value;
  613. }
  614. } elseif ( is_string( $value ) ) {
  615. return wp_kses( $value, $allowed_html, $allowed_protocols );
  616. }
  617. return $value;
  618. }
  619. /**
  620. * Parses blocks out of a content string, and renders those appropriate for the excerpt.
  621. *
  622. * As the excerpt should be a small string of text relevant to the full post content,
  623. * this function renders the blocks that are most likely to contain such text.
  624. *
  625. * @since 5.0.0
  626. *
  627. * @param string $content The content to parse.
  628. * @return string The parsed and filtered content.
  629. */
  630. function excerpt_remove_blocks( $content ) {
  631. $allowed_inner_blocks = array(
  632. // Classic blocks have their blockName set to null.
  633. null,
  634. 'core/freeform',
  635. 'core/heading',
  636. 'core/html',
  637. 'core/list',
  638. 'core/media-text',
  639. 'core/paragraph',
  640. 'core/preformatted',
  641. 'core/pullquote',
  642. 'core/quote',
  643. 'core/table',
  644. 'core/verse',
  645. );
  646. $allowed_wrapper_blocks = array(
  647. 'core/columns',
  648. 'core/column',
  649. 'core/group',
  650. );
  651. /**
  652. * Filters the list of blocks that can be used as wrapper blocks, allowing
  653. * excerpts to be generated from the `innerBlocks` of these wrappers.
  654. *
  655. * @since 5.8.0
  656. *
  657. * @param array $allowed_wrapper_blocks The list of allowed wrapper blocks.
  658. */
  659. $allowed_wrapper_blocks = apply_filters( 'excerpt_allowed_wrapper_blocks', $allowed_wrapper_blocks );
  660. $allowed_blocks = array_merge( $allowed_inner_blocks, $allowed_wrapper_blocks );
  661. /**
  662. * Filters the list of blocks that can contribute to the excerpt.
  663. *
  664. * If a dynamic block is added to this list, it must not generate another
  665. * excerpt, as this will cause an infinite loop to occur.
  666. *
  667. * @since 5.0.0
  668. *
  669. * @param array $allowed_blocks The list of allowed blocks.
  670. */
  671. $allowed_blocks = apply_filters( 'excerpt_allowed_blocks', $allowed_blocks );
  672. $blocks = parse_blocks( $content );
  673. $output = '';
  674. foreach ( $blocks as $block ) {
  675. if ( in_array( $block['blockName'], $allowed_blocks, true ) ) {
  676. if ( ! empty( $block['innerBlocks'] ) ) {
  677. if ( in_array( $block['blockName'], $allowed_wrapper_blocks, true ) ) {
  678. $output .= _excerpt_render_inner_blocks( $block, $allowed_blocks );
  679. continue;
  680. }
  681. // Skip the block if it has disallowed or nested inner blocks.
  682. foreach ( $block['innerBlocks'] as $inner_block ) {
  683. if (
  684. ! in_array( $inner_block['blockName'], $allowed_inner_blocks, true ) ||
  685. ! empty( $inner_block['innerBlocks'] )
  686. ) {
  687. continue 2;
  688. }
  689. }
  690. }
  691. $output .= render_block( $block );
  692. }
  693. }
  694. return $output;
  695. }
  696. /**
  697. * Render inner blocks from the allowed wrapper blocks
  698. * for generating an excerpt.
  699. *
  700. * @since 5.8
  701. * @access private
  702. *
  703. * @param array $parsed_block The parsed block.
  704. * @param array $allowed_blocks The list of allowed inner blocks.
  705. * @return string The rendered inner blocks.
  706. */
  707. function _excerpt_render_inner_blocks( $parsed_block, $allowed_blocks ) {
  708. $output = '';
  709. foreach ( $parsed_block['innerBlocks'] as $inner_block ) {
  710. if ( ! in_array( $inner_block['blockName'], $allowed_blocks, true ) ) {
  711. continue;
  712. }
  713. if ( empty( $inner_block['innerBlocks'] ) ) {
  714. $output .= render_block( $inner_block );
  715. } else {
  716. $output .= _excerpt_render_inner_blocks( $inner_block, $allowed_blocks );
  717. }
  718. }
  719. return $output;
  720. }
  721. /**
  722. * Renders a single block into a HTML string.
  723. *
  724. * @since 5.0.0
  725. *
  726. * @global WP_Post $post The post to edit.
  727. *
  728. * @param array $parsed_block A single parsed block object.
  729. * @return string String of rendered HTML.
  730. */
  731. function render_block( $parsed_block ) {
  732. global $post;
  733. /**
  734. * Allows render_block() to be short-circuited, by returning a non-null value.
  735. *
  736. * @since 5.1.0
  737. *
  738. * @param string|null $pre_render The pre-rendered content. Default null.
  739. * @param array $parsed_block The block being rendered.
  740. */
  741. $pre_render = apply_filters( 'pre_render_block', null, $parsed_block );
  742. if ( ! is_null( $pre_render ) ) {
  743. return $pre_render;
  744. }
  745. $source_block = $parsed_block;
  746. /**
  747. * Filters the block being rendered in render_block(), before it's processed.
  748. *
  749. * @since 5.1.0
  750. *
  751. * @param array $parsed_block The block being rendered.
  752. * @param array $source_block An un-modified copy of $parsed_block, as it appeared in the source content.
  753. */
  754. $parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block );
  755. $context = array();
  756. if ( $post instanceof WP_Post ) {
  757. $context['postId'] = $post->ID;
  758. /*
  759. * The `postType` context is largely unnecessary server-side, since the ID
  760. * is usually sufficient on its own. That being said, since a block's
  761. * manifest is expected to be shared between the server and the client,
  762. * it should be included to consistently fulfill the expectation.
  763. */
  764. $context['postType'] = $post->post_type;
  765. }
  766. /**
  767. * Filters the default context provided to a rendered block.
  768. *
  769. * @since 5.5.0
  770. *
  771. * @param array $context Default context.
  772. * @param array $parsed_block Block being rendered, filtered by `render_block_data`.
  773. */
  774. $context = apply_filters( 'render_block_context', $context, $parsed_block );
  775. $block = new WP_Block( $parsed_block, $context );
  776. return $block->render();
  777. }
  778. /**
  779. * Parses blocks out of a content string.
  780. *
  781. * @since 5.0.0
  782. *
  783. * @param string $content Post content.
  784. * @return array[] Array of parsed block objects.
  785. */
  786. function parse_blocks( $content ) {
  787. /**
  788. * Filter to allow plugins to replace the server-side block parser
  789. *
  790. * @since 5.0.0
  791. *
  792. * @param string $parser_class Name of block parser class.
  793. */
  794. $parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' );
  795. $parser = new $parser_class();
  796. return $parser->parse( $content );
  797. }
  798. /**
  799. * Parses dynamic blocks out of `post_content` and re-renders them.
  800. *
  801. * @since 5.0.0
  802. *
  803. * @param string $content Post content.
  804. * @return string Updated post content.
  805. */
  806. function do_blocks( $content ) {
  807. $blocks = parse_blocks( $content );
  808. $output = '';
  809. foreach ( $blocks as $block ) {
  810. $output .= render_block( $block );
  811. }
  812. // If there are blocks in this content, we shouldn't run wpautop() on it later.
  813. $priority = has_filter( 'the_content', 'wpautop' );
  814. if ( false !== $priority && doing_filter( 'the_content' ) && has_blocks( $content ) ) {
  815. remove_filter( 'the_content', 'wpautop', $priority );
  816. add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
  817. }
  818. return $output;
  819. }
  820. /**
  821. * If do_blocks() needs to remove wpautop() from the `the_content` filter, this re-adds it afterwards,
  822. * for subsequent `the_content` usage.
  823. *
  824. * @access private
  825. *
  826. * @since 5.0.0
  827. *
  828. * @param string $content The post content running through this filter.
  829. * @return string The unmodified content.
  830. */
  831. function _restore_wpautop_hook( $content ) {
  832. $current_priority = has_filter( 'the_content', '_restore_wpautop_hook' );
  833. add_filter( 'the_content', 'wpautop', $current_priority - 1 );
  834. remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority );
  835. return $content;
  836. }
  837. /**
  838. * Returns the current version of the block format that the content string is using.
  839. *
  840. * If the string doesn't contain blocks, it returns 0.
  841. *
  842. * @since 5.0.0
  843. *
  844. * @param string $content Content to test.
  845. * @return int The block format version is 1 if the content contains one or more blocks, 0 otherwise.
  846. */
  847. function block_version( $content ) {
  848. return has_blocks( $content ) ? 1 : 0;
  849. }
  850. /**
  851. * Registers a new block style.
  852. *
  853. * @since 5.3.0
  854. *
  855. * @param string $block_name Block type name including namespace.
  856. * @param array $style_properties Array containing the properties of the style name,
  857. * label, style (name of the stylesheet to be enqueued),
  858. * inline_style (string containing the CSS to be added).
  859. * @return bool True if the block style was registered with success and false otherwise.
  860. */
  861. function register_block_style( $block_name, $style_properties ) {
  862. return WP_Block_Styles_Registry::get_instance()->register( $block_name, $style_properties );
  863. }
  864. /**
  865. * Unregisters a block style.
  866. *
  867. * @since 5.3.0
  868. *
  869. * @param string $block_name Block type name including namespace.
  870. * @param string $block_style_name Block style name.
  871. * @return bool True if the block style was unregistered with success and false otherwise.
  872. */
  873. function unregister_block_style( $block_name, $block_style_name ) {
  874. return WP_Block_Styles_Registry::get_instance()->unregister( $block_name, $block_style_name );
  875. }
  876. /**
  877. * Checks whether the current block type supports the feature requested.
  878. *
  879. * @since 5.8.0
  880. *
  881. * @param WP_Block_Type $block_type Block type to check for support.
  882. * @param string $feature Name of the feature to check support for.
  883. * @param mixed $default Fallback value for feature support, defaults to false.
  884. *
  885. * @return boolean Whether or not the feature is supported.
  886. */
  887. function block_has_support( $block_type, $feature, $default = false ) {
  888. $block_support = $default;
  889. if ( $block_type && property_exists( $block_type, 'supports' ) ) {
  890. $block_support = _wp_array_get( $block_type->supports, $feature, $default );
  891. }
  892. return true === $block_support || is_array( $block_support );
  893. }
  894. /**
  895. * Converts typography keys declared under `supports.*` to `supports.typography.*`.
  896. *
  897. * Displays a `_doing_it_wrong()` notice when a block using the older format is detected.
  898. *
  899. * @since 5.8.0
  900. *
  901. * @param array $metadata Metadata for registering a block type.
  902. * @return array Filtered metadata for registering a block type.
  903. */
  904. function wp_migrate_old_typography_shape( $metadata ) {
  905. if ( ! isset( $metadata['supports'] ) ) {
  906. return $metadata;
  907. }
  908. $typography_keys = array(
  909. '__experimentalFontFamily',
  910. '__experimentalFontStyle',
  911. '__experimentalFontWeight',
  912. '__experimentalLetterSpacing',
  913. '__experimentalTextDecoration',
  914. '__experimentalTextTransform',
  915. 'fontSize',
  916. 'lineHeight',
  917. );
  918. foreach ( $typography_keys as $typography_key ) {
  919. $support_for_key = _wp_array_get( $metadata['supports'], array( $typography_key ), null );
  920. if ( null !== $support_for_key ) {
  921. _doing_it_wrong(
  922. 'register_block_type_from_metadata()',
  923. sprintf(
  924. /* translators: 1: Block type, 2: Typography supports key, e.g: fontSize, lineHeight, etc. 3: block.json, 4: Old metadata key, 5: New metadata key. */
  925. __( 'Block "%1$s" is declaring %2$s support in %3$s file under %4$s. %2$s support is now declared under %5$s.' ),
  926. $metadata['name'],
  927. "<code>$typography_key</code>",
  928. '<code>block.json</code>',
  929. "<code>supports.$typography_key</code>",
  930. "<code>supports.typography.$typography_key</code>"
  931. ),
  932. '5.8.0'
  933. );
  934. _wp_array_set( $metadata['supports'], array( 'typography', $typography_key ), $support_for_key );
  935. unset( $metadata['supports'][ $typography_key ] );
  936. }
  937. }
  938. return $metadata;
  939. }
  940. /**
  941. * Helper function that constructs a WP_Query args array from
  942. * a `Query` block properties.
  943. *
  944. * It's used in Query Loop, Query Pagination Numbers and Query Pagination Next blocks.
  945. *
  946. * @since 5.8.0
  947. *
  948. * @param WP_Block $block Block instance.
  949. * @param int $page Current query's page.
  950. *
  951. * @return array Returns the constructed WP_Query arguments.
  952. */
  953. function build_query_vars_from_query_block( $block, $page ) {
  954. $query = array(
  955. 'post_type' => 'post',
  956. 'order' => 'DESC',
  957. 'orderby' => 'date',
  958. 'post__not_in' => array(),
  959. );
  960. if ( isset( $block->context['query'] ) ) {
  961. if ( ! empty( $block->context['query']['postType'] ) ) {
  962. $post_type_param = $block->context['query']['postType'];
  963. if ( is_post_type_viewable( $post_type_param ) ) {
  964. $query['post_type'] = $post_type_param;
  965. }
  966. }
  967. if ( isset( $block->context['query']['sticky'] ) && ! empty( $block->context['query']['sticky'] ) ) {
  968. $sticky = get_option( 'sticky_posts' );
  969. if ( 'only' === $block->context['query']['sticky'] ) {
  970. $query['post__in'] = $sticky;
  971. } else {
  972. $query['post__not_in'] = array_merge( $query['post__not_in'], $sticky );
  973. }
  974. }
  975. if ( ! empty( $block->context['query']['exclude'] ) ) {
  976. $excluded_post_ids = array_map( 'intval', $block->context['query']['exclude'] );
  977. $excluded_post_ids = array_filter( $excluded_post_ids );
  978. $query['post__not_in'] = array_merge( $query['post__not_in'], $excluded_post_ids );
  979. }
  980. if (
  981. isset( $block->context['query']['perPage'] ) &&
  982. is_numeric( $block->context['query']['perPage'] )
  983. ) {
  984. $per_page = absint( $block->context['query']['perPage'] );
  985. $offset = 0;
  986. if (
  987. isset( $block->context['query']['offset'] ) &&
  988. is_numeric( $block->context['query']['offset'] )
  989. ) {
  990. $offset = absint( $block->context['query']['offset'] );
  991. }
  992. $query['offset'] = ( $per_page * ( $page - 1 ) ) + $offset;
  993. $query['posts_per_page'] = $per_page;
  994. }
  995. if ( ! empty( $block->context['query']['categoryIds'] ) ) {
  996. $term_ids = array_map( 'intval', $block->context['query']['categoryIds'] );
  997. $term_ids = array_filter( $term_ids );
  998. $query['category__in'] = $term_ids;
  999. }
  1000. if ( ! empty( $block->context['query']['tagIds'] ) ) {
  1001. $term_ids = array_map( 'intval', $block->context['query']['tagIds'] );
  1002. $term_ids = array_filter( $term_ids );
  1003. $query['tag__in'] = $term_ids;
  1004. }
  1005. if (
  1006. isset( $block->context['query']['order'] ) &&
  1007. in_array( strtoupper( $block->context['query']['order'] ), array( 'ASC', 'DESC' ), true )
  1008. ) {
  1009. $query['order'] = strtoupper( $block->context['query']['order'] );
  1010. }
  1011. if ( isset( $block->context['query']['orderBy'] ) ) {
  1012. $query['orderby'] = $block->context['query']['orderBy'];
  1013. }
  1014. if (
  1015. isset( $block->context['query']['author'] ) &&
  1016. (int) $block->context['query']['author'] > 0
  1017. ) {
  1018. $query['author'] = (int) $block->context['query']['author'];
  1019. }
  1020. if ( ! empty( $block->context['query']['search'] ) ) {
  1021. $query['s'] = $block->context['query']['search'];
  1022. }
  1023. }
  1024. return $query;
  1025. }