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

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