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

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