PluginProbe
Elementor Website Builder – more than just a page builder / 4.3.0
Elementor Website Builder – more than just a page builder v4.3.0
4.3.0 4.3.0-beta3 4.3.0-beta2 4.3.0-beta1 4.2.4 4.2.3 4.2.2 4.2.1 4.2.0 4.1.5 4.2.0-beta2 4.2.0-dev2 4.2.0-beta1 4.1.4 4.1.3 4.1.2 4.1.1 4.1.0 4.1.0-beta3 4.1.0-dev3 4.0.9 4.1.0-beta2 4.1.0-dev2 4.0.8 4.1.0-beta1 All 453 releases
elementor / modules / mcp / abilities / manage-elements-ability.php

manage-elements-ability.php in Elementor Website Builder – more than just a page builder 4.3.0, at modules/mcp/abilities/manage-elements-ability.php

873 lines 31.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Elementor\Modules\Mcp\Abilities;
4
5 use Elementor\Core\Base\Document;
6 use Elementor\Core\Utils\Document\Document_Mutator;
7 use Elementor\Modules\AtomicWidgets\CssConverter\Converter_Registry_Factory;
8 use Elementor\Modules\AtomicWidgets\CssConverter\Css_Converter;
9 use Elementor\Modules\AtomicWidgets\CssConverter\Expander_Registry_Factory;
10 use Elementor\Modules\AtomicWidgets\CssConverter\Metrics\Null_Failure_Reporter;
11 use Elementor\Modules\AtomicWidgets\CssConverter\Variable_Prop_Value_Transformer;
12 use Elementor\Modules\AtomicWidgets\Module as AtomicWidgetsModule;
13 use Elementor\Modules\AtomicWidgets\PlainResolvers\Plain_Values_Resolver;
14 use Elementor\Modules\Components\Components_Repository;
15 use Elementor\Modules\GlobalClasses\Global_Classes_Repository;
16 use Elementor\Modules\GlobalClasses\Utils\Atomic_Elements_Utils;
17 use Elementor\Modules\Interactions\Module as Interactions_Module;
18 use Elementor\Modules\Mcp\Abilities\Appliers\Class_Applier;
19 use Elementor\Modules\Mcp\Abilities\Appliers\Component_Instance_Applier;
20 use Elementor\Modules\Mcp\Abilities\Appliers\Element_Config_Applier;
21 use Elementor\Modules\Mcp\Abilities\Appliers\Interactions_Applier;
22 use Elementor\Modules\Mcp\Abilities\Appliers\Style_Applier;
23 use Elementor\Modules\Mcp\Abilities\Build_Composition\Widget_Type_Resolver;
24 use Elementor\Modules\Mcp\Abilities\Build_Composition\Xml_Parser;
25 use Elementor\Modules\Mcp\Abilities\Utils\Bulk_Operations_Result;
26 use Elementor\Modules\Mcp\Abilities\Utils\Document_Mutation_Save;
27 use Elementor\Modules\Mcp\Abilities\Utils\Tool_Performance_Metrics;
28 use Elementor\Modules\Mcp\Abilities\Utils\Widget_Context_Helper;
29 use Elementor\Modules\Mcp\Events\Mcp_Event_Dispatcher;
30 use Elementor\Modules\Variables\Module as Variables_Module;
31 use Elementor\Modules\Variables\Services\Batch_Operations\Batch_Processor;
32 use Elementor\Modules\Variables\Services\Variables_Service;
33 use Elementor\Modules\Variables\Storage\Variables_Repository;
34 use Elementor\Plugin;
35
36 if ( ! defined( 'ABSPATH' ) ) {
37 exit;
38 }
39
40 class Manage_Elements_Ability extends Abstract_Ability {
41
42 const MAX_BATCH_SIZE = 50;
43
44 private ?Document_Mutator $mutator;
45
46 public function __construct( ?Document_Mutator $mutator = null ) {
47 $this->mutator = $mutator;
48 }
49
50 protected function get_ability_id(): string {
51 return 'elementor/manage-elements';
52 }
53
54 protected function get_definition(): Ability_Definition {
55 return new Ability_Definition(
56 __( 'Manage Elements', 'elementor' ),
57 sprintf(
58 /* translators: %s: comma-separated list of V3-allowlisted widget types. */
59 __( 'Bulk surgical edits on existing V4 (atomic) elements in a document (up to 50 operations applied to a single document tree, saved once). V4 elements and a closed V3 allowlist (%s — see elementor/list-widget-schemas) can be operation targets. Allowlisted V3 updates: settings merge raw without schema validation; classes are written to V3\'s space-separated _css_classes; style CSS is wrapped in `selector { ... }` and stored in V3\'s custom_css (requires Elementor Pro, otherwise emits a warning). Other V3 targets return elementor_v3_not_supported per-op and must be edited directly in the Elementor editor. new_parent_id on action=move may reference either V3 or V4 containers. Each operation: action=update merges partial plain settings, plain-CSS string style (with pseudo-state and breakpoint support; breakpoints use @media (--mobile) syntax — NOT pixel queries), global class labels, and native-shape interactions; action=delete removes the element; action=move re-parents it under new_parent_id at optional index; action=duplicate clones the element (with fresh ids) right after the source. WARNING: This tool performs a read-modify-write on the current document. Do NOT use element IDs obtained from a prior get-page-structure read if build-composition was called in between — use only IDs from the build-composition resolved_xml response to avoid silently overwriting its changes.', 'elementor' ),
60 implode( ', ', Widget_Context_Helper::V3_ALLOWLIST )
61 ),
62 'elementor',
63 [
64 'type' => 'object',
65 'required' => [ 'status', 'results', 'post_id', 'edit_url' ],
66 'properties' => [
67 'status' => [ 'type' => 'string' ],
68 'results' => [ 'type' => 'array' ],
69 'post_id' => [ 'type' => 'integer' ],
70 'edit_url' => [
71 'type' => 'string',
72 'format' => 'uri',
73 'description' => 'Elementor editor URL for the document. Share with the user when they need a link (they must be logged into WordPress as an editor). To self-validate the render, call elementor/create-preview-link.',
74 ],
75 'version' => [ 'type' => 'string' ],
76 ],
77 ],
78 [
79 'annotations' => [
80 'readonly' => false,
81 'idempotent' => false,
82 'destructive' => true,
83 ],
84 ],
85 fn() => current_user_can( 'edit_posts' ),
86 [
87 'type' => 'object',
88 'required' => [ 'post_id', 'operations' ],
89 'properties' => [
90 'post_id' => [ 'type' => 'integer' ],
91 'operations' => [
92 'type' => 'array',
93 'description' => 'Bulk operations (1–50) applied in order to a single document tree, saved once at the end. Partial success is supported: failed ops return per-op errors while sibling valid ops still apply.',
94 'items' => [
95 'type' => 'object',
96 'required' => [ 'action', 'element_id' ],
97 'properties' => [
98 'action' => [
99 'type' => 'string',
100 'enum' => [ 'update', 'delete', 'move', 'duplicate' ],
101 ],
102 'element_id' => [ 'type' => 'string' ],
103 'settings' => [
104 'type' => 'object',
105 'description' => 'update only: partial plain settings map merged onto existing settings. Set a top-level key to null to remove it from the element\'s settings (subject to widget schema validation).',
106 ],
107 'style' => [
108 'type' => 'string',
109 'description' => 'update only: plain CSS string. Supports &:hover/&:focus/&:active nesting and @media(--breakpoint) blocks (e.g. @media(--mobile)). Merged with existing local style variants. Use style_apply_mode to control merge behaviour.',
110 ],
111 'style_apply_mode' => [
112 'type' => 'string',
113 'enum' => [ 'patch', 'replace' ],
114 'default' => 'patch',
115 'description' => 'patch (default): merge incoming style variants with existing. replace: discard existing variants for the affected breakpoints before writing new ones. Pass an empty string with replace to wipe all local style variants.',
116 ],
117 'classes' => [
118 'type' => 'array',
119 'items' => [ 'type' => 'string' ],
120 'description' => 'update only: global class labels to attach (prepended to existing). Pass an empty array [] to remove all global classes from the element (local styles are preserved).',
121 ],
122 'interactions' => [
123 'type' => 'array',
124 'items' => [ 'type' => 'object' ],
125 'description' => 'update only: array of interaction items in the native shape. Replaces existing interactions on the element; send [] to clear. Read elementor://interactions/schema for the full shape.',
126 ],
127 'new_parent_id' => [
128 'type' => 'string',
129 'description' => "move only: target parent id or 'document' for root.",
130 ],
131 'index' => [
132 'type' => [ 'integer', 'null' ],
133 'description' => 'move only: insertion index within new_parent_id (null = append).',
134 ],
135 ],
136 ],
137 ],
138 ],
139 ]
140 );
141 }
142
143 public function execute( $input = [] ) {
144 $started_at = hrtime( true );
145 $input = is_array( $input ) ? $input : [];
146 $post_id = isset( $input['post_id'] ) ? (int) $input['post_id'] : 0;
147 $operations = $input['operations'] ?? null;
148
149 if ( empty( $input['post_id'] ) ) {
150 $error = $this->bad_request( __( 'post_id is required.', 'elementor' ) );
151 $this->emit_mcp_manage_elements_executed( $started_at, $post_id, null, $error );
152 return $error;
153 }
154
155 if ( ! is_array( $operations ) ) {
156 $error = $this->bad_request( __( 'operations array is required.', 'elementor' ) );
157 $this->emit_mcp_manage_elements_executed( $started_at, $post_id, null, $error );
158 return $error;
159 }
160
161 if ( empty( $operations ) ) {
162 $error = $this->bad_request( __( 'operations must not be empty.', 'elementor' ) );
163 $this->emit_mcp_manage_elements_executed( $started_at, $post_id, null, $error );
164 return $error;
165 }
166
167 if ( count( $operations ) > self::MAX_BATCH_SIZE ) {
168 $error = new \WP_Error(
169 'batch_size_exceeded',
170 sprintf(
171 /* translators: %d: maximum operations per request */
172 __( 'Maximum %d operations per request.', 'elementor' ),
173 self::MAX_BATCH_SIZE
174 ),
175 [
176 'status' => \WP_Http::BAD_REQUEST,
177 'max_allowed' => self::MAX_BATCH_SIZE,
178 ]
179 );
180 $this->emit_mcp_manage_elements_executed( $started_at, $post_id, null, $error, $operations );
181 return $error;
182 }
183
184 if ( ! current_user_can( 'edit_post', $post_id ) ) {
185 $error = new \WP_Error(
186 'elementor_forbidden',
187 __( 'You do not have permission to edit this post.', 'elementor' ),
188 [ 'status' => \WP_Http::FORBIDDEN ]
189 );
190 $this->emit_mcp_manage_elements_executed( $started_at, $post_id, null, $error, $operations );
191 return $error;
192 }
193
194 $document = $this->resolve_document( $post_id );
195 if ( is_wp_error( $document ) ) {
196 $this->emit_mcp_manage_elements_executed( $started_at, $post_id, null, $document, $operations );
197 return $document;
198 }
199
200 return $this->handle_bulk( $document, $operations, $started_at );
201 }
202
203 private function handle_bulk( Document $document, array $operations, int $started_at ): array {
204 $results = new Bulk_Operations_Result();
205 $tree = $this->get_tree( $document );
206 $any_change = false;
207 $pending_events = [];
208 $all_warning_codes = [];
209 $class_attachments = 0;
210 $interactions_count = 0;
211
212 foreach ( $operations as $index => $operation ) {
213 $index = (int) $index;
214
215 if ( ! is_array( $operation ) ) {
216 $results->add_error( $index, '', 'invalid_input', __( 'Invalid operation.', 'elementor' ) );
217 continue;
218 }
219
220 $action = $operation['action'] ?? '';
221 $element_id = $operation['element_id'] ?? '';
222
223 if ( ! is_string( $element_id ) || '' === $element_id ) {
224 $results->add_error( $index, $action, 'invalid_input', __( 'element_id is required.', 'elementor' ) );
225 continue;
226 }
227
228 $outcome = $this->apply_operation( $document, $tree, $action, $element_id, $operation );
229
230 if ( is_wp_error( $outcome ) ) {
231 $results->add_error( $index, $action, $outcome->get_error_code(), $outcome->get_error_message() );
232 continue;
233 }
234
235 $tree = $outcome['tree'];
236 $any_change = true;
237
238 $extra = [ 'element_id' => $element_id ];
239 if ( ! empty( $outcome['warnings'] ) ) {
240 $extra['warnings'] = $outcome['warnings'];
241 }
242 $results->add_success( $index, $action, $extra );
243
244 $all_warning_codes = array_merge( $all_warning_codes, $outcome['warning_codes'] ?? [] );
245 $class_attachments += count( $outcome['event_metadata']['applied_classes'] ?? [] );
246 $interactions_count += count( $outcome['event_metadata']['interactions_events'] ?? [] );
247
248 if ( ! empty( $outcome['event_metadata'] ) ) {
249 $pending_events[] = [ 'action' => $action ] + $outcome['event_metadata'];
250 }
251 }
252
253 $response = $results->to_array();
254 $response['post_id'] = (int) $document->get_main_id();
255 $post_id = (int) $document->get_main_id();
256
257 if ( ! $any_change ) {
258 $response = $this->with_edit_url( $response, $document );
259 $this->emit_mcp_manage_elements_executed( $started_at, $post_id, $document, null, $operations, $response, $all_warning_codes, $class_attachments, $interactions_count );
260 return $response;
261 }
262
263 $save_result = Document_Mutation_Save::elements_preserving_live_status( $this->get_mutator(), $document, $tree );
264 if ( is_wp_error( $save_result ) ) {
265 $response['status'] = 'error';
266 $response['save_error'] = $save_result->get_error_message();
267 $response = $this->with_edit_url( $response, $document );
268 $this->emit_mcp_manage_elements_executed( $started_at, $post_id, $document, $save_result, $operations, $response, $all_warning_codes, 0, 0 );
269 return $response;
270 }
271
272 Plugin::$instance->files_manager->clear_cache();
273
274 $this->emit_update_events( $pending_events, $tree );
275
276 $saved_post = $save_result->get_post();
277 $response['version'] = $saved_post ? $saved_post->post_modified_gmt : current_time( 'mysql', true );
278 $response = $this->with_edit_url( $response, $document );
279 $this->emit_mcp_manage_elements_executed( $started_at, $post_id, $document, null, $operations, $response, $all_warning_codes, $class_attachments, $interactions_count );
280 return $response;
281 }
282
283 private function with_edit_url( array $response, Document $document ): array {
284 $response['edit_url'] = $document->get_edit_url();
285
286 return $response;
287 }
288
289 private function apply_operation( Document $document, array $tree, string $action, string $element_id, array $operation ) {
290 $v3_error = $this->reject_v3_target( $tree, $element_id );
291 if ( $v3_error ) {
292 return $v3_error;
293 }
294
295 switch ( $action ) {
296 case 'update':
297 return $this->apply_update( $document, $tree, $element_id, $operation );
298 case 'delete':
299 return $this->apply_delete( $tree, $element_id );
300 case 'move':
301 return $this->apply_move( $tree, $element_id, $operation );
302 case 'duplicate':
303 return $this->apply_duplicate( $tree, $element_id );
304 default:
305 return new \WP_Error(
306 'invalid_input',
307 sprintf(
308 /* translators: %s: action name */
309 __( 'Unknown action: %s.', 'elementor' ),
310 $action
311 )
312 );
313 }
314 }
315
316 private function reject_v3_target( array $tree, string $element_id ): ?\WP_Error {
317 $node = $this->get_mutator()->find_by_id( $tree, $element_id );
318 if ( null === $node ) {
319 return null;
320 }
321
322 $type = $node['widgetType'] ?? $node['elType'] ?? null;
323 if ( ! is_string( $type ) || '' === $type ) {
324 return null;
325 }
326
327 if ( Widget_Context_Helper::is_v3_allowlisted( $type ) ) {
328 return null;
329 }
330
331 $instance = Atomic_Elements_Utils::get_element_instance( $type );
332 if ( $instance && Atomic_Elements_Utils::is_atomic_element( $instance ) ) {
333 return null;
334 }
335
336 return new \WP_Error(
337 'elementor_v3_not_supported',
338 __( 'Legacy V3 element cannot be modified through this MCP. Edit V3 elements directly in the Elementor editor.', 'elementor' ),
339 [
340 'status' => \WP_Http::BAD_REQUEST,
341 'element_id' => $element_id,
342 'version' => 'v3',
343 ]
344 );
345 }
346
347 private function apply_delete( array $tree, string $element_id ) {
348 $new_tree = $this->get_mutator()->remove( $tree, $element_id );
349 if ( is_wp_error( $new_tree ) ) {
350 return $this->to_public_error( $new_tree );
351 }
352
353 return [
354 'tree' => $new_tree,
355 'warnings' => [],
356 'warning_codes' => [],
357 ];
358 }
359
360 private function apply_duplicate( array $tree, string $element_id ) {
361 $source_node = $this->get_mutator()->find_by_id( $tree, $element_id );
362 $new_tree = $this->get_mutator()->duplicate( $tree, $element_id );
363 if ( is_wp_error( $new_tree ) ) {
364 return $this->to_public_error( $new_tree );
365 }
366
367 return [
368 'tree' => $new_tree,
369 'warnings' => [],
370 'warning_codes' => [],
371 'event_metadata' => [
372 'duplicated_element_types' => is_array( $source_node ) ? $this->collect_element_types( $source_node ) : [],
373 ],
374 ];
375 }
376
377 private function collect_element_types( array $node ): array {
378 $types = [];
379 $stack = [ $node ];
380
381 while ( ! empty( $stack ) ) {
382 $current = array_pop( $stack );
383 $type = $current['widgetType'] ?? $current['elType'] ?? '';
384
385 if ( '' !== $type ) {
386 $types[] = $type;
387 }
388
389 foreach ( $current['elements'] ?? [] as $child ) {
390 $stack[] = $child;
391 }
392 }
393
394 return $types;
395 }
396
397 private function apply_move( array $tree, string $element_id, array $operation ) {
398 $new_parent_id = $operation['new_parent_id'] ?? '';
399 if ( ! is_string( $new_parent_id ) || '' === $new_parent_id ) {
400 return new \WP_Error( 'invalid_input', __( 'new_parent_id is required for action=move.', 'elementor' ) );
401 }
402
403 $index = array_key_exists( 'index', $operation ) && null !== $operation['index'] ? (int) $operation['index'] : null;
404
405 $new_tree = $this->get_mutator()->move( $tree, $element_id, $new_parent_id, $index );
406 if ( is_wp_error( $new_tree ) ) {
407 return $this->to_public_error( $new_tree );
408 }
409
410 return [
411 'tree' => $new_tree,
412 'warnings' => [],
413 'warning_codes' => [],
414 ];
415 }
416
417 private function apply_update( Document $document, array $tree, string $element_id, array $operation ) {
418 $settings = $this->as_map( $operation['settings'] ?? [] );
419 $style = $operation['style'] ?? null;
420 $has_style = isset( $operation['style'] );
421 $has_classes = array_key_exists( 'classes', $operation );
422 $classes = $has_classes ? $operation['classes'] : null;
423 $interactions = $operation['interactions'] ?? null;
424
425 $has_change = ! empty( $settings ) || $has_style || $has_classes || null !== $interactions;
426 if ( ! $has_change ) {
427 return new \WP_Error( 'invalid_input', __( 'update requires at least one of settings, style, classes, or interactions.', 'elementor' ) );
428 }
429
430 $style_apply_mode = $operation['style_apply_mode'] ?? 'patch';
431 if ( ! in_array( $style_apply_mode, [ 'patch', 'replace' ], true ) ) {
432 return new \WP_Error( 'invalid_input', __( 'style_apply_mode must be "patch" or "replace".', 'elementor' ) );
433 }
434
435 if ( null === $this->get_mutator()->find_by_id( $tree, $element_id ) ) {
436 return new \WP_Error( 'elementor_not_found', __( 'Element not found.', 'elementor' ) );
437 }
438
439 $index = $this->get_mutator()->build_ref_index( $tree, $element_id );
440 if ( empty( $index ) ) {
441 return new \WP_Error( 'elementor_not_found', __( 'Element not found.', 'elementor' ) );
442 }
443
444 $node_snapshot = $index[ $element_id ];
445 $element_type = $node_snapshot['widgetType'] ?? $node_snapshot['elType'] ?? null;
446 if ( ! $element_type ) {
447 return new \WP_Error( 'invalid_input', __( 'Element has no resolvable type.', 'elementor' ) );
448 }
449
450 $xml_parser = new Xml_Parser();
451 $type_resolver = new Widget_Type_Resolver( $xml_parser );
452 $widget_config = $type_resolver->resolve_type_config( $element_type );
453 if ( is_wp_error( $widget_config ) ) {
454 return $widget_config;
455 }
456 $widget_configs = [ $element_type => $widget_config ];
457
458 $variables_service = $this->create_variables_service();
459 $warnings = [];
460 $warning_codes = [];
461 $applied_classes = [];
462 $variable_connections = [];
463 $interactions_events = [];
464
465 if ( null !== $interactions ) {
466 if ( ! is_array( $interactions ) ) {
467 return new \WP_Error( 'invalid_input', __( 'interactions must be an array of interaction items.', 'elementor' ) );
468 }
469 if ( ! Plugin::$instance->experiments->is_feature_active( Interactions_Module::EXPERIMENT_NAME ) ) {
470 return new \WP_Error(
471 'elementor_invalid_interactions',
472 __( 'Interactions experiment is not active. Interactions were not applied.', 'elementor' ),
473 [ 'status' => \WP_Http::BAD_REQUEST ]
474 );
475 }
476
477 $previous_items = $node_snapshot['interactions']['items'] ?? [];
478
479 $interactions_applier = new Interactions_Applier( $this->get_plain_values_resolver() );
480 $interactions_result = $interactions_applier->apply( $index, [ $element_id => $interactions ] );
481 if ( $interactions_result['error'] ) {
482 return $interactions_result['error'];
483 }
484 $warnings = array_merge( $warnings, $interactions_result['warnings'] );
485
486 $interactions_events = $this->build_interactions_events( (string) $element_type, $previous_items, $interactions );
487 }
488
489 if ( ! empty( $settings ) ) {
490 if ( Element_Config_Applier::COMPONENT_INSTANCE_WIDGET_TYPE === $element_type ) {
491 $component_applier = new Component_Instance_Applier( new Components_Repository(), $this->get_plain_values_resolver() );
492 $component_error = $component_applier->apply_partial( $index, [ $element_id => $settings ], $document );
493 if ( $component_error ) {
494 return $component_error;
495 }
496 } else {
497 $config_applier = new Element_Config_Applier( $type_resolver, $this->get_plain_values_resolver() );
498 $config_result = $config_applier->apply(
499 $index,
500 [ $element_id => $settings ],
501 $widget_configs,
502 $document
503 );
504 if ( $config_result['error'] ) {
505 return $config_result['error'];
506 }
507 $warnings = array_merge( $warnings, $config_result['warnings'] );
508 $warning_codes = array_merge( $warning_codes, $config_result['warning_codes'] ?? [] );
509 }
510 }
511
512 if ( $has_classes ) {
513 if ( ! is_array( $classes ) ) {
514 return new \WP_Error( 'invalid_input', __( 'classes must be an array of global class labels.', 'elementor' ) );
515 }
516 $class_applier = new Class_Applier( $this->create_global_classes_repository() );
517 $class_error = $class_applier->apply( $index, [ $element_id => $classes ] );
518 if ( $class_error ) {
519 return $class_error;
520 }
521 $applied_classes = $classes;
522 }
523
524 if ( $has_style ) {
525 $style_applier = new Style_Applier( $this->create_css_converter( $variables_service ), $this->get_active_breakpoints() );
526 $style_result = $style_applier->apply( $index, [ $element_id => $style ], $style_apply_mode, $widget_configs );
527 if ( $style_result['error'] ) {
528 return $style_result['error'];
529 }
530 $warnings = array_merge( $warnings, $style_result['warnings'] );
531 $warning_codes = array_merge( $warning_codes, $style_result['warning_codes'] ?? [] );
532 $variable_connections = $style_result['variable_connections'][ $element_id ] ?? [];
533 }
534
535 return [
536 'tree' => $tree,
537 'warnings' => $warnings,
538 'warning_codes' => $warning_codes,
539 'event_metadata' => [
540 'element_id' => $element_id,
541 'element_type' => (string) $element_type,
542 'applied_classes' => $applied_classes,
543 'variable_connections' => $variable_connections,
544 'interactions_events' => $interactions_events,
545 ],
546 ];
547 }
548
549 protected function build_interactions_events( string $element_type, array $previous_items, array $new_items ): array {
550 if ( [] === $new_items ) {
551 return [
552 [
553 'event_name' => 'interactions_cleared',
554 'payload' => [
555 'affected_element_type' => $element_type,
556 'target_value' => count( $previous_items ),
557 ],
558 ],
559 ];
560 }
561
562 $previous_by_id = [];
563 foreach ( $previous_items as $item ) {
564 if ( ! is_array( $item ) ) {
565 continue;
566 }
567
568 $id = $this->extract_interaction_id( $item );
569 if ( null !== $id ) {
570 $previous_by_id[ $id ] = true;
571 }
572 }
573
574 $events = [];
575
576 foreach ( $new_items as $item ) {
577 if ( ! is_array( $item ) ) {
578 continue;
579 }
580
581 $id = $item['interaction_id'] ?? '';
582 $is_update = is_string( $id ) && '' !== $id && isset( $previous_by_id[ $id ] );
583 $event_name = $is_update ? 'interaction_updated' : 'interaction_created';
584
585 $events[] = [
586 'event_name' => $event_name,
587 'payload' => [
588 'affected_element_type' => $element_type,
589 'interaction_trigger' => $this->stringify_interaction_field( $item['trigger'] ?? '' ),
590 'interaction_effect' => $this->stringify_interaction_field( $item['animation'] ?? '' ),
591 ],
592 ];
593 }
594
595 return $events;
596 }
597
598 private function extract_interaction_id( array $item ): ?string {
599 if ( isset( $item['interaction_id'] ) && is_string( $item['interaction_id'] ) && '' !== $item['interaction_id'] ) {
600 return $item['interaction_id'];
601 }
602
603 $nested = $item['value']['interaction_id']['value'] ?? $item['interaction_id']['value'] ?? null;
604
605 if ( is_string( $nested ) && '' !== $nested ) {
606 return $nested;
607 }
608
609 return null;
610 }
611
612 private function stringify_interaction_field( $value ): string {
613 if ( is_string( $value ) ) {
614 return $value;
615 }
616
617 if ( is_array( $value ) ) {
618 if ( isset( $value['effect'] ) && is_string( $value['effect'] ) ) {
619 return $value['effect'];
620 }
621
622 $nested_effect = $value['value']['effect']['value'] ?? $value['effect']['value'] ?? null;
623 if ( is_string( $nested_effect ) && '' !== $nested_effect ) {
624 return $nested_effect;
625 }
626
627 if ( isset( $value['value'] ) && ( is_string( $value['value'] ) || is_numeric( $value['value'] ) ) ) {
628 return (string) $value['value'];
629 }
630 if ( isset( $value['$$type'] ) && is_string( $value['$$type'] ) ) {
631 return (string) $value['$$type'];
632 }
633 }
634
635 return '';
636 }
637
638 private function resolve_document( int $post_id ) {
639 $document = Plugin::$instance->documents->get_doc_or_auto_save( $post_id, get_current_user_id() )
640 ?? Plugin::$instance->documents->get( $post_id );
641
642 if ( ! $document ) {
643 return new \WP_Error(
644 'elementor_not_found',
645 __( 'Post not found.', 'elementor' ),
646 [ 'status' => \WP_Http::NOT_FOUND ]
647 );
648 }
649
650 return $document;
651 }
652
653 private function get_tree( Document $document ): array {
654 $tree = $document->get_elements_data();
655
656 return is_array( $tree ) ? $tree : [];
657 }
658
659 private function to_public_error( \WP_Error $error ): \WP_Error {
660 $data = $error->get_error_data();
661 $status = is_array( $data ) && isset( $data['status'] ) ? $data['status'] : \WP_Http::NOT_FOUND;
662
663 if ( \WP_Http::NOT_FOUND === $status ) {
664 return new \WP_Error( 'elementor_not_found', $error->get_error_message(), [ 'status' => $status ] );
665 }
666
667 return $error;
668 }
669
670 private function bad_request( string $message ): \WP_Error {
671 return new \WP_Error( 'invalid_input', $message, [ 'status' => \WP_Http::BAD_REQUEST ] );
672 }
673
674 private function as_map( $value ): array {
675 if ( is_object( $value ) ) {
676 $value = (array) $value;
677 }
678
679 return is_array( $value ) ? $value : [];
680 }
681
682 private function get_mutator(): Document_Mutator {
683 return $this->mutator ?? Document_Mutator::instance();
684 }
685
686 private function create_global_classes_repository(): Global_Classes_Repository {
687 $kit = Plugin::$instance->kits_manager->get_active_kit();
688
689 return Global_Classes_Repository::make( $kit );
690 }
691
692 private function create_css_converter( ?Variables_Service $variables_service ): Css_Converter {
693 $variable_transformer = $variables_service
694 ? new Variable_Prop_Value_Transformer( $variables_service )
695 : null;
696
697 return new Css_Converter(
698 Converter_Registry_Factory::create( $variables_service ),
699 new Null_Failure_Reporter(),
700 Expander_Registry_Factory::create( $variables_service ),
701 $variable_transformer
702 );
703 }
704
705 private function create_variables_service(): ?Variables_Service {
706 if ( ! $this->is_variables_active() ) {
707 return null;
708 }
709
710 $kit = Plugin::$instance->kits_manager->get_active_kit();
711 if ( ! $kit ) {
712 return null;
713 }
714
715 return new Variables_Service(
716 new Variables_Repository( $kit ),
717 new Batch_Processor()
718 );
719 }
720
721 private function get_plain_values_resolver(): Plain_Values_Resolver {
722 return AtomicWidgetsModule::instance()->get_settings_plain_values_resolver();
723 }
724
725 private function is_variables_active(): bool {
726 $experiments = Plugin::$instance->experiments;
727
728 return $experiments->is_feature_active( Variables_Module::EXPERIMENT_NAME )
729 && $experiments->is_feature_active( AtomicWidgetsModule::EXPERIMENT_NAME );
730 }
731
732 private function get_active_breakpoints(): array {
733 return array_keys( Plugin::$instance->breakpoints->get_active_breakpoints() );
734 }
735
736 private function emit_update_events( array $pending_events, array $tree ): void {
737 if ( empty( $pending_events ) ) {
738 return;
739 }
740
741 $all_labels = $this->create_global_classes_repository()->all_labels();
742 $class_counts = $this->count_class_usage_in_tree( $tree );
743
744 foreach ( $pending_events as $meta ) {
745 $action = $meta['action'] ?? '';
746
747 if ( 'duplicate' === $action ) {
748 foreach ( $meta['duplicated_element_types'] ?? [] as $element_name ) {
749 Mcp_Event_Dispatcher::emit( 'element_added', [
750 'element_name' => $element_name,
751 ] );
752 }
753 continue;
754 }
755
756 $element_type = $meta['element_type'] ?? '';
757
758 foreach ( $meta['applied_classes'] ?? [] as $label ) {
759 $class_id = array_search( $label, $all_labels, true );
760
761 if ( false === $class_id ) {
762 continue;
763 }
764
765 Mcp_Event_Dispatcher::emit( 'class_applied', [
766 'target_name' => 'apply_class',
767 'id' => (string) $class_id,
768 'name' => $label,
769 'affected_element_type' => $element_type,
770 'total_instances_after_apply' => $class_counts[ $class_id ] ?? 0,
771 ] );
772 }
773
774 foreach ( $meta['variable_connections'] as $connection ) {
775 Mcp_Event_Dispatcher::emit( 'variable_connected', [
776 'id' => $connection['variable_id'],
777 'var_type' => $connection['var_type'],
778 'control_path' => $connection['control_path'],
779 ] );
780 }
781
782 foreach ( $meta['interactions_events'] ?? [] as $ie ) {
783 Mcp_Event_Dispatcher::emit( $ie['event_name'], $ie['payload'] );
784 }
785 }
786 }
787
788 private function count_class_usage_in_tree( array $tree ): array {
789 $counts = [];
790 $this->walk_tree_for_class_counts( $tree, $counts );
791 return $counts;
792 }
793
794 private function walk_tree_for_class_counts( array $elements, array &$counts ): void {
795 foreach ( $elements as $element ) {
796 $class_values = $element['settings']['classes']['value'] ?? [];
797
798 if ( is_array( $class_values ) ) {
799 foreach ( $class_values as $class_id ) {
800 if ( is_string( $class_id ) && ! str_starts_with( $class_id, Style_Applier::LOCAL_STYLE_ID_PREFIX ) ) {
801 $counts[ $class_id ] = ( $counts[ $class_id ] ?? 0 ) + 1;
802 }
803 }
804 }
805
806 if ( ! empty( $element['elements'] ) ) {
807 $this->walk_tree_for_class_counts( $element['elements'], $counts );
808 }
809 }
810 }
811
812 private function emit_mcp_manage_elements_executed(
813 int $started_at,
814 int $post_id,
815 ?Document $document = null,
816 ?\WP_Error $top_level_error = null,
817 array $operations = [],
818 array $response = [],
819 array $warning_codes = [],
820 int $class_attachments = 0,
821 int $interactions_count = 0
822 ): void {
823 $duration_ms = Tool_Performance_Metrics::duration_ms_since( $started_at );
824
825 [ 'status' => $status, 'error_code' => $error_code ] = Tool_Performance_Metrics::resolve_status( $response, $top_level_error );
826
827 $failed_results = array_filter( $response['results'] ?? [], fn( $r ) => 'error' === ( $r['status'] ?? '' ) );
828 $failed_count = count( $failed_results );
829 $failed_codes = array_values( array_unique( array_column( $failed_results, 'code' ) ) );
830
831 $ops_count = count( $operations );
832 $by_action = [];
833 foreach ( $operations as $op ) {
834 $action = $op['action'] ?? '';
835 if ( is_string( $action ) && '' !== $action ) {
836 $by_action[ $action ] = ( $by_action[ $action ] ?? 0 ) + 1;
837 }
838 }
839
840 $dominant_action = '';
841 if ( ! empty( $by_action ) ) {
842 arsort( $by_action );
843 $dominant_action = (string) array_key_first( $by_action );
844 }
845
846 $payload = [
847 'tool_name' => $this->get_ability_id(),
848 'status' => $status,
849 'duration_ms' => $duration_ms,
850 'post_id' => $post_id,
851 'action' => $dominant_action,
852 'operations_count' => $ops_count,
853 'operations_by_type' => $by_action,
854 'failed_operations_count' => $failed_count,
855 'failed_operation_codes' => $failed_codes,
856 'class_attachments_count' => $class_attachments,
857 'interactions_applied_count' => $interactions_count,
858 'warning_count' => count( array_unique( $warning_codes ) ),
859 'warning_types' => array_values( array_unique( $warning_codes ) ),
860 ];
861
862 if ( null !== $document ) {
863 $payload['document_type'] = $document->get_name();
864 }
865
866 if ( null !== $error_code ) {
867 $payload['error_code'] = $error_code;
868 }
869
870 Mcp_Event_Dispatcher::emit( 'mcp_manage_elements_executed', $payload );
871 }
872 }
873