PluginProbe
TableKit – WordPress Table Builder for Data Tables, WooCommerce Product Tables & Post Tables / trunk
TableKit – WordPress Table Builder for Data Tables, WooCommerce Product Tables & Post Tables vtrunk
2.2.13 2.2.12 2.2.11 2.2.10 2.2.9 2.2.8 2.2.7 2.2.6 2.2.5 2.2.4 2.2.3 trunk 1.0.0 1.0.1 2.0.0 2.0.1 2.1.0 2.1.1 2.1.2 2.2.0 2.2.1 2.2.2
table-builder-block / includes / Shortcode / Shortcode.php

Shortcode.php in TableKit – WordPress Table Builder for Data Tables, WooCommerce Product Tables & Post Tables trunk, at includes/Shortcode/Shortcode.php

553 lines 20.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * The [tableKit] shortcode
4 *
5 * @package TableKit
6 */
7
8 namespace TableBuilder\Shortcode;
9
10 use TableBuilder\Shortcode\ShortcodeUtils;
11 use TableBuilder\Render\BlockRenderer;
12 use TableBuilder\Traits\Singleton;
13
14 defined( 'ABSPATH' ) || exit;
15
16 /**
17 * Handles registration and rendering of the [tableKit] shortcode.
18 */
19 class Shortcode {
20
21
22 use Singleton;
23
24 /**
25 * Whether frontend assets have been enqueued at least once.
26 *
27 * @var bool
28 */
29 private static bool $assets_enqueued = false;
30
31 // Default shortcode attribute values.
32 private const DEFAULT_ATTS = array(
33 'id' => '',
34 'post_id' => 0,
35 'block_id' => '',
36 'class' => '',
37 'attrs_json' => '{}',
38 );
39
40 // Default block attribute values.
41 private const DEFAULT_BLOCK_ATTRS = array(
42 'headers' => array(),
43 'footers' => array(),
44 'hasHeader' => true,
45 'hasFooter' => false,
46 'columnCount' => 0,
47 );
48
49 /**
50 * Hooks shortcode registration into WordPress init.
51 */
52 protected function __construct() {
53 add_action( 'init', array( $this, 'register_shortcodes' ) );
54 }
55
56 /**
57 * Registers all shortcodes for this plugin.
58 *
59 * @return void
60 */
61 public function register_shortcodes(): void {
62 add_shortcode( 'tableKit', array( $this, 'render' ) );
63 }
64
65 /**
66 * [tableKit] shortcode callback. Renders either every table block found in
67 * the resolved source post (when no specific block/id is given) or a single
68 * resolved block.
69 *
70 * @param array|string $raw_atts Raw shortcode attributes as passed by WordPress.
71 * @param string $content Optional. Shortcode enclosed content (currently unused
72 * beyond being passed through to the block renderer).
73 * @return string Rendered HTML.
74 */
75 public function render( $raw_atts, string $content = '' ): string {
76 $atts = $this->sanitize_atts( shortcode_atts( self::DEFAULT_ATTS, (array) $raw_atts, 'tableKit' ) );
77 $ids = $this->parse_ids( $atts );
78
79 ob_start();
80
81 if ( empty( $ids['block_id'] ) && empty( $ids['raw_id'] ) ) {
82 echo $this->render_all_blocks( $ids, $atts, $content ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built from the_content filter output and esc_*()-escaped pieces, see render_all_blocks().
83 return (string) ob_get_clean();
84 }
85
86 $block = $this->locate_block( $ids['post_id'], $ids['block_id'], $ids['raw_id'] );
87
88 if ( ! empty( $block ) ) {
89 echo $this->render_single_block( $block, $atts, $ids, $content ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- delegates to BlockRenderer::render_table_builder(), which escapes/kses's its own output.
90 }
91
92 return (string) ob_get_clean();
93 }
94
95 // -------------------------------------------------------------------------
96 // Multi-block rendering (no block_id given)
97 // -------------------------------------------------------------------------
98
99 /**
100 * Renders the source post/page content for post_id-only shortcodes.
101 * For standalone tablekit_table CPT entries, this preserves the original
102 * behavior of rendering the stored block content.
103 *
104 * @param array $ids Resolved ID set from parse_ids() (post_id/block_id/raw_id).
105 * @param array $atts Sanitized shortcode attributes.
106 * @param string $content Shortcode enclosed content (unused here).
107 * @return string Rendered HTML, or an empty string if the post can't be found/viewed.
108 */
109 private function render_all_blocks( array $ids, array $atts, string $content ): string {
110 if ( empty( $ids['post_id'] ) ) {
111 return '';
112 }
113
114 $post_id = (int) $ids['post_id'];
115 static $cleared = array();
116 if ( ShortcodeUtils::is_elementor_editor() && ! isset( $cleared[ $post_id ] ) ) {
117 clean_post_cache( $post_id );
118 $cleared[ $post_id ] = true;
119 }
120
121 $post = get_post( $post_id );
122
123 if ( ! $post || empty( $post->post_content ) || ! $this->can_view_post( $post ) ) {
124 return '';
125 }
126 $this->block_enqueue_assets();
127 $css = $this->collect_blocks_css_from_content( $post->post_content );
128 $style = $css ? '<style id="tbk-shortcode-' . absint( $post->ID ) . '">' . $css . '</style>' : '';
129
130 $previous_post = $GLOBALS['post'] ?? null;
131 // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- required so the "the_content" filter (and any callback that reads $GLOBALS['post']/get_post()) sees the correct post context; restored immediately below via wp_reset_postdata()/the original value.
132 $GLOBALS['post'] = $post; // Ensure filters use the shortcode post context.
133 setup_postdata( $post );
134 $content = (string) apply_filters( 'the_content', $post->post_content ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- "the_content" is a WordPress core filter, not a hook defined by this plugin.
135 wp_reset_postdata();
136 // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- restoring the previous global post value, not overriding it.
137 $GLOBALS['post'] = $previous_post;
138
139 return $style . $content . ShortcodeUtils::get_elementor_init_script();
140 }
141
142 // -------------------------------------------------------------------------
143 // Single-block rendering
144 // -------------------------------------------------------------------------
145
146 /**
147 * Renders a single resolved block. Used both by the multi-block path and the
148 * specific block_id path.
149 *
150 * @param array $block Parsed block array to render.
151 * @param array $atts Sanitized shortcode attributes.
152 * @param array $ids Resolved ID set from parse_ids().
153 * @param string $content Shortcode enclosed content, passed through to the "tablekit/render_block" filter.
154 * @return string Rendered HTML.
155 */
156 private function render_single_block( array $block, array $atts, array $ids, string $content ): string {
157 // Pro hooks handle their own block types.
158 /**
159 * Filters the rendered output for a single [tableKit] block, letting the
160 * Pro add-on (or third parties) render block types this plugin doesn't know about.
161 *
162 * @since Unknown
163 *
164 * @param string|null $output Rendered HTML to short-circuit with, or null to use the default renderer.
165 * @param array $block Parsed block array to render.
166 * @param array $atts Sanitized shortcode attributes.
167 * @param array $ids Resolved ID set from parse_ids().
168 * @param string $content Shortcode enclosed content.
169 */
170 // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- slash-namespaced hook name is this plugin's established public API (used by the Pro add-on); renaming would be a breaking change.
171 $output = apply_filters( 'tablekit/render_block', null, $block, $atts, $ids, $content );
172 if ( null !== $output ) {
173 return (string) $output;
174 }
175
176 $attrs = $this->prepare_attrs( $block, $atts, $ids['block_id'] );
177 $rows = $block['innerBlocks'] ?? array();
178 $css = ShortcodeUtils::collect_block_css( $block );
179 $this->block_enqueue_assets();
180 $style = $css ? '<style id="tb-' . esc_attr( $attrs['blockID'] ) . '">' . $css . '</style>' : '';
181
182 return $style . BlockRenderer::render_table_builder( $attrs, $rows, $content );
183 }
184
185 // -------------------------------------------------------------------------
186 // Attribute Preparation
187 // -------------------------------------------------------------------------
188
189 /**
190 * Resolves a block's final attribute set: applies any `attrs_json` shortcode
191 * override, assigns a stable block ID, appends an extra CSS class, and fills
192 * in default header/footer/column values.
193 *
194 * @param array $block Parsed block array (its stored `attrs` are the base).
195 * @param array $atts Sanitized shortcode attributes.
196 * @param string $block_id Resolved block ID (may be empty; falls back to the block's own ID or a generated UUID).
197 * @return array Final attribute array.
198 */
199 private function prepare_attrs( array $block, array $atts, string $block_id ): array {
200 $attrs = $block['attrs'] ?? array();
201 $rows = $block['innerBlocks'] ?? array();
202
203 // Override stored attributes with any inline JSON overrides.
204 $json_overrides = ShortcodeUtils::decode_json( $atts['attrs_json'] );
205 if ( $json_overrides ) {
206 $attrs = array_replace_recursive( $attrs, $json_overrides );
207 }
208
209 // Ensure a stable unique block ID.
210 if ( $block_id ) {
211 $attrs['blockID'] = $block_id;
212 } elseif ( empty( $attrs['blockID'] ) ) {
213 $attrs['blockID'] = 'tb-' . wp_generate_uuid4();
214 }
215
216 // Append any extra CSS class passed via shortcode.
217 if ( ! empty( $atts['class'] ) ) {
218 $extra_class = sanitize_html_class( $atts['class'] );
219 $attrs['blockClass'] = trim( ( $attrs['blockClass'] ?? '' ) . ' ' . $extra_class );
220 }
221
222 return $this->apply_block_defaults( $attrs, $rows );
223 }
224
225 /**
226 * Merges in default block attribute values, and generates placeholder header/footer
227 * cells when a table has headers/footers enabled but no cell data yet.
228 *
229 * @param array $attrs Block attributes to fill in defaults for.
230 * @param array $rows The block's inner row blocks, used to detect column count when needed.
231 * @return array Attribute array with defaults applied.
232 */
233 private function apply_block_defaults( array $attrs, array $rows ): array {
234 $attrs = array_replace_recursive( self::DEFAULT_BLOCK_ATTRS, $attrs );
235
236 $col_count = (int) $attrs['columnCount'];
237
238 if ( ! $col_count && $rows ) {
239 $col_count = $this->detect_column_count( $rows );
240 }
241
242 if ( $attrs['hasHeader'] && empty( $attrs['headers'] ) && $col_count ) {
243 $attrs['headers'] = $this->generate_placeholder_cells( $col_count, 'Header' );
244 }
245
246 if ( $attrs['hasFooter'] && empty( $attrs['footers'] ) && $col_count ) {
247 $attrs['footers'] = $this->generate_placeholder_cells( $col_count, 'Footer' );
248 }
249
250 return $attrs;
251 }
252
253 /**
254 * Counts columns from the first "tablebuilder/table-builder-row" block's inner blocks.
255 *
256 * @param array $rows Row blocks (a table block's innerBlocks).
257 * @return int Detected column count, or 0 if no row block is found.
258 */
259 private function detect_column_count( array $rows ): int {
260 foreach ( $rows as $row ) {
261 if ( 'tablebuilder/table-builder-row' === ( $row['blockName'] ?? '' ) ) {
262 return count( $row['innerBlocks'] ?? array() );
263 }
264 }
265
266 return 0;
267 }
268
269 /**
270 * Builds a list of placeholder cell arrays, e.g. "Header 1", "Header 2", ...
271 *
272 * @param int $count Number of cells to generate.
273 * @param string $prefix Label prefix, e.g. "Header" or "Footer".
274 * @return array[] Array of ['title' => string] cell descriptors.
275 */
276 private function generate_placeholder_cells( int $count, string $prefix ): array {
277 return array_map(
278 static fn( int $i ) => array( 'title' => "{$prefix} " . ( $i + 1 ) ),
279 range( 0, $count - 1 )
280 );
281 }
282
283 // -------------------------------------------------------------------------
284 // ID Resolution
285 // -------------------------------------------------------------------------
286
287 /**
288 * Resolves the "id" attribute (which may be a numeric post ID or an alphanumeric
289 * block ID) alongside the explicit "post_id"/"block_id" attributes into a single
290 * unambiguous ID set.
291 *
292 * @param array $atts Sanitized shortcode attributes.
293 * @return array{raw_id:string,post_id:int,block_id:string} Resolved IDs.
294 */
295 private function parse_ids( array $atts ): array {
296 $raw_id = trim( (string) ( $atts['id'] ?? '' ) );
297 $post_id = (int) ( $atts['post_id'] ?? 0 );
298 $block_id = (string) ( $atts['block_id'] ?? '' );
299
300 if ( ! $post_id && ctype_digit( $raw_id ) ) {
301 $post_id = (int) $raw_id;
302 }
303
304 if ( ! $block_id && $raw_id && ! ctype_digit( $raw_id ) ) {
305 $block_id = $raw_id;
306 }
307
308 return compact( 'raw_id', 'post_id', 'block_id' );
309 }
310
311 // -------------------------------------------------------------------------
312 // Block Resolution (specific block_id path only)
313 // -------------------------------------------------------------------------
314
315 /**
316 * Locates a target block, either within a specific post (when $post_id is given)
317 * or by searching the database for any post containing the block ID.
318 *
319 * @param int $post_id Post ID to look within first, or 0 to skip straight to a database search.
320 * @param string $block_id Explicit block ID to search for.
321 * @param string $raw_id Fallback ID (from the shortcode's "id" attribute) used when $block_id is empty.
322 * @return array The located block, or an empty array if not found.
323 */
324 private function locate_block( int $post_id, string $block_id, string $raw_id ): array {
325 if ( $post_id ) {
326 $block = $this->get_block_from_post( $post_id, $block_id );
327 if ( $block ) {
328 return $block;
329 }
330 }
331
332 $lookup = $block_id ? $block_id : $raw_id;
333
334 return $lookup ? $this->search_block_by_id( $lookup ) : array();
335 }
336
337 /**
338 * Parses a specific post's block content and finds the target block.
339 *
340 * @param int $post_id Post ID to load and parse.
341 * @param string $block_id Block ID to search for.
342 * @return array The located block, or an empty array if not found/not viewable.
343 */
344 private function get_block_from_post( int $post_id, string $block_id ): array {
345 $post = get_post( $post_id );
346
347 if ( ! $post || empty( $post->post_content ) || ! $this->can_view_post( $post ) ) {
348 return array();
349 }
350
351 return $this->find_table_block( parse_blocks( $post->post_content ), $block_id );
352 }
353
354 /**
355 * Whether the current request is allowed to see a post's content.
356 * Prevents the [tableKit] shortcode from being used to pull table
357 * content out of private/draft/pending posts the viewer can't read.
358 *
359 * @param \WP_Post $post Post to check.
360 * @return bool True if the post is published, or the viewer has "read_post" capability on it.
361 */
362 private function can_view_post( \WP_Post $post ): bool {
363 if ( 'publish' === $post->post_status ) {
364 return true;
365 }
366
367 return current_user_can( 'read_post', $post->ID );
368 }
369
370 /**
371 * Searches the database for posts containing the given block ID.
372 * Candidate post IDs are cached for 5 minutes per block ID.
373 *
374 * @param string $block_id Block ID (or short ID) to search for in post content.
375 * @return array The located block, or an empty array if not found.
376 */
377 private function search_block_by_id( string $block_id ): array {
378 global $wpdb;
379
380 $cache_key = 'tablekit_block_search_' . md5( $block_id );
381 $candidate_ids = wp_cache_get( $cache_key, 'table-builder-block' );
382
383 if ( false === $candidate_ids ) {
384 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- no WP_Query equivalent for "find posts whose content contains this block ID"; result is cached just below.
385 $candidate_ids = $wpdb->get_col(
386 $wpdb->prepare(
387 "SELECT ID
388 FROM {$wpdb->posts}
389 WHERE post_content LIKE %s
390 AND post_status NOT IN ('trash', 'auto-draft')
391 LIMIT 10",
392 '%' . $wpdb->esc_like( $block_id ) . '%'
393 )
394 );
395
396 wp_cache_set( $cache_key, $candidate_ids, 'table-builder-block', 5 * MINUTE_IN_SECONDS );
397 }
398
399 foreach ( $candidate_ids as $id ) {
400 $block = $this->get_block_from_post( (int) $id, $block_id );
401 if ( $block ) {
402 return $block;
403 }
404 }
405
406 return array();
407 }
408
409 /**
410 * Recursively searches a block tree for a table block matching the given ID
411 * (by blockID or shortId attribute), or the first table block if no ID is given.
412 *
413 * @param array $blocks Block tree to search (parsed blocks, possibly with innerBlocks).
414 * @param string $block_id Block ID to match; empty string matches the first table block found.
415 * @return array The matched block, or an empty array if not found.
416 */
417 private function find_table_block( array $blocks, string $block_id ): array {
418 /**
419 * Filters the block names treated as "table blocks" by the [tableKit] shortcode,
420 * letting the Pro add-on (or third parties) register additional table block types.
421 *
422 * @since Unknown
423 *
424 * @param string[] $block_names Block names to match, e.g. "tablebuilder/table-builder".
425 */
426 // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- slash-namespaced hook name is this plugin's established public API (used by the Pro add-on); renaming would be a breaking change.
427 $block_names = apply_filters( 'tablekit/block_names', array( 'tablebuilder/table-builder' ) );
428
429 foreach ( $blocks as $block ) {
430 if ( in_array( $block['blockName'] ?? '', $block_names, true ) ) {
431 $id = (string) ( $block['attrs']['blockID'] ?? '' );
432 $short_id = (string) ( $block['attrs']['shortId'] ?? '' );
433
434 if ( ! $block_id || $id === $block_id || $short_id === $block_id ) {
435 return $block;
436 }
437 }
438
439 if ( ! empty( $block['innerBlocks'] ) ) {
440 $found = $this->find_table_block( $block['innerBlocks'], $block_id );
441 if ( $found ) {
442 return $found;
443 }
444 }
445 }
446
447 return array();
448 }
449
450 // -------------------------------------------------------------------------
451 // CSS Collection
452 // -------------------------------------------------------------------------
453
454 /**
455 * Collects combined CSS for every table block found within a block of post content.
456 *
457 * @param string $content Serialized block content (e.g. a post's post_content).
458 * @return string Combined CSS, or an empty string if there's no content/no table blocks.
459 */
460 public function collect_blocks_css_from_content( string $content ): string {
461 if ( '' === trim( $content ) ) {
462 return '';
463 }
464
465 $blocks = parse_blocks( $content );
466 if ( empty( $blocks ) ) {
467 return '';
468 }
469
470 /** This filter is documented in includes/Shortcode/Shortcode.php */
471 // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- slash-namespaced hook name is this plugin's established public API (used by the Pro add-on); renaming would be a breaking change.
472 $block_names = apply_filters( 'tablekit/block_names', array( 'tablebuilder/table-builder' ) );
473 $css = '';
474
475 foreach ( $blocks as $block ) {
476 $css .= $this->collect_css_from_block_tree( $block, $block_names );
477 }
478
479 return $css;
480 }
481
482 /**
483 * Recursively collects CSS from a block and its inner blocks, for any block
484 * whose name is in the given allow-list.
485 *
486 * @param array $block Parsed block array.
487 * @param array $block_names Block names to collect CSS for (e.g. "tablebuilder/table-builder").
488 * @return string Combined CSS from this block and its descendants.
489 */
490 private function collect_css_from_block_tree( array $block, array $block_names ): string {
491 $css = '';
492
493 if ( in_array( $block['blockName'] ?? '', $block_names, true ) ) {
494 $css .= ShortcodeUtils::collect_block_css( $block );
495 }
496
497 foreach ( $block['innerBlocks'] ?? array() as $inner_block ) {
498 $css .= $this->collect_css_from_block_tree( $inner_block, $block_names );
499 }
500
501 return $css;
502 }
503
504 // -------------------------------------------------------------------------
505 // Asset Management
506 // -------------------------------------------------------------------------
507
508 /**
509 * Enqueues the plugin's shared styles + the base table-builder block's assets,
510 * once per request.
511 *
512 * @return void
513 */
514 private function block_enqueue_assets(): void {
515 if ( self::$assets_enqueued ) {
516 return;
517 }
518
519 self::$assets_enqueued = true;
520 ShortcodeUtils::enqueue_shared_styles();
521 ShortcodeUtils::enqueue_block_assets( 'tablebuilder/table-builder' );
522 }
523
524 // -------------------------------------------------------------------------
525 // Public API
526 // -------------------------------------------------------------------------
527
528 /**
529 * Whether the shortcode's shared frontend assets have been enqueued yet this request.
530 *
531 * @return bool
532 */
533 public static function is_assets_enqueued(): bool {
534 return self::$assets_enqueued;
535 }
536
537 /**
538 * Sanitizes raw shortcode attributes.
539 *
540 * @param array $atts Raw attributes (already merged with defaults via shortcode_atts()).
541 * @return array Sanitized attributes.
542 */
543 private function sanitize_atts( array $atts ): array {
544 $atts['id'] = sanitize_text_field( (string) ( $atts['id'] ?? '' ) );
545 $atts['post_id'] = absint( $atts['post_id'] ?? 0 );
546 $atts['block_id'] = sanitize_text_field( (string) ( $atts['block_id'] ?? '' ) );
547 $atts['class'] = sanitize_text_field( (string) ( $atts['class'] ?? '' ) );
548 $atts['attrs_json'] = (string) ( $atts['attrs_json'] ?? '' );
549
550 return $atts;
551 }
552 }
553