PluginProbe
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! / 3.2.1
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! v3.2.1
3.7.5 3.7.4 3.7.3 3.7.2 1-final 3.7.1 3.7.0 3.6.8 3.6.7 3.6.6 3.6.5 3.6.4 3.6.3 3.6.2 3.6.1 3.0.3 3.0.4 3.0.5 3.0.6 3.0.7 3.0.8 3.0.9 3.1.0 3.1.1 3.1.10 All 111 releases
templately / includes / Core / Importer / WPImport.php

WPImport.php in Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! 3.2.1, at includes/Core/Importer/WPImport.php

1,776 lines 56.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Templately\Core\Importer;
4
5 use Templately\Core\Importer\Parsers\WXR_Parser;
6 use Templately\Core\Importer\Utils\Utils;
7 use Templately\Utils\Helper;
8 use WP_Error;
9 use WP_Importer;
10 use function wp_import_cleanup;
11
12 if ( ! defined( 'ABSPATH' ) ) {
13 exit; // Exit if accessed directly.
14 }
15
16 /**
17 * Originally made by WordPress part of WordPress/Importer.
18 * https://plugins.trac.wordpress.org/browser/wordpress-importer/trunk/class-wp-import.php
19 *
20 * What was done ( by Elementor):
21 * Reformat of the code.
22 * Changed text domain.
23 * Changed methods visibility.
24 * Changed method from `get_authors_from_import` to `set_authors_from_import`.
25 * Changed method from `get_author_mapping` to `set_author_mapping`.
26 * Removed use of '$_POST' the input 'options' will be passed via constructor args.
27 * Removed echos, UI and print methods, all echos replaced with `$this->output` append.
28 * Removed `die` ( exit(s) ).
29 *
30 * What was done ( by Templately):
31 * Add Action For Every Part Of Import for SSE
32 */
33
34 if ( ! class_exists( 'WP_Importer' ) ) {
35 $class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
36
37 if ( file_exists( $class_wp_importer ) ) {
38 require $class_wp_importer;
39 }
40 }
41
42 if ( ! function_exists( 'wp_import_cleanup' ) ) {
43 $wp_import = ABSPATH . 'wp-admin/includes/import.php';
44
45 if ( file_exists( $wp_import ) ) {
46 require $wp_import;
47 }
48 }
49
50 class WPImport extends WP_Importer {
51 const DEFAULT_BUMP_REQUEST_TIMEOUT = 60;
52 const DEFAULT_ALLOW_CREATE_USERS = true;
53 const DEFAULT_IMPORT_ATTACHMENT_SIZE_LIMIT = 0; // 0 = unlimited.
54
55 /**
56 * @var string
57 */
58 private $requested_file_path;
59 /**
60 * @var string
61 */
62 private $import_data_key;
63
64 /**
65 * @var array
66 */
67 private $args;
68
69 /**
70 * @var FullSiteImport
71 */
72 private $origin;
73
74 /**
75 * @var array
76 */
77 private $output = [
78 'status' => 'failed',
79 'errors' => [],
80 ];
81
82 /*
83 * WXR attachment ID
84 */
85 private $id;
86
87 // Information to import from WXR file.
88 private $version;
89 private $authors = [];
90 public $posts = [];
91 public $terms = [];
92 private $base_url = '';
93 private $page_on_front;
94 private $base_blog_url = '';
95
96 // Mappings from old information to new.
97 public $processed_taxonomies;
98 public $processed_terms = [];
99 public $processed_posts = [];
100 public $url_remap = [];
101 private $processed_authors = [];
102 private $author_mapping = [];
103 private $processed_menu_items = [];
104 private $post_orphans = [];
105 private $menu_item_orphans = [];
106 private $mapped_terms_slug = [];
107
108 private $fetch_attachments = false;
109 private $featured_images = [];
110
111 /**
112 * @var array[] [meta_key => meta_value] Meta value that should be set for every imported post.
113 */
114 private $posts_meta = [];
115
116 /**
117 * @var array[] [meta_key => meta_value] Meta value that should be set for every imported term.
118 */
119 private $terms_meta = [];
120
121 public static $_replace_image_ids = [];
122
123 /**
124 * Parses filename from a Content-Disposition header value.
125 *
126 * As per RFC6266:
127 *
128 * content-disposition = "Content-Disposition" ":"
129 * disposition-type *( ";" disposition-parm )
130 *
131 * disposition-type = "inline" | "attachment" | disp-ext-type
132 * ; case-insensitive
133 * disp-ext-type = token
134 *
135 * disposition-parm = filename-parm | disp-ext-parm
136 *
137 * filename-parm = "filename" "=" value
138 * | "filename*" "=" ext-value
139 *
140 * disp-ext-parm = token "=" value
141 * | ext-token "=" ext-value
142 * ext-token = <the characters in token, followed by "*">
143 *
144 * @param string[] $disposition_header List of Content-Disposition header values.
145 *
146 * @return string|null Filename if available, or null if not found.
147 * @link http://tools.ietf.org/html/rfc2388
148 * @link http://tools.ietf.org/html/rfc6266
149 *
150 * @see WP_REST_Attachments_Controller::get_filename_from_disposition()
151 *
152 */
153 protected static function get_filename_from_disposition( $disposition_header ) {
154 // Get the filename.
155 $filename = null;
156
157 foreach ( $disposition_header as $value ) {
158 $value = trim( $value );
159
160 if ( strpos( $value, ';' ) === false ) {
161 continue;
162 }
163
164 list( $type, $attr_parts ) = explode( ';', $value, 2 );
165
166 $attr_parts = explode( ';', $attr_parts );
167 $attributes = [];
168
169 foreach ( $attr_parts as $part ) {
170 if ( strpos( $part, '=' ) === false ) {
171 continue;
172 }
173
174 list( $key, $value ) = explode( '=', $part, 2 );
175
176 $attributes[ trim( $key ) ] = trim( $value );
177 }
178
179 if ( empty( $attributes['filename'] ) ) {
180 continue;
181 }
182
183 $filename = trim( $attributes['filename'] );
184
185 // Unquote quoted filename, but after trimming.
186 if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) {
187 $filename = substr( $filename, 1, -1 );
188 }
189 }
190
191 return $filename;
192 }
193
194 /**
195 * Retrieves file extension by mime type.
196 *
197 * @param string $mime_type Mime type to search extension for.
198 *
199 * @return string|null File extension if available, or null if not found.
200 */
201 protected static function get_file_extension_by_mime_type( $mime_type ) {
202 static $map = null;
203
204 if ( is_array( $map ) ) {
205 return isset( $map[ $mime_type ] ) ? $map[ $mime_type ] : null;
206 }
207
208 $mime_types = wp_get_mime_types();
209 $map = array_flip( $mime_types );
210
211 // Some types have multiple extensions, use only the first one.
212 foreach ( $map as $type => $extensions ) {
213 $map[ $type ] = strtok( $extensions, '|' );
214 }
215
216 return isset( $map[ $mime_type ] ) ? $map[ $mime_type ] : null;
217 }
218
219 /**
220 * The main controller for the actual import stage.
221 *
222 * @param string $file Path to the WXR file for importing
223 */
224 private function import( $file ) {
225 add_filter( 'import_post_meta_key', function ( $key ) {
226 return $this->is_valid_meta_key( $key );
227 } );
228 add_filter( 'http_request_timeout', function () {
229 return self::DEFAULT_BUMP_REQUEST_TIMEOUT;
230 } );
231
232 if ( ! $this->import_start( $file ) ) {
233 return;
234 }
235
236
237 $this->set_author_mapping();
238
239 wp_suspend_cache_invalidation( true );
240 $imported_summary = [
241 'terms' => $this->process_terms(),
242 'posts' => $this->process_posts(),
243 ];
244 wp_suspend_cache_invalidation( false );
245
246 // Update incorrect/missing information in the DB.
247 $this->backfill_parents();
248 $this->backfill_attachment_urls();
249 $this->remap_featured_images();
250
251 $this->import_end();
252
253 $is_some_succeed = false;
254 foreach ( $imported_summary as $item ) {
255 if ( $item > 0 ) {
256 $is_some_succeed = true;
257 break;
258 }
259 }
260
261 if ( $is_some_succeed ) {
262 $this->output['status'] = 'success';
263 $this->output['summary'] = $imported_summary;
264 }
265 }
266
267 /**
268 * Parses the WXR file and prepares us for the task of processing parsed data.
269 *
270 * @param string $file Path to the WXR file for importing
271 */
272 private function import_start( string $file ): bool {
273 if ( ! is_file( $file ) ) {
274 $this->output['errors'] = [ esc_html__( 'The file does not exist, please try again.', 'elementor' ) ];
275
276 return false;
277 }
278
279 $import_data = $this->parse( $file );
280
281 if ( is_wp_error( $import_data ) ) {
282 /**
283 * @var WP_Error $import_data ;
284 */
285 $this->output['errors'] = [ $import_data->get_error_message() ];
286
287 return false;
288 }
289 $this->version = $import_data['version'];
290 $this->set_authors_from_import( $import_data );
291 $this->posts = $import_data['posts'];
292 $this->terms = $import_data['terms'];
293 $this->base_url = esc_url( $import_data['base_url'] );
294 $this->base_blog_url = esc_url( $import_data['base_blog_url'] );
295 $this->page_on_front = $import_data['page_on_front'];
296
297 wp_defer_term_counting( true );
298 wp_defer_comment_counting( true );
299
300 do_action( 'import_start', $this );
301
302 return true;
303 }
304
305 /**
306 * Performs post-import cleanup of files and the cache
307 */
308 private function import_end() {
309 wp_import_cleanup( $this->id );
310
311 wp_cache_flush();
312
313 foreach ( get_taxonomies() as $tax ) {
314 delete_option( "{$tax}_children" );
315 _get_term_hierarchy( $tax );
316 }
317
318 wp_defer_term_counting( false );
319 wp_defer_comment_counting( false );
320
321 do_action( 'import_end' );
322 }
323
324 /**
325 * Retrieve authors from parsed WXR data and set it to `$this->>authors`.
326 *
327 * Uses the provided author information from WXR 1.1 files
328 * or extracts info from each post for WXR 1.0 files
329 *
330 * @param array $import_data Data returned by a WXR parser
331 */
332 private function set_authors_from_import( $import_data ) {
333 if ( ! empty( $import_data['authors'] ) ) {
334 $this->authors = $import_data['authors'];
335 // No author information, grab it from the posts.
336 } else {
337 foreach ( $import_data['posts'] as $post ) {
338 $login = sanitize_user( $post['post_author'], true );
339
340 if ( empty( $login ) ) {
341 /* translators: %s: Post author. */
342 $this->output['errors'][] = sprintf( esc_html__( 'Failed to import author %s. Their posts will be attributed to the current user.', 'elementor' ), $post['post_author'] );
343 continue;
344 }
345
346 if ( ! isset( $this->authors[ $login ] ) ) {
347 $this->authors[ $login ] = [
348 'author_login' => $login,
349 'author_display_name' => $post['post_author'],
350 ];
351 }
352 }
353 }
354 }
355
356 private function retrieve_attributes($attributes){
357 $params = $this->origin->get_request_params();
358 $attr_values = $params["imported_data"][$this->import_data_key] ?? [];
359 foreach ($attributes as $attribute) {
360 if(isset($attr_values[$attribute])){
361 $this->$attribute = $attr_values[$attribute];
362 }
363 }
364 }
365
366 private function backup_attributes($attributes){
367 $params = $this->origin->get_request_params();
368 $attr_values = $params["imported_data"][$this->import_data_key] ?? [];
369
370 foreach ($attributes as $attribute) {
371 if(isset($this->$attribute)){
372 $attr_values[$attribute] = $this->$attribute;
373 }
374 }
375 $this->origin->update_progress( null, [$this->import_data_key => $attr_values]);
376 }
377
378 /**
379 * Map old author logins to local user IDs based on decisions made
380 * in import options form. Can map to an existing user, create a new user
381 * or falls back to the current user in case of error with either of the previous
382 */
383 private function set_author_mapping() {
384 if ( ! isset( $this->args['imported_authors'] ) ) {
385 return;
386 }
387
388 $attributes = [
389 'processed_authors',
390 'author_mapping',
391 'output',
392 ];
393
394 $processed_templates = $this->origin->get_progress([], $this->import_data_key);
395 if (!empty($processed_templates)) {
396 $this->retrieve_attributes($attributes);
397 return;
398 }
399
400 $create_users = apply_filters( 'import_allow_create_users', self::DEFAULT_ALLOW_CREATE_USERS );
401
402 foreach ( (array) $this->args['imported_authors'] as $i => $old_login ) {
403 // Multisite adds strtolower to sanitize_user. Need to sanitize here to stop breakage in process_posts.
404 $santized_old_login = sanitize_user( $old_login, true );
405 $old_id = isset( $this->authors[ $old_login ]['author_id'] ) ? (int) $this->authors[ $old_login ]['author_id'] : false;
406
407 if ( ! empty( $this->args['user_map'][ $i ] ) ) {
408 $user = get_userdata( (int) $this->args['user_map'][ $i ] );
409 if ( isset( $user->ID ) ) {
410 if ( $old_id ) {
411 $this->processed_authors[ $old_id ] = $user->ID;
412 }
413 $this->author_mapping[ $santized_old_login ] = $user->ID;
414 }
415 } elseif ( $create_users ) {
416 $user_id = 0;
417 if ( ! empty( $this->args['user_new'][ $i ] ) ) {
418 $user_id = wp_create_user( $this->args['user_new'][ $i ], wp_generate_password() );
419 } elseif ( '1.0' !== $this->version ) {
420 $user_data = [
421 'user_login' => $old_login,
422 'user_pass' => wp_generate_password(),
423 'user_email' => isset( $this->authors[ $old_login ]['author_email'] ) ? $this->authors[ $old_login ]['author_email'] : '',
424 'display_name' => $this->authors[ $old_login ]['author_display_name'],
425 'first_name' => isset( $this->authors[ $old_login ]['author_first_name'] ) ? $this->authors[ $old_login ]['author_first_name'] : '',
426 'last_name' => isset( $this->authors[ $old_login ]['author_last_name'] ) ? $this->authors[ $old_login ]['author_last_name'] : '',
427 ];
428 $user_id = wp_insert_user( $user_data );
429 }
430
431 if ( ! is_wp_error( $user_id ) ) {
432 if ( $old_id ) {
433 $this->processed_authors[ $old_id ] = $user_id;
434 }
435 $this->author_mapping[ $santized_old_login ] = $user_id;
436 } else {
437 /* translators: %s: Author display name. */
438 $error = sprintf( esc_html__( 'Failed to create new user for %s. Their posts will be attributed to the current user.', 'elementor' ), $this->authors[ $old_login ]['author_display_name'] );
439
440 if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
441 $error .= PHP_EOL . $user_id->get_error_message();
442 }
443
444 $this->output['errors'][] = $error;
445 }
446 }
447
448 // Failsafe: if the user_id was invalid, default to the current user.
449 if ( ! isset( $this->author_mapping[ $santized_old_login ] ) ) {
450 if ( $old_id ) {
451 $this->processed_authors[ $old_id ] = (int) get_current_user_id();
452 }
453 $this->author_mapping[ $santized_old_login ] = (int) get_current_user_id();
454 }
455 }
456
457 $this->backup_attributes($attributes);
458 $this->origin->update_progress( true, null, $this->import_data_key );
459 }
460
461 /**
462 * Create new terms based on import information
463 *
464 * Doesn't create a term its slug already exists
465 *
466 * @return array|array[] the ids of succeed/failed imported terms.
467 */
468 private function process_terms(): array {
469 $params = $this->origin->get_request_params();
470 $result = $params["imported_data"]["wp_import_terms_" . $this->import_data_key] ?? [
471 'succeed' => [],
472 'failed' => [],
473 ];
474
475 $attributes = [
476 'terms',
477 'output',
478 'mapped_terms_slug',
479 'processed_terms',
480 ];
481 $processed_templates = $this->origin->get_progress([], $this->import_data_key);
482 if (!empty($processed_templates)) {
483 $this->retrieve_attributes($attributes);
484 return $result;
485 }
486
487 $this->terms = apply_filters( 'wp_import_terms', $this->terms );
488 if ( empty( $this->terms ) ) {
489 return $result;
490 }
491 foreach ( $this->terms as $term ) {
492
493 // if the term already exists in the correct taxonomy leave it alone
494 $term_id = term_exists( $term['slug'], $term['term_taxonomy'] );
495 if ( $term_id ) {
496 if ( is_array( $term_id ) ) {
497 $term_id = $term_id['term_id'];
498 }
499
500 if ( isset( $term['term_id'] ) ) {
501 if ( 'nav_menu' === $term['term_taxonomy'] ) {
502 // BC - support old kits that the menu terms are part of the 'nav_menu_item' post type
503 // and not part of the taxonomies.
504 if ( ! empty( $this->processed_taxonomies[ $term['term_taxonomy'] ] ) ) {
505 foreach ( $this->processed_taxonomies[ $term['term_taxonomy'] ] as $processed_term ) {
506 $old_slug = $processed_term['old_slug'];
507 $new_slug = $processed_term['new_slug'];
508
509 $this->mapped_terms_slug[ $old_slug ] = $new_slug;
510 $result['succeed'][ $old_slug ] = $new_slug;
511 }
512 continue;
513 } else {
514 $term = $this->handle_duplicated_nav_menu_term( $term );
515 }
516 } else {
517 $this->processed_terms[ (int) $term['term_id'] ] = (int) $term_id;
518 $result['succeed'][ (int) $term['term_id'] ] = (int) $term_id;
519 continue;
520 }
521 }
522 }
523
524 if ( empty( $term['term_parent'] ) ) {
525 $parent = 0;
526 } else {
527 $parent = term_exists( $term['term_parent'], $term['term_taxonomy'] );
528 if ( is_array( $parent ) ) {
529 $parent = $parent['term_id'];
530 }
531 }
532
533 $description = $term['term_description'] ?? '';
534 $args = [
535 'slug' => $term['slug'],
536 'description' => wp_slash( $description ),
537 'parent' => (int) $parent,
538 ];
539
540 $id = wp_insert_term( wp_slash( $term['term_name'] ), $term['term_taxonomy'], $args );
541 if ( ! is_wp_error( $id ) ) {
542 if ( isset( $term['term_id'] ) ) {
543 $this->processed_terms[ (int) $term['term_id'] ] = $id['term_id'];
544 $result['succeed'][ (int) $term['term_id'] ] = $id['term_id'];
545
546 $this->update_term_meta( $id['term_id'] );
547 }
548 } else {
549 /* translators: 1: Term taxonomy, 2: Term name. */
550 $error = sprintf( esc_html__( 'Failed to import %1$s %2$s', 'elementor' ), $term['term_taxonomy'], $term['term_name'] );
551
552 if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
553 $error .= PHP_EOL . $id->get_error_message();
554 }
555
556 $result['failed'][] = $id;
557 $this->output['errors'][] = $error;
558 continue;
559 }
560
561 $this->process_termmeta( $term, $id['term_id'] );
562
563 do_action( 'templately_import.process_term', $term, $result, $this );
564 }
565
566 unset( $this->terms );
567
568 $this->backup_attributes($attributes);
569 // Add the template to the processed templates and update the session data
570 $this->origin->update_progress( true, [ "wp_import_terms_" . $this->import_data_key => $result ]);
571 return $result;
572 }
573
574 /**
575 * Add metadata to imported term.
576 *
577 * @param array $term Term data from WXR import.
578 * @param int $term_id ID of the newly created term.
579 */
580 private function process_termmeta( $term, $term_id ) {
581 if ( ! function_exists( 'add_term_meta' ) ) {
582 return;
583 }
584
585 if ( ! isset( $term['termmeta'] ) ) {
586 $term['termmeta'] = [];
587 }
588
589 /**
590 * Filters the metadata attached to an imported term.
591 *
592 * @param array $termmeta Array of term meta.
593 * @param int $term_id ID of the newly created term.
594 * @param array $term Term data from the WXR import.
595 */
596 $term['termmeta'] = apply_filters( 'wp_import_term_meta', $term['termmeta'], $term_id, $term );
597
598 if ( empty( $term['termmeta'] ) ) {
599 return;
600 }
601
602 foreach ( $term['termmeta'] as $meta ) {
603 /**
604 * Filters the meta key for an imported piece of term meta.
605 *
606 * @param string $meta_key Meta key.
607 * @param int $term_id ID of the newly created term.
608 * @param array $term Term data from the WXR import.
609 */
610 $key = apply_filters( 'import_term_meta_key', $meta['key'], $term_id, $term );
611 if ( ! $key ) {
612 continue;
613 }
614
615 // Export gets meta straight from the DB so could have a serialized string
616 $value = maybe_unserialize( $meta['value'] );
617
618 add_term_meta( $term_id, wp_slash( $key ), wp_slash_strings_only( $value ) );
619
620 /**
621 * Fires after term meta is imported.
622 *
623 * @param int $term_id ID of the newly created term.
624 * @param string $key Meta key.
625 * @param mixed $value Meta value.
626 */
627 do_action( 'import_term_meta', $term_id, $key, $value );
628 }
629 }
630
631 /**
632 * Create new posts based on import information
633 *
634 * Posts marked as having a parent which doesn't exist will become top level items.
635 * Doesn't create a new post if: the post type doesn't exist, the given post ID
636 * is already noted as imported or a post with the same title and date already exists.
637 * Note that new/updated terms, comments and meta are imported for the last of the above.
638 *
639 * @return array the ids of succeed/failed imported posts.
640 */
641 private function process_posts(): array {
642 $backup_key = "wp_import_" . $this->import_data_key;
643 $params = $this->origin->get_request_params();
644 $result = $params["imported_data"][$backup_key] ?? [
645 'succeed' => [],
646 'failed' => [],
647 ];
648
649 $attributes = [
650 'output',
651 'menu_item_orphans',
652 'processed_menu_items',
653 'post_orphans',
654 'processed_posts',
655 'featured_images',
656 ];
657 $this->retrieve_attributes($attributes);
658
659 $this->posts = apply_filters( 'wp_import_posts', $this->posts );
660
661 $processed_templates = $this->origin->get_progress([], $this->import_data_key);
662
663 foreach ( $this->posts as $key => $post ) {
664 if (in_array($key, $processed_templates)) {
665 continue;
666 }
667
668 // Add the template to the processed templates and update the session data
669 $processed_templates[] = $key;
670 $this->origin->update_progress( $processed_templates, null, $this->import_data_key);
671
672 $post = apply_filters( 'wp_import_post_data_raw', $post );
673
674 if ( ! post_type_exists( $post['post_type'] ) ) {
675 /* translators: 1: Post title, 2: Post type. */
676 $this->output['errors'][] = sprintf( esc_html__( 'Failed to import %1$s: Invalid post type %2$s', 'elementor' ), $post['post_title'], $post['post_type'] );
677 do_action( 'wp_import_post_exists', $post );
678 continue;
679 }
680
681 if ( isset( $this->processed_posts[ $post['post_id'] ] ) && ! empty( $post['post_id'] ) ) {
682 continue;
683 }
684
685 if ( 'auto-draft' === $post['status'] ) {
686 continue;
687 }
688
689 if(!empty($post['post_content']) && !empty($post['post_id'])){
690 $post['post_content'] = Utils::import_and_replace_attachments($post['post_content'], $post['post_id']);
691 }
692
693 if ( 'nav_menu_item' === $post['post_type'] ) {
694 $result['succeed'] += $this->process_menu_item( $post );
695 continue;
696 }
697
698 if ( 'wp_navigation' === $post['post_type'] ) {
699 $processed = $this->process_navigation( $post );
700 if ( ! $processed ) {
701 continue;
702 }
703 }
704
705 $post_type_object = get_post_type_object( $post['post_type'] );
706
707 $post_parent = (int) $post['post_parent'];
708 if ( $post_parent ) {
709 // if we already know the parent, map it to the new local ID.
710 if ( isset( $this->processed_posts[ $post_parent ] ) ) {
711 $post_parent = $this->processed_posts[ $post_parent ];
712 // otherwise record the parent for later.
713 } else {
714 $this->post_orphans[ (int) $post['post_id'] ] = $post_parent;
715 $post_parent = 0;
716 }
717 }
718
719 // Map the post author.
720 $author = sanitize_user( $post['post_author'], true );
721 if ( isset( $this->author_mapping[ $author ] ) ) {
722 $author = $this->author_mapping[ $author ];
723 } else {
724 $author = (int) get_current_user_id();
725 }
726
727 $postdata = [
728 'post_author' => $author,
729 'post_content' => $post['post_content'],
730 'post_excerpt' => $post['post_excerpt'],
731 'post_title' => $post['post_title'],
732 'post_status' => $post['status'],
733 'post_name' => $post['post_name'],
734 'comment_status' => $post['comment_status'],
735 'ping_status' => $post['ping_status'],
736 'guid' => $post['guid'],
737 'post_parent' => $post_parent,
738 'menu_order' => $post['menu_order'],
739 'post_type' => $post['post_type'],
740 'post_password' => $post['post_password'],
741 ];
742
743 $original_post_id = $post['post_id'];
744 $postdata = apply_filters( 'wp_import_post_data_processed', $postdata, $post );
745
746 $postdata = wp_slash( $postdata );
747
748 if ( 'attachment' === $postdata['post_type'] ) {
749 $remote_url = ! empty( $post['attachment_url'] ) ? $post['attachment_url'] : $post['guid'];
750 $attachment_sizes = [];
751 // try to use _wp_attached file for upload folder placement to ensure the same location as the export site
752 // e.g. location is 2003/05/image.jpg but the attachment post_date is 2010/09, see media_handle_upload()
753 $postdata['upload_date'] = $post['post_date'];
754 if ( isset( $post['postmeta'] ) ) {
755 foreach ( $post['postmeta'] as $meta ) {
756 if ( '_wp_attached_file' === $meta['key'] ) {
757 if ( preg_match( '%^[0-9]{4}/[0-9]{2}%', $meta['value'], $matches ) ) {
758 $postdata['upload_date'] = $matches[0];
759 }
760 // break;
761 }
762 else if ( '_wp_attachment_metadata' === $meta['key'] ) {
763 $attachment_metadata = maybe_unserialize( $meta['value'] );
764 $attachment_sizes = $attachment_metadata['sizes'] ?? [];
765 // break;
766 }
767 }
768 }
769
770 $post_id = $this->process_attachment( $postdata, $remote_url, $attachment_sizes, $original_post_id );
771 $comment_post_id = $post_id;
772 } else {
773 $post_id = wp_insert_post( $postdata, true );
774
775 $this->update_post_meta( $post_id );
776
777 $comment_post_id = $post_id;
778 do_action( 'wp_import_insert_post', $post_id, $original_post_id, $postdata, $post );
779 }
780
781 if ( is_wp_error( $post_id ) ) {
782 /* translators: 1: Post type singular label, 2: Post title. */
783 $error = sprintf( __( 'Failed to import %1$s %2$s', 'elementor' ), $post_type_object->labels->singular_name, $post['post_title'] );
784
785 if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
786 $error .= PHP_EOL . $post_id->get_error_message();
787 }
788
789 $result['failed'][] = $original_post_id;
790
791 $this->output['errors'][] = $error;
792
793 if ( 'attachment' === $postdata['post_type'] ) {
794 do_action( 'templately_import.process_post', $post, $result, $this );
795 }
796
797 // Add the template to the processed templates and update the session data
798 $this->backup_attributes($attributes);
799 $this->origin->update_progress( null, [ $backup_key => $result ], $this->import_data_key);
800
801 // If it's not the last item, send the SSE message and exit
802 if(Helper::fsi_should_exit() && 'attachment' === $postdata['post_type'] && end($this->posts) !== $post) {
803 $this->origin->sse_message( [
804 'type' => 'continue',
805 'action' => 'continue',
806 'results' => __METHOD__ . '::' . __LINE__,
807 'data' => Helper::fsi_should_exit(),
808 ] );
809 exit;
810 }
811 continue;
812 }
813
814 $result['succeed'][ $original_post_id ] = $post_id;
815
816 if ( 1 === $post['is_sticky'] ) {
817 stick_post( $post_id );
818 }
819
820 if ( $this->page_on_front === $original_post_id ) {
821 Utils::update_option( 'page_on_front', $post_id );
822 }
823
824 // Map pre-import ID to local ID.
825 $this->processed_posts[ (int) $post['post_id'] ] = (int) $post_id;
826
827 if ( ! isset( $post['terms'] ) ) {
828 $post['terms'] = [];
829 }
830
831 $post['terms'] = apply_filters( 'wp_import_post_terms', $post['terms'], $post_id, $post );
832
833 // add categories, tags and other terms
834 if ( ! empty( $post['terms'] ) ) {
835 $terms_to_set = [];
836 foreach ( $post['terms'] as $term ) {
837 // back compat with WXR 1.0 map 'tag' to 'post_tag'
838 $taxonomy = ( 'tag' === $term['domain'] ) ? 'post_tag' : $term['domain'];
839 $term_exists = term_exists( $term['slug'], $taxonomy );
840 $term_id = is_array( $term_exists ) ? $term_exists['term_id'] : $term_exists;
841 if ( ! $term_id ) {
842 $t = wp_insert_term( $term['name'], $taxonomy, [ 'slug' => $term['slug'] ] );
843 if ( ! is_wp_error( $t ) ) {
844 $term_id = $t['term_id'];
845
846 $this->update_term_meta( $term_id );
847
848 do_action( 'wp_import_insert_term', $t, $term, $post_id, $post );
849 } else {
850 /* translators: 1: Taxonomy name, 2: Term name. */
851 $error = sprintf( esc_html__( 'Failed to import %1$s %2$s', 'elementor' ), $taxonomy, $term['name'] );
852
853 if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
854 $error .= PHP_EOL . $t->get_error_message();
855 }
856
857 $this->output['errors'][] = $error;
858
859 do_action( 'wp_import_insert_term_failed', $t, $term, $post_id, $post );
860 continue;
861 }
862 }
863 $terms_to_set[ $taxonomy ][] = (int) $term_id;
864 }
865
866 foreach ( $terms_to_set as $tax => $ids ) {
867 $tt_ids = wp_set_post_terms( $post_id, $ids, $tax );
868 do_action( 'wp_import_set_post_terms', $tt_ids, $ids, $tax, $post_id, $post );
869 }
870 unset( $post['terms'], $terms_to_set );
871 }
872
873 if ( ! isset( $post['comments'] ) ) {
874 $post['comments'] = [];
875 }
876
877 $post['comments'] = apply_filters( 'wp_import_post_comments', $post['comments'], $post_id, $post );
878
879 // Add/update comments.
880 if ( ! empty( $post['comments'] ) ) {
881 $num_comments = 0;
882 $inserted_comments = [];
883 foreach ( $post['comments'] as $comment ) {
884 $comment_id = $comment['comment_id'];
885 $newcomments[ $comment_id ]['comment_post_ID'] = $comment_post_id;
886 $newcomments[ $comment_id ]['comment_author'] = $comment['comment_author'];
887 $newcomments[ $comment_id ]['comment_author_email'] = $comment['comment_author_email'];
888 $newcomments[ $comment_id ]['comment_author_IP'] = $comment['comment_author_IP'];
889 $newcomments[ $comment_id ]['comment_author_url'] = $comment['comment_author_url'];
890 $newcomments[ $comment_id ]['comment_date'] = $comment['comment_date'];
891 $newcomments[ $comment_id ]['comment_date_gmt'] = $comment['comment_date_gmt'];
892 $newcomments[ $comment_id ]['comment_content'] = $comment['comment_content'];
893 $newcomments[ $comment_id ]['comment_approved'] = $comment['comment_approved'];
894 $newcomments[ $comment_id ]['comment_type'] = $comment['comment_type'];
895 $newcomments[ $comment_id ]['comment_parent'] = $comment['comment_parent'];
896 $newcomments[ $comment_id ]['commentmeta'] = isset( $comment['commentmeta'] ) ? $comment['commentmeta'] : [];
897 if ( isset( $this->processed_authors[ $comment['comment_user_id'] ] ) ) {
898 $newcomments[ $comment_id ]['user_id'] = $this->processed_authors[ $comment['comment_user_id'] ];
899 }
900 }
901
902 ksort( $newcomments );
903
904 foreach ( $newcomments as $key => $comment ) {
905 if ( isset( $inserted_comments[ $comment['comment_parent'] ] ) ) {
906 $comment['comment_parent'] = $inserted_comments[ $comment['comment_parent'] ];
907 }
908
909 $comment_data = wp_slash( $comment );
910 unset( $comment_data['commentmeta'] ); // Handled separately, wp_insert_comment() also expects `comment_meta`.
911 $comment_data = wp_filter_comment( $comment_data );
912
913 $inserted_comments[ $key ] = wp_insert_comment( $comment_data );
914
915 do_action( 'wp_import_insert_comment', $inserted_comments[ $key ], $comment, $comment_post_id, $post );
916
917 foreach ( $comment['commentmeta'] as $meta ) {
918 $value = maybe_unserialize( $meta['value'] );
919
920 add_comment_meta( $inserted_comments[ $key ], wp_slash( $meta['key'] ), wp_slash_strings_only( $value ) );
921 }
922
923 $num_comments++;
924 }
925 unset( $newcomments, $inserted_comments, $post['comments'] );
926 }
927
928 if ( ! isset( $post['postmeta'] ) ) {
929 $post['postmeta'] = [];
930 }
931
932 $post['postmeta'] = apply_filters( 'wp_import_post_meta', $post['postmeta'], $post_id, $post );
933
934 // Add/update post meta.
935 if ( ! empty( $post['postmeta'] ) ) {
936 foreach ( $post['postmeta'] as $meta ) {
937 $key = apply_filters( 'import_post_meta_key', $meta['key'], $post_id, $post );
938 $value = false;
939
940 if ( '_edit_last' === $key ) {
941 if ( isset( $this->processed_authors[ (int) $meta['value'] ] ) ) {
942 $value = $this->processed_authors[ (int) $meta['value'] ];
943 } else {
944 $key = false;
945 }
946 }
947
948 if ( $key ) {
949 // Export gets meta straight from the DB so could have a serialized string.
950 if ( ! $value ) {
951 $value = maybe_unserialize( $meta['value'] );
952 }
953
954 add_post_meta( $post_id, wp_slash( $key ), wp_slash_strings_only( $value ) );
955
956 do_action( 'import_post_meta', $post_id, $key, $value );
957
958 // If the post has a featured image, take note of this in case of remap.
959 if ( '_thumbnail_id' === $key ) {
960 $this->featured_images[ $post_id ] = (int) $value;
961 }
962 }
963 }
964 }
965
966 do_action( 'templately_import.process_post', $post, $result, $this );
967
968 // Add the template to the processed templates and update the session data
969 $this->backup_attributes($attributes);
970 $this->origin->update_progress( null, [ $backup_key => $result ], $this->import_data_key);
971
972
973 // If it's not the last item, send the SSE message and exit
974 if(Helper::fsi_should_exit() && 'attachment' === $postdata['post_type'] && end($this->posts) !== $post) {
975 $this->origin->sse_message( [
976 'type' => 'continue',
977 'action' => 'continue',
978 'results' => __METHOD__ . '::' . __LINE__,
979 'data' => Helper::fsi_should_exit(),
980 ] );
981 exit;
982 }
983 }
984
985 unset( $this->posts );
986
987 return $result;
988 }
989
990 /**
991 * Attempt to create a new menu item from import data
992 *
993 * Fails for draft, orphaned menu items and those without an associated nav_menu
994 * or an invalid nav_menu term. If the post type or term object which the menu item
995 * represents doesn't exist then the menu item will not be imported (waits until the
996 * end of the import to retry again before discarding).
997 *
998 * @param array $item Menu item details from WXR file
999 */
1000 private function process_menu_item( $item ) {
1001 $result = [];
1002
1003 // Skip draft, orphaned menu items.
1004 if ( 'draft' === $item['status'] ) {
1005 return;
1006 }
1007
1008 $menu_slug = false;
1009 if ( isset( $item['terms'] ) ) {
1010 // Loop through terms, assume first nav_menu term is correct menu.
1011 foreach ( $item['terms'] as $term ) {
1012 if ( 'nav_menu' === $term['domain'] ) {
1013 $menu_slug = $term['slug'];
1014 break;
1015 }
1016 }
1017 }
1018
1019 // No nav_menu term associated with this menu item.
1020 if ( ! $menu_slug ) {
1021 $this->output['errors'][] = esc_html__( 'Menu item skipped due to missing menu slug', 'elementor' );
1022
1023 return $result;
1024 }
1025
1026 // If menu was already exists, refer the items to the duplicated menu created.
1027 if ( array_key_exists( $menu_slug, $this->mapped_terms_slug ) ) {
1028 $menu_slug = $this->mapped_terms_slug[ $menu_slug ];
1029 }
1030
1031 $menu_id = term_exists( $menu_slug, 'nav_menu' );
1032 if ( ! $menu_id ) {
1033 /* translators: %s: Menu slug. */
1034 $this->output['errors'][] = sprintf( esc_html__( 'Menu item skipped due to invalid menu slug: %s', 'elementor' ), $menu_slug );
1035
1036 return $result;
1037 } else {
1038 $menu_id = is_array( $menu_id ) ? $menu_id['term_id'] : $menu_id;
1039 }
1040
1041 $post_meta_key_value = [];
1042 foreach ( $item['postmeta'] as $meta ) {
1043 $post_meta_key_value[ $meta['key'] ] = $meta['value'];
1044 }
1045
1046 $_menu_item_type = $post_meta_key_value['_menu_item_type'];
1047 $_menu_item_url = $post_meta_key_value['_menu_item_url'];
1048
1049 // Skip menu items 'taxonomy' type, when the taxonomy is not exits.
1050 if ( 'taxonomy' === $_menu_item_type && ! taxonomy_exists( $post_meta_key_value['_menu_item_object'] ) ) {
1051 return $result;
1052 }
1053
1054 // Skip menu items 'post_type' type, when the post type is not exits.
1055 if ( 'post_type' === $_menu_item_type && ! post_type_exists( $post_meta_key_value['_menu_item_object'] ) ) {
1056 return $result;
1057 }
1058
1059 $_menu_item_object_id = $post_meta_key_value['_menu_item_object_id'];
1060 if ( 'taxonomy' === $_menu_item_type && isset( $this->processed_terms[ (int) $_menu_item_object_id ] ) ) {
1061 $_menu_item_object_id = $this->processed_terms[ (int) $_menu_item_object_id ];
1062 } elseif ( 'post_type' === $_menu_item_type && isset( $this->processed_posts[ (int) $_menu_item_object_id ] ) ) {
1063 $_menu_item_object_id = $this->processed_posts[ (int) $_menu_item_object_id ];
1064 } elseif ( 'custom' === $_menu_item_type ) {
1065 // FIXME: Later on you need to check if there is custom menu link related fixes any.
1066 $_menu_item_url = URL::migrate( $_menu_item_url, $this->base_blog_url );
1067 if ( str_starts_with( $_menu_item_url, $this->base_blog_url ) ) {
1068 $_menu_item_url = '#';
1069 }
1070 } else {
1071 return $result;
1072 }
1073
1074 $_menu_item_menu_item_parent = $post_meta_key_value['_menu_item_menu_item_parent'];
1075 if ( isset( $this->processed_menu_items[ (int) $_menu_item_menu_item_parent ] ) ) {
1076 $_menu_item_menu_item_parent = $this->processed_menu_items[ (int) $_menu_item_menu_item_parent ];
1077 } elseif ( $_menu_item_menu_item_parent ) {
1078 $this->menu_item_orphans[ (int) $item['post_id'] ] = (int) $_menu_item_menu_item_parent;
1079 $_menu_item_menu_item_parent = 0;
1080 }
1081
1082 // wp_update_nav_menu_item expects CSS classes as a space separated string
1083 $_menu_item_classes = maybe_unserialize( $post_meta_key_value['_menu_item_classes'] );
1084 if ( is_array( $_menu_item_classes ) ) {
1085 $_menu_item_classes = implode( ' ', $_menu_item_classes );
1086 }
1087
1088 $args = [
1089 'menu-item-object-id' => $_menu_item_object_id,
1090 'menu-item-object' => $post_meta_key_value['_menu_item_object'],
1091 'menu-item-parent-id' => $_menu_item_menu_item_parent,
1092 'menu-item-position' => (int) $item['menu_order'],
1093 'menu-item-type' => $_menu_item_type,
1094 'menu-item-title' => $item['post_title'],
1095 'menu-item-url' => $_menu_item_url,
1096 'menu-item-description' => $item['post_content'],
1097 'menu-item-attr-title' => $item['post_excerpt'],
1098 'menu-item-target' => $post_meta_key_value['_menu_item_target'],
1099 'menu-item-classes' => $_menu_item_classes,
1100 'menu-item-xfn' => $post_meta_key_value['_menu_item_xfn'],
1101 'menu-item-status' => $item['status'],
1102 ];
1103
1104 $id = wp_update_nav_menu_item( $menu_id, 0, $args );
1105 if ( $id && ! is_wp_error( $id ) ) {
1106 $this->processed_menu_items[ (int) $item['post_id'] ] = (int) $id;
1107 $result[ $item['post_id'] ] = $id;
1108
1109 $this->update_post_meta( $id );
1110 }
1111
1112 return $result;
1113 }
1114
1115 private function process_navigation( &$item ): bool {
1116 if ( 'draft' === $item['status'] ) {
1117 return false;
1118 }
1119
1120 $content = parse_blocks( $item['post_content'] );
1121
1122 $parsed_blocks = [];
1123 foreach ( $content as $block ) {
1124 if ( empty( $block['blockName'] ) ) {
1125 continue;
1126 }
1127
1128 $this->prepare_block( $block );
1129 $parsed_blocks[] = $block;
1130 }
1131
1132 $item['post_content'] = serialize_blocks( $parsed_blocks );
1133
1134 return true;
1135 }
1136
1137 private function prepare_block( &$block ) {
1138 if ( $block['blockName'] == 'core/navigation-link' || $block['blockName'] == 'core/navigation-submenu' ) {
1139 $attrs = &$block['attrs'];
1140 switch ( $attrs['kind'] ) {
1141 case 'post-type':
1142 if ( isset( $this->processed_posts[ (int) $attrs['id'] ] ) ) {
1143 $attrs['id'] = $this->processed_posts[ (int) $attrs['id'] ];
1144 $attrs['url'] = get_permalink( $attrs['id'] );
1145 }
1146 break;
1147 case 'taxonomy':
1148 if ( isset( $this->processed_terms[ (int) $attrs['id'] ] ) ) {
1149 $attrs['id'] = $this->processed_terms[ (int) $attrs['id'] ];
1150 $attrs['url'] = get_term_link( $attrs['id'], $attrs['type'] );
1151 }
1152 break;
1153 }
1154 if ( ! empty( $block['innerBlocks'] ) ) {
1155 foreach ( $block['innerBlocks'] as &$b ) {
1156 $this->prepare_block( $b );
1157 }
1158 }
1159 }
1160 }
1161
1162 /**
1163 * If fetching attachments is enabled then attempt to create a new attachment
1164 *
1165 * @param array $post Attachment post details from WXR
1166 * @param string $url URL to fetch attachment from
1167 *
1168 * @return int|WP_Error Post ID on success, WP_Error otherwise
1169 */
1170 public function process_attachment( $post, $url, $sizes = [], $original_post_id = null ) {
1171 if ( ! $this->fetch_attachments ) {
1172 return new WP_Error( 'attachment_processing_error', esc_html__( 'Fetching attachments is not enabled', 'elementor' ) );
1173 }
1174 if ( ! function_exists( 'wp_crop_image' ) ) {
1175 include( ABSPATH . 'wp-admin/includes/image.php' );
1176 }
1177 // if the URL is absolute, but does not contain address, then upload it assuming base_site_url.
1178 if ( preg_match( '|^/[\w\W]+$|', $url ) ) {
1179 $url = rtrim( $this->base_url, '/' ) . $url;
1180 }
1181
1182 if($saved_image = $this->get_saved_image($url)){
1183 $this->url_remap[ $url ] = wp_get_attachment_url( $saved_image );
1184 $this->url_remap[ $this->remove_extension($url) ] = $this->remove_extension(wp_get_attachment_url( $saved_image ));
1185
1186 $full_size_path = get_attached_file($saved_image);
1187 $metadata = wp_get_attachment_metadata($saved_image);
1188 $metadata = $this->import_sizes($sizes, $metadata, $full_size_path, $saved_image);
1189 wp_update_attachment_metadata( $saved_image, $metadata );
1190 return $saved_image;
1191 }
1192
1193 // Check if the URL is from the wp-includes/images directory
1194 if (strpos($url, 'wp-includes/images') !== false) {
1195 // Get the URL for 'wp-includes/images' directory of the current site
1196 $current_site_url = get_site_url(null, 'wp-includes/images');
1197
1198 // Use regex to replace the old URL base with the new URL base
1199 $updated_url = preg_replace('#https?://[^/]+/(wp-includes/images)#', $current_site_url, $url);
1200
1201 return $updated_url;
1202 }
1203
1204 $upload_dir = wp_upload_dir( $post['upload_date'] );
1205 if ( ! ( $upload_dir && false === $upload_dir['error'] ) ) {
1206 return new WP_Error( 'upload_dir_error', $upload_dir['error'] );
1207 }
1208
1209 // Move the file to the uploads dir.
1210 $file_name = basename( parse_url( $url, PHP_URL_PATH ) );
1211 $file_name = wp_unique_filename( $upload_dir['path'], $file_name );
1212 $dest_file = $upload_dir['path'] . "/$file_name";
1213 $start = microtime(true);
1214
1215 $upload = apply_filters( 'templately_import_copy_attachment', null, $original_post_id, $dest_file, $upload_dir );
1216 if ( null === $upload ) {
1217 $upload = $this->fetch_remote_file( $url, $dest_file, $upload_dir );
1218 }
1219
1220 $end = microtime(true);
1221 $duration = $end - $start;
1222 error_log('Duration: ' . $duration);
1223
1224 if ( is_wp_error( $upload ) ) {
1225 return $upload;
1226 }
1227
1228 $info = wp_check_filetype( $upload['file'] );
1229 if ( $info ) {
1230 $post['post_mime_type'] = $info['type'];
1231 } else {
1232 return new WP_Error( 'attachment_processing_error', esc_html__( 'Invalid file type', 'elementor' ) );
1233 }
1234
1235 $this->url_remap[ $post['guid'] ] = $upload['url']; // r13735, really needed?
1236 $post['guid'] = $upload['url'];
1237
1238 // As per wp-admin/includes/upload.php.
1239 $post_id = wp_insert_attachment( $post, $upload['file'] );
1240
1241 if(is_wp_error($post_id)){
1242 return $post_id;
1243 }
1244
1245 $this->update_post_meta( $post_id );
1246
1247 // Generate attachment metadata
1248 $metadata = wp_generate_attachment_metadata( $post_id, $upload['file'] );
1249
1250 // error_log('Metadata: ' . print_r($metadata, true));
1251
1252 // For gutenberg pages
1253 $metadata = $this->import_sizes($sizes, $metadata, $upload['file'], $post_id);
1254
1255 // error_log('Metadata: ' . print_r($metadata, true));
1256 wp_update_attachment_metadata( $post_id, $metadata );
1257
1258 // @todo: add missing image sizes
1259
1260 update_post_meta( $post_id, '_elementor_source_image_hash', sha1( $url ) );
1261 self::$_replace_image_ids[ sha1( $url ) ] = $post_id;
1262
1263 // Remap resized image URLs, works by stripping the extension and remapping the URL stub.
1264 if ( preg_match( '!^image/!', $info['type'] ) ) {
1265 $this->url_remap[ $this->remove_extension($url) ] = $this->remove_extension($upload['url']);
1266 }
1267
1268 return $post_id;
1269 }
1270
1271 private function remove_extension($url) {
1272 $parts = pathinfo($url);
1273 $name = basename($parts['basename'], ".{$parts['extension']}"); // PATHINFO_FILENAME in PHP 5.2
1274
1275 return $parts['dirname'] . '/' . $name;
1276 }
1277
1278 /**
1279 * Attempt to download a remote file attachment
1280 *
1281 * @param string $url URL of item to fetch
1282 * @param array $post Attachment details
1283 *
1284 * @return array|WP_Error Local file location details on success, WP_Error otherwise
1285 */
1286 private function fetch_remote_file( $url, $new_file, $uploads ) {
1287 // Extract the file name from the new_file.
1288 $file_name = basename( $new_file );
1289
1290 // Include the file for the download_url function
1291 if(!function_exists('wp_tempnam')) {
1292 require_once ABSPATH . 'wp-admin/includes/file.php';
1293 }
1294
1295 $tmp_file_name = wp_tempnam( $file_name );
1296 if ( ! $tmp_file_name ) {
1297 return new WP_Error( 'import_no_file', esc_html__( 'Could not create temporary file.', 'elementor' ) );
1298 }
1299
1300 // Fetch the remote URL and write it to the placeholder file.
1301 $attempt = 0;
1302 $retry_count = 3;
1303 $remote_response = null;
1304 do {
1305 $remote_response = wp_safe_remote_get( $url, [
1306 'timeout' => 300,
1307 'stream' => true,
1308 'filename' => $tmp_file_name,
1309 'headers' => [
1310 'Accept-Encoding' => 'identity',
1311 ]
1312 ] );
1313 $attempt++;
1314 } while (is_wp_error( $remote_response ) && $attempt < $retry_count);
1315
1316
1317 if ( is_wp_error( $remote_response ) ) {
1318 @unlink( $tmp_file_name );
1319
1320 return new WP_Error( 'import_file_error', sprintf( /* translators: 1: WordPress error message, 2: WordPress error code. */ esc_html__( 'Request failed due to an error: %1$s (%2$s)', 'elementor' ), esc_html( $remote_response->get_error_message() ), esc_html( $remote_response->get_error_code() ) ) );
1321 }
1322
1323 $remote_response_code = (int) wp_remote_retrieve_response_code( $remote_response );
1324
1325 // Make sure the fetch was successful.
1326 if ( 200 !== $remote_response_code ) {
1327 @unlink( $tmp_file_name );
1328 return new WP_Error( 'import_file_error', sprintf( /* translators: 1: HTTP error message, 2: HTTP error code. */ esc_html__( 'Remote server returned the following unexpected result: %1$s (%2$s)', 'elementor' ), get_status_header_desc( $remote_response_code ), esc_html( $remote_response_code ) ) );
1329 }
1330
1331 $headers = wp_remote_retrieve_headers( $remote_response );
1332
1333 // Request failed.
1334 if ( ! $headers ) {
1335 @unlink( $tmp_file_name );
1336
1337 return new WP_Error( 'import_file_error', esc_html__( 'Remote server did not respond', 'elementor' ) );
1338 }
1339
1340 $filesize = (int) filesize( $tmp_file_name );
1341
1342 if ( 0 === $filesize ) {
1343 @unlink( $tmp_file_name );
1344
1345 return new WP_Error( 'import_file_error', esc_html__( 'Zero size file downloaded', 'elementor' ) );
1346 }
1347
1348 if ( ! isset( $headers['content-encoding'] ) && isset( $headers['content-length'] ) && $filesize !== (int) $headers['content-length'] ) {
1349 @unlink( $tmp_file_name );
1350
1351 return new WP_Error( 'import_file_error', esc_html__( 'Downloaded file has incorrect size', 'elementor' ) );
1352 }
1353
1354 $max_size = (int) apply_filters( 'import_attachment_size_limit', self::DEFAULT_IMPORT_ATTACHMENT_SIZE_LIMIT );
1355 if ( ! empty( $max_size ) && $filesize > $max_size ) {
1356 @unlink( $tmp_file_name );
1357
1358 /* translators: %s: Max file size. */
1359
1360 return new WP_Error( 'import_file_error', sprintf( esc_html__( 'Remote file is too large, limit is %s', 'elementor' ), size_format( $max_size ) ) );
1361 }
1362
1363 // Override file name with Content-Disposition header value.
1364 if ( ! empty( $headers['content-disposition'] ) ) {
1365 $file_name_from_disposition = self::get_filename_from_disposition( (array) $headers['content-disposition'] );
1366 if ( $file_name_from_disposition ) {
1367 $file_name = $file_name_from_disposition;
1368 }
1369 }
1370
1371 // Set file extension if missing.
1372 $file_ext = pathinfo( $file_name, PATHINFO_EXTENSION );
1373 if ( ! $file_ext && ! empty( $headers['content-type'] ) ) {
1374 $extension = self::get_file_extension_by_mime_type( $headers['content-type'] );
1375 if ( $extension ) {
1376 $file_name = "{$file_name}.{$extension}";
1377 }
1378 }
1379
1380 // Handle the upload like _wp_handle_upload() does.
1381 $wp_filetype = wp_check_filetype_and_ext( $tmp_file_name, $file_name );
1382 $ext = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext'];
1383 $type = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type'];
1384 $proper_filename = empty( $wp_filetype['proper_filename'] ) ? '' : $wp_filetype['proper_filename'];
1385
1386 // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect.
1387 if ( $proper_filename ) {
1388 $file_name = $proper_filename;
1389 }
1390
1391 if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
1392 return new WP_Error( 'import_file_error', esc_html__( 'Sorry, this file type is not permitted for security reasons.', 'elementor' ) );
1393 }
1394
1395 $move_new_file = copy( $tmp_file_name, $new_file );
1396
1397 if ( ! $move_new_file ) {
1398 @unlink( $tmp_file_name );
1399
1400 return new WP_Error( 'import_file_error', esc_html__( 'The uploaded file could not be moved', 'elementor' ) );
1401 }
1402
1403 // Set correct file permissions.
1404 $stat = stat( dirname( $new_file ) );
1405 $perms = $stat['mode'] & 0000666;
1406 chmod( $new_file, $perms );
1407
1408 $upload = [
1409 'file' => $new_file,
1410 'url' => $uploads['url'] . "/$file_name",
1411 'type' => $wp_filetype['type'],
1412 'error' => false,
1413 ];
1414
1415 // Keep track of the old and new urls so we can substitute them later.
1416 $this->url_remap[ $url ] = $upload['url'];
1417 // Keep track of the destination if the remote url is redirected somewhere else.
1418 if ( isset( $headers['x-final-location'] ) && $headers['x-final-location'] !== $url ) {
1419 $this->url_remap[ $headers['x-final-location'] ] = $upload['url'];
1420 }
1421
1422 return $upload;
1423 }
1424
1425 /**
1426 * Get saved image.
1427 *
1428 * Retrieve new image ID, if the image has a new ID after the import.
1429 *
1430 * @since 2.0.0
1431 * @access private
1432 *
1433 * @param string $url The image URL.
1434 *
1435 * @return false|array New image ID or false.
1436 */
1437 private function get_saved_image( $url ) {
1438 global $wpdb;
1439
1440 $hash = sha1( $url );
1441
1442 if ( isset( self::$_replace_image_ids[ $hash ] ) ) {
1443 return self::$_replace_image_ids[ $hash ];
1444 }
1445
1446 $post_id = $wpdb->get_var(
1447 $wpdb->prepare(
1448 'SELECT `post_id` FROM `' . $wpdb->postmeta . '`
1449 WHERE `meta_key` = \'_elementor_source_image_hash\'
1450 AND `meta_value` = %s
1451 ;',
1452 $hash
1453 )
1454 );
1455
1456 if ( $post_id ) {
1457 self::$_replace_image_ids[ $hash ] = $post_id;
1458 return (int) $post_id;
1459 }
1460
1461 return false;
1462 }
1463
1464
1465 public function import_sizes($sizes, $metadata, $full_size_file, $post_id) {
1466 if (!empty($sizes)) {
1467 do_action('templately_import.finalize_gutenberg_attachment', $post_id);
1468
1469 foreach ($sizes as $size_name => $size) {
1470 $size_dimension = $size['width'] . 'x' . $size['height'];
1471 $size_name = !is_string($size_name) ? $size_dimension : $size_name;
1472 $unique_destination_file = $this->create_unique_destination_file($full_size_file, $size);
1473 // check non cropped sizes. with dynamic height
1474 if (!$this->size_exists_in_metadata(basename($unique_destination_file), $metadata)) {
1475 if ($unique_destination_file) {
1476 $missing_size = $this->generate_missing_size_from_full($full_size_file, $unique_destination_file, $size);
1477 if ($missing_size && !is_wp_error($missing_size)) {
1478 unset($missing_size['path']);
1479 $metadata['sizes'][$size_name] = $missing_size;
1480 do_action('templately_import.finalize_gutenberg_attachment', $post_id, $size_dimension);
1481 }
1482 }
1483 }
1484 }
1485 }
1486 return $metadata;
1487 }
1488
1489 public function generate_missing_size_from_full($full_size_file, $destination_file, $size) {
1490 // Generate the missing size from the full-size image
1491 $editor = wp_get_image_editor($full_size_file);
1492 if (is_wp_error($editor)) {
1493 return $editor;
1494 }
1495
1496 $resized = $editor->resize($size['width'], $size['height'], true);
1497 if (is_wp_error($resized)) {
1498 return $resized;
1499 }
1500
1501 $saved = $editor->save($destination_file);
1502 if (is_wp_error($saved)) {
1503 return $saved;
1504 }
1505
1506 return $saved;
1507 }
1508
1509 public function size_exists_in_metadata($size_file, $metadata) {
1510 if (isset($metadata['sizes']) && is_array($metadata['sizes'])) {
1511 foreach ($metadata['sizes'] as $size => $size_info) {
1512 if ($size_info['file'] == $size_file) {
1513 return true;
1514 }
1515 }
1516 }
1517 return false;
1518 }
1519
1520 public function create_unique_destination_file($full_size_file, $size) {
1521 $pathinfo = pathinfo($full_size_file);
1522 $directory = $pathinfo['dirname'];
1523 $filename = $pathinfo['filename'];
1524 $extension = $pathinfo['extension'];
1525
1526 $destination_file = $directory . '/' . $filename . '-' . $size['width'] . 'x' . $size['height'] . '.' . $extension;
1527
1528 // Skip if the file already exists
1529 if (file_exists($destination_file)) {
1530 // return false;
1531 }
1532
1533 return $destination_file;
1534 }
1535
1536 public function create_size_array($destination_file, $size_dimension) {
1537 list($width, $height) = explode('x', $size_dimension);
1538 return array(
1539 'file' => basename($destination_file),
1540 'width' => $width,
1541 'height' => $height,
1542 'mime-type' => wp_check_filetype($destination_file)['type'],
1543 'filesize' => filesize($destination_file),
1544 'resized' => false,
1545 );
1546 }
1547
1548
1549 /**
1550 * Attempt to associate posts and menu items with previously missing parents
1551 *
1552 * An imported post's parent may not have been imported when it was first created
1553 * so try again. Similarly for child menu items and menu items which were missing
1554 * the object (e.g. post) they represent in the menu
1555 */
1556 private function backfill_parents() {
1557 global $wpdb;
1558
1559 // Find parents for post orphans.
1560 foreach ( $this->post_orphans as $child_id => $parent_id ) {
1561 $local_child_id = false;
1562 $local_parent_id = false;
1563
1564 if ( isset( $this->processed_posts[ $child_id ] ) ) {
1565 $local_child_id = $this->processed_posts[ $child_id ];
1566 }
1567 if ( isset( $this->processed_posts[ $parent_id ] ) ) {
1568 $local_parent_id = $this->processed_posts[ $parent_id ];
1569 }
1570
1571 if ( $local_child_id && $local_parent_id ) {
1572 $wpdb->update( $wpdb->posts, [ 'post_parent' => $local_parent_id ], [ 'ID' => $local_child_id ], '%d', '%d' );
1573 clean_post_cache( $local_child_id );
1574 }
1575 }
1576
1577 // Find parents for menu item orphans.
1578 foreach ( $this->menu_item_orphans as $child_id => $parent_id ) {
1579 $local_child_id = 0;
1580 $local_parent_id = 0;
1581 if ( isset( $this->processed_menu_items[ $child_id ] ) ) {
1582 $local_child_id = $this->processed_menu_items[ $child_id ];
1583 }
1584 if ( isset( $this->processed_menu_items[ $parent_id ] ) ) {
1585 $local_parent_id = $this->processed_menu_items[ $parent_id ];
1586 }
1587
1588 if ( $local_child_id && $local_parent_id ) {
1589 update_post_meta( $local_child_id, '_menu_item_menu_item_parent', (int) $local_parent_id );
1590 }
1591 }
1592 }
1593
1594 /**
1595 * Use stored mapping information to update old attachment URLs
1596 */
1597 private function backfill_attachment_urls() {
1598 global $wpdb;
1599 // Make sure we do the longest urls first, in case one is a substring of another.
1600 uksort( $this->url_remap, function ( $a, $b ) {
1601 // Return the difference in length between two strings.
1602 return strlen( $b ) - strlen( $a );
1603 } );
1604
1605 foreach ( $this->url_remap as $from_url => $to_url ) {
1606 // Remap urls in post_content.
1607 $processed_posts_placeholders = implode(',', array_fill(0, count($this->processed_posts), '%d'));
1608
1609 // Prepare the query for posts
1610 $query_posts = $wpdb->prepare(
1611 "UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s) WHERE ID IN ($processed_posts_placeholders)",
1612 $from_url,
1613 $to_url,
1614 ...$this->processed_posts
1615 );
1616 $wpdb->query($query_posts);
1617
1618 // Prepare the query for postmeta
1619 $query_postmeta = $wpdb->prepare(
1620 "UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key='enclosure' AND post_id IN ($processed_posts_placeholders)",
1621 $from_url,
1622 $to_url,
1623 ...$this->processed_posts
1624 );
1625 $wpdb->query($query_postmeta);
1626 }
1627 }
1628
1629 /**
1630 * Update _thumbnail_id meta to new, imported attachment IDs
1631 */
1632 private function remap_featured_images() {
1633 // Cycle through posts that have a featured image.
1634 foreach ( $this->featured_images as $post_id => $value ) {
1635 if ( isset( $this->processed_posts[ $value ] ) ) {
1636 $new_id = $this->processed_posts[ $value ];
1637 // Only update if there's a difference.
1638 if ( $new_id !== $value ) {
1639 update_post_meta( $post_id, '_thumbnail_id', $new_id );
1640 }
1641 }
1642 }
1643 }
1644
1645 /**
1646 * Parse a WXR file
1647 *
1648 * @param string $file Path to WXR file for parsing
1649 *
1650 * @return array Information gathered from the WXR file
1651 */
1652 private function parse( $file ): array {
1653 $parser = new WXR_Parser();
1654
1655 return $parser->parse( $file );
1656 }
1657
1658 /**
1659 * Decide if the given meta key maps to information we will want to import
1660 *
1661 * @param string $key The meta key to check
1662 *
1663 * @return string|bool The key if we do want to import, false if not
1664 */
1665 private function is_valid_meta_key( $key ) {
1666 // Skip attachment metadata since we'll regenerate it from scratch.
1667 // Skip _edit_lock as not relevant for import
1668 if ( in_array( $key, [ '_wp_attached_file', '_wp_attachment_metadata', '_edit_lock', '_elementor_source_image_hash', 'sm_cloud' ] ) ) {
1669 return false;
1670 }
1671
1672 return $key;
1673 }
1674
1675 /**
1676 * @param $term
1677 *
1678 * @return mixed
1679 */
1680 private function handle_duplicated_nav_menu_term( $term ) {
1681 $duplicate_slug = $term['slug'] . '-duplicate';
1682 $duplicate_name = $term['term_name'] . ' duplicate';
1683
1684 while ( term_exists( $duplicate_slug, 'nav_menu' ) ) {
1685 $duplicate_slug .= '-duplicate';
1686 $duplicate_name .= ' duplicate';
1687 }
1688
1689 $this->mapped_terms_slug[ $term['slug'] ] = $duplicate_slug;
1690
1691 $term['slug'] = $duplicate_slug;
1692 $term['term_name'] = $duplicate_name;
1693
1694 return $term;
1695 }
1696
1697 /**
1698 * Add all term_meta to specified term.
1699 *
1700 * @param $term_id
1701 *
1702 * @return void
1703 */
1704 private function update_term_meta( $term_id ) {
1705 foreach ( $this->terms_meta as $meta_key => $meta_value ) {
1706 update_term_meta( $term_id, $meta_key, $meta_value );
1707 }
1708 }
1709
1710 /**
1711 * Add all post_meta to specified term.
1712 *
1713 * @param $post_id
1714 *
1715 * @return void
1716 */
1717 private function update_post_meta( $post_id ) {
1718 foreach ( $this->posts_meta as $meta_key => $meta_value ) {
1719 update_post_meta( $post_id, $meta_key, $meta_value );
1720 }
1721 }
1722
1723 public function run(): array {
1724 $this->import( $this->requested_file_path );
1725
1726 return $this->output;
1727 }
1728
1729 /**
1730 * @param $file
1731 * @param array $args
1732 */
1733 public function __construct( $file, array $args = [] ) {
1734 parent::__construct();
1735
1736 $this->args = $args;
1737
1738 if ( ! empty( $args['json'] ) ) {
1739 $this->json = $args['json'];
1740 }
1741
1742 if ( ! empty( $args['origin'] ) ) {
1743 $this->origin = $args['origin'];
1744 }
1745
1746 if ( ! empty( $file ) ) {
1747 $this->requested_file_path = $file;
1748 $this->import_data_key = 'wp_importer_attributes_' . md5($this->requested_file_path);
1749 }
1750
1751 if ( ! empty( $this->args['fetch_attachments'] ) ) {
1752 $this->fetch_attachments = true;
1753 }
1754
1755 if ( isset( $this->args['posts'] ) && is_array( $this->args['posts'] ) ) {
1756 $this->processed_posts = $this->args['posts'];
1757 }
1758
1759 if ( isset( $this->args['terms'] ) && is_array( $this->args['terms'] ) ) {
1760 $this->processed_terms = $this->args['terms'];
1761 }
1762
1763 if ( isset( $this->args['taxonomies'] ) && is_array( $this->args['taxonomies'] ) ) {
1764 $this->processed_taxonomies = $this->args['taxonomies'];
1765 }
1766
1767 if ( ! empty( $this->args['posts_meta'] ) ) {
1768 $this->posts_meta = $this->args['posts_meta'];
1769 }
1770
1771 if ( ! empty( $this->args['terms_meta'] ) ) {
1772 $this->terms_meta = $this->args['terms_meta'];
1773 }
1774 }
1775 }
1776