-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmcp-abilities-elementor.php
More file actions
6809 lines (5987 loc) · 223 KB
/
Copy pathmcp-abilities-elementor.php
File metadata and controls
6809 lines (5987 loc) · 223 KB
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
/**
* Plugin Name: MCP Abilities - Elementor
* Plugin URI: https://github.com/bjornfix/mcp-abilities-elementor
* Description: Elementor abilities for MCP. Get, update, and patch Elementor page data. Manage templates and cache.
* Version: 2.3.36
* Author: basicus
* Author URI: https://profiles.wordpress.org/basicus/
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Requires at least: 6.9
* Tested up to: 7.0
* Requires PHP: 8.0
*
* @package MCP_Abilities_Elementor
*/
declare( strict_types=1 );
// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
require_once __DIR__ . '/includes/ability-schema.php';
require_once __DIR__ . '/includes/ability-registry.php';
require_once __DIR__ . '/includes/document-repository.php';
require_once __DIR__ . '/includes/guidance.php';
require_once __DIR__ . '/includes/template-query.php';
require_once __DIR__ . '/includes/design-audit-runner.php';
require_once __DIR__ . '/includes/register-document.php';
require_once __DIR__ . '/includes/register-design.php';
require_once __DIR__ . '/includes/register-elements.php';
require_once __DIR__ . '/includes/register-templates.php';
require_once __DIR__ . '/includes/register-pro.php';
require_once __DIR__ . '/includes/register-site-tools.php';
/**
* Check if Abilities API is available.
*/
function mcp_abilities_elementor_check_dependencies(): bool {
if ( ! function_exists( 'wp_register_ability' ) ) {
add_action( 'admin_notices', function () {
echo '<div class="notice notice-error"><p><strong>MCP Abilities - Elementor</strong> requires the <a href="https://github.com/WordPress/abilities-api">Abilities API</a> plugin to be installed and activated.</p></div>';
} );
return false;
}
return true;
}
/**
* Check if Elementor is active.
*/
function mcp_abilities_elementor_is_active(): bool {
return class_exists( '\\Elementor\\Plugin' ) || defined( 'ELEMENTOR_VERSION' );
}
/**
* Return input schema fragment for high-risk Elementor document writes.
*
* @param string $ability_name Ability name.
* @return array
*/
function mcp_abilities_elementor_dangerous_action_confirmation_schema( string $ability_name ): array {
return array(
'type' => 'string',
'description' => sprintf(
/* translators: %s: Ability name. */
__( 'Required for this high-risk Elementor document write. Must exactly equal "%s".', 'mcp-abilities-elementor' ),
$ability_name
),
);
}
/**
* Require explicit per-ability confirmation for full/raw Elementor document writes.
*
* @param array $input Ability input.
* @param string $ability_name Ability name.
* @return true|WP_Error
*/
function mcp_abilities_elementor_confirm_dangerous_action( array $input, string $ability_name ) {
$confirmation = isset( $input['confirm_dangerous_action'] ) ? (string) $input['confirm_dangerous_action'] : '';
if ( $ability_name === $confirmation ) {
return true;
}
return new WP_Error(
'mcp_elementor_dangerous_action_confirmation_required',
sprintf(
/* translators: 1: Ability name, 2: Confirmation parameter name, 3: Confirmation value. */
__( 'High-risk Elementor ability "%1$s" requires explicit confirmation. Set %2$s to "%3$s" after verifying the target and rollback path.', 'mcp-abilities-elementor' ),
$ability_name,
'confirm_dangerous_action',
$ability_name
)
);
}
/**
* Convert an Elementor dangerous-action guard result to ability output.
*
* @param true|WP_Error $result Guard result.
* @param string $ability_name Ability name.
* @return array|null
*/
function mcp_abilities_elementor_dangerous_action_error_response( $result, string $ability_name ): ?array {
if ( ! is_wp_error( $result ) ) {
return null;
}
return array(
'success' => false,
'message' => $result->get_error_message(),
'ability' => $ability_name,
'code' => $result->get_error_code(),
);
}
/**
* Normalize cache scope input for write abilities.
*
* Supported values:
* - none: skip cache invalidation (advanced/debug use)
* - post: clear post-level caches and touch the post (default)
* - site: clear post-level caches + site-wide Elementor cache
*
* @param mixed $raw Raw input value.
* @param string $default Default scope.
* @return string
*/
function mcp_abilities_elementor_normalize_cache_scope( $raw, string $default = 'post' ): string {
$scope = is_string( $raw ) ? strtolower( trim( $raw ) ) : '';
if ( in_array( $scope, array( 'none', 'post', 'site' ), true ) ) {
return $scope;
}
return $default;
}
/**
* Get Elementor raw data meta normalized as a JSON string.
*
* Older/broken writes can leave the meta in unexpected shapes. This helper
* normalizes the value so read abilities can remain schema-safe.
*
* @param int $post_id Post ID.
* @return string
*/
function mcp_abilities_elementor_get_raw_data_meta( int $post_id ): string {
$value = get_post_meta( $post_id, '_elementor_data', true );
if ( is_string( $value ) ) {
return $value;
}
if ( is_array( $value ) ) {
$json = wp_json_encode( $value );
return is_string( $json ) ? $json : '';
}
return '';
}
/**
* Filter name for translation sibling providers used by guarded writes.
*
* @return string
*/
function mcp_abilities_elementor_translation_sibling_filter_name(): string {
return 'mcp_abilities_elementor_translation_sibling_post_ids';
}
/**
* Get sibling translation post IDs for a post from registered language providers.
*
* Elementor document meta must be independently editable per language. Some
* multilingual plugins can copy custom fields such as _elementor_data to
* translation siblings during update_post_meta(), so guarded writes snapshot
* sibling rows first and restore them if a sync hook changes them.
*
* @param int $post_id Source post ID.
* @return int[]
*/
function mcp_abilities_elementor_get_translation_sibling_post_ids( int $post_id ): array {
$post = get_post( $post_id );
if ( ! $post ) {
return array();
}
$sibling_ids = array();
$sibling_ids = apply_filters( mcp_abilities_elementor_translation_sibling_filter_name(), $sibling_ids, $post_id, $post );
if ( ! is_array( $sibling_ids ) ) {
return array();
}
return array_values(
array_unique(
array_filter(
array_map( 'intval', $sibling_ids ),
static function ( int $sibling_id ) use ( $post_id ): bool {
return $sibling_id > 0 && $sibling_id !== $post_id;
}
)
)
);
}
/**
* Capture sibling meta values through WordPress metadata APIs.
*
* @param int[] $post_ids Post IDs.
* @param string $meta_key Meta key.
* @return array<int,mixed>
*/
function mcp_abilities_elementor_capture_sibling_meta_values( array $post_ids, string $meta_key ): array {
$snapshot = array();
foreach ( $post_ids as $post_id ) {
$post_id = (int) $post_id;
if ( $post_id > 0 ) {
$snapshot[ $post_id ] = get_post_meta( $post_id, $meta_key, true );
}
}
return $snapshot;
}
/**
* Prepare a captured meta value for safe restore through update_post_meta().
*
* WordPress unslashes meta values before storage. JSON-backed Elementor meta
* captured through get_post_meta() is already unslashed, so restoring it as a
* plain string corrupts escaped quotes in values such as links and text editor
* HTML. Slashing only the JSON-backed string values mirrors normal Elementor
* write paths while leaving scalar/non-JSON meta untouched.
*
* @param string $meta_key Meta key.
* @param mixed $value Captured meta value.
* @return mixed
*/
function mcp_abilities_elementor_prepare_sibling_meta_restore_value( string $meta_key, $value ) {
$json_meta_keys = array(
'_elementor_data',
'_elementor_page_settings',
'_elementor_popup_display_settings',
'_elementor_conditions',
);
if ( ! in_array( $meta_key, $json_meta_keys, true ) ) {
return $value;
}
if ( is_string( $value ) ) {
return wp_slash( $value );
}
if ( is_array( $value ) ) {
$json = wp_json_encode( $value );
return is_string( $json ) ? wp_slash( $json ) : $value;
}
return $value;
}
/**
* Restore sibling meta values if a multilingual sync changed them.
*
* @param array<int,mixed> $snapshot Captured sibling values.
* @param string $meta_key Meta key.
* @return array
*/
function mcp_abilities_elementor_restore_sibling_meta_values( array $snapshot, string $meta_key ): array {
$restored = array();
foreach ( $snapshot as $post_id => $value ) {
$post_id = (int) $post_id;
if ( $post_id > 0 && get_post_meta( $post_id, $meta_key, true ) !== $value ) {
update_post_meta( $post_id, $meta_key, mcp_abilities_elementor_prepare_sibling_meta_restore_value( $meta_key, $value ) );
clean_post_cache( $post_id );
$restored[] = $post_id;
}
}
return array(
'restored_post_ids' => $restored,
'restored_count' => count( $restored ),
);
}
/**
* Schedule a final sibling meta restore after late multilingual sync hooks.
*
* @param array<int,mixed> $snapshot Captured sibling values.
* @param string $meta_key Meta key.
* @return bool
*/
function mcp_abilities_elementor_schedule_shutdown_sibling_meta_restore( array $snapshot, string $meta_key ): bool {
if ( empty( $snapshot ) ) {
return false;
}
register_shutdown_function(
static function () use ( $snapshot, $meta_key ): void {
mcp_abilities_elementor_restore_sibling_meta_values( $snapshot, $meta_key );
}
);
return true;
}
/**
* Update _elementor_data while preserving translated sibling documents.
*
* @param int $post_id Post ID.
* @param mixed $meta_value Meta value.
* @return array
*/
function mcp_abilities_elementor_update_guarded_elementor_data( int $post_id, $meta_value ): array {
$sibling_ids = mcp_abilities_elementor_get_translation_sibling_post_ids( $post_id );
$snapshot = mcp_abilities_elementor_capture_sibling_meta_values( $sibling_ids, '_elementor_data' );
$result = update_post_meta( $post_id, '_elementor_data', $meta_value );
$restore = mcp_abilities_elementor_restore_sibling_meta_values( $snapshot, '_elementor_data' );
$scheduled = mcp_abilities_elementor_schedule_shutdown_sibling_meta_restore( $snapshot, '_elementor_data' );
return array(
'updated' => false !== $result,
'protected_post_ids' => $sibling_ids,
'protected_count' => count( $sibling_ids ),
'restored_post_ids' => $restore['restored_post_ids'],
'restored_count' => $restore['restored_count'],
'shutdown_restore_scheduled' => $scheduled,
);
}
/**
* Update _elementor_page_settings while preserving translated sibling settings.
*
* @param int $post_id Post ID.
* @param mixed $meta_value Meta value.
* @return array
*/
function mcp_abilities_elementor_update_guarded_page_settings( int $post_id, $meta_value ): array {
$sibling_ids = mcp_abilities_elementor_get_translation_sibling_post_ids( $post_id );
$snapshot = mcp_abilities_elementor_capture_sibling_meta_values( $sibling_ids, '_elementor_page_settings' );
$result = update_post_meta( $post_id, '_elementor_page_settings', $meta_value );
$restore = mcp_abilities_elementor_restore_sibling_meta_values( $snapshot, '_elementor_page_settings' );
$scheduled = mcp_abilities_elementor_schedule_shutdown_sibling_meta_restore( $snapshot, '_elementor_page_settings' );
return array(
'updated' => false !== $result,
'protected_post_ids' => $sibling_ids,
'protected_count' => count( $sibling_ids ),
'restored_post_ids' => $restore['restored_post_ids'],
'restored_count' => $restore['restored_count'],
'shutdown_restore_scheduled' => $scheduled,
);
}
/**
* Decode Elementor JSON into a schema-safe array.
*
* @param mixed $raw Raw Elementor data value.
* @param string|null $error Optional decode error output.
* @return array
*/
function mcp_abilities_elementor_decode_data_meta( $raw, ?string &$error = null ): array {
$error = null;
if ( is_array( $raw ) ) {
return $raw;
}
if ( ! is_string( $raw ) || '' === $raw ) {
return array();
}
$decoded = json_decode( $raw, true );
if ( JSON_ERROR_NONE !== json_last_error() ) {
$error = json_last_error_msg();
return array();
}
return is_array( $decoded ) ? $decoded : array();
}
/**
* Check whether an Elementor element is a container using a background image.
*
* Elementor's CSS compiler can be sensitive to incomplete hand-authored
* container payloads. We treat background-image containers specially so
* targeted replacements inherit enough of the original frame to remain
* compiler-safe.
*
* @param array $element Elementor element data.
* @return bool
*/
function mcp_abilities_elementor_is_background_image_container( array $element ): bool {
if ( 'container' !== ( $element['elType'] ?? '' ) ) {
return false;
}
$settings = $element['settings'] ?? null;
if ( ! is_array( $settings ) ) {
return false;
}
$background_type = $settings['background_background'] ?? '';
$background = $settings['background_image'] ?? null;
if ( 'classic' !== $background_type ) {
return false;
}
if ( is_array( $background ) ) {
return ! empty( $background['url'] ) || ! empty( $background['id'] );
}
if ( is_string( $background ) ) {
return '' !== trim( $background );
}
return false;
}
/**
* Normalize replacement payload for background-image containers.
*
* Copy compiler-relevant container settings from the original element when the
* incoming payload omits them. This keeps targeted updates from silently
* dropping background CSS generation on installs where Elementor expects a
* fuller container frame.
*
* @param array $new_element Replacement payload.
* @param array $original_element Existing stored element.
* @return array
*/
function mcp_abilities_elementor_normalize_background_container_element( array $new_element, array $original_element ): array {
if ( ! mcp_abilities_elementor_is_background_image_container( $new_element ) ) {
return $new_element;
}
if ( 'container' !== ( $original_element['elType'] ?? '' ) ) {
return $new_element;
}
if ( ! isset( $new_element['settings'] ) || ! is_array( $new_element['settings'] ) ) {
$new_element['settings'] = array();
}
$settings = $new_element['settings'];
$original_settings = is_array( $original_element['settings'] ?? null ) ? $original_element['settings'] : array();
$inherited_setting_keys = array(
'content_width',
'width',
'width_tablet',
'width_mobile',
'flex_basis',
'flex_basis_tablet',
'flex_basis_mobile',
'min_height',
'min_height_tablet',
'min_height_mobile',
'flex_direction',
'flex_justify_content',
'flex_align_items',
'padding',
'padding_tablet',
'padding_mobile',
'padding_laptop',
'padding_widescreen',
'padding_widescreen_extra',
'padding_mobile_extra',
'padding_tablet_extra',
);
foreach ( $inherited_setting_keys as $key ) {
if ( array_key_exists( $key, $settings ) || ! array_key_exists( $key, $original_settings ) ) {
continue;
}
$settings[ $key ] = $original_settings[ $key ];
}
if ( empty( $settings['content_width'] ) ) {
$settings['content_width'] = 'full';
}
if ( empty( $settings['flex_basis'] ) && ! empty( $settings['width'] ) ) {
$settings['flex_basis'] = $settings['width'];
}
if ( empty( $settings['flex_direction'] ) ) {
$settings['flex_direction'] = 'column';
}
$new_element['settings'] = $settings;
return $new_element;
}
/**
* Append a CSS class to Elementor settings without duplicating tokens.
*
* @param array $settings Elementor settings array.
* @param string $class_name CSS class to ensure on the element.
* @return array
*/
function mcp_abilities_elementor_append_css_class( array $settings, string $class_name ): array {
$class_name = trim( $class_name );
if ( '' === $class_name ) {
return $settings;
}
$existing = isset( $settings['css_classes'] ) && is_string( $settings['css_classes'] ) ? $settings['css_classes'] : '';
$tokens = preg_split( '/\s+/', trim( $existing ) );
$tokens = is_array( $tokens ) ? array_values( array_filter( $tokens, 'strlen' ) ) : array();
if ( ! in_array( $class_name, $tokens, true ) ) {
$tokens[] = $class_name;
}
$settings['css_classes'] = implode( ' ', $tokens );
return $settings;
}
/**
* Determine whether an Elementor subtree contains a background-image container.
*
* @param array $element Elementor element data.
* @return bool
*/
function mcp_abilities_elementor_subtree_has_background_image_container( array $element ): bool {
if ( mcp_abilities_elementor_is_background_image_container( $element ) ) {
return true;
}
$children = $element['elements'] ?? null;
if ( ! is_array( $children ) ) {
return false;
}
foreach ( $children as $child ) {
if ( is_array( $child ) && mcp_abilities_elementor_subtree_has_background_image_container( $child ) ) {
return true;
}
}
return false;
}
/**
* Normalize a full Elementor tree for background-image subtree safety.
*
* Elementor can apply lazyload descendant resets from top-level parent
* containers. When a top-level subtree contains a native background-image
* container, append `e-no-lazyload` to that subtree root so generated
* background CSS can actually paint on the frontend.
*
* @param array $elements Top-level Elementor data array.
* @return array
*/
function mcp_abilities_elementor_normalize_background_container_subtrees( array $elements ): array {
foreach ( $elements as $index => $element ) {
if ( ! is_array( $element ) ) {
continue;
}
if (
'container' === ( $element['elType'] ?? '' ) &&
mcp_abilities_elementor_subtree_has_background_image_container( $element )
) {
$settings = is_array( $element['settings'] ?? null ) ? $element['settings'] : array();
$element['settings'] = mcp_abilities_elementor_append_css_class( $settings, 'e-no-lazyload' );
}
$elements[ $index ] = $element;
}
return $elements;
}
/**
* Deep-merge Elementor settings arrays.
*
* Scalar values from $overrides replace values in $base. Nested arrays are
* merged recursively unless either side is a numerically indexed list, in
* which case the override replaces the base.
*
* @param array $base Existing settings.
* @param array $overrides Incoming overrides.
* @return array
*/
function mcp_abilities_elementor_merge_settings( array $base, array $overrides ): array {
foreach ( $overrides as $key => $value ) {
if ( is_array( $value ) && isset( $base[ $key ] ) && is_array( $base[ $key ] ) ) {
$base_is_list = array_values( $base[ $key ] ) === $base[ $key ];
$override_is_list = array_values( $value ) === $value;
if ( $base_is_list || $override_is_list ) {
$base[ $key ] = $value;
continue;
}
$base[ $key ] = mcp_abilities_elementor_merge_settings( $base[ $key ], $value );
continue;
}
$base[ $key ] = $value;
}
return $base;
}
/**
* Find an Elementor element by ID with depth/path metadata.
*
* @param array $elements Elementor tree.
* @param string $target_id Target element ID.
* @param int $depth Current recursion depth.
* @param array $path Current ID path.
* @return array|null
*/
function mcp_abilities_elementor_find_element_meta( array $elements, string $target_id, int $depth = 0, array $path = array() ): ?array {
foreach ( $elements as $index => $element ) {
if ( ! is_array( $element ) ) {
continue;
}
$current_path = $path;
if ( isset( $element['id'] ) && is_string( $element['id'] ) ) {
$current_path[] = $element['id'];
}
if ( ( $element['id'] ?? null ) === $target_id ) {
return array(
'element' => $element,
'depth' => $depth,
'index' => $index,
'path' => $current_path,
);
}
if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
$child_meta = mcp_abilities_elementor_find_element_meta( $element['elements'], $target_id, $depth + 1, $current_path );
if ( is_array( $child_meta ) ) {
return $child_meta;
}
}
}
return null;
}
/**
* Replace an Elementor element in a tree by ID.
*
* @param array $elements Elementor tree.
* @param string $target_id Target element ID.
* @param array $new_element Replacement element.
* @return bool True when replaced.
*/
function mcp_abilities_elementor_replace_element_in_tree( array &$elements, string $target_id, array $new_element ): bool {
foreach ( $elements as $index => &$element ) {
if ( ! is_array( $element ) ) {
continue;
}
if ( ( $element['id'] ?? null ) === $target_id ) {
$elements[ $index ] = $new_element;
return true;
}
if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
if ( mcp_abilities_elementor_replace_element_in_tree( $element['elements'], $target_id, $new_element ) ) {
return true;
}
}
}
return false;
}
/**
* Generate a short Elementor-like element ID.
*
* Elementor stores IDs as short hex-ish strings. A random 7 character token is
* enough for practical uniqueness inside one page, and we still collision-check
* before writing.
*
* @return string
*/
function mcp_abilities_elementor_generate_element_id(): string {
try {
return substr( bin2hex( random_bytes( 4 ) ), 0, 7 );
} catch ( \Throwable $e ) {
return substr( str_replace( '-', '', wp_generate_uuid4() ), 0, 7 );
}
}
/**
* Collect all element IDs from a tree.
*
* @param array $elements Elementor tree.
* @param array $ids Existing IDs.
* @return array
*/
function mcp_abilities_elementor_collect_element_ids( array $elements, array $ids = array() ): array {
foreach ( $elements as $element ) {
if ( ! is_array( $element ) ) {
continue;
}
if ( isset( $element['id'] ) && is_string( $element['id'] ) && '' !== $element['id'] ) {
$ids[] = $element['id'];
}
if ( isset( $element['elements'] ) && is_array( $element['elements'] ) ) {
$ids = mcp_abilities_elementor_collect_element_ids( $element['elements'], $ids );
}
}
return array_values( array_unique( $ids ) );
}
/**
* Generate an element ID that is not already present in the tree.
*
* @param array $elements Elementor tree.
* @param string|null $requested_id Optional caller-provided ID.
* @return string
*/
function mcp_abilities_elementor_unique_element_id( array $elements, ?string $requested_id = null ): string {
$existing = mcp_abilities_elementor_collect_element_ids( $elements );
$requested_id = is_string( $requested_id ) ? sanitize_key( $requested_id ) : '';
if ( '' !== $requested_id && ! in_array( $requested_id, $existing, true ) ) {
return $requested_id;
}
do {
$id = mcp_abilities_elementor_generate_element_id();
} while ( in_array( $id, $existing, true ) );
return $id;
}
/**
* Create a minimal Elementor container element.
*
* @param array $settings Container settings.
* @param array $children Child elements.
* @param string|null $id Optional ID.
* @return array
*/
function mcp_abilities_elementor_build_container_element( array $settings = array(), array $children = array(), ?string $id = null ): array {
return array(
'id' => $id ?: mcp_abilities_elementor_generate_element_id(),
'elType' => 'container',
'settings' => $settings,
'elements' => array_values( array_filter( $children, 'is_array' ) ),
);
}
/**
* Create a minimal Elementor widget element.
*
* @param string $widget_type Elementor widget type.
* @param array $settings Widget settings.
* @param string|null $id Optional ID.
* @return array
*/
function mcp_abilities_elementor_build_widget_element( string $widget_type, array $settings = array(), ?string $id = null ): array {
return array(
'id' => $id ?: mcp_abilities_elementor_generate_element_id(),
'elType' => 'widget',
'widgetType' => sanitize_key( $widget_type ),
'settings' => $settings,
'elements' => array(),
);
}
/**
* Create a native Elementor Nested Tabs widget containing Posts widgets.
*
* @param array $tabs Tab definitions.
* @param array $base_posts_settings Settings shared by all Posts widgets.
* @param array $tabs_settings Nested Tabs widget settings.
* @param string|null $id Optional tabs widget ID.
* @param array $existing_ids IDs already present in the document.
* @return array|WP_Error
*/
function mcp_abilities_elementor_build_post_tabs_element( array $tabs, array $base_posts_settings = array(), array $tabs_settings = array(), ?string $id = null, array $existing_ids = array() ) {
$existing_ids = array_values( array_unique( array_filter( array_map( 'strval', $existing_ids ) ) ) );
$next_id = static function ( ?string $requested_id = null ) use ( &$existing_ids ): string {
$requested_id = is_string( $requested_id ) ? sanitize_key( $requested_id ) : '';
if ( '' !== $requested_id && ! in_array( $requested_id, $existing_ids, true ) ) {
$existing_ids[] = $requested_id;
return $requested_id;
}
do {
$generated = mcp_abilities_elementor_generate_element_id();
} while ( in_array( $generated, $existing_ids, true ) );
$existing_ids[] = $generated;
return $generated;
};
$tabs_widget_id = $next_id( $id );
$settings = array_replace_recursive(
array(
'tabs_direction' => 'block-start',
'tabs_justify_horizontal' => 'start',
'horizontal_scroll' => 'disable',
'breakpoint_selector' => 'none',
),
$tabs_settings
);
if ( isset( $settings['horizontal_scroll_mobile'] ) && ! isset( $settings['horizontal_scroll'] ) ) {
$settings['horizontal_scroll'] = $settings['horizontal_scroll_mobile'];
}
if ( isset( $settings['tabs_direction'] ) && 'row' === $settings['tabs_direction'] ) {
$settings['tabs_direction'] = 'block-start';
}
if ( isset( $settings['tabs_justify_horizontal'] ) && 'flex-start' === $settings['tabs_justify_horizontal'] ) {
$settings['tabs_justify_horizontal'] = 'start';
}
$settings['tabs'] = array();
$child_containers = array();
foreach ( $tabs as $index => $tab ) {
if ( ! is_array( $tab ) ) {
return new WP_Error( 'mcp_elementor_invalid_post_tab', 'Each tab must be an object.' );
}
$title = isset( $tab['title'] ) ? sanitize_text_field( (string) $tab['title'] ) : '';
if ( '' === $title ) {
return new WP_Error( 'mcp_elementor_invalid_post_tab_title', 'Each tab requires a non-empty title.' );
}
$tab_id = $next_id( isset( $tab['tab_id'] ) ? (string) $tab['tab_id'] : $tabs_widget_id . 'tab' . ( $index + 1 ) );
$posts_id = $next_id( isset( $tab['posts_element_id'] ) ? (string) $tab['posts_element_id'] : $tab_id . 'posts' );
$post_settings = $base_posts_settings;
if ( isset( $tab['posts_settings'] ) && is_array( $tab['posts_settings'] ) ) {
$post_settings = array_replace_recursive( $post_settings, $tab['posts_settings'] );
}
$settings['tabs'][] = array(
'_id' => $tab_id,
'tab_title' => $title,
);
$container_settings = array(
'content_width' => 'full',
'flex_direction' => 'column',
'padding' => array(
'unit' => 'px',
'top' => 0,
'right' => 0,
'bottom' => 0,
'left' => 0,
'isLinked' => false,
),
);
if ( isset( $tab['container_settings'] ) && is_array( $tab['container_settings'] ) ) {
$container_settings = array_replace_recursive( $container_settings, $tab['container_settings'] );
}
$child_containers[] = mcp_abilities_elementor_build_container_element(
$container_settings,
array(
mcp_abilities_elementor_build_widget_element( 'posts', $post_settings, $posts_id ),
),
$tab_id
);
}
if ( empty( $settings['tabs'] ) ) {
return new WP_Error( 'mcp_elementor_post_tabs_empty', 'At least one tab is required.' );
}
return array(
'id' => $tabs_widget_id,
'elType' => 'widget',
'widgetType' => 'nested-tabs',
'settings' => $settings,
'elements' => $child_containers,
);
}
/**
* Insert an element into an Elementor tree.
*
* @param array $elements Elementor tree by reference.
* @param array $new_element Element to insert.
* @param string|null $parent_id Parent element ID, or empty for top level.
* @param int $position Position, -1 to append.
* @return bool
*/
function mcp_abilities_elementor_insert_element_in_tree( array &$elements, array $new_element, ?string $parent_id = null, int $position = -1 ): bool {
$parent_id = is_string( $parent_id ) ? trim( $parent_id ) : '';
if ( '' === $parent_id ) {
$insert_at = ( $position >= 0 ) ? min( $position, count( $elements ) ) : count( $elements );
array_splice( $elements, $insert_at, 0, array( $new_element ) );
return true;
}
foreach ( $elements as &$element ) {
if ( ! is_array( $element ) ) {
continue;
}
if ( ( $element['id'] ?? null ) === $parent_id ) {
if ( ! isset( $element['elements'] ) || ! is_array( $element['elements'] ) ) {
$element['elements'] = array();
}
$insert_at = ( $position >= 0 ) ? min( $position, count( $element['elements'] ) ) : count( $element['elements'] );
array_splice( $element['elements'], $insert_at, 0, array( $new_element ) );
return true;
}
if ( isset( $element['elements'] ) && is_array( $element['elements'] ) ) {
if ( mcp_abilities_elementor_insert_element_in_tree( $element['elements'], $new_element, $parent_id, $position ) ) {
return true;
}
}
}
return false;
}
/**
* Remove an element from an Elementor tree and return the removed element.
*
* @param array $elements Elementor tree by reference.
* @param string $target_id Element ID.
* @param array $removed Removed element output.
* @param int $depth Current depth.
* @return bool
*/
function mcp_abilities_elementor_remove_element_from_tree( array &$elements, string $target_id, array &$removed = array(), int $depth = 0 ): bool {
foreach ( $elements as $index => &$element ) {
if ( ! is_array( $element ) ) {
continue;
}
if ( ( $element['id'] ?? null ) === $target_id ) {
$removed = array(
'element' => $element,
'depth' => $depth,
'index' => $index,
);
unset( $elements[ $index ] );
$elements = array_values( $elements );
return true;
}
if ( isset( $element['elements'] ) && is_array( $element['elements'] ) ) {
if ( mcp_abilities_elementor_remove_element_from_tree( $element['elements'], $target_id, $removed, $depth + 1 ) ) {
return true;
}
}
}
return false;
}
/**
* Check whether a subtree contains an element ID.
*
* @param array $element Elementor element.
* @param string $target_id Target ID.
* @return bool
*/
function mcp_abilities_elementor_subtree_contains_element_id( array $element, string $target_id ): bool {
if ( ( $element['id'] ?? null ) === $target_id ) {
return true;
}
$children = isset( $element['elements'] ) && is_array( $element['elements'] ) ? $element['elements'] : array();
foreach ( $children as $child ) {
if ( is_array( $child ) && mcp_abilities_elementor_subtree_contains_element_id( $child, $target_id ) ) {
return true;
}
}
return false;
}
/**
* Reassign all IDs in a duplicated Elementor subtree.
*
* @param array $element Elementor element.
* @param array $existing Existing IDs.