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

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