Нет описания

blocks.php 44KB

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