-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathExport_Command.php
More file actions
660 lines (588 loc) · 17.6 KB
/
Export_Command.php
File metadata and controls
660 lines (588 loc) · 17.6 KB
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
<?php
use WP_CLI\Utils;
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- Changing breaks Phar compat.
define( 'WP_CLI_EXPORT_COMMAND_NO_SPLIT', '-1' );
/**
* Exports WordPress content to a WXR file.
*
* ## EXAMPLES
*
* # Export posts published by the user between given start and end date
* $ wp export --dir=/tmp/ --user=admin --post_type=post --start_date=2011-01-01 --end_date=2011-12-31
* Starting export process...
* Writing to file /tmp/staging.wordpress.2016-05-24.000.xml
* Success: All done with export.
*
* @package wp-cli
*/
class Export_Command extends WP_CLI_Command {
/**
* Maximum length of the site name component in the export filename.
*/
const MAX_FILENAME_SITENAME_LENGTH = 50;
/**
* Initialize the array of arguments that will be eventually be passed to export_wp.
*
* @var array
*/
public $export_args = [];
private $stdout;
private $max_file_size;
private $include_once;
private $wxr_path;
private $exclude = [];
/**
* Exports WordPress content to a WXR file.
*
* Generates one or more WXR files containing authors, terms, posts,
* comments, and attachments. WXR files do not include site configuration
* (options) or the attachment files themselves.
*
* ## OPTIONS
*
* [--dir=<dirname>]
* : Full path to directory where WXR export files should be stored. Defaults
* to current working directory.
*
* [--stdout]
* : Output the whole XML using standard output (incompatible with --dir=)
*
* [--skip_comments]
* : Don't include comments in the WXR export file.
*
* [--skip_authors]
* : Don't include authors in the WXR export file.
*
* [--skip_terms]
* : Don't include terms (categories, tags, custom taxonomy terms and nav menu terms) in the WXR export file.
*
* [--max_file_size=<MB>]
* : A single export file should have this many megabytes. -1 for unlimited.
* ---
* default: 15
* ---
*
* [--filename_format=<format>]
* : Use a custom format for export filenames. Defaults to '{site}.wordpress.{date}.{n}.xml'.
*
* [--include_once=<before_posts>]
* : Include specified export section only in the first export file. Valid options
* are categories, tags, nav_menu_items, custom_taxonomies_terms. Separate multiple
* sections with a comma. Defaults to none.
*
* [--allow_orphan_terms]
* : Export orphaned terms with `parent=0`, instead of throwing an exception.
*
* ## FILTERS
*
* [--start_date=<date>]
* : Export only posts published after this date, in format YYYY-MM-DD.
*
* [--end_date=<date>]
* : Export only posts published before this date, in format YYYY-MM-DD.
*
* [--post_type=<post-type>]
* : Export only posts with this post_type. Separate multiple post types with a
* comma.
* ---
* default: any
* ---
*
* [--post_type__not_in=<post-type>]
* : Export all post types except those identified. Separate multiple post types
* with a comma. Defaults to none.
*
* [--post__in=<pid>]
* : Export all posts specified as a comma-separated or space-separated list of IDs.
* Post's attachments won't be exported unless --with_attachments is specified.
*
* [--with_attachments]
* : Force including attachments in case --post__in has been specified.
*
* [--start_id=<pid>]
* : Export only posts with IDs greater than or equal to this post ID.
*
* [--max_num_posts=<num>]
* : Export no more than <num> posts (excluding attachments).
*
* [--author=<author>]
* : Export only posts by this author. Can be either user login or user ID.
*
* [--category=<name|id>]
* : Export only posts in this category.
*
* [--post_status=<status>]
* : Export only posts with this status.
*
* ## EXAMPLES
*
* # Export posts published by the user between given start and end date
* $ wp export --dir=/tmp/ --user=admin --post_type=post --start_date=2011-01-01 --end_date=2011-12-31
* Starting export process...
* Writing to file /tmp/staging.wordpress.2016-05-24.000.xml
* Success: All done with export.
*
* # Export posts by IDs
* $ wp export --dir=/tmp/ --post__in=123,124,125
* Starting export process...
* Writing to file /tmp/staging.wordpress.2016-05-24.000.xml
* Success: All done with export.
*
* # Export a random subset of content
* $ wp export --post__in="$(wp post list --post_type=post --orderby=rand --posts_per_page=8 --format=ids)"
* Starting export process...
* Writing to file /var/www/example.com/public_html/staging.wordpress.2016-05-24.000.xml
* Success: All done with export.
*/
public function __invoke( $_, $assoc_args ) {
$defaults = [
'dir' => null,
'stdout' => false,
'start_date' => null,
'end_date' => null,
'post_type' => null,
'post_type__not_in' => null,
'max_num_posts' => null,
'author' => null,
'category' => null,
'post_status' => null,
'post__in' => null,
'with_attachments' => true, // or FALSE if user requested some post__in
'start_id' => null,
'skip_comments' => null,
'skip_authors' => null,
'skip_terms' => null,
'max_file_size' => 15,
'filename_format' => '{site}.wordpress.{date}.{n}.xml',
'include_once' => null,
'allow_orphan_terms' => null,
];
if ( ! empty( $assoc_args['stdout'] ) && ( ! empty( $assoc_args['dir'] ) || ! empty( $assoc_args['filename_format'] ) ) ) {
WP_CLI::error( '--stdout and --dir cannot be used together.' );
}
if ( ! empty( $assoc_args['post__in'] ) && empty( $assoc_args['with_attachments'] ) ) {
$defaults['with_attachments'] = false;
}
$assoc_args = wp_parse_args( $assoc_args, $defaults );
$this->validate_args( $assoc_args );
$this->export_args['with_attachments'] = Utils\get_flag_value(
$assoc_args,
'with_attachments',
$defaults['with_attachments']
);
$this->export_args['skip_authors'] = Utils\get_flag_value(
$assoc_args,
'skip_authors',
$defaults['skip_authors']
);
$this->export_args['skip_terms'] = Utils\get_flag_value(
$assoc_args,
'skip_terms',
$defaults['skip_terms']
);
// Re-calculate exclusions after validation to ensure consistency.
$this->exclude = [];
if ( $this->export_args['skip_authors'] ) {
$this->exclude[] = 'authors';
}
if ( $this->export_args['skip_terms'] ) {
$this->exclude = array_merge( $this->exclude, array( 'categories', 'tags', 'nav_menu_terms', 'custom_taxonomies_terms' ) );
}
if ( ! function_exists( 'wp_export' ) ) {
self::load_export_api();
}
if ( ! $this->stdout ) {
WP_CLI::log( 'Starting export process...' );
}
add_action(
'wp_export_new_file',
static function ( $file_path ) {
WP_CLI::log( sprintf( 'Writing to file %s', $file_path ) );
Utils\wp_clear_object_cache(); // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.wp_clear_object_cacheDeprecatedRemoved @phpstan-ignore-line
}
);
try {
if ( $this->stdout ) {
wp_export(
[
'filters' => $this->export_args,
'writer' => WP_Export_File_Writer::class,
'writer_args' => 'php://output',
]
);
} else {
wp_export(
[
'filters' => $this->export_args,
'writer' => WP_Export_Split_Files_Writer::class,
'writer_args' => [
'max_file_size' => $this->max_file_size,
'destination_directory' => $this->wxr_path,
'filename_template' => self::get_filename_template( $assoc_args['filename_format'] ),
'include_once' => $this->include_once,
'exclude' => $this->exclude,
],
]
);
}
} catch ( Exception $e ) {
WP_CLI::error( $e->getMessage() );
}
if ( ! $this->stdout ) {
WP_CLI::success( 'All done with export.' );
}
}
private static function get_filename_template( $filename_format ) {
$sitename = sanitize_key( get_bloginfo( 'name' ) );
if ( empty( $sitename ) ) {
$sitename = 'site';
}
$sitename = function_exists( 'mb_substr' ) ? mb_substr( $sitename, 0, self::MAX_FILENAME_SITENAME_LENGTH ) : substr( $sitename, 0, self::MAX_FILENAME_SITENAME_LENGTH );
return str_replace( [ '{site}', '{date}', '{n}' ], [ $sitename, date( 'Y-m-d' ), '%03d' ], $filename_format ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
}
public static function load_export_api() {
require dirname( __DIR__ ) . '/functions.php';
}
private function validate_args( $args ) {
$has_errors = false;
foreach ( $args as $key => $value ) {
if ( is_callable( [ $this, 'check_' . $key ] ) ) {
/** @phpstan-ignore argument.type */
$result = call_user_func( [ $this, 'check_' . $key ], $value );
if ( false === $result ) {
$has_errors = true;
}
}
}
if ( $args['stdout'] ) {
$this->wxr_path = null;
$this->stdout = true;
}
if ( $has_errors ) {
WP_CLI::halt( 1 );
}
}
/**
* @param string $path
*
* @phpstan-ignore method.unused
*/
private function check_dir( $path ) {
if ( empty( $path ) ) {
$path = (string) getcwd();
} elseif ( ! is_dir( $path ) ) {
WP_CLI::error( sprintf( "The directory '%s' does not exist.", $path ) );
} elseif ( ! is_writable( $path ) ) {
WP_CLI::error( sprintf( "The directory '%s' is not writable.", $path ) );
}
$this->wxr_path = trailingslashit( $path );
return true;
}
/**
* @param string $date
*
* @phpstan-ignore method.unused
*/
private function check_start_date( $date ) {
if ( null === $date ) {
return true;
}
$time = strtotime( $date );
if ( ! empty( $date ) && false === $time ) {
WP_CLI::warning( sprintf( 'The start_date %s is invalid.', $date ) );
return false;
}
$this->export_args['start_date'] = date( 'Y-m-d', (int) $time ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
return true;
}
/**
* @param string $date
*
* @phpstan-ignore method.unused
*/
private function check_end_date( $date ) {
if ( null === $date ) {
return true;
}
$time = strtotime( $date );
if ( ! empty( $date ) && false === $time ) {
WP_CLI::warning( sprintf( 'The end_date %s is invalid.', $date ) );
return false;
}
$this->export_args['end_date'] = date( 'Y-m-d', (int) $time ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
return true;
}
/**
* @param string $post_type
*
* @phpstan-ignore method.unused
*/
private function check_post_type( $post_type ) {
if ( null === $post_type || 'any' === $post_type ) {
return true;
}
$post_type = array_unique( array_filter( explode( ',', $post_type ) ) );
$post_types = get_post_types();
foreach ( $post_type as $type ) {
if ( ! in_array( $type, $post_types, true ) ) {
WP_CLI::warning(
sprintf(
'The post type %s does not exist. Choose "any" or any of these existing post types instead: %s',
$type,
implode( ', ', $post_types )
)
);
return false;
}
}
$this->export_args['post_type'] = $post_type;
return true;
}
/**
* @param string $post_type
*
* @phpstan-ignore method.unused
*/
private function check_post_type__not_in( $post_type ) {
if ( null === $post_type ) {
return true;
}
$post_type = array_unique( array_filter( explode( ',', $post_type ) ) );
$post_types = get_post_types();
foreach ( $post_type as $type ) {
if ( ! in_array( $type, $post_types, true ) ) {
WP_CLI::warning(
sprintf(
'The post type %s does not exist. Use any of these existing post types instead: %s',
$type,
implode( ', ', $post_types )
)
);
return false;
}
}
$this->export_args['post_type'] = array_diff( $post_types, $post_type );
return true;
}
/**
* @param string $post__in
*
* @phpstan-ignore method.unused
*/
private function check_post__in( $post__in ) {
if ( null === $post__in ) {
return true;
}
$separator = false !== stripos( $post__in, ' ' ) ? ' ' : ',';
$post__in = array_filter( array_unique( array_map( 'intval', explode( $separator, $post__in ) ) ) );
if ( empty( $post__in ) ) {
WP_CLI::warning( 'post__in should be comma-separated or space-separated post IDs.' );
return false;
}
// New exporter uses a different argument.
$this->export_args['post_ids'] = $post__in;
return true;
}
/**
* @param string $start_id
*
* @phpstan-ignore method.unused
*/
private function check_start_id( $start_id ) {
if ( null === $start_id ) {
return true;
}
$start_id = (int) $start_id;
// Post IDs must be greater than 0.
if ( 0 >= $start_id ) {
WP_CLI::warning( "Invalid start ID: {$start_id}" );
return false;
}
$this->export_args['start_id'] = $start_id;
return true;
}
/**
* @param string $author
*
* @phpstan-ignore method.unused
*/
private function check_author( $author ) {
if ( null === $author ) {
return true;
}
// phpcs:ignore WordPress.WP.DeprecatedFunctions.get_users_of_blogFound -- Fallback.
$authors = function_exists( 'get_users' ) ? get_users() : get_users_of_blog(); // @phpstan-ignore-line
if ( empty( $authors ) ) {
WP_CLI::warning( '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 ) {
$authors_nice = [];
foreach ( $authors as $_author ) {
$authors_nice[] = sprintf( '%s (%s)', $_author->user_login, $_author->display_name );
}
WP_CLI::warning( sprintf( 'Could not find a matching author for %s. The following authors exist: %s', $author, implode( ', ', $authors_nice ) ) );
return false;
}
$this->export_args['author'] = $hit;
return true;
}
/**
* @phpstan-ignore method.unused
*/
private function check_max_num_posts( $num ) {
if ( null !== $num && ( ! is_numeric( $num ) || $num <= 0 ) ) {
WP_CLI::warning( 'max_num_posts should be a positive integer.' );
return false;
}
$this->export_args['max_num_posts'] = (int) $num;
return true;
}
/**
* @param string $category
*
* @phpstan-ignore method.unused
*/
private function check_category( $category ) {
if ( null === $category ) {
return true;
}
if ( is_numeric( $category ) ) {
$category = (int) $category;
}
$term = category_exists( $category );
if ( empty( $term ) ) {
WP_CLI::warning( sprintf( 'Could not find a category matching %s.', $category ) );
return false;
}
$this->export_args['category'] = $category;
return true;
}
/**
* @param string $status
*
* @phpstan-ignore method.unused
*/
private function check_post_status( $status ) {
if ( null === $status ) {
return true;
}
// spellchecker:ignore-next-line
$statuses = get_post_stati();
if ( empty( $statuses ) || is_wp_error( $statuses ) ) {
WP_CLI::warning( 'Could not find any post statuses.' );
return false;
}
if ( ! isset( $statuses[ $status ] ) ) {
WP_CLI::warning( sprintf( 'Could not find a post_status matching %s. Here is a list of available statuses: %s', $status, implode( ', ', array_keys( $statuses ) ) ) );
return false;
}
$this->export_args['status'] = $status;
return true;
}
/**
* @param string|null $skip
*
* @phpstan-ignore method.unused
*/
private function check_skip_comments( $skip ) {
if ( null === $skip ) {
return true;
}
if ( 0 !== (int) $skip && 1 !== (int) $skip ) {
WP_CLI::warning( 'skip_comments needs to be 0 (no) or 1 (yes).' );
return false;
}
$this->export_args['skip_comments'] = $skip;
return true;
}
/**
* @param string|null $skip
*
* @phpstan-ignore method.unused
*/
private function check_skip_authors( $skip ) {
if ( null === $skip ) {
return true;
}
if ( 0 !== (int) $skip && 1 !== (int) $skip ) {
WP_CLI::warning( 'skip_authors needs to be 0 (no) or 1 (yes).' );
return false;
}
$this->export_args['skip_authors'] = $skip;
return true;
}
/**
* @param string|null $skip
*
* @phpstan-ignore method.unused
*/
private function check_skip_terms( $skip ) {
if ( null === $skip ) {
return true;
}
if ( 0 !== (int) $skip && 1 !== (int) $skip ) {
WP_CLI::warning( 'skip_terms needs to be 0 (no) or 1 (yes).' );
return false;
}
$this->export_args['skip_terms'] = $skip;
return true;
}
/**
* @param string $size
*
* @phpstan-ignore method.unused
*/
private function check_max_file_size( $size ) {
if ( ! is_numeric( $size ) ) {
WP_CLI::warning( 'max_file_size should be numeric.' );
return false;
}
$this->max_file_size = $size;
return true;
}
/**
* @param string $once
*
* @phpstan-ignore method.unused
*/
private function check_include_once( $once ) {
if ( null === $once ) {
return true;
}
$separator = false !== stripos( $once, ' ' ) ? ' ' : ',';
$once = array_filter( array_unique( array_map( 'strtolower', explode( $separator, $once ) ) ) );
$once = array_intersect( $once, array( 'categories', 'tags', 'nav_menu_terms', 'custom_taxonomies_terms' ) );
if ( empty( $once ) ) {
WP_CLI::warning( 'include_once should be comma-separated values for optional before_posts sections.' );
return false;
}
$this->include_once = $once;
return true;
}
/**
* @param string $allow_orphan_terms
*
* @phpstan-ignore method.unused
*/
private function check_allow_orphan_terms( $allow_orphan_terms ) {
if ( null === $allow_orphan_terms ) {
return true;
}
if ( 0 !== (int) $allow_orphan_terms && 1 !== (int) $allow_orphan_terms ) {
WP_CLI::warning( 'allow_orphan_terms needs to be 0 (no) or 1 (yes).' );
return false;
}
$this->export_args['allow_orphan_terms'] = $allow_orphan_terms;
return true;
}
}