forked from Automattic/WordPress-CLI-Exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli-exporter.php
902 lines (783 loc) · 32.3 KB
/
cli-exporter.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
<?php
/**
* CLI Version of the WordPress Exporter
* Author: Thorsten Ott, Automattic
* Author URI: http://hitchhackerguide.com
* Version: 0.3
*
* License: GPLv2
*
* Changelog:
*
* == v0.3 ==
* - Remove trailing whitespace
* - Add instructions at the top of the file
*
* == v0.2 ==
* - Implement hostname hack used in CLI Importer (re-reun script with forced HTTP_HOST) so we don't lose custom post types and taxonomies
* - Single-site instances no longer need to specify blog parameter
* - For non-all post_type lookups, grab attachments in the batch along with the parent instead of upfront
*
* Instructions:
*
* Make sure to set $wordpress_root_dir and $_SERVER['HTTP_HOST'] according to your environment.
*
* Then execute the script with the following parameters ( brackets indicate optional parameters ):
*
* php cli-exporter.php --blog=blogname --path=/tmp/ --user=admin [--start_date=2011-01-01] [--end_date=2011-12-31] [--post_type=post] [--author=admin] [-- * category=Uncategorized] [--post_status=publish] [--skip_comments=1] [--file_item_count=1000] [--post_ids=2335108,2335110,2335114,2335111,2335112,2335109,2335113]
*
* blogname: the name or blog_id of the blog you like to export
* path: the full path to the directory where exports should be stored
* user: the WordPress username or ID that will run this export
* start_date: only export posts older than this date (format: YYYY-MM-DD)
* end_date: only export posts newer than this date (format: YYYY-MM-DD)
* post_type: export only posts matching this post_type
* author: export only posts for this user_login or user_id
* category: export only posts with this category name
* post_status: export only posts with a particular post status
* skip_comments: if this is set to 1 then comments will not be exported
* file_item_count: how many items to include per file (will automatically break up into several files at the specified interval)
* post_ids: export specific post ids, regardless of arguments
*
*/
cli_set_hostname();
define( 'SAVEQUERIES', false );
set_time_limit( 0 );
ini_set( 'memory_limit', '768M' );
if ( empty( $_SERVER['HTTP_HOST'] ) )
$_SERVER['HTTP_HOST'] = 'localhost'; // set this to your main blog_address
if ( empty( $_SERVER['HTTP_HOST'] ) )
die( 'You need to the default HTTP_HOST in line ' . ( __LINE__ - 2 ) . "\n" );
$wordpress_root_dir = dirname( dirname( __FILE__ ) ); // set this to the root directory of your WordPress install that holds wp-load.php
if ( !file_exists( $wordpress_root_dir . '/wp-load.php' ) )
die( 'You need to the $wordpress_root_dir in line ' . ( __LINE__ - 2 ) . "\n" );
ob_start();
require_once $wordpress_root_dir . '/wp-load.php'; // you need to adjust this to your path
require_once ABSPATH . 'wp-admin/includes/admin.php';
require_once ABSPATH . 'wp-admin/includes/export.php';
ob_end_clean();
class WordPress_CLI_Export {
public $args;
private $validate_args = array();
private $required_args = array();
public $debug_mode = true;
// Import Vars
public $wxr_path = '';
public $blog_id = 0;
public $user_id = 0;
public $blog_address = 0;
public $export_args = array();
public function __construct() {
$this->args = $this->get_cli_arguments();
}
public function init() {
if ( !$this->validate_args() ) {
$this->debug_msg( "Problems with arguments" );
exit;
}
// In a single site instance, we don't need to pass in the blog_id, so let's force initialize the blog context
if ( empty( $this->blog_id ) )
$this->cli_init_blog();
if ( !empty( $this->args->hostname ) ) {
$this->dispatch();
} else {
// Re-run the export with a forced HTTP_HOST so that the full blog context is initialized
$this->debug_msg( "Initializing Environment" );
$this->args->hostname = $this->blog_host;
foreach( $this->args as $key => $value )
$args[] = "--$key=". escapeshellarg( $value );
$command = "php " . __FILE__ . " " . implode( " ", (array) $args );
$this->debug_msg( "$command" );
system( $command );
}
}
public function dispatch() {
$this->debug_msg( "Starting Export" );
$this->wxr_path = $this->args->path;
$this->export_wp( $this->export_args );
}
public function stop_the_insanity() {
global $wpdb, $wp_object_cache;
$wpdb->queries = array(); // or define( 'WP_IMPORTING', true );
if ( !is_object( $wp_object_cache ) )
return;
$wp_object_cache->group_ops = array();
$wp_object_cache->stats = array();
$wp_object_cache->memcache_debug = array();
$wp_object_cache->cache = array();
if ( method_exists( $wp_object_cache, '__remoteset' ) )
$wp_object_cache->__remoteset(); // important
}
public function debug_msg( $msg ) {
$msg = date( "Y-m-d H:i:s : " ) . $msg;
if ( $this->debug_mode )
echo $msg . "\n";
else
error_log( $msg );
}
public function set_required_arg( $name, $description='' ) {
$this->required_args[$name] = $description;
}
public function set_argument_validation( $name_match, $value_match, $description='argument validation error' ) {
$this->validate_args[] = array( 'name_match' => $name_match, 'value_match' => $value_match, 'description' => $description );
}
private function validate_args() {
$result = true;
$this->debug_msg( "Validating arguments" );
if ( empty( $_SERVER['argv'][1] ) && !empty( $this->required_args ) ) {
$this->show_help();
$result = false;
} else {
foreach ( $this->required_args as $name => $description ) {
if ( !isset( $this->args->$name ) ) {
$this->raise_required_argument_error( $name, $description );
$result = false;
}
}
}
foreach ( $this->validate_args as $validator ) {
foreach ( $this->args as $name => $value ) {
$name_match_result = preg_match( $validator['name_match'], $name );
if ( ! $name_match_result ) {
continue;
} else {
$value_match_result = $this->dispatch_argument_validator( $validator['value_match'], $value );
if ( ! $value_match_result ) {
$this->raise_argument_error( $name, $value, $validator );
$result = false;
continue;
}
}
}
}
return $result;
}
private function dispatch_argument_validator( $match, $value ) {
$match_result = false;
if ( is_callable( array( &$this, $match ) ) ) {
$_match_result = call_user_func( array( &$this, $match ), $value );
} else if ( is_callable( $match ) ) {
$_match_result = call_user_func( $match, $value );
} else {
$_match_result = preg_match( $match, $value );
}
return $_match_result;
}
private function raise_argument_error( $name, $value, $validator ) {
printf( "Validation of %s with value %s failed: %s\n", $name, $value, $validator['description'] );
}
private function raise_required_argument_error( $name, $description ) {
printf( "Argument --%s is required: %s\n", $name, $description );
}
private function show_help() {
$msg = '';
$example = "php " . __FILE__ . " --blog=blogname --path=/tmp/ --user=admin [--start_date=2011-01-01] --end_date=2011-12-31] [--post_type=post] [--author=admin] [--category=Uncategorized] [--post_status=publish] [--skip_comments=1] [--file_item_count=1000]";
printf( "Please call the script with the following arguments: \n%s\n", $example );
foreach ( $this->required_args as $name => $description )
$msg .= $this->raise_required_argument_error( $name, $description );
}
private function cli_init_blog( $blog = 0 ) {
if ( is_multisite() ) {
if ( empty( $blog ) ) {
$this->debug_msg( "blog_id cannot be empty" );
die();
}
if ( is_numeric( $blog ) ) {
$blog_id = (int) $blog;
} else {
$blog_id = get_id_from_blogname( $blog );
}
} else {
$blog_id = 1;
}
if ( $blog_id > 0 ) {
$home_url = get_home_url( $blog_id );
$this->blog_host = parse_url( $home_url, PHP_URL_HOST );
$sanitized_home_url = $home_url;
$sanitized_home_url = str_replace( 'http://', '', $sanitized_home_url );
$sanitized_home_url = preg_replace( '#/$#', '', $sanitized_home_url );
$this->blog_address = $sanitized_home_url;
$this->debug_msg( sprintf( "the blog_address we found is %s (%d)", $this->blog_address, $blog_id ) );
$this->args->blog = $blog_id;
if ( function_exists( 'is_multisite' ) && is_multisite() )
switch_to_blog( (int) $blog_id );
$this->blog_id = (int) $blog_id;
return true;
} else {
$this->debug_msg( sprintf( "could not get a blog_id for this address: %s", var_export( $blog_id, true ) ) );
die();
}
}
private function cli_set_user( $user_id ) {
if ( is_numeric( $user_id ) ) {
$user_id = (int) $user_id;
} else {
$user_id = (int) username_exists( $user_id );
}
if ( !$user_id || !wp_set_current_user( $user_id ) ) {
$this->debug_msg( sprintf( "could not get a user_id for this user: %s", var_export( $user_id, true ) ) );
die();
}
$current_user = wp_get_current_user();
$this->user_id = (int) $user_id;
return $user_id;
}
private function get_cli_arguments() {
$_ARG = new StdClass;
$argv = $_SERVER['argv'];
array_shift( $argv );
foreach ( $argv as $arg ) {
if ( preg_match( '#--([^=]+)=(.*)#', $arg, $reg ) )
$_ARG->$reg[1] = $reg[2];
elseif ( preg_match( '#-([a-zA-Z0-9])#', $arg, $reg ) )
$_ARG->$reg[1] = 'true';
}
return $_ARG;
}
private function export_wp( $args = array() ) {
global $wpdb, $post;
/**
* Wrap given string in XML CDATA tag.
*
* @since 2.1.0
*
* @param string $str String to wrap in XML CDATA tag.
*/
function wxr_cdata( $str ) {
if ( seems_utf8( $str ) == false )
$str = utf8_encode( $str );
// $str = ent2ncr(esc_html($str));
$str = '<![CDATA[' . str_replace( ']]>', ']]]]><![CDATA[>', $str ) . ']]>';
return $str;
}
/**
* Return the URL of the site
*
* @since 2.5.0
*
* @return string Site URL.
*/
function wxr_site_url() {
// ms: the base url
if ( is_multisite() )
return network_home_url();
// wp: the blog url
else
return get_bloginfo_rss( 'url' );
}
/**
* Output a cat_name XML tag from a given category object
*
* @since 2.1.0
*
* @param object $category Category Object
*/
function wxr_cat_name( $category ) {
if ( empty( $category->name ) )
return;
echo '<wp:cat_name>' . wxr_cdata( $category->name ) . '</wp:cat_name>';
}
/**
* Output a category_description XML tag from a given category object
*
* @since 2.1.0
*
* @param object $category Category Object
*/
function wxr_category_description( $category ) {
if ( empty( $category->description ) )
return;
echo '<wp:category_description>' . wxr_cdata( $category->description ) . '</wp:category_description>';
}
/**
* Output a tag_name XML tag from a given tag object
*
* @since 2.3.0
*
* @param object $tag Tag Object
*/
function wxr_tag_name( $tag ) {
if ( empty( $tag->name ) )
return;
echo '<wp:tag_name>' . wxr_cdata( $tag->name ) . '</wp:tag_name>';
}
/**
* Output a tag_description XML tag from a given tag object
*
* @since 2.3.0
*
* @param object $tag Tag Object
*/
function wxr_tag_description( $tag ) {
if ( empty( $tag->description ) )
return;
echo '<wp:tag_description>' . wxr_cdata( $tag->description ) . '</wp:tag_description>';
}
/**
* Output a term_name XML tag from a given term object
*
* @since 2.9.0
*
* @param object $term Term Object
*/
function wxr_term_name( $term ) {
if ( empty( $term->name ) )
return;
echo '<wp:term_name>' . wxr_cdata( $term->name ) . '</wp:term_name>';
}
/**
* Output a term_description XML tag from a given term object
*
* @since 2.9.0
*
* @param object $term Term Object
*/
function wxr_term_description( $term ) {
if ( empty( $term->description ) )
return;
echo '<wp:term_description>' . wxr_cdata( $term->description ) . '</wp:term_description>';
}
/**
* Output list of authors with posts
*
* @since 3.1.0
*/
function wxr_authors_list() {
global $wpdb;
$authors = array();
$results = $wpdb->get_results( "SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_status != 'auto-draft'" );
foreach ( (array) $results as $result )
$authors[] = get_userdata( $result->post_author );
$authors = array_filter( $authors );
foreach ( $authors as $author ) {
echo "\t<wp:author>";
echo '<wp:author_id>' . $author->ID . '</wp:author_id>';
echo '<wp:author_login>' . $author->user_login . '</wp:author_login>';
echo '<wp:author_email>' . $author->user_email . '</wp:author_email>';
echo '<wp:author_display_name>' . wxr_cdata( $author->display_name ) . '</wp:author_display_name>';
echo '<wp:author_first_name>' . wxr_cdata( $author->user_firstname ) . '</wp:author_first_name>';
echo '<wp:author_last_name>' . wxr_cdata( $author->user_lastname ) . '</wp:author_last_name>';
echo "</wp:author>\n";
}
}
/**
* Ouput all navigation menu terms
*
* @since 3.1.0
*/
function wxr_nav_menu_terms() {
$nav_menus = wp_get_nav_menus();
if ( empty( $nav_menus ) || ! is_array( $nav_menus ) )
return;
foreach ( $nav_menus as $menu ) {
echo "\t<wp:term><wp:term_id>{$menu->term_id}</wp:term_id><wp:term_taxonomy>nav_menu</wp:term_taxonomy><wp:term_slug>{$menu->slug}</wp:term_slug>";
wxr_term_name( $menu );
echo "</wp:term>\n";
}
}
/**
* Output list of taxonomy terms, in XML tag format, associated with a post
*
* @since 2.3.0
*/
function wxr_post_taxonomy() {
global $post;
$taxonomies = get_object_taxonomies( $post->post_type );
if ( empty( $taxonomies ) )
return;
$terms = wp_get_object_terms( $post->ID, $taxonomies );
foreach ( (array) $terms as $term ) {
echo "\t\t<category domain=\"{$term->taxonomy}\" nicename=\"{$term->slug}\">" . wxr_cdata( $term->name ) . "</category>\n";
}
}
function wxr_filter_postmeta( $return_me, $meta_key ) {
// We ignore the attachment metadata on import so no point in exporting it
if ( in_array( $meta_key, array( '_edit_lock', '_wp_attachment_metadata', '_wp_attached_file' ) ) )
$return_me = true;
return $return_me;
}
add_filter( 'wxr_export_skip_postmeta', 'wxr_filter_postmeta', 10, 2 );
// now we can use the functions we need.
$this->debug_msg( "Initialized all functions we need" );
/**
* This is mostly the original code of export_wp defined in wp-admin/includes/export.php
*/
$defaults = array( 'post_type' => 'all', 'author' => false, 'category' => false,
'start_date' => false, 'end_date' => false, 'status' => false, 'skip_comments' => false, 'file_item_count' => 1000,
'post_ids' => '',
);
$args = wp_parse_args( $args, $defaults );
$this->debug_msg( "Exporting with " . __CLASS__ . " with arguments: " . var_export( $args, true ) );
do_action( 'export_wp' );
if ( 'all' != $args['post_type'] && post_type_exists( $args['post_type'] ) ) {
$ptype = get_post_type_object( $args['post_type'] );
if ( ! $ptype->can_export )
$args['post_type'] = 'post';
$where = $wpdb->prepare( "{$wpdb->posts}.post_type = %s", $args['post_type'] );
} else {
$post_types = get_post_types( array( 'can_export' => true ) );
$esses = array_fill( 0, count( $post_types ), '%s' );
$where = $wpdb->prepare( "{$wpdb->posts}.post_type IN (" . implode( ',', $esses ) . ')', $post_types );
}
if ( $args['status'] && ( 'post' == $args['post_type'] || 'page' == $args['post_type'] ) )
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_status = %s", $args['status'] );
else
$where .= " AND {$wpdb->posts}.post_status != 'auto-draft'";
$join = '';
if ( $args['category'] && 'post' == $args['post_type'] ) {
if ( $term = term_exists( $args['category'], 'category' ) ) {
$join = "INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)";
$where .= $wpdb->prepare( " AND {$wpdb->term_relationships}.term_taxonomy_id = %d", $term['term_taxonomy_id'] );
}
}
// Check that the author is a valid author and use it if so
if ( $args['author'] ) {
if ( is_numeric( $args['author'] ) )
$author = get_user_by( 'id', $args['author'] );
else
$author = get_user_by( 'login', $args['author'] );
if ( $author && !is_wp_error( $author ) )
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_author = %d", $author->ID );
}
if ( $args['start_date'] )
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date >= %s", date( 'Y-m-d 00:00:00', strtotime( $args['start_date'] ) ) );
if ( $args['end_date'] )
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date <= %s", date( 'Y-m-d 23:59:59', strtotime( $args['end_date'] ) ) );
// grab a snapshot of post IDs, just in case it changes during the export
if ( empty( $args['post_ids'] ) )
$all_the_post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} $join WHERE $where ORDER BY post_date ASC, post_parent ASC" );
else
$all_the_post_ids = array_map( 'intval', explode( ',', $args['post_ids'] ) );
// get the requested terms ready, empty unless posts filtered by category or all post_types
$cats = $tags = $terms = array();
if ( isset( $term ) && $term ) {
$cat = get_term( $term['term_id'], 'category' );
$cats = array( $cat->term_id => $cat );
unset( $term, $cat );
} else if ( 'all' == $args['post_type'] ) {
$categories = (array) get_categories( array( 'get' => 'all' ) );
$tags = (array) get_tags( array( 'get' => 'all' ) );
$custom_taxonomies = get_taxonomies( array( '_builtin' => false ) );
$custom_terms = (array) get_terms( $custom_taxonomies, array( 'get' => 'all' ) );
// put categories in order with no child going before its parent
while ( $cat = array_shift( $categories ) ) {
if ( $cat->parent == 0 || isset( $cats[$cat->parent] ) )
$cats[$cat->term_id] = $cat;
else
$categories[] = $cat;
}
// put terms in order with no child going before its parent
while ( $t = array_shift( $custom_terms ) ) {
if ( $t->parent == 0 || isset( $terms[$t->parent] ) )
$terms[$t->term_id] = $t;
else
$custom_terms[] = $t;
}
unset( $categories, $custom_taxonomies, $custom_terms );
}
$this->debug_msg( 'Exporting ' . count( $all_the_post_ids ) . ' items to be broken into ' . ceil( count( $all_the_post_ids ) / $args['file_item_count'] ) . ' files' );
$this->debug_msg( 'Exporting ' . count( $cats ) . ' categories' );
$this->debug_msg( 'Exporting ' . count( $tags ) . ' tags' );
$this->debug_msg( 'Exporting ' . count( $terms ) . ' terms' );
$sitename = sanitize_key( get_bloginfo( 'name' ) );
if ( ! empty( $sitename ) )
$sitename .= '.';
$append = array( date( 'Y-m-d' ) );
foreach( array_keys( $args ) as $arg_key ) {
if ( $defaults[$arg_key] <> $args[$arg_key] )
$append[]= "$arg_key-" . (string) sanitize_key( $args[$arg_key] );
}
$file_name_base = $sitename . 'wordpress.' . implode( ".", $append );
$file_count = 1;
while ( $post_ids = array_splice( $all_the_post_ids, 0, $args['file_item_count'] ) ) {
// Get attachments for posts if we're not doing an all lookup
if ( 'all' != $args['post_type'] ) {
$attachment_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_parent IN (". implode( ",", array_map( 'intval', $post_ids ) ) .")" );
if ( is_array( $attachment_ids ) )
$post_ids = array_merge( $post_ids, $attachment_ids );
}
$full_path = trailingslashit( $this->wxr_path ) . $file_name_base . '.' . str_pad( $file_count, 3, '0', STR_PAD_LEFT ) . '.xml';
// Create the file if it doesn't exist
if ( ! file_exists( $full_path ) ) {
touch( $full_path );
$this->debug_msg( 'Created file ' . $full_path );
}
if ( ! file_exists( $full_path ) ) {
$this->debug_msg( "Failed to create file " . $full_path );
exit;
}
$this->debug_msg( 'Writing to file ' . $full_path );
$this->start_export();
echo '<?xml version="1.0" encoding="' . get_bloginfo( 'charset' ) . "\" ?>\n";
?>
<!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your site. -->
<!-- It contains information about your site's posts, pages, comments, categories, and other content. -->
<!-- You may use this file to transfer that content from one site to another. -->
<!-- This file is not intended to serve as a complete backup of your site. -->
<!-- To import this information into a WordPress site follow these steps: -->
<!-- 1. Log in to that site as an administrator. -->
<!-- 2. Go to Tools: Import in the WordPress admin panel. -->
<!-- 3. Install the "WordPress" importer from the list. -->
<!-- 4. Activate & Run Importer. -->
<!-- 5. Upload this file using the form provided on that page. -->
<!-- 6. You will first be asked to map the authors in this export file to users -->
<!-- on the site. For each author, you may choose to map to an -->
<!-- existing user on the site or to create a new user. -->
<!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. -->
<!-- contained in this file into your site. -->
<?php the_generator( 'export' ); ?>
<rss version="2.0"
xmlns:excerpt="http://wordpress.org/export/<?php echo WXR_VERSION; ?>/excerpt/"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:wp="http://wordpress.org/export/<?php echo WXR_VERSION; ?>/"
>
<channel>
<title><?php bloginfo_rss( 'name' ); ?></title>
<link><?php bloginfo_rss( 'url' ); ?></link>
<description><?php bloginfo_rss( 'description' ); ?></description>
<pubDate><?php echo date( 'D, d M Y H:i:s +0000' ); ?></pubDate>
<language><?php echo get_option( 'rss_language' ); ?></language>
<wp:wxr_version><?php echo WXR_VERSION; ?></wp:wxr_version>
<wp:base_site_url><?php echo wxr_site_url(); ?></wp:base_site_url>
<wp:base_blog_url><?php bloginfo_rss( 'url' ); ?></wp:base_blog_url>
<?php wxr_authors_list(); ?>
<?php foreach ( $cats as $c ) : ?>
<wp:category><wp:term_id><?php echo $c->term_id ?></wp:term_id><wp:category_nicename><?php echo $c->slug; ?></wp:category_nicename><wp:category_parent><?php echo $c->parent ? $cats[$c->parent]->slug : ''; ?></wp:category_parent><?php wxr_cat_name( $c ); ?><?php wxr_category_description( $c ); ?></wp:category>
<?php endforeach; ?>
<?php foreach ( $tags as $t ) : ?>
<wp:tag><wp:term_id><?php echo $t->term_id ?></wp:term_id><wp:tag_slug><?php echo $t->slug; ?></wp:tag_slug><?php wxr_tag_name( $t ); ?><?php wxr_tag_description( $t ); ?></wp:tag>
<?php endforeach; ?>
<?php foreach ( $terms as $t ) : ?>
<wp:term><wp:term_id><?php echo $t->term_id ?></wp:term_id><wp:term_taxonomy><?php echo $t->taxonomy; ?></wp:term_taxonomy><wp:term_slug><?php echo $t->slug; ?></wp:term_slug><wp:term_parent><?php echo $t->parent ? $terms[$t->parent]->slug : ''; ?></wp:term_parent><?php wxr_term_name( $t ); ?><?php wxr_term_description( $t ); ?></wp:term>
<?php endforeach; ?>
<?php if ( 'all' == $args['post_type'] ) wxr_nav_menu_terms(); ?>
<?php do_action( 'rss2_head' ); ?>
<?php
$this->flush_export( $full_path, false );
?>
<?php if ( $post_ids ) {
global $wp_query;
$wp_query->in_the_loop = true; // Fake being in the loop.
// fetch 20 posts at a time rather than loading the entire table into memory
while ( $next_posts = array_splice( $post_ids, 0, 20 ) ) {
$where = 'WHERE ID IN (' . join( ',', $next_posts ) . ')';
$posts = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} $where" );
// Begin Loop
foreach ( $posts as $post ) {
setup_postdata( $post );
$is_sticky = is_sticky( $post->ID ) ? 1 : 0;
?>
<item>
<title><?php echo apply_filters( 'the_title_rss', $post->post_title ); ?></title>
<link><?php the_permalink_rss() ?></link>
<pubDate><?php echo mysql2date( 'D, d M Y H:i:s +0000', get_post_time( 'Y-m-d H:i:s', true ), false ); ?></pubDate>
<dc:creator><?php echo get_the_author_meta( 'login' ); ?></dc:creator>
<guid isPermaLink="false"><?php esc_url( the_guid() ); ?></guid>
<description></description>
<content:encoded><?php echo wxr_cdata( apply_filters( 'the_content_export', $post->post_content ) ); ?></content:encoded>
<excerpt:encoded><?php echo wxr_cdata( apply_filters( 'the_excerpt_export', $post->post_excerpt ) ); ?></excerpt:encoded>
<wp:post_id><?php echo $post->ID; ?></wp:post_id>
<wp:post_date><?php echo $post->post_date; ?></wp:post_date>
<wp:post_date_gmt><?php echo $post->post_date_gmt; ?></wp:post_date_gmt>
<wp:comment_status><?php echo $post->comment_status; ?></wp:comment_status>
<wp:ping_status><?php echo $post->ping_status; ?></wp:ping_status>
<wp:post_name><?php echo $post->post_name; ?></wp:post_name>
<wp:status><?php echo $post->post_status; ?></wp:status>
<wp:post_parent><?php echo $post->post_parent; ?></wp:post_parent>
<wp:menu_order><?php echo $post->menu_order; ?></wp:menu_order>
<wp:post_type><?php echo $post->post_type; ?></wp:post_type>
<wp:post_password><?php echo $post->post_password; ?></wp:post_password>
<wp:is_sticky><?php echo $is_sticky; ?></wp:is_sticky>
<?php if ( $post->post_type == 'attachment' ) : ?>
<wp:attachment_url><?php echo wp_get_attachment_url( $post->ID ); ?></wp:attachment_url>
<?php endif; ?>
<?php wxr_post_taxonomy(); ?>
<?php $postmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) );
foreach ( $postmeta as $meta ) :
if ( apply_filters( 'wxr_export_skip_postmeta', false, $meta->meta_key, $meta ) )
continue;
?>
<wp:postmeta>
<wp:meta_key><?php echo $meta->meta_key; ?></wp:meta_key>
<wp:meta_value><?php echo wxr_cdata( $meta->meta_value ); ?></wp:meta_value>
</wp:postmeta>
<?php endforeach; ?>
<?php if ( false === $args['skip_comments'] ): ?>
<?php $comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID ) );
foreach ( $comments as $c ) : ?>
<wp:comment>
<wp:comment_id><?php echo $c->comment_ID; ?></wp:comment_id>
<wp:comment_author><?php echo wxr_cdata( $c->comment_author ); ?></wp:comment_author>
<wp:comment_author_email><?php echo $c->comment_author_email; ?></wp:comment_author_email>
<wp:comment_author_url><?php echo esc_url_raw( $c->comment_author_url ); ?></wp:comment_author_url>
<wp:comment_author_IP><?php echo $c->comment_author_IP; ?></wp:comment_author_IP>
<wp:comment_date><?php echo $c->comment_date; ?></wp:comment_date>
<wp:comment_date_gmt><?php echo $c->comment_date_gmt; ?></wp:comment_date_gmt>
<wp:comment_content><?php echo wxr_cdata( $c->comment_content ); ?></wp:comment_content>
<wp:comment_approved><?php echo $c->comment_approved; ?></wp:comment_approved>
<wp:comment_type><?php echo $c->comment_type; ?></wp:comment_type>
<wp:comment_parent><?php echo $c->comment_parent; ?></wp:comment_parent>
<wp:comment_user_id><?php echo $c->user_id; ?></wp:comment_user_id>
<?php $c_meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->commentmeta WHERE comment_id = %d", $c->comment_ID ) );
foreach ( $c_meta as $meta ) : ?>
<wp:commentmeta>
<wp:meta_key><?php echo $meta->meta_key; ?></wp:meta_key>
<wp:meta_value><?php echo wxr_cdata( $meta->meta_value ); ?></wp:meta_value>
</wp:commentmeta>
<?php endforeach; ?>
</wp:comment>
<?php endforeach; ?>
<?php endif; ?>
</item>
<?php
$this->flush_export( $full_path );
}
}
} ?>
</channel>
</rss>
<?php
$this->flush_export( $full_path );
$this->end_export();
$this->stop_the_insanity();
$file_count++;
}
$this->debug_msg( 'All done!' );
}
private function start_export() {
ob_start();
}
private function end_export() {
ob_end_clean();
}
private function flush_export( $file_path, $append = true ) {
$result = ob_get_clean();
if ( $append )
$append = FILE_APPEND;
file_put_contents( $file_path, $result, $append );
$this->start_export();
}
private function check_start_date( $date ) {
$time = strtotime( $date );
if ( !empty( $date ) && !$time ) {
return false;
}
$this->export_args['start_date'] = date( 'Y-m-d', $time );
return true;
}
private function check_end_date( $date ) {
$time = strtotime( $date );
if ( !empty( $date ) && !$time ) {
return false;
}
$this->export_args['end_date'] = date( 'Y-m-d', $time );
return true;
}
private function check_post_type( $post_type ) {
$post_types = get_post_types();
if ( !in_array( $post_type, $post_types ) ) {
$this->debug_msg( 'The post type ' . $post_type . ' does not exists. Choose "all" or any of these instead: ' . var_export( $post_types, true ) );
return false;
}
$this->export_args['post_type'] = $post_type;
return true;
}
private function check_author( $author ) {
$authors = get_users_of_blog();
if ( empty( $authors ) || is_wp_error( $authors ) ) {
$this->debug_msg( 'Could not find any authors in this blog' );
return false;
}
$hit = false;
foreach( $authors as $user ) {
if ( $hit )
break;
if ( (int) $author == $user->ID || $author == $user->user_login )
$hit = $user->ID;
}
if ( false === $hit ) {
$this->debug_msg( 'Could not find a matching author for ' . $author . '. The following authors exist: ' . var_export( $authors, true ) );
return false;
}
$this->export_args['author'] = $hit;
return true;
}
private function check_category( $category ) {
$term = category_exists( $category );
if ( empty( $term ) || is_wp_error( $term ) ) {
$this->debug_msg( 'Could not find a category matching ' . $category );
return false;
}
$this->export_args['category'] = $category;
return true;
}
private function check_status( $status ) {
$stati = get_post_statuses();
if ( empty( $stati ) || is_wp_error( $stati ) ) {
$this->debug_msg( 'Could not find any post stati' );
return false;
}
if ( !isset( $stati[$status] ) ) {
$this->debug_msg( 'There is no such post_status: ' . $status . '. Here is a list of available stati: ' . var_export( $stati, true ) );
return false;
}
$this->export_args['status'] = $status;
return true;
}
private function check_skip_comments( $skip ) {
if ( (int) $skip <> 0 && (int) $skip <> 1 ) {
$this->debug_msg( "skip_comments needs to be 0 (no) or 1 (yes)" );
return false;
}
$this->export_args['skip_comments'] = $skip;
return true;
}
private function check_file_item_count( $file_item_count ) {
$file_item_count = intval( $file_item_count );
if ( $file_item_count <= 1 ) {
$this->debug_msg( "file_item_count needs to be a valid integer larger than 1" );
return false;
}
$this->export_args['file_item_count'] = $file_item_count;
return true;
}
private function check_post_ids( $post_ids ) {
if ( empty( $post_ids ) )
return true;
if ( !is_integer( $post_ids ) || false === strpos( $post_ids, ',' ) ) {
$this->debug_msg( "post_ids needs to be one or more post IDs separated by commas" );
return false;
}
$this->export_args['post_ids'] = $post_ids;
return true;
}
}
function cli_set_hostname() {
foreach ( $_SERVER['argv'] as $arg ) {
if ( preg_match( '#--hostname=([^\s]+)#', $arg, $reg ) ) {
$_SERVER['HTTP_HOST'] = $reg[1];
return;
}
}
}
$exporter = new WordPress_CLI_Export;
if ( is_multisite() )
$exporter->set_required_arg( 'blog', 'Blog ID or name of the blog you like to export' );
$exporter->set_required_arg( 'path', 'Full Path to directory where WXR export files should be stored' );
$exporter->set_required_arg( 'user', 'Username/ID the import should run as' );
$exporter->set_argument_validation( '#^blog$#', 'cli_init_blog', 'blog invalid' );
$exporter->set_argument_validation( '#^user$#', 'cli_set_user', 'user invalid' );
$exporter->set_argument_validation( '#^path$#', 'is_dir', 'path does not exist' );
// optional filters
$exporter->set_argument_validation( '#^start_date$#', 'check_start_date', 'invalid start_date use format YYYY-MM-DD' );
$exporter->set_argument_validation( '#^end_date$#', 'check_end_date', 'invalid end_date use format YYYY-MM-DD' );
$exporter->set_argument_validation( '#^post_type$#', 'check_post_type', 'invalid post_type' );
$exporter->set_argument_validation( '#^author$#', 'check_author', 'invalid author' );
$exporter->set_argument_validation( '#^category$#', 'check_category', 'invalid category' );
$exporter->set_argument_validation( '#^post_status$#', 'check_status', 'invalid status' );
$exporter->set_argument_validation( '#^skip_comments#', 'check_skip_comments', 'please set this value to 0 or 1' );
$exporter->set_argument_validation( '#^file_item_count#', 'check_file_item_count', 'please set this to a valid integer' );
$exporter->set_argument_validation( '#^post_ids#', 'check_post_ids', 'please set this to comma-separated string of post IDs' );
$exporter->init();