PluginProbe
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! / 3.0.6
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! v3.0.6
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.0.6, at includes/Core/Importer/WPImport.php

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