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

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

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