PluginProbe
Elementor Website Builder – more than just a page builder / 3.16.0-dev2
Elementor Website Builder – more than just a page builder v3.16.0-dev2
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.16.0-dev2, at app/modules/import-export/module.php

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