-
Notifications
You must be signed in to change notification settings - Fork 63
/
class-wxr-importer.php
2280 lines (1913 loc) · 64.4 KB
/
class-wxr-importer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
class WXR_Importer extends WP_Importer {
/**
* Maximum supported WXR version
*/
const MAX_WXR_VERSION = 1.2;
/**
* Regular expression for checking if a post references an attachment
*
* Note: This is a quick, weak check just to exclude text-only posts. More
* vigorous checking is done later to verify.
*/
const REGEX_HAS_ATTACHMENT_REFS = '!
(
# Match anything with an image or attachment class
class=[\'"].*?\b(wp-image-\d+|attachment-[\w\-]+)\b
|
# Match anything that looks like an upload URL
src=[\'"][^\'"]*(
[0-9]{4}/[0-9]{2}/[^\'"]+\.(jpg|jpeg|png|gif)
|
content/uploads[^\'"]+
)[\'"]
)!ix';
/**
* Version of WXR we're importing.
*
* Defaults to 1.0 for compatibility. Typically overridden by a
* `<wp:wxr_version>` tag at the start of the file.
*
* @var string
*/
protected $version = '1.0';
// information to import from WXR file
protected $categories = array();
protected $tags = array();
protected $base_url = '';
// TODO: REMOVE THESE
protected $processed_terms = array();
protected $processed_posts = array();
protected $processed_menu_items = array();
protected $menu_item_orphans = array();
protected $missing_menu_items = array();
// NEW STYLE
protected $mapping = array();
protected $requires_remapping = array();
protected $exists = array();
protected $user_slug_override = array();
protected $url_remap = array();
protected $featured_images = array();
/**
* Logger instance.
*
* @var WP_Importer_Logger
*/
protected $logger;
/**
* Constructor
*
* @param array $options {
* @var bool $prefill_existing_posts Should we prefill `post_exists` calls? (True prefills and uses more memory, false checks once per imported post and takes longer. Default is true.)
* @var bool $prefill_existing_comments Should we prefill `comment_exists` calls? (True prefills and uses more memory, false checks once per imported comment and takes longer. Default is true.)
* @var bool $prefill_existing_terms Should we prefill `term_exists` calls? (True prefills and uses more memory, false checks once per imported term and takes longer. Default is true.)
* @var bool $update_attachment_guids Should attachment GUIDs be updated to the new URL? (True updates the GUID, which keeps compatibility with v1, false doesn't update, and allows deduplication and reimporting. Default is false.)
* @var bool $fetch_attachments Fetch attachments from the remote server. (True fetches and creates attachment posts, false skips attachments. Default is false.)
* @var bool $aggressive_url_search Should we search/replace for URLs aggressively? (True searches all posts' content for old URLs and replaces, false checks for `<img class="wp-image-*">` only. Default is false.)
* @var int $default_author User ID to use if author is missing or invalid. (Default is null, which leaves posts unassigned.)
* }
*/
public function __construct( $options = array() ) {
// Initialize some important variables
$empty_types = array(
'post' => array(),
'comment' => array(),
'term' => array(),
'user' => array(),
);
$this->mapping = $empty_types;
$this->mapping['user_slug'] = array();
$this->mapping['term_id'] = array();
$this->requires_remapping = $empty_types;
$this->exists = $empty_types;
$this->options = wp_parse_args( $options, array(
'prefill_existing_posts' => true,
'prefill_existing_comments' => true,
'prefill_existing_terms' => true,
'update_attachment_guids' => false,
'fetch_attachments' => false,
'aggressive_url_search' => false,
'default_author' => null,
) );
}
public function set_logger( $logger ) {
$this->logger = $logger;
}
/**
* Get a stream reader for the file.
*
* @param string $file Path to the XML file.
* @return XMLReader|WP_Error Reader instance on success, error otherwise.
*/
protected function get_reader( $file ) {
// Avoid loading external entities for security
$old_value = null;
if ( function_exists( 'libxml_disable_entity_loader' ) ) {
// $old_value = libxml_disable_entity_loader( true );
}
$reader = new XMLReader();
$status = $reader->open( $file );
if ( ! is_null( $old_value ) ) {
// libxml_disable_entity_loader( $old_value );
}
if ( ! $status ) {
return new WP_Error( 'wxr_importer.cannot_parse', __( 'Could not open the file for parsing', 'wordpress-importer' ) );
}
return $reader;
}
/**
* The main controller for the actual import stage.
*
* @param string $file Path to the WXR file for importing
*/
public function get_preliminary_information( $file ) {
// Let's run the actual importer now, woot
$reader = $this->get_reader( $file );
if ( is_wp_error( $reader ) ) {
return $reader;
}
// Set the version to compatibility mode first
$this->version = '1.0';
// Start parsing!
$data = new WXR_Import_Info();
while ( $reader->read() ) {
// Only deal with element opens
if ( $reader->nodeType !== XMLReader::ELEMENT ) {
continue;
}
switch ( $reader->name ) {
case 'wp:wxr_version':
// Upgrade to the correct version
$this->version = $reader->readString();
if ( version_compare( $this->version, self::MAX_WXR_VERSION, '>' ) ) {
$this->logger->warning( sprintf(
__( 'This WXR file (version %s) is newer than the importer (version %s) and may not be supported. Please consider updating.', 'wordpress-importer' ),
$this->version,
self::MAX_WXR_VERSION
) );
}
// Handled everything in this node, move on to the next
$reader->next();
break;
case 'generator':
$data->generator = $reader->readString();
$reader->next();
break;
case 'title':
$data->title = $reader->readString();
$reader->next();
break;
case 'wp:base_site_url':
$data->siteurl = $reader->readString();
$reader->next();
break;
case 'wp:base_blog_url':
$data->home = $reader->readString();
$reader->next();
break;
case 'wp:author':
$node = $reader->expand();
$parsed = $this->parse_author_node( $node );
if ( is_wp_error( $parsed ) ) {
$this->log_error( $parsed );
// Skip the rest of this post
$reader->next();
break;
}
$data->users[] = $parsed;
// Handled everything in this node, move on to the next
$reader->next();
break;
case 'item':
$node = $reader->expand();
$parsed = $this->parse_post_node( $node );
if ( is_wp_error( $parsed ) ) {
$this->log_error( $parsed );
// Skip the rest of this post
$reader->next();
break;
}
if ( $parsed['data']['post_type'] === 'attachment' ) {
$data->media_count++;
} else {
$data->post_count++;
}
$data->comment_count += count( $parsed['comments'] );
// Handled everything in this node, move on to the next
$reader->next();
break;
case 'wp:category':
case 'wp:tag':
case 'wp:term':
$data->term_count++;
// Handled everything in this node, move on to the next
$reader->next();
break;
}
}
$data->version = $this->version;
return $data;
}
/**
* The main controller for the actual import stage.
*
* @param string $file Path to the WXR file for importing
*/
public function parse_authors( $file ) {
// Let's run the actual importer now, woot
$reader = $this->get_reader( $file );
if ( is_wp_error( $reader ) ) {
return $reader;
}
// Set the version to compatibility mode first
$this->version = '1.0';
// Start parsing!
$authors = array();
while ( $reader->read() ) {
// Only deal with element opens
if ( $reader->nodeType !== XMLReader::ELEMENT ) {
continue;
}
switch ( $reader->name ) {
case 'wp:wxr_version':
// Upgrade to the correct version
$this->version = $reader->readString();
if ( version_compare( $this->version, self::MAX_WXR_VERSION, '>' ) ) {
$this->logger->warning( sprintf(
__( 'This WXR file (version %s) is newer than the importer (version %s) and may not be supported. Please consider updating.', 'wordpress-importer' ),
$this->version,
self::MAX_WXR_VERSION
) );
}
// Handled everything in this node, move on to the next
$reader->next();
break;
case 'wp:author':
$node = $reader->expand();
$parsed = $this->parse_author_node( $node );
if ( is_wp_error( $parsed ) ) {
$this->log_error( $parsed );
// Skip the rest of this post
$reader->next();
break;
}
$authors[] = $parsed;
// Handled everything in this node, move on to the next
$reader->next();
break;
}
}
return $authors;
}
/**
* The main controller for the actual import stage.
*
* @param string $file Path to the WXR file for importing
*/
public function import( $file ) {
add_filter( 'import_post_meta_key', array( $this, 'is_valid_meta_key' ) );
add_filter( 'http_request_timeout', array( &$this, 'bump_request_timeout' ) );
$result = $this->import_start( $file );
if ( is_wp_error( $result ) ) {
return $result;
}
// Let's run the actual importer now, woot
$reader = $this->get_reader( $file );
if ( is_wp_error( $reader ) ) {
return $reader;
}
// Set the version to compatibility mode first
$this->version = '1.0';
// Reset other variables
$this->base_url = '';
// Start parsing!
while ( $reader->read() ) {
// Only deal with element opens
if ( $reader->nodeType !== XMLReader::ELEMENT ) {
continue;
}
switch ( $reader->name ) {
case 'wp:wxr_version':
// Upgrade to the correct version
$this->version = $reader->readString();
if ( version_compare( $this->version, self::MAX_WXR_VERSION, '>' ) ) {
$this->logger->warning( sprintf(
__( 'This WXR file (version %s) is newer than the importer (version %s) and may not be supported. Please consider updating.', 'wordpress-importer' ),
$this->version,
self::MAX_WXR_VERSION
) );
}
// Handled everything in this node, move on to the next
$reader->next();
break;
case 'wp:base_site_url':
$this->base_url = $reader->readString();
// Handled everything in this node, move on to the next
$reader->next();
break;
case 'item':
$node = $reader->expand();
$parsed = $this->parse_post_node( $node );
if ( is_wp_error( $parsed ) ) {
$this->log_error( $parsed );
// Skip the rest of this post
$reader->next();
break;
}
$this->process_post( $parsed['data'], $parsed['meta'], $parsed['comments'], $parsed['terms'] );
// Handled everything in this node, move on to the next
$reader->next();
break;
case 'wp:author':
$node = $reader->expand();
$parsed = $this->parse_author_node( $node );
if ( is_wp_error( $parsed ) ) {
$this->log_error( $parsed );
// Skip the rest of this post
$reader->next();
break;
}
$status = $this->process_author( $parsed['data'], $parsed['meta'] );
if ( is_wp_error( $status ) ) {
$this->log_error( $status );
}
// Handled everything in this node, move on to the next
$reader->next();
break;
case 'wp:category':
$node = $reader->expand();
$parsed = $this->parse_term_node( $node, 'category' );
if ( is_wp_error( $parsed ) ) {
$this->log_error( $parsed );
// Skip the rest of this post
$reader->next();
break;
}
$status = $this->process_term( $parsed['data'], $parsed['meta'] );
// Handled everything in this node, move on to the next
$reader->next();
break;
case 'wp:tag':
$node = $reader->expand();
$parsed = $this->parse_term_node( $node, 'tag' );
if ( is_wp_error( $parsed ) ) {
$this->log_error( $parsed );
// Skip the rest of this post
$reader->next();
break;
}
$status = $this->process_term( $parsed['data'], $parsed['meta'] );
// Handled everything in this node, move on to the next
$reader->next();
break;
case 'wp:term':
$node = $reader->expand();
$parsed = $this->parse_term_node( $node );
if ( is_wp_error( $parsed ) ) {
$this->log_error( $parsed );
// Skip the rest of this post
$reader->next();
break;
}
$status = $this->process_term( $parsed['data'], $parsed['meta'] );
// Handled everything in this node, move on to the next
$reader->next();
break;
default:
// Skip this node, probably handled by something already
break;
}
}
// Now that we've done the main processing, do any required
// post-processing and remapping.
$this->post_process();
if ( $this->options['aggressive_url_search'] ) {
$this->replace_attachment_urls_in_content();
}
// $this->remap_featured_images();
$this->import_end();
}
/**
* Log an error instance to the logger.
*
* @param WP_Error $error Error instance to log.
*/
protected function log_error( WP_Error $error ) {
$this->logger->warning( $error->get_error_message() );
// Log the data as debug info too
$data = $error->get_error_data();
if ( ! empty( $data ) ) {
$this->logger->debug( var_export( $data, true ) );
}
}
/**
* Parses the WXR file and prepares us for the task of processing parsed data
*
* @param string $file Path to the WXR file for importing
*/
protected function import_start( $file ) {
if ( ! is_file( $file ) ) {
return new WP_Error( 'wxr_importer.file_missing', __( 'The file does not exist, please try again.', 'wordpress-importer' ) );
}
// Suspend bunches of stuff in WP core
wp_defer_term_counting( true );
wp_defer_comment_counting( true );
wp_suspend_cache_invalidation( true );
// Prefill exists calls if told to
if ( $this->options['prefill_existing_posts'] ) {
$this->prefill_existing_posts();
}
if ( $this->options['prefill_existing_comments'] ) {
$this->prefill_existing_comments();
}
if ( $this->options['prefill_existing_terms'] ) {
$this->prefill_existing_terms();
}
/**
* Begin the import.
*
* Fires before the import process has begun. If you need to suspend
* caching or heavy processing on hooks, do so here.
*/
do_action( 'import_start' );
}
/**
* Performs post-import cleanup of files and the cache
*/
protected function import_end() {
// Re-enable stuff in core
wp_suspend_cache_invalidation( false );
wp_cache_flush();
foreach ( get_taxonomies() as $tax ) {
delete_option( "{$tax}_children" );
_get_term_hierarchy( $tax );
}
wp_defer_term_counting( false );
wp_defer_comment_counting( false );
/**
* Complete the import.
*
* Fires after the import process has finished. If you need to update
* your cache or re-enable processing, do so here.
*/
do_action( 'import_end' );
}
/**
* Set the user mapping.
*
* @param array $mapping List of map arrays (containing `old_slug`, `old_id`, `new_id`)
*/
public function set_user_mapping( $mapping ) {
foreach ( $mapping as $map ) {
if ( empty( $map['old_slug'] ) || empty( $map['old_id'] ) || empty( $map['new_id'] ) ) {
$this->logger->warning( __( 'Invalid author mapping', 'wordpress-importer' ) );
$this->logger->debug( var_export( $map, true ) );
continue;
}
$old_slug = $map['old_slug'];
$old_id = $map['old_id'];
$new_id = $map['new_id'];
$this->mapping['user'][ $old_id ] = $new_id;
$this->mapping['user_slug'][ $old_slug ] = $new_id;
}
}
/**
* Set the user slug overrides.
*
* Allows overriding the slug in the import with a custom/renamed version.
*
* @param string[] $overrides Map of old slug to new slug.
*/
public function set_user_slug_overrides( $overrides ) {
foreach ( $overrides as $original => $renamed ) {
$this->user_slug_override[ $original ] = $renamed;
}
}
/**
* Parse a post node into post data.
*
* @param DOMElement $node Parent node of post data (typically `item`).
* @return array|WP_Error Post data array on success, error otherwise.
*/
protected function parse_post_node( $node ) {
$data = array();
$meta = array();
$comments = array();
$terms = array();
foreach ( $node->childNodes as $child ) {
// We only care about child elements
if ( $child->nodeType !== XML_ELEMENT_NODE ) {
continue;
}
switch ( $child->tagName ) {
case 'wp:post_type':
$data['post_type'] = $child->textContent;
break;
case 'title':
$data['post_title'] = $child->textContent;
break;
case 'guid':
$data['guid'] = $child->textContent;
break;
case 'dc:creator':
$data['post_author'] = $child->textContent;
break;
case 'content:encoded':
$data['post_content'] = $child->textContent;
break;
case 'excerpt:encoded':
$data['post_excerpt'] = $child->textContent;
break;
case 'wp:post_id':
$data['post_id'] = $child->textContent;
break;
case 'wp:post_date':
$data['post_date'] = $child->textContent;
break;
case 'wp:post_date_gmt':
$data['post_date_gmt'] = $child->textContent;
break;
case 'wp:comment_status':
$data['comment_status'] = $child->textContent;
break;
case 'wp:ping_status':
$data['ping_status'] = $child->textContent;
break;
case 'wp:post_name':
$data['post_name'] = $child->textContent;
break;
case 'wp:status':
$data['post_status'] = $child->textContent;
if ( $data['post_status'] === 'auto-draft' ) {
// Bail now
return new WP_Error(
'wxr_importer.post.cannot_import_draft',
__( 'Cannot import auto-draft posts' ),
$data
);
}
break;
case 'wp:post_parent':
$data['post_parent'] = $child->textContent;
break;
case 'wp:menu_order':
$data['menu_order'] = $child->textContent;
break;
case 'wp:post_password':
$data['post_password'] = $child->textContent;
break;
case 'wp:is_sticky':
$data['is_sticky'] = $child->textContent;
break;
case 'wp:attachment_url':
$data['attachment_url'] = $child->textContent;
break;
case 'wp:postmeta':
$meta_item = $this->parse_meta_node( $child );
if ( ! empty( $meta_item ) ) {
$meta[] = $meta_item;
}
break;
case 'wp:comment':
$comment_item = $this->parse_comment_node( $child );
if ( ! empty( $comment_item ) ) {
$comments[] = $comment_item;
}
break;
case 'category':
$term_item = $this->parse_category_node( $child );
if ( ! empty( $term_item ) ) {
$terms[] = $term_item;
}
break;
}
}
return compact( 'data', 'meta', 'comments', 'terms' );
}
/**
* Create new posts based on import information
*
* Posts marked as having a parent which doesn't exist will become top level items.
* Doesn't create a new post if: the post type doesn't exist, the given post ID
* is already noted as imported or a post with the same title and date already exists.
* Note that new/updated terms, comments and meta are imported for the last of the above.
*/
protected function process_post( $data, $meta, $comments, $terms ) {
/**
* Pre-process post data.
*
* @param array $data Post data. (Return empty to skip.)
* @param array $meta Meta data.
* @param array $comments Comments on the post.
* @param array $terms Terms on the post.
*/
$data = apply_filters( 'wxr_importer.pre_process.post', $data, $meta, $comments, $terms );
if ( empty( $data ) ) {
return false;
}
$original_id = isset( $data['post_id'] ) ? (int) $data['post_id'] : 0;
$parent_id = isset( $data['post_parent'] ) ? (int) $data['post_parent'] : 0;
$author_id = isset( $data['post_author'] ) ? (int) $data['post_author'] : 0;
// Have we already processed this?
if ( isset( $this->mapping['post'][ $original_id ] ) ) {
return;
}
$post_type_object = get_post_type_object( $data['post_type'] );
// Is this type even valid?
if ( ! $post_type_object ) {
$this->logger->warning( sprintf(
__( 'Failed to import "%s": Invalid post type %s', 'wordpress-importer' ),
$data['post_title'],
$data['post_type']
) );
return false;
}
$post_exists = $this->post_exists( $data );
if ( $post_exists ) {
$this->logger->info( sprintf(
__( '%s "%s" already exists.', 'wordpress-importer' ),
$post_type_object->labels->singular_name,
$data['post_title']
) );
/**
* Post processing already imported.
*
* @param array $data Raw data imported for the post.
*/
do_action( 'wxr_importer.process_already_imported.post', $data );
// Even though this post already exists, new comments might need importing
$this->process_comments( $comments, $original_id, $data, $post_exists );
return false;
}
// Map the parent post, or mark it as one we need to fix
$requires_remapping = false;
if ( $parent_id ) {
if ( isset( $this->mapping['post'][ $parent_id ] ) ) {
$data['post_parent'] = $this->mapping['post'][ $parent_id ];
} else {
$meta[] = array( 'key' => '_wxr_import_parent', 'value' => $parent_id );
$requires_remapping = true;
$data['post_parent'] = 0;
}
}
// Map the author, or mark it as one we need to fix
$author = sanitize_user( $data['post_author'], true );
if ( empty( $author ) ) {
// Missing or invalid author, use default if available.
$data['post_author'] = $this->options['default_author'];
} elseif ( isset( $this->mapping['user_slug'][ $author ] ) ) {
$data['post_author'] = $this->mapping['user_slug'][ $author ];
} else {
$meta[] = array( 'key' => '_wxr_import_user_slug', 'value' => $author );
$requires_remapping = true;
$data['post_author'] = (int) get_current_user_id();
}
// Does the post look like it contains attachment images?
if ( preg_match( self::REGEX_HAS_ATTACHMENT_REFS, $data['post_content'] ) ) {
$meta[] = array( 'key' => '_wxr_import_has_attachment_refs', 'value' => true );
$requires_remapping = true;
}
// Whitelist to just the keys we allow
$postdata = array(
'import_id' => $data['post_id'],
);
$allowed = array(
'post_author' => true,
'post_date' => true,
'post_date_gmt' => true,
'post_content' => true,
'post_excerpt' => true,
'post_title' => true,
'post_status' => true,
'post_name' => true,
'comment_status' => true,
'ping_status' => true,
'guid' => true,
'post_parent' => true,
'menu_order' => true,
'post_type' => true,
'post_password' => true,
);
foreach ( $data as $key => $value ) {
if ( ! isset( $allowed[ $key ] ) ) {
continue;
}
$postdata[ $key ] = $data[ $key ];
}
$postdata = apply_filters( 'wp_import_post_data_processed', $postdata, $data );
if ( 'attachment' === $postdata['post_type'] ) {
if ( ! $this->options['fetch_attachments'] ) {
$this->logger->notice( sprintf(
__( 'Skipping attachment "%s", fetching attachments disabled' ),
$data['post_title']
) );
/**
* Post processing skipped.
*
* @param array $data Raw data imported for the post.
* @param array $meta Raw meta data, already processed by {@see process_post_meta}.
*/
do_action( 'wxr_importer.process_skipped.post', $data, $meta );
return false;
}
$remote_url = ! empty( $data['attachment_url'] ) ? $data['attachment_url'] : $data['guid'];
$post_id = $this->process_attachment( $postdata, $meta, $remote_url );
} else {
$post_id = wp_insert_post( $postdata, true );
do_action( 'wp_import_insert_post', $post_id, $original_id, $postdata, $data );
}
if ( is_wp_error( $post_id ) ) {
$this->logger->error( sprintf(
__( 'Failed to import "%s" (%s)', 'wordpress-importer' ),
$data['post_title'],
$post_type_object->labels->singular_name
) );
$this->logger->debug( $post_id->get_error_message() );
/**
* Post processing failed.
*
* @param WP_Error $post_id Error object.
* @param array $data Raw data imported for the post.
* @param array $meta Raw meta data, already processed by {@see process_post_meta}.
* @param array $comments Raw comment data, already processed by {@see process_comments}.
* @param array $terms Raw term data, already processed.
*/
do_action( 'wxr_importer.process_failed.post', $post_id, $data, $meta, $comments, $terms );
return false;
}
// Ensure stickiness is handled correctly too
if ( $data['is_sticky'] === '1' ) {
stick_post( $post_id );
}
// map pre-import ID to local ID
$this->mapping['post'][ $original_id ] = (int) $post_id;
if ( $requires_remapping ) {
$this->requires_remapping['post'][ $post_id ] = true;
}
$this->mark_post_exists( $data, $post_id );
$this->logger->info( sprintf(
__( 'Imported "%s" (%s)', 'wordpress-importer' ),
$data['post_title'],
$post_type_object->labels->singular_name
) );
$this->logger->debug( sprintf(
__( 'Post %d remapped to %d', 'wordpress-importer' ),
$original_id,
$post_id
) );
// Handle the terms too
$terms = apply_filters( 'wp_import_post_terms', $terms, $post_id, $data );
if ( ! empty( $terms ) ) {
$term_ids = array();
foreach ( $terms as $term ) {
$taxonomy = $term['taxonomy'];
$key = sha1( $taxonomy . ':' . $term['slug'] );
if ( isset( $this->mapping['term'][ $key ] ) ) {
$term_ids[ $taxonomy ][] = (int) $this->mapping['term'][ $key ];
} else {
$meta[] = array( 'key' => '_wxr_import_term', 'value' => $term );
$requires_remapping = true;
}
}
foreach ( $term_ids as $tax => $ids ) {
$tt_ids = wp_set_post_terms( $post_id, $ids, $tax );
do_action( 'wp_import_set_post_terms', $tt_ids, $ids, $tax, $post_id, $data );
}
}
$this->process_comments( $comments, $post_id, $data );
$this->process_post_meta( $meta, $post_id, $data );
if ( 'nav_menu_item' === $data['post_type'] ) {
$this->process_menu_item_meta( $post_id, $data, $meta );
}
/**
* Post processing completed.
*
* @param int $post_id New post ID.
* @param array $data Raw data imported for the post.
* @param array $meta Raw meta data, already processed by {@see process_post_meta}.
* @param array $comments Raw comment data, already processed by {@see process_comments}.
* @param array $terms Raw term data, already processed.
*/
do_action( 'wxr_importer.processed.post', $post_id, $data, $meta, $comments, $terms );
}
/**
* Attempt to create a new menu item from import data
*
* Fails for draft, orphaned menu items and those without an associated nav_menu
* or an invalid nav_menu term. If the post type or term object which the menu item
* represents doesn't exist then the menu item will not be imported (waits until the
* end of the import to retry again before discarding).
*
* @param array $item Menu item details from WXR file
*/
protected function process_menu_item_meta( $post_id, $data, $meta ) {
$item_type = get_post_meta( $post_id, '_menu_item_type', true );
$original_object_id = get_post_meta( $post_id, '_menu_item_object_id', true );
$object_id = null;
$this->logger->debug( sprintf( 'Processing menu item %s', $item_type ) );
$requires_remapping = false;
switch ( $item_type ) {
case 'taxonomy':
if ( isset( $this->mapping['term_id'][ $original_object_id ] ) ) {
$object_id = $this->mapping['term_id'][ $original_object_id ];
} else {
add_post_meta( $post_id, '_wxr_import_menu_item', wp_slash( $original_object_id ) );
$requires_remapping = true;
}
break;
case 'post_type':
if ( isset( $this->mapping['post'][ $original_object_id ] ) ) {
$object_id = $this->mapping['post'][ $original_object_id ];
} else {
add_post_meta( $post_id, '_wxr_import_menu_item', wp_slash( $original_object_id ) );
$requires_remapping = true;
}
break;
case 'custom':
// Custom refers to itself, wonderfully easy.
$object_id = $post_id;
break;
default:
// associated object is missing or not imported yet, we'll retry later
$this->missing_menu_items[] = $item;
$this->logger->debug( 'Unknown menu item type' );
break;