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

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