mirrored from git://develop.git.wordpress.org/
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
blocks.php
1613 lines (1456 loc) · 54.2 KB
/
blocks.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Functions related to registering and parsing blocks.
*
* @package WordPress
* @subpackage Blocks
* @since 5.0.0
*/
/**
* Removes the block asset's path prefix if provided.
*
* @since 5.5.0
*
* @param string $asset_handle_or_path Asset handle or prefixed path.
* @return string Path without the prefix or the original value.
*/
function remove_block_asset_path_prefix( $asset_handle_or_path ) {
$path_prefix = 'file:';
if ( ! str_starts_with( $asset_handle_or_path, $path_prefix ) ) {
return $asset_handle_or_path;
}
$path = substr(
$asset_handle_or_path,
strlen( $path_prefix )
);
if ( str_starts_with( $path, './' ) ) {
$path = substr( $path, 2 );
}
return $path;
}
/**
* Generates the name for an asset based on the name of the block
* and the field name provided.
*
* @since 5.5.0
* @since 6.1.0 Added `$index` parameter.
*
* @param string $block_name Name of the block.
* @param string $field_name Name of the metadata field.
* @param int $index Optional. Index of the asset when multiple items passed.
* Default 0.
* @return string Generated asset name for the block's field.
*/
function generate_block_asset_handle( $block_name, $field_name, $index = 0 ) {
if ( str_starts_with( $block_name, 'core/' ) ) {
$asset_handle = str_replace( 'core/', 'wp-block-', $block_name );
if ( str_starts_with( $field_name, 'editor' ) ) {
$asset_handle .= '-editor';
}
if ( str_starts_with( $field_name, 'view' ) ) {
$asset_handle .= '-view';
}
if ( $index > 0 ) {
$asset_handle .= '-' . ( $index + 1 );
}
return $asset_handle;
}
$field_mappings = array(
'editorScript' => 'editor-script',
'script' => 'script',
'viewScript' => 'view-script',
'editorStyle' => 'editor-style',
'style' => 'style',
);
$asset_handle = str_replace( '/', '-', $block_name ) .
'-' . $field_mappings[ $field_name ];
if ( $index > 0 ) {
$asset_handle .= '-' . ( $index + 1 );
}
return $asset_handle;
}
/**
* Finds a script handle for the selected block metadata field. It detects
* when a path to file was provided and finds a corresponding asset file
* with details necessary to register the script under automatically
* generated handle name. It returns unprocessed script handle otherwise.
*
* @since 5.5.0
* @since 6.1.0 Added `$index` parameter.
*
* @param array $metadata Block metadata.
* @param string $field_name Field name to pick from metadata.
* @param int $index Optional. Index of the script to register when multiple items passed.
* Default 0.
* @return string|false Script handle provided directly or created through
* script's registration, or false on failure.
*/
function register_block_script_handle( $metadata, $field_name, $index = 0 ) {
if ( empty( $metadata[ $field_name ] ) ) {
return false;
}
$script_handle = $metadata[ $field_name ];
if ( is_array( $script_handle ) ) {
if ( empty( $script_handle[ $index ] ) ) {
return false;
}
$script_handle = $script_handle[ $index ];
}
$script_path = remove_block_asset_path_prefix( $script_handle );
if ( $script_handle === $script_path ) {
return $script_handle;
}
$script_asset_raw_path = dirname( $metadata['file'] ) . '/' . substr_replace( $script_path, '.asset.php', - strlen( '.js' ) );
$script_handle = generate_block_asset_handle( $metadata['name'], $field_name, $index );
$script_asset_path = wp_normalize_path(
realpath( $script_asset_raw_path )
);
if ( empty( $script_asset_path ) ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: 1: Asset file location, 2: Field name, 3: Block name. */
__( 'The asset file (%1$s) for the "%2$s" defined in "%3$s" block definition is missing.' ),
$script_asset_raw_path,
$field_name,
$metadata['name']
),
'5.5.0'
);
return false;
}
// Path needs to be normalized to work in Windows env.
static $wpinc_path_norm = '';
if ( ! $wpinc_path_norm ) {
$wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) );
}
// Cache $template_path_norm and $stylesheet_path_norm to avoid unnecessary additional calls.
static $template_path_norm = '';
static $stylesheet_path_norm = '';
if ( ! $template_path_norm || ! $stylesheet_path_norm ) {
$template_path_norm = wp_normalize_path( get_template_directory() );
$stylesheet_path_norm = wp_normalize_path( get_stylesheet_directory() );
}
$script_path_norm = wp_normalize_path( realpath( dirname( $metadata['file'] ) . '/' . $script_path ) );
$is_core_block = isset( $metadata['file'] ) && str_starts_with( $metadata['file'], $wpinc_path_norm );
/*
* Determine if the block script was registered in a theme, by checking if the script path starts with either
* the parent (template) or child (stylesheet) directory path.
*/
$is_parent_theme_block = str_starts_with( $script_path_norm, $template_path_norm );
$is_child_theme_block = str_starts_with( $script_path_norm, $stylesheet_path_norm );
$is_theme_block = ( $is_parent_theme_block || $is_child_theme_block );
$script_uri = plugins_url( $script_path, $metadata['file'] );
if ( $is_core_block ) {
$script_uri = includes_url( str_replace( $wpinc_path_norm, '', $script_path_norm ) );
} elseif ( $is_theme_block ) {
// Get the script path deterministically based on whether or not it was registered in a parent or child theme.
$script_uri = $is_parent_theme_block
? get_theme_file_uri( str_replace( $template_path_norm, '', $script_path_norm ) )
: get_theme_file_uri( str_replace( $stylesheet_path_norm, '', $script_path_norm ) );
}
$script_asset = require $script_asset_path;
$script_dependencies = isset( $script_asset['dependencies'] ) ? $script_asset['dependencies'] : array();
$result = wp_register_script(
$script_handle,
$script_uri,
$script_dependencies,
isset( $script_asset['version'] ) ? $script_asset['version'] : false
);
if ( ! $result ) {
return false;
}
if ( ! empty( $metadata['textdomain'] ) && in_array( 'wp-i18n', $script_dependencies, true ) ) {
wp_set_script_translations( $script_handle, $metadata['textdomain'] );
}
return $script_handle;
}
/**
* Finds a style handle for the block metadata field. It detects when a path
* to file was provided and registers the style under automatically
* generated handle name. It returns unprocessed style handle otherwise.
*
* @since 5.5.0
* @since 6.1.0 Added `$index` parameter.
*
* @param array $metadata Block metadata.
* @param string $field_name Field name to pick from metadata.
* @param int $index Optional. Index of the style to register when multiple items passed.
* Default 0.
* @return string|false Style handle provided directly or created through
* style's registration, or false on failure.
*/
function register_block_style_handle( $metadata, $field_name, $index = 0 ) {
if ( empty( $metadata[ $field_name ] ) ) {
return false;
}
$style_handle = $metadata[ $field_name ];
if ( is_array( $style_handle ) ) {
if ( empty( $style_handle[ $index ] ) ) {
return false;
}
$style_handle = $style_handle[ $index ];
}
$style_handle_name = generate_block_asset_handle( $metadata['name'], $field_name, $index );
// If the style handle is already registered, skip re-registering.
if ( wp_style_is( $style_handle_name, 'registered' ) ) {
return $style_handle_name;
}
static $wpinc_path_norm = '';
if ( ! $wpinc_path_norm ) {
$wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) );
}
$is_core_block = isset( $metadata['file'] ) && str_starts_with( $metadata['file'], $wpinc_path_norm );
// Skip registering individual styles for each core block when a bundled version provided.
if ( $is_core_block && ! wp_should_load_separate_core_block_assets() ) {
return false;
}
$style_path = remove_block_asset_path_prefix( $style_handle );
$is_style_handle = $style_handle === $style_path;
// Allow only passing style handles for core blocks.
if ( $is_core_block && ! $is_style_handle ) {
return false;
}
// Return the style handle unless it's the first item for every core block that requires special treatment.
if ( $is_style_handle && ! ( $is_core_block && 0 === $index ) ) {
return $style_handle;
}
// Check whether styles should have a ".min" suffix or not.
$suffix = SCRIPT_DEBUG ? '' : '.min';
if ( $is_core_block ) {
$style_path = ( 'editorStyle' === $field_name ) ? "editor{$suffix}.css" : "style{$suffix}.css";
}
$style_path_norm = wp_normalize_path( realpath( dirname( $metadata['file'] ) . '/' . $style_path ) );
$has_style_file = '' !== $style_path_norm;
if ( $has_style_file ) {
$style_uri = plugins_url( $style_path, $metadata['file'] );
// Cache $template_path_norm and $stylesheet_path_norm to avoid unnecessary additional calls.
static $template_path_norm = '';
static $stylesheet_path_norm = '';
if ( ! $template_path_norm || ! $stylesheet_path_norm ) {
$template_path_norm = wp_normalize_path( get_template_directory() );
$stylesheet_path_norm = wp_normalize_path( get_stylesheet_directory() );
}
// Determine if the block style was registered in a theme, by checking if the script path starts with either
// the parent (template) or child (stylesheet) directory path.
$is_parent_theme_block = str_starts_with( $style_path_norm, $template_path_norm );
$is_child_theme_block = str_starts_with( $style_path_norm, $stylesheet_path_norm );
$is_theme_block = ( $is_parent_theme_block || $is_child_theme_block );
if ( $is_core_block ) {
// All possible $style_path variants for core blocks are hard-coded above.
$style_uri = includes_url( 'blocks/' . str_replace( 'core/', '', $metadata['name'] ) . '/' . $style_path );
} elseif ( $is_theme_block ) {
// Get the script path deterministically based on whether or not it was registered in a parent or child theme.
$style_uri = $is_parent_theme_block
? get_theme_file_uri( str_replace( $template_path_norm, '', $style_path_norm ) )
: get_theme_file_uri( str_replace( $stylesheet_path_norm, '', $style_path_norm ) );
}
} else {
$style_uri = false;
}
$version = ! $is_core_block && isset( $metadata['version'] ) ? $metadata['version'] : false;
$result = wp_register_style(
$style_handle_name,
$style_uri,
array(),
$version
);
if ( ! $result ) {
return false;
}
if ( $has_style_file ) {
wp_style_add_data( $style_handle_name, 'path', $style_path_norm );
if ( $is_core_block ) {
$rtl_file = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $style_path_norm );
} else {
$rtl_file = str_replace( '.css', '-rtl.css', $style_path_norm );
}
if ( is_rtl() && file_exists( $rtl_file ) ) {
wp_style_add_data( $style_handle_name, 'rtl', 'replace' );
wp_style_add_data( $style_handle_name, 'suffix', $suffix );
wp_style_add_data( $style_handle_name, 'path', $rtl_file );
}
}
return $style_handle_name;
}
/**
* Gets i18n schema for block's metadata read from `block.json` file.
*
* @since 5.9.0
*
* @return object The schema for block's metadata.
*/
function get_block_metadata_i18n_schema() {
static $i18n_block_schema;
if ( ! isset( $i18n_block_schema ) ) {
$i18n_block_schema = wp_json_file_decode( __DIR__ . '/block-i18n.json' );
}
return $i18n_block_schema;
}
/**
* Registers a block type from the metadata stored in the `block.json` file.
*
* @since 5.5.0
* @since 5.7.0 Added support for `textdomain` field and i18n handling for all translatable fields.
* @since 5.9.0 Added support for `variations` and `viewScript` fields.
* @since 6.1.0 Added support for `render` field.
* @since 6.3.0 Added `selectors` field.
*
* @param string $file_or_folder Path to the JSON file with metadata definition for
* the block or path to the folder where the `block.json` file is located.
* If providing the path to a JSON file, the filename must end with `block.json`.
* @param array $args Optional. Array of block type arguments. Accepts any public property
* of `WP_Block_Type`. See WP_Block_Type::__construct() for information
* on accepted arguments. Default empty array.
* @return WP_Block_Type|false The registered block type on success, or false on failure.
*/
function register_block_type_from_metadata( $file_or_folder, $args = array() ) {
/*
* Get an array of metadata from a PHP file.
* This improves performance for core blocks as it's only necessary to read a single PHP file
* instead of reading a JSON file per-block, and then decoding from JSON to PHP.
* Using a static variable ensures that the metadata is only read once per request.
*/
static $core_blocks_meta;
if ( ! $core_blocks_meta ) {
$core_blocks_meta = require ABSPATH . WPINC . '/blocks/blocks-json.php';
}
$metadata_file = ( ! str_ends_with( $file_or_folder, 'block.json' ) ) ?
trailingslashit( $file_or_folder ) . 'block.json' :
$file_or_folder;
$is_core_block = str_starts_with( $file_or_folder, ABSPATH . WPINC );
if ( ! $is_core_block && ! file_exists( $metadata_file ) ) {
return false;
}
// Try to get metadata from the static cache for core blocks.
$metadata = false;
if ( $is_core_block ) {
$core_block_name = str_replace( ABSPATH . WPINC . '/blocks/', '', $file_or_folder );
if ( ! empty( $core_blocks_meta[ $core_block_name ] ) ) {
$metadata = $core_blocks_meta[ $core_block_name ];
}
}
// If metadata is not found in the static cache, read it from the file.
if ( ! $metadata ) {
$metadata = wp_json_file_decode( $metadata_file, array( 'associative' => true ) );
}
if ( ! is_array( $metadata ) || empty( $metadata['name'] ) ) {
return false;
}
$metadata['file'] = wp_normalize_path( realpath( $metadata_file ) );
/**
* Filters the metadata provided for registering a block type.
*
* @since 5.7.0
*
* @param array $metadata Metadata for registering a block type.
*/
$metadata = apply_filters( 'block_type_metadata', $metadata );
// Add `style` and `editor_style` for core blocks if missing.
if ( ! empty( $metadata['name'] ) && str_starts_with( $metadata['name'], 'core/' ) ) {
$block_name = str_replace( 'core/', '', $metadata['name'] );
if ( ! isset( $metadata['style'] ) ) {
$metadata['style'] = "wp-block-$block_name";
}
if ( current_theme_supports( 'wp-block-styles' ) && wp_should_load_separate_core_block_assets() ) {
$metadata['style'] = (array) $metadata['style'];
$metadata['style'][] = "wp-block-{$block_name}-theme";
}
if ( ! isset( $metadata['editorStyle'] ) ) {
$metadata['editorStyle'] = "wp-block-{$block_name}-editor";
}
}
$settings = array();
$property_mappings = array(
'apiVersion' => 'api_version',
'title' => 'title',
'category' => 'category',
'parent' => 'parent',
'ancestor' => 'ancestor',
'icon' => 'icon',
'description' => 'description',
'keywords' => 'keywords',
'attributes' => 'attributes',
'providesContext' => 'provides_context',
'usesContext' => 'uses_context',
'selectors' => 'selectors',
'supports' => 'supports',
'styles' => 'styles',
'variations' => 'variations',
'example' => 'example',
);
$textdomain = ! empty( $metadata['textdomain'] ) ? $metadata['textdomain'] : null;
$i18n_schema = get_block_metadata_i18n_schema();
foreach ( $property_mappings as $key => $mapped_key ) {
if ( isset( $metadata[ $key ] ) ) {
$settings[ $mapped_key ] = $metadata[ $key ];
if ( $textdomain && isset( $i18n_schema->$key ) ) {
$settings[ $mapped_key ] = translate_settings_using_i18n_schema( $i18n_schema->$key, $settings[ $key ], $textdomain );
}
}
}
$script_fields = array(
'editorScript' => 'editor_script_handles',
'script' => 'script_handles',
'viewScript' => 'view_script_handles',
);
foreach ( $script_fields as $metadata_field_name => $settings_field_name ) {
if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
$scripts = $metadata[ $metadata_field_name ];
$processed_scripts = array();
if ( is_array( $scripts ) ) {
for ( $index = 0; $index < count( $scripts ); $index++ ) {
$result = register_block_script_handle(
$metadata,
$metadata_field_name,
$index
);
if ( $result ) {
$processed_scripts[] = $result;
}
}
} else {
$result = register_block_script_handle(
$metadata,
$metadata_field_name
);
if ( $result ) {
$processed_scripts[] = $result;
}
}
$settings[ $settings_field_name ] = $processed_scripts;
}
}
$style_fields = array(
'editorStyle' => 'editor_style_handles',
'style' => 'style_handles',
);
foreach ( $style_fields as $metadata_field_name => $settings_field_name ) {
if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
$styles = $metadata[ $metadata_field_name ];
$processed_styles = array();
if ( is_array( $styles ) ) {
for ( $index = 0; $index < count( $styles ); $index++ ) {
$result = register_block_style_handle(
$metadata,
$metadata_field_name,
$index
);
if ( $result ) {
$processed_styles[] = $result;
}
}
} else {
$result = register_block_style_handle(
$metadata,
$metadata_field_name
);
if ( $result ) {
$processed_styles[] = $result;
}
}
$settings[ $settings_field_name ] = $processed_styles;
}
}
if ( ! empty( $metadata['render'] ) ) {
$template_path = wp_normalize_path(
realpath(
dirname( $metadata['file'] ) . '/' .
remove_block_asset_path_prefix( $metadata['render'] )
)
);
if ( $template_path ) {
/**
* Renders the block on the server.
*
* @since 6.1.0
*
* @param array $attributes Block attributes.
* @param string $content Block default content.
* @param WP_Block $block Block instance.
*
* @return string Returns the block content.
*/
$settings['render_callback'] = static function( $attributes, $content, $block ) use ( $template_path ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
ob_start();
require $template_path;
return ob_get_clean();
};
}
}
/**
* Filters the settings determined from the block type metadata.
*
* @since 5.7.0
*
* @param array $settings Array of determined settings for registering a block type.
* @param array $metadata Metadata provided for registering a block type.
*/
$settings = apply_filters(
'block_type_metadata_settings',
array_merge(
$settings,
$args
),
$metadata
);
return WP_Block_Type_Registry::get_instance()->register(
$metadata['name'],
$settings
);
}
/**
* Registers a block type. The recommended way is to register a block type using
* the metadata stored in the `block.json` file.
*
* @since 5.0.0
* @since 5.8.0 First parameter now accepts a path to the `block.json` file.
*
* @param string|WP_Block_Type $block_type Block type name including namespace, or alternatively
* a path to the JSON file with metadata definition for the block,
* or a path to the folder where the `block.json` file is located,
* or a complete WP_Block_Type instance.
* In case a WP_Block_Type is provided, the $args parameter will be ignored.
* @param array $args Optional. Array of block type arguments. Accepts any public property
* of `WP_Block_Type`. See WP_Block_Type::__construct() for information
* on accepted arguments. Default empty array.
*
* @return WP_Block_Type|false The registered block type on success, or false on failure.
*/
function register_block_type( $block_type, $args = array() ) {
if ( is_string( $block_type ) && file_exists( $block_type ) ) {
return register_block_type_from_metadata( $block_type, $args );
}
return WP_Block_Type_Registry::get_instance()->register( $block_type, $args );
}
/**
* Unregisters a block type.
*
* @since 5.0.0
*
* @param string|WP_Block_Type $name Block type name including namespace, or alternatively
* a complete WP_Block_Type instance.
* @return WP_Block_Type|false The unregistered block type on success, or false on failure.
*/
function unregister_block_type( $name ) {
return WP_Block_Type_Registry::get_instance()->unregister( $name );
}
/**
* Determines whether a post or content string has blocks.
*
* This test optimizes for performance rather than strict accuracy, detecting
* the pattern of a block but not validating its structure. For strict accuracy,
* you should use the block parser on post content.
*
* @since 5.0.0
*
* @see parse_blocks()
*
* @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object.
* Defaults to global $post.
* @return bool Whether the post has blocks.
*/
function has_blocks( $post = null ) {
if ( ! is_string( $post ) ) {
$wp_post = get_post( $post );
if ( ! $wp_post instanceof WP_Post ) {
return false;
}
$post = $wp_post->post_content;
}
return str_contains( (string) $post, '<!-- wp:' );
}
/**
* Determines whether a $post or a string contains a specific block type.
*
* This test optimizes for performance rather than strict accuracy, detecting
* whether the block type exists but not validating its structure and not checking
* reusable blocks. For strict accuracy, you should use the block parser on post content.
*
* @since 5.0.0
*
* @see parse_blocks()
*
* @param string $block_name Full block type to look for.
* @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object.
* Defaults to global $post.
* @return bool Whether the post content contains the specified block.
*/
function has_block( $block_name, $post = null ) {
if ( ! has_blocks( $post ) ) {
return false;
}
if ( ! is_string( $post ) ) {
$wp_post = get_post( $post );
if ( $wp_post instanceof WP_Post ) {
$post = $wp_post->post_content;
}
}
/*
* Normalize block name to include namespace, if provided as non-namespaced.
* This matches behavior for WordPress 5.0.0 - 5.3.0 in matching blocks by
* their serialized names.
*/
if ( ! str_contains( $block_name, '/' ) ) {
$block_name = 'core/' . $block_name;
}
// Test for existence of block by its fully qualified name.
$has_block = str_contains( $post, '<!-- wp:' . $block_name . ' ' );
if ( ! $has_block ) {
/*
* If the given block name would serialize to a different name, test for
* existence by the serialized form.
*/
$serialized_block_name = strip_core_block_namespace( $block_name );
if ( $serialized_block_name !== $block_name ) {
$has_block = str_contains( $post, '<!-- wp:' . $serialized_block_name . ' ' );
}
}
return $has_block;
}
/**
* Returns an array of the names of all registered dynamic block types.
*
* @since 5.0.0
*
* @return string[] Array of dynamic block names.
*/
function get_dynamic_block_names() {
$dynamic_block_names = array();
$block_types = WP_Block_Type_Registry::get_instance()->get_all_registered();
foreach ( $block_types as $block_type ) {
if ( $block_type->is_dynamic() ) {
$dynamic_block_names[] = $block_type->name;
}
}
return $dynamic_block_names;
}
/**
* Given an array of attributes, returns a string in the serialized attributes
* format prepared for post content.
*
* The serialized result is a JSON-encoded string, with unicode escape sequence
* substitution for characters which might otherwise interfere with embedding
* the result in an HTML comment.
*
* This function must produce output that remains in sync with the output of
* the serializeAttributes JavaScript function in the block editor in order
* to ensure consistent operation between PHP and JavaScript.
*
* @since 5.3.1
*
* @param array $block_attributes Attributes object.
* @return string Serialized attributes.
*/
function serialize_block_attributes( $block_attributes ) {
$encoded_attributes = wp_json_encode( $block_attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
$encoded_attributes = preg_replace( '/--/', '\\u002d\\u002d', $encoded_attributes );
$encoded_attributes = preg_replace( '/</', '\\u003c', $encoded_attributes );
$encoded_attributes = preg_replace( '/>/', '\\u003e', $encoded_attributes );
$encoded_attributes = preg_replace( '/&/', '\\u0026', $encoded_attributes );
// Regex: /\\"/
$encoded_attributes = preg_replace( '/\\\\"/', '\\u0022', $encoded_attributes );
return $encoded_attributes;
}
/**
* Returns the block name to use for serialization. This will remove the default
* "core/" namespace from a block name.
*
* @since 5.3.1
*
* @param string|null $block_name Optional. Original block name. Null if the block name is unknown,
* e.g. Classic blocks have their name set to null. Default null.
* @return string Block name to use for serialization.
*/
function strip_core_block_namespace( $block_name = null ) {
if ( is_string( $block_name ) && str_starts_with( $block_name, 'core/' ) ) {
return substr( $block_name, 5 );
}
return $block_name;
}
/**
* Returns the content of a block, including comment delimiters.
*
* @since 5.3.1
*
* @param string|null $block_name Block name. Null if the block name is unknown,
* e.g. Classic blocks have their name set to null.
* @param array $block_attributes Block attributes.
* @param string $block_content Block save content.
* @return string Comment-delimited block content.
*/
function get_comment_delimited_block_content( $block_name, $block_attributes, $block_content ) {
if ( is_null( $block_name ) ) {
return $block_content;
}
$serialized_block_name = strip_core_block_namespace( $block_name );
$serialized_attributes = empty( $block_attributes ) ? '' : serialize_block_attributes( $block_attributes ) . ' ';
if ( empty( $block_content ) ) {
return sprintf( '<!-- wp:%s %s/-->', $serialized_block_name, $serialized_attributes );
}
return sprintf(
'<!-- wp:%s %s-->%s<!-- /wp:%s -->',
$serialized_block_name,
$serialized_attributes,
$block_content,
$serialized_block_name
);
}
/**
* Returns the content of a block, including comment delimiters, serializing all
* attributes from the given parsed block.
*
* This should be used when preparing a block to be saved to post content.
* Prefer `render_block` when preparing a block for display. Unlike
* `render_block`, this does not evaluate a block's `render_callback`, and will
* instead preserve the markup as parsed.
*
* @since 5.3.1
*
* @param array $block A representative array of a single parsed block object. See WP_Block_Parser_Block.
* @return string String of rendered HTML.
*/
function serialize_block( $block ) {
$block_content = '';
$index = 0;
foreach ( $block['innerContent'] as $chunk ) {
$block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ] );
}
if ( ! is_array( $block['attrs'] ) ) {
$block['attrs'] = array();
}
return get_comment_delimited_block_content(
$block['blockName'],
$block['attrs'],
$block_content
);
}
/**
* Returns a joined string of the aggregate serialization of the given
* parsed blocks.
*
* @since 5.3.1
*
* @param array[] $blocks An array of representative arrays of parsed block objects. See serialize_block().
* @return string String of rendered HTML.
*/
function serialize_blocks( $blocks ) {
return implode( '', array_map( 'serialize_block', $blocks ) );
}
/**
* Filters and sanitizes block content to remove non-allowable HTML
* from parsed block attribute values.
*
* @since 5.3.1
*
* @param string $text Text that may contain block content.
* @param array[]|string $allowed_html Optional. An array of allowed HTML elements and attributes,
* or a context name such as 'post'. See wp_kses_allowed_html()
* for the list of accepted context names. Default 'post'.
* @param string[] $allowed_protocols Optional. Array of allowed URL protocols.
* Defaults to the result of wp_allowed_protocols().
* @return string The filtered and sanitized content result.
*/
function filter_block_content( $text, $allowed_html = 'post', $allowed_protocols = array() ) {
$result = '';
if ( str_contains( $text, '<!--' ) && str_contains( $text, '--->' ) ) {
$text = preg_replace_callback( '%<!--(.*?)--->%', '_filter_block_content_callback', $text );
}
$blocks = parse_blocks( $text );
foreach ( $blocks as $block ) {
$block = filter_block_kses( $block, $allowed_html, $allowed_protocols );
$result .= serialize_block( $block );
}
return $result;
}
/**
* Callback used for regular expression replacement in filter_block_content().
*
* @private
* @since 6.2.1
*
* @param array $matches Array of preg_replace_callback matches.
* @return string Replacement string.
*/
function _filter_block_content_callback( $matches ) {
return '<!--' . rtrim( $matches[1], '-' ) . '-->';
}
/**
* Filters and sanitizes a parsed block to remove non-allowable HTML
* from block attribute values.
*
* @since 5.3.1
*
* @param WP_Block_Parser_Block $block The parsed block object.
* @param array[]|string $allowed_html An array of allowed HTML elements and attributes,
* or a context name such as 'post'. See wp_kses_allowed_html()
* for the list of accepted context names.
* @param string[] $allowed_protocols Optional. Array of allowed URL protocols.
* Defaults to the result of wp_allowed_protocols().
* @return array The filtered and sanitized block object result.
*/
function filter_block_kses( $block, $allowed_html, $allowed_protocols = array() ) {
$block['attrs'] = filter_block_kses_value( $block['attrs'], $allowed_html, $allowed_protocols );
if ( is_array( $block['innerBlocks'] ) ) {
foreach ( $block['innerBlocks'] as $i => $inner_block ) {
$block['innerBlocks'][ $i ] = filter_block_kses( $inner_block, $allowed_html, $allowed_protocols );
}
}
return $block;
}
/**
* Filters and sanitizes a parsed block attribute value to remove
* non-allowable HTML.
*
* @since 5.3.1
*
* @param string[]|string $value The attribute value to filter.
* @param array[]|string $allowed_html An array of allowed HTML elements and attributes,
* or a context name such as 'post'. See wp_kses_allowed_html()
* for the list of accepted context names.
* @param string[] $allowed_protocols Optional. Array of allowed URL protocols.
* Defaults to the result of wp_allowed_protocols().
* @return string[]|string The filtered and sanitized result.
*/
function filter_block_kses_value( $value, $allowed_html, $allowed_protocols = array() ) {
if ( is_array( $value ) ) {
foreach ( $value as $key => $inner_value ) {
$filtered_key = filter_block_kses_value( $key, $allowed_html, $allowed_protocols );
$filtered_value = filter_block_kses_value( $inner_value, $allowed_html, $allowed_protocols );
if ( $filtered_key !== $key ) {
unset( $value[ $key ] );
}
$value[ $filtered_key ] = $filtered_value;
}
} elseif ( is_string( $value ) ) {
return wp_kses( $value, $allowed_html, $allowed_protocols );
}
return $value;
}
/**
* Parses blocks out of a content string, and renders those appropriate for the excerpt.
*
* As the excerpt should be a small string of text relevant to the full post content,
* this function renders the blocks that are most likely to contain such text.
*
* @since 5.0.0
*
* @param string $content The content to parse.
* @return string The parsed and filtered content.
*/
function excerpt_remove_blocks( $content ) {
$allowed_inner_blocks = array(
// Classic blocks have their blockName set to null.
null,
'core/freeform',
'core/heading',
'core/html',
'core/list',
'core/media-text',
'core/paragraph',
'core/preformatted',
'core/pullquote',
'core/quote',
'core/table',
'core/verse',
);
$allowed_wrapper_blocks = array(
'core/columns',
'core/column',
'core/group',
);
/**
* Filters the list of blocks that can be used as wrapper blocks, allowing
* excerpts to be generated from the `innerBlocks` of these wrappers.
*
* @since 5.8.0
*
* @param string[] $allowed_wrapper_blocks The list of names of allowed wrapper blocks.
*/
$allowed_wrapper_blocks = apply_filters( 'excerpt_allowed_wrapper_blocks', $allowed_wrapper_blocks );
$allowed_blocks = array_merge( $allowed_inner_blocks, $allowed_wrapper_blocks );
/**
* Filters the list of blocks that can contribute to the excerpt.
*
* If a dynamic block is added to this list, it must not generate another
* excerpt, as this will cause an infinite loop to occur.
*
* @since 5.0.0
*
* @param string[] $allowed_blocks The list of names of allowed blocks.
*/
$allowed_blocks = apply_filters( 'excerpt_allowed_blocks', $allowed_blocks );
$blocks = parse_blocks( $content );
$output = '';
foreach ( $blocks as $block ) {
if ( in_array( $block['blockName'], $allowed_blocks, true ) ) {
if ( ! empty( $block['innerBlocks'] ) ) {
if ( in_array( $block['blockName'], $allowed_wrapper_blocks, true ) ) {
$output .= _excerpt_render_inner_blocks( $block, $allowed_blocks );
continue;
}
// Skip the block if it has disallowed or nested inner blocks.
foreach ( $block['innerBlocks'] as $inner_block ) {
if (
! in_array( $inner_block['blockName'], $allowed_inner_blocks, true ) ||
! empty( $inner_block['innerBlocks'] )
) {
continue 2;