PluginProbe
Elementor Website Builder – more than just a page builder / 3.28.0-dev3
Elementor Website Builder – more than just a page builder v3.28.0-dev3
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 4.1.0-dev1 4.0.7 All 451 releases
elementor / app / modules / import-export / module.php

module.php in Elementor Website Builder – more than just a page builder 3.28.0-dev3, at app/modules/import-export/module.php

913 lines 29.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace Elementor\App\Modules\ImportExport;
3
4 use Elementor\App\Modules\ImportExport\Processes\Export;
5 use Elementor\App\Modules\ImportExport\Processes\Import;
6 use Elementor\App\Modules\ImportExport\Processes\Revert;
7 use Elementor\Core\Base\Module as BaseModule;
8 use Elementor\Core\Common\Modules\Ajax\Module as Ajax;
9 use Elementor\Core\Files\Uploads_Manager;
10 use Elementor\Modules\System_Info\Reporters\Server;
11 use Elementor\Plugin;
12 use Elementor\Tools;
13 use Elementor\Utils as ElementorUtils;
14 use Elementor\App\Modules\ImportExport\Utils as ImportExportUtils;
15
16 if ( ! defined( 'ABSPATH' ) ) {
17 exit; // Exit if accessed directly.
18 }
19
20 /**
21 * Import Export Module
22 *
23 * Responsible for initializing Elementor App functionality
24 */
25 class Module extends BaseModule {
26 const FORMAT_VERSION = '2.0';
27
28 const EXPORT_TRIGGER_KEY = 'elementor_export_kit';
29
30 const UPLOAD_TRIGGER_KEY = 'elementor_upload_kit';
31
32 const IMPORT_TRIGGER_KEY = 'elementor_import_kit';
33
34 const IMPORT_RUNNER_TRIGGER_KEY = 'elementor_import_kit__runner';
35
36 const REFERRER_KIT_LIBRARY = 'kit-library';
37
38 const REFERRER_LOCAL = 'local';
39
40 const PLUGIN_PERMISSIONS_ERROR_KEY = 'plugin-installation-permissions-error';
41
42 const KIT_LIBRARY_ERROR_KEY = 'invalid-kit-library-zip-error';
43
44 const NO_WRITE_PERMISSIONS_KEY = 'no-write-permissions';
45
46 const THIRD_PARTY_ERROR = 'third-party-error';
47
48 const DOMDOCUMENT_MISSING = 'domdocument-missing';
49
50 const OPTION_KEY_ELEMENTOR_IMPORT_SESSIONS = 'elementor_import_sessions';
51
52 const OPTION_KEY_ELEMENTOR_REVERT_SESSIONS = 'elementor_revert_sessions';
53
54 const META_KEY_ELEMENTOR_IMPORT_SESSION_ID = '_elementor_import_session_id';
55
56 const META_KEY_ELEMENTOR_EDIT_MODE = '_elementor_edit_mode';
57 const IMPORT_PLUGINS_ACTION = 'import-plugins';
58
59 /**
60 * Assigning the export process to a property, so we can use the process from outside the class.
61 *
62 * @var Export
63 */
64 public $export;
65
66 /**
67 * Assigning the import process to a property, so we can use the process from outside the class.
68 *
69 * @var Import
70 */
71 public $import;
72
73 /**
74 * Assigning the revert process to a property, so we can use the process from outside the class.
75 *
76 * @var Revert
77 */
78 public $revert;
79
80 /**
81 * Get name.
82 *
83 * @access public
84 *
85 * @return string
86 */
87 public function get_name() {
88 return 'import-export';
89 }
90
91 public function __construct() {
92 $this->register_actions();
93
94 if ( ElementorUtils::is_wp_cli() ) {
95 \WP_CLI::add_command( 'elementor kit', WP_CLI::class );
96 }
97
98 ( new Usage() )->register();
99
100 $this->revert = new Revert();
101 }
102
103 public function get_init_settings() {
104 if ( ! Plugin::$instance->app->is_current() ) {
105 return [];
106 }
107
108 return $this->get_config_data();
109 }
110
111 /**
112 * Register the import/export tab in elementor tools.
113 */
114 public function register_settings_tab( Tools $tools ) {
115 $tools->add_tab( 'import-export-kit', [
116 'label' => esc_html__( 'Import / Export Kit', 'elementor' ),
117 'sections' => [
118 'intro' => [
119 'label' => esc_html__( 'Template Kits', 'elementor' ),
120 'callback' => function() {
121 $this->render_import_export_tab_content();
122 },
123 'fields' => [],
124 ],
125 ],
126 ] );
127 }
128
129 /**
130 * Render the import/export tab content.
131 */
132 private function render_import_export_tab_content() {
133 $intro_text_link = sprintf( '<a href="https://go.elementor.com/wp-dash-import-export-general/" target="_blank">%s</a>', esc_html__( 'Learn more', 'elementor' ) );
134
135 $intro_text = sprintf(
136 /* translators: 1: New line break, 2: Learn more link. */
137 __( 'Design sites faster with a template kit that contains some or all components of a complete site, like templates, content & site settings.%1$sYou can import a kit and apply it to your site, or export the elements from this site to be used anywhere else. %2$s', 'elementor' ),
138 '<br>',
139 $intro_text_link
140 );
141
142 $content_data = [
143 'export' => [
144 'title' => esc_html__( 'Export a Template Kit', 'elementor' ),
145 'button' => [
146 'url' => Plugin::$instance->app->get_base_url() . '#/export',
147 'text' => esc_html__( 'Start Export', 'elementor' ),
148 ],
149 'description' => esc_html__( 'Bundle your whole site - or just some of its elements - to be used for another website.', 'elementor' ),
150 'link' => [
151 'url' => 'https://go.elementor.com/wp-dash-import-export-export-flow/',
152 'text' => esc_html__( 'Learn More', 'elementor' ),
153 ],
154 ],
155 'import' => [
156 'title' => esc_html__( 'Import a Template Kit', 'elementor' ),
157 'button' => [
158 'url' => Plugin::$instance->app->get_base_url() . '#/import',
159 'text' => esc_html__( 'Start Import', 'elementor' ),
160 ],
161 'description' => esc_html__( 'Apply the design and settings of another site to this one.', 'elementor' ),
162 'link' => [
163 'url' => 'https://go.elementor.com/wp-dash-import-export-import-flow/',
164 'text' => esc_html__( 'Learn More', 'elementor' ),
165 ],
166 ],
167 ];
168
169 $last_imported_kit = $this->revert->get_last_import_session();
170 $penultimate_imported_kit = $this->revert->get_penultimate_import_session();
171
172 $user_date_format = get_option( 'date_format' );
173 $user_time_format = get_option( 'time_format' );
174 $date_format = $user_date_format . ' ' . $user_time_format;
175
176 $should_show_revert_section = $this->should_show_revert_section( $last_imported_kit );
177
178 if ( $should_show_revert_section ) {
179 if ( ! empty( $penultimate_imported_kit ) ) {
180 $revert_text = sprintf(
181 esc_html__( 'Remove all the content and site settings that came with "%1$s" on %2$s %3$s and revert to the site setting that came with "%4$s" on %5$s.', 'elementor' ),
182 ! empty( $last_imported_kit['kit_title'] ) ? $last_imported_kit['kit_title'] : esc_html__( 'imported kit', 'elementor' ),
183 gmdate( $date_format, $last_imported_kit['start_timestamp'] ),
184 '<br>',
185 ! empty( $penultimate_imported_kit['kit_title'] ) ? $penultimate_imported_kit['kit_title'] : esc_html__( 'imported kit', 'elementor' ),
186 gmdate( $date_format, $penultimate_imported_kit['start_timestamp'] )
187 );
188 } else {
189 $revert_text = sprintf(
190 esc_html__( 'Remove all the content and site settings that came with "%1$s" on %2$s.%3$s Your original site settings will be restored.', 'elementor' ),
191 ! empty( $last_imported_kit['kit_title'] ) ? $last_imported_kit['kit_title'] : esc_html__( 'imported kit', 'elementor' ),
192 gmdate( $date_format, $last_imported_kit['start_timestamp'] ),
193 '<br>'
194 );
195 }
196 }
197 ?>
198
199 <div class="tab-import-export-kit__content">
200 <p class="tab-import-export-kit__info"><?php ElementorUtils::print_unescaped_internal_string( $intro_text ); ?></p>
201
202 <div class="tab-import-export-kit__wrapper">
203 <?php foreach ( $content_data as $data ) { ?>
204 <div class="tab-import-export-kit__container">
205 <div class="tab-import-export-kit__box">
206 <h2><?php ElementorUtils::print_unescaped_internal_string( $data['title'] ); ?></h2>
207 <a href="<?php ElementorUtils::print_unescaped_internal_string( $data['button']['url'] ); ?>" class="elementor-button e-primary">
208 <?php ElementorUtils::print_unescaped_internal_string( $data['button']['text'] ); ?>
209 </a>
210 </div>
211 <p><?php ElementorUtils::print_unescaped_internal_string( $data['description'] ); ?></p>
212 <a href="<?php ElementorUtils::print_unescaped_internal_string( $data['link']['url'] ); ?>" target="_blank"><?php ElementorUtils::print_unescaped_internal_string( $data['link']['text'] ); ?></a>
213 </div>
214 <?php } ?>
215 </div>
216
217 <?php
218 if ( $should_show_revert_section ) {
219
220 $link_attributes = [
221 'href' => $this->get_revert_href(),
222 'id' => 'elementor-import-export__revert_kit',
223 'class' => 'button',
224 ];
225 ?>
226 <div class="tab-import-export-kit__revert">
227 <h2>
228 <?php ElementorUtils::print_unescaped_internal_string( esc_html__( 'Remove the most recent Kit', 'elementor' ) ); ?>
229 </h2>
230 <p class="tab-import-export-kit__info">
231 <?php ElementorUtils::print_unescaped_internal_string( $revert_text ); ?>
232 </p>
233 <?php $this->render_last_kit_thumbnail( $last_imported_kit ); ?>
234 <a <?php ElementorUtils::print_html_attributes( $link_attributes ); ?> >
235 <?php ElementorUtils::print_unescaped_internal_string( esc_html__( 'Remove Kit', 'elementor' ) ); ?>
236 </a>
237 </div>
238 <?php } ?>
239 </div>
240 <?php
241 }
242
243 private function get_revert_href(): string {
244 $admin_post_url = admin_url( 'admin-post.php?action=elementor_revert_kit' );
245 $nonced_admin_post_url = wp_nonce_url( $admin_post_url, 'elementor_revert_kit' );
246 return $this->maybe_add_referrer_param( $nonced_admin_post_url );
247 }
248
249 /**
250 * Checks if referred by a kit and adds the referrer ID to the href
251 *
252 * @param string $href
253 *
254 * @return string
255 */
256 private function maybe_add_referrer_param( string $href ): string {
257 $param_name = 'referrer_kit';
258
259 if ( empty( $_GET[ $param_name ] ) ) {
260 return $href;
261 }
262
263 return add_query_arg( $param_name, sanitize_key( $_GET[ $param_name ] ), $href );
264 }
265
266 /**
267 * Render the last kit thumbnail if exists
268 *
269 * @param $last_imported_kit
270 *
271 * @return void
272 */
273 private function render_last_kit_thumbnail( $last_imported_kit ) {
274 if ( empty( $last_imported_kit['kit_thumbnail'] ) ) {
275 return;
276 }
277
278 ?>
279 <div class="tab-import-export-kit__kit-item-row">
280 <article class="tab-import-export-kit__kit-item">
281 <header>
282 <h3>
283 <?php echo esc_html( $last_imported_kit['kit_title'] ); ?>
284 </h3>
285 </header>
286 <img
287 src="<?php echo esc_url( $last_imported_kit['kit_thumbnail'] ); ?>"
288 alt="<?php echo esc_attr( $last_imported_kit['kit_title'] ); ?>"
289 loading="lazy"
290 >
291 </article>
292 </div>
293 <?php
294 }
295
296 /**
297 * Upload a kit zip file and get the kit data.
298 *
299 * Assigning the Import process to the 'import' property,
300 * so it will be available to use in different places such as: WP_Cli, Pro, etc.
301 *
302 * @param string $file Path to the file.
303 * @param string $referrer Referrer of the file 'local' or 'kit-library'.
304 * @return array
305 * @throws \Exception
306 */
307 public function upload_kit( $file, $referrer ) {
308 $this->ensure_writing_permissions();
309
310 $this->import = new Import( $file, [ 'referrer' => $referrer ] );
311
312 return [
313 'session' => $this->import->get_session_id(),
314 'manifest' => $this->import->get_manifest(),
315 'conflicts' => $this->import->get_settings_conflicts(),
316 ];
317 }
318
319 /**
320 * Import a kit by session_id.
321 * Upload and import a kit by kit zip file.
322 *
323 * If the split_to_chunks flag is true, the process won't start
324 * It will initialize the import process and return the session_id and the runners.
325 *
326 * Assigning the Import process to the 'import' property,
327 * so it will be available to use in different places such as: WP_Cli, Pro, etc.
328 *
329 * @param string $path Path to the file or session_id.
330 * @param array $settings Settings the import use to determine which content to import.
331 * (e.g: include, selected_plugins, selected_cpt, selected_override_conditions, etc.)
332 * @param bool $split_to_chunks Determine if the import process should be split into chunks.
333 * @return array
334 * @throws \Exception
335 */
336 public function import_kit( string $path, array $settings, bool $split_to_chunks = false ): array {
337 $this->ensure_writing_permissions();
338 $this->ensure_DOMDocument_exists();
339
340 $this->import = new Import( $path, $settings );
341 $this->import->register_default_runners();
342
343 remove_filter( 'elementor/document/save/data', [ Plugin::$instance->modules_manager->get_modules( 'content-sanitizer' ), 'sanitize_content' ] );
344 do_action( 'elementor/import-export/import-kit', $this->import );
345
346 if ( $split_to_chunks ) {
347 $this->import->init_import_session( true );
348
349 return [
350 'session' => $this->import->get_session_id(),
351 'runners' => $this->import->get_runners_name(),
352 ];
353 }
354
355 return $this->import->run();
356 }
357
358 /**
359 * Resuming import process by re-creating the import instance and running the specific runner.
360 *
361 * @param string $session_id The id off the import session.
362 * @param string $runner_name The specific runner that we want to run.
363 *
364 * @return array Two types of response.
365 * 1. The status and the runner name.
366 * 2. The imported data. (Only if the runner is the last one in the import process)
367 * @throws \Exception
368 */
369 public function import_kit_by_runner( string $session_id, string $runner_name ): array {
370 // Check session_id
371 $this->import = Import::from_session( $session_id );
372 $runners = $this->import->get_runners_name();
373
374 $run = $this->import->run_runner( $runner_name );
375
376 if ( end( $runners ) === $run['runner'] ) {
377 return $this->import->get_imported_data();
378 }
379
380 return $run;
381 }
382
383 /**
384 * Export a kit.
385 *
386 * Assigning the Export process to the 'export' property,
387 * so it will be available to use in different places such as: WP_Cli, Pro, etc.
388 *
389 * @param array $settings Settings the export use to determine which content to export.
390 * (e.g: include, kit_info, selected_plugins, selected_cpt, etc.)
391 * @return array
392 * @throws \Exception
393 */
394 public function export_kit( array $settings ) {
395 $this->ensure_writing_permissions();
396
397 $this->export = new Export( $settings );
398 $this->export->register_default_runners();
399
400 do_action( 'elementor/import-export/export-kit', $this->export );
401
402 return $this->export->run();
403 }
404
405 /**
406 * Handle revert kit ajax request.
407 */
408 public function revert_last_imported_kit() {
409 $this->revert = new Revert();
410 $this->revert->register_default_runners();
411
412 do_action( 'elementor/import-export/revert-kit', $this->revert );
413
414 $this->revert->run();
415 }
416
417
418 /**
419 * Handle revert last imported kit ajax request.
420 */
421 public function handle_revert_last_imported_kit() {
422 check_admin_referer( 'elementor_revert_kit' );
423
424 $this->revert_last_imported_kit();
425
426 wp_safe_redirect( admin_url( 'admin.php?page=' . Tools::PAGE_ID . '#tab-import-export-kit' ) );
427 die;
428 }
429
430 /**
431 * Register appropriate actions.
432 */
433 private function register_actions() {
434 add_action( 'admin_init', function() {
435 if ( wp_doing_ajax() &&
436 isset( $_POST['action'] ) &&
437 wp_verify_nonce( ElementorUtils::get_super_global_value( $_POST, '_nonce' ), Ajax::NONCE_KEY ) &&
438 current_user_can( 'manage_options' )
439 ) {
440 $this->maybe_handle_ajax();
441 }
442 } );
443
444 add_action( 'admin_post_elementor_revert_kit', [ $this, 'handle_revert_last_imported_kit' ] );
445
446 add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
447
448 $page_id = Tools::PAGE_ID;
449
450 add_action( "elementor/admin/after_create_settings/{$page_id}", [ $this, 'register_settings_tab' ] );
451
452 // TODO 18/04/2023 : This needs to be moved to the runner itself after https://elementor.atlassian.net/browse/HTS-434 is done.
453 if ( self::IMPORT_PLUGINS_ACTION === ElementorUtils::get_super_global_value( $_SERVER, 'HTTP_X_ELEMENTOR_ACTION' ) ) {
454 add_filter( 'woocommerce_create_pages', [ $this, 'empty_pages' ], 10, 0 );
455 }
456 // TODO ^^^
457 }
458
459 /**
460 * Prevent the creation of the default WooCommerce pages (Cart, Checkout, etc.)
461 *
462 * TODO 18/04/2023 : This needs to be moved to the runner itself after https://elementor.atlassian.net/browse/HTS-434 is done.
463 *
464 * @return array
465 */
466 public function empty_pages(): array {
467 return [];
468 }
469
470 private function ensure_writing_permissions() {
471 $server = new Server();
472
473 $paths_to_check = [
474 Server::KEY_PATH_WP_CONTENT_DIR => $server->get_system_path( Server::KEY_PATH_WP_CONTENT_DIR ),
475 Server::KEY_PATH_UPLOADS_DIR => $server->get_system_path( Server::KEY_PATH_UPLOADS_DIR ),
476 Server::KEY_PATH_ELEMENTOR_UPLOADS_DIR => $server->get_system_path( Server::KEY_PATH_ELEMENTOR_UPLOADS_DIR ),
477 ];
478
479 $permissions = $server->get_paths_permissions( $paths_to_check );
480
481 // WP Content dir has to be exists and writable.
482 if ( ! $permissions[ Server::KEY_PATH_WP_CONTENT_DIR ]['write'] ) {
483 throw new \Error( self::NO_WRITE_PERMISSIONS_KEY ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
484 }
485
486 // WP Uploads dir has to be exists and writable.
487 if ( ! $permissions[ Server::KEY_PATH_UPLOADS_DIR ]['write'] ) {
488 throw new \Error( self::NO_WRITE_PERMISSIONS_KEY ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
489 }
490
491 // Elementor uploads dir permissions is divided to 2 cases:
492 // 1. If the dir exists, it has to be writable.
493 // 2. If the dir doesn't exist, the parent dir has to be writable (wp uploads dir), so we can create it.
494 if ( $permissions[ Server::KEY_PATH_ELEMENTOR_UPLOADS_DIR ]['exists'] && ! $permissions[ Server::KEY_PATH_ELEMENTOR_UPLOADS_DIR ]['write'] ) {
495 throw new \Error( self::NO_WRITE_PERMISSIONS_KEY ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
496 }
497 }
498
499 private function ensure_DOMDocument_exists() {
500 if ( ! class_exists( 'DOMDocument' ) ) {
501 throw new \Error( self::DOMDOCUMENT_MISSING ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
502 }
503 }
504
505 /**
506 * Enqueue admin scripts
507 */
508 public function enqueue_scripts() {
509 wp_enqueue_script(
510 'elementor-import-export-admin',
511 $this->get_js_assets_url( 'import-export-admin' ),
512 [ 'elementor-common' ],
513 ELEMENTOR_VERSION,
514 true
515 );
516
517 wp_localize_script(
518 'elementor-import-export-admin',
519 'elementorImportExport',
520 [
521 'lastImportedSession' => $this->revert->get_last_import_session(),
522 'appUrl' => Plugin::$instance->app->get_base_url() . '#/kit-library',
523 ]
524 );
525 }
526
527 /**
528 * Assign each ajax action to a method.
529 */
530 private function maybe_handle_ajax() {
531 // phpcs:ignore WordPress.Security.NonceVerification.Missing
532 $action = ElementorUtils::get_super_global_value( $_POST, 'action' );
533
534 try {
535 switch ( $action ) {
536 case static::EXPORT_TRIGGER_KEY:
537 $this->handle_export_kit();
538 break;
539
540 case static::UPLOAD_TRIGGER_KEY:
541 $this->handle_upload_kit();
542 break;
543
544 case static::IMPORT_TRIGGER_KEY:
545 $this->handle_import_kit();
546 break;
547
548 case static::IMPORT_RUNNER_TRIGGER_KEY:
549 $this->handle_import_kit__runner();
550 break;
551
552 default:
553 break;
554 }
555 } catch ( \Error $e ) {
556 if ( isset( $this->import ) ) {
557 $this->import->finalize_import_session_option();
558 }
559
560 Plugin::$instance->logger->get_logger()->error( $e->getMessage(), [
561 'meta' => [
562 'trace' => $e->getTraceAsString(),
563 ],
564 ] );
565
566 if ( isset( $this->import ) && $this->is_third_party_class( $e->getTrace()[0]['class'] ) ) {
567 wp_send_json_error( self::THIRD_PARTY_ERROR, 500 );
568 }
569
570 wp_send_json_error( $e->getMessage(), 500 );
571 }
572 }
573
574 /**
575 * Handle upload kit ajax request.
576 */
577 private function handle_upload_kit() {
578 // PHPCS - A URL that should contain special chars (auth headers information).
579 $file_url = isset( $_POST['e_import_file'] )
580 // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
581 ? wp_unslash( $_POST['e_import_file'] )
582 : '';
583
584 // Import from kit library
585 if ( ! empty( $file_url ) ) {
586 if (
587 ! wp_verify_nonce( ElementorUtils::get_super_global_value( $_POST, 'e_kit_library_nonce' ), 'kit-library-import' )
588 ) {
589 throw new \Error( 'Invalid kit library nonce.' );
590 }
591
592 if ( ! filter_var( $file_url, FILTER_VALIDATE_URL ) || 0 !== strpos( $file_url, 'http' ) ) {
593 throw new \Error( static::KIT_LIBRARY_ERROR_KEY ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
594 }
595
596 $remote_zip_request = wp_safe_remote_get( $file_url );
597
598 if ( is_wp_error( $remote_zip_request ) ) {
599 Plugin::$instance->logger->get_logger()->error( $remote_zip_request->get_error_message() );
600 throw new \Error( static::KIT_LIBRARY_ERROR_KEY ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
601 }
602
603 if ( 200 !== $remote_zip_request['response']['code'] ) {
604 Plugin::$instance->logger->get_logger()->error( $remote_zip_request['response']['message'] );
605 throw new \Error( static::KIT_LIBRARY_ERROR_KEY ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
606 }
607
608 $file_name = Plugin::$instance->uploads_manager->create_temp_file( $remote_zip_request['body'], 'kit.zip' );
609 $referrer = static::REFERRER_KIT_LIBRARY;
610 } else {
611 // PHPCS - Already validated in caller function.
612 $file_name = ElementorUtils::get_super_global_value( $_FILES, 'e_import_file' )['tmp_name'];
613 $referrer = static::REFERRER_LOCAL;
614 }
615
616 Plugin::$instance->logger->get_logger()->info( 'Uploading Kit: ', [
617 'meta' => [
618 'kit_id' => ElementorUtils::get_super_global_value( $_POST, 'kit_id' ),
619 'referrer' => $referrer,
620 ],
621 ] );
622
623 $uploaded_kit = $this->upload_kit( $file_name, $referrer );
624
625 $session_dir = $uploaded_kit['session'];
626 $manifest = $uploaded_kit['manifest'];
627 $conflicts = $uploaded_kit['conflicts'];
628
629 if ( ! empty( $file_url ) ) {
630 Plugin::$instance->uploads_manager->remove_file_or_dir( dirname( $file_name ) );
631 }
632
633 if ( isset( $manifest['plugins'] ) && ! current_user_can( 'install_plugins' ) ) {
634 throw new \Error( static::PLUGIN_PERMISSIONS_ERROR_KEY ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
635 }
636
637 $result = [
638 'session' => $session_dir,
639 'manifest' => $manifest,
640 ];
641
642 if ( ! empty( $conflicts ) ) {
643 $result['conflicts'] = $conflicts;
644 } else {
645 // Moved into the IE process \Elementor\App\Modules\ImportExport\Processes\Import::get_default_settings_conflicts
646 // TODO: remove in 3.10.0
647 $result = apply_filters( 'elementor/import/stage_1/result', $result );
648 }
649
650 wp_send_json_success( $result );
651 }
652
653 /**
654 * Handle import kit ajax request.
655 */
656 private function handle_import_kit() {
657 // PHPCS - Already validated in caller function
658 $settings = json_decode( ElementorUtils::get_super_global_value( $_POST, 'data' ), true ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
659 $tmp_folder_id = $settings['session'];
660
661 $import = $this->import_kit( $tmp_folder_id, $settings, true );
662
663 // get_settings_config() added manually because the frontend Ajax request doesn't trigger the get_init_settings().
664 $import['configData'] = $this->get_config_data();
665
666 Plugin::$instance->logger->get_logger()->info(
667 sprintf( 'Selected import runners: %1$s',
668 implode( ', ', $import['runners'] )
669 )
670 );
671
672 wp_send_json_success( $import );
673 }
674
675 /**
676 * Handle ajax request for running specific runner in the import kit process.
677 */
678 private function handle_import_kit__runner() {
679 // PHPCS - Already validated in caller function
680 $settings = json_decode( ElementorUtils::get_super_global_value( $_POST, 'data' ), true ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
681 $session_id = $settings['session'];
682 $runner = $settings['runner'];
683
684 $import = $this->import_kit_by_runner( $session_id, $runner );
685
686 // get_settings_config() added manually because the frontend Ajax request doesn't trigger the get_init_settings().
687 $import['configData'] = $this->get_config_data();
688
689 if ( ! empty( $import['status'] ) ) {
690 Plugin::$instance->logger->get_logger()->info(
691 sprintf( 'Import runner completed: %1$s %2$s',
692 $import['runner'],
693 ( 'success' === $import['status'] ? '' : '' )
694 )
695 );
696 }
697
698 do_action( 'elementor/import-export/import-kit/runner/after-run', $import );
699
700 wp_send_json_success( $import );
701 }
702
703 /**
704 * Handle export kit ajax request.
705 */
706 private function handle_export_kit() {
707 // PHPCS - Already validated in caller function
708 $settings = json_decode( ElementorUtils::get_super_global_value( $_POST, 'data' ), true ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
709 $export = $this->export_kit( $settings );
710
711 $file_name = $export['file_name'];
712 $file = ElementorUtils::file_get_contents( $file_name );
713
714 if ( ! $file ) {
715 throw new \Error( 'Could not read the exported file.' );
716 }
717
718 Plugin::$instance->uploads_manager->remove_file_or_dir( dirname( $file_name ) );
719
720 $result = [
721 'manifest' => $export['manifest'],
722 'file' => base64_encode( $file ),
723 ];
724
725 wp_send_json_success( $result );
726 }
727
728 /**
729 * Get config data that will be exposed to the frontend.
730 */
731 private function get_config_data() {
732 $export_nonce = wp_create_nonce( 'elementor_export' );
733 $export_url = add_query_arg( [ '_nonce' => $export_nonce ], Plugin::$instance->app->get_base_url() );
734
735 return [
736 'exportURL' => $export_url,
737 'summaryTitles' => $this->get_summary_titles(),
738 'builtinWpPostTypes' => ImportExportUtils::get_builtin_wp_post_types(),
739 'elementorPostTypes' => ImportExportUtils::get_elementor_post_types(),
740 'isUnfilteredFilesEnabled' => Uploads_Manager::are_unfiltered_uploads_enabled(),
741 'elementorHomePageUrl' => $this->get_elementor_home_page_url(),
742 'recentlyEditedElementorPageUrl' => $this->get_recently_edited_elementor_page_url(),
743 'tools_url' => Tools::get_url(),
744 'importSessions' => Revert::get_import_sessions(),
745 'lastImportedSession' => $this->revert->get_last_import_session(),
746 ];
747 }
748
749 /**
750 * Get labels of Elementor document types, Elementor Post types, WordPress Post types and Custom Post types.
751 */
752 private function get_summary_titles() {
753 $summary_titles = [];
754
755 $document_types = Plugin::$instance->documents->get_document_types();
756
757 foreach ( $document_types as $name => $document_type ) {
758 $summary_titles['templates'][ $name ] = [
759 'single' => $document_type::get_title(),
760 'plural' => $document_type::get_plural_title(),
761 ];
762 }
763
764 $elementor_post_types = ImportExportUtils::get_elementor_post_types();
765 $wp_builtin_post_types = ImportExportUtils::get_builtin_wp_post_types();
766 $post_types = array_merge( $elementor_post_types, $wp_builtin_post_types );
767
768 foreach ( $post_types as $post_type ) {
769 $post_type_object = get_post_type_object( $post_type );
770
771 $summary_titles['content'][ $post_type ] = [
772 'single' => $post_type_object->labels->singular_name ?? '',
773 'plural' => $post_type_object->label ?? '',
774 ];
775 }
776
777 $custom_post_types = ImportExportUtils::get_registered_cpt_names();
778 if ( ! empty( $custom_post_types ) ) {
779 foreach ( $custom_post_types as $custom_post_type ) {
780
781 $custom_post_types_object = get_post_type_object( $custom_post_type );
782 // CPT data appears in two arrays:
783 // 1. content object: in order to show the export summary when completed in getLabel function
784 $summary_titles['content'][ $custom_post_type ] = [
785 'single' => $custom_post_types_object->labels->singular_name ?? '',
786 'plural' => $custom_post_types_object->label ?? '',
787 ];
788
789 // 2. customPostTypes object: in order to actually export the data
790 $summary_titles['content']['customPostTypes'][ $custom_post_type ] = [
791 'single' => $custom_post_types_object->labels->singular_name ?? '',
792 'plural' => $custom_post_types_object->label ?? '',
793 ];
794 }
795 }
796
797 $active_kit = Plugin::$instance->kits_manager->get_active_kit();
798
799 foreach ( $active_kit->get_tabs() as $key => $tab ) {
800 $summary_titles['site-settings'][ $key ] = $tab->get_title();
801 }
802
803 return $summary_titles;
804 }
805
806 public function should_show_revert_section( $last_imported_kit ) {
807 if ( empty( $last_imported_kit ) ) {
808 return false;
809 }
810
811 // TODO: BC - remove in the future
812 // The 'templates' runner was in core and moved to the Pro plugin. (Part of it still exits in the Core for BC)
813 // The runner that is in the core version is missing the revert functionality,
814 // therefore we shouldn't display the revert section if the import process done with the core version.
815 $is_import_templates_ran = isset( $last_imported_kit['runners']['templates'] );
816 if ( $this->has_pro() && $is_import_templates_ran ) {
817 $has_imported_templates = ! empty( $last_imported_kit['runners']['templates'] );
818
819 return $has_imported_templates;
820 }
821
822 return true;
823 }
824
825 public function has_pro(): bool {
826 return ElementorUtils::has_pro();
827 }
828
829 private function get_elementor_editor_home_page_url() {
830 if ( 'page' !== get_option( 'show_on_front' ) ) {
831 return '';
832 }
833
834 $frontpage_id = get_option( 'page_on_front' );
835
836 return $this->get_elementor_editor_page_url( $frontpage_id );
837 }
838
839 private function get_elementor_home_page_url() {
840 if ( 'page' !== get_option( 'show_on_front' ) ) {
841 return '';
842 }
843
844 $frontpage_id = get_option( 'page_on_front' );
845
846 return $this->get_elementor_page_url( $frontpage_id );
847 }
848
849 private function get_recently_edited_elementor_page_url() {
850 $query = ElementorUtils::get_recently_edited_posts_query( [ 'posts_per_page' => 1 ] );
851
852 if ( ! isset( $query->post ) ) {
853 return '';
854 }
855
856 return $this->get_elementor_page_url( $query->post->ID );
857 }
858
859 private function get_recently_edited_elementor_editor_page_url() {
860 $query = ElementorUtils::get_recently_edited_posts_query( [ 'posts_per_page' => 1 ] );
861
862 if ( ! isset( $query->post ) ) {
863 return '';
864 }
865
866 return $this->get_elementor_editor_page_url( $query->post->ID );
867 }
868
869 private function get_elementor_document( $page_id ) {
870 $document = Plugin::$instance->documents->get( $page_id );
871
872 if ( ! $document || ! $document->is_built_with_elementor() ) {
873 return false;
874 }
875
876 return $document;
877 }
878
879 private function get_elementor_page_url( $page_id ) {
880 $document = $this->get_elementor_document( $page_id );
881
882 return $document ? $document->get_preview_url() : '';
883 }
884
885 private function get_elementor_editor_page_url( $page_id ) {
886 $document = $this->get_elementor_document( $page_id );
887
888 return $document ? $document->get_edit_url() : '';
889 }
890
891 /**
892 * @param string $class
893 *
894 * @return bool
895 */
896 public function is_third_party_class( $class ) {
897 $allowed_classes = [
898 'Elementor\\',
899 'ElementorPro\\',
900 'WP_',
901 'wp_',
902 ];
903
904 foreach ( $allowed_classes as $allowed_class ) {
905 if ( str_starts_with( $class, $allowed_class ) ) {
906 return false;
907 }
908 }
909
910 return true;
911 }
912 }
913