Skip to content

Commit e09d28a

Browse files
CopilotswissspidyCopilot
authored
Allow importing WXR files via HTTP/HTTPS/FTP and STDIN (#104)
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Pascal Birchler <pascalb@google.com>
1 parent 6403326 commit e09d28a

3 files changed

Lines changed: 173 additions & 12 deletions

File tree

‎composer.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
}
1313
],
1414
"require": {
15-
"wp-cli/wp-cli": "^2.12"
15+
"wp-cli/wp-cli": "^2.13"
1616
},
1717
"require-dev": {
1818
"wordpress/wordpress-importer": "^0.9",

‎features/import.feature‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,3 +458,65 @@ Feature: Import content.
458458
Then STDOUT should not be empty
459459
And STDERR should be empty
460460

461+
@require-wp-5.2 @require-mysql
462+
Scenario: Import from STDIN
463+
Given a WP install
464+
And I run `wp plugin install wordpress-importer --activate`
465+
And I run `wp site empty --yes`
466+
And I run `wp post generate --post_type=post --count=2`
467+
468+
When I run `wp post list --post_type=post --format=count`
469+
Then STDOUT should be:
470+
"""
471+
2
472+
"""
473+
474+
When I run `wp export`
475+
Then save STDOUT 'Writing to file %s' as {EXPORT_FILE}
476+
477+
When I run `wp site empty --yes`
478+
Then STDOUT should not be empty
479+
480+
When I run `wp post list --post_type=post --format=count`
481+
Then STDOUT should be:
482+
"""
483+
0
484+
"""
485+
486+
When I run `cat {EXPORT_FILE} | wp import - --authors=skip`
487+
Then STDOUT should contain:
488+
"""
489+
Starting the import process...
490+
"""
491+
And STDOUT should contain:
492+
"""
493+
Finished importing from 'STDIN' file.
494+
"""
495+
And STDERR should be empty
496+
497+
When I run `wp post list --post_type=post --format=count`
498+
Then STDOUT should be:
499+
"""
500+
2
501+
"""
502+
503+
@require-wp-5.2 @require-mysql
504+
Scenario: Import from a URL
505+
Given a WP install
506+
And I run `wp plugin install wordpress-importer --activate`
507+
508+
When I run `wp import https://raw.githubusercontent.com/WordPress/theme-test-data/b47acf980696897936265182cb684dca648476c7/theme-preview.xml --authors=skip`
509+
Then STDOUT should contain:
510+
"""
511+
Starting the import process...
512+
"""
513+
And STDOUT should contain:
514+
"""
515+
Downloading 'https://raw.githubusercontent.com/WordPress/theme-test-data/b47acf980696897936265182cb684dca648476c7/theme-preview.xml'...
516+
"""
517+
And STDOUT should contain:
518+
"""
519+
Finished importing from 'https://raw.githubusercontent.com/WordPress/theme-test-data/b47acf980696897936265182cb684dca648476c7/theme-preview.xml' file.
520+
"""
521+
And STDERR should be empty
522+

‎src/Import_Command.php‎

Lines changed: 110 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class Import_Command extends WP_CLI_Command {
1818
*
1919
* <file>...
2020
* : Path to one or more valid WXR files for importing. Directories are also accepted.
21+
* A URL to a WXR file is also accepted. Use '-' to import from STDIN.
2122
*
2223
* --authors=<authors>
2324
* : How the author mapping should be handled. Options are 'create', 'mapping.csv', or 'skip'. The first will create any non-existent users from the WXR file. The second will read author mapping associations from a CSV, or create a CSV for editing if the file path doesn't exist. The CSV requires two columns, and a header row like "old_user_login,new_user_login". The last option will skip any author mapping.
@@ -42,6 +43,20 @@ class Import_Command extends WP_CLI_Command {
4243
* -- Tue, 21 Jun 2016 05:31:12 +0000
4344
* -- Imported post as post_id #1
4445
* Success: Finished importing from 'example.wordpress.2016-06-21.xml' file.
46+
*
47+
* # Import content from a WXR file via HTTP
48+
* $ wp import https://raw.githubusercontent.com/WordPress/theme-test-data/refs/heads/master/theme-preview.xml --authors=skip
49+
* Starting the import process...
50+
* Downloading 'https://raw.githubusercontent.com/WordPress/theme-test-data/refs/heads/master/theme-preview.xml'...
51+
* Success: Finished importing from 'https://raw.githubusercontent.com/WordPress/theme-test-data/refs/heads/master/theme-preview.xml' file.
52+
*
53+
* # Import content from STDIN
54+
* $ wp export --stdout | wp import - --authors=skip
55+
* Starting the import process...
56+
* Success: Finished importing from 'STDIN' file.
57+
*
58+
* @param array<string> $args Positional arguments.
59+
* @param array{authors: 'create'|'mappings.csv'|'skip', skip?: string, rewrite_urls?: bool, importer?: string} $assoc_args Associative arguments.
4560
*/
4661
public function __invoke( $args, $assoc_args ) {
4762
$defaults = array(
@@ -56,6 +71,10 @@ public function __invoke( $args, $assoc_args ) {
5671
$assoc_args['skip'] = explode( ',', $assoc_args['skip'] );
5772
}
5873

74+
/**
75+
* @var array{authors: 'create'|'mappings.csv'|'skip', skip: array<string>, rewrite_urls: bool, importer: class-string<WP_Import>} $assoc_args
76+
*/
77+
5978
$importer = $this->is_importer_available();
6079
if ( is_wp_error( $importer ) ) {
6180
WP_CLI::error( $importer );
@@ -75,8 +94,66 @@ public function __invoke( $args, $assoc_args ) {
7594

7695
WP_CLI::log( 'Starting the import process...' );
7796

78-
$new_args = [];
97+
$new_args = [];
98+
$temp_files = []; // Map of temp_file_path => original source (URL or 'STDIN')
99+
79100
foreach ( $args as $arg ) {
101+
// Handle STDIN input
102+
if ( '-' === $arg ) {
103+
if ( ! \WP_CLI\Utils\has_stdin() ) {
104+
WP_CLI::warning( 'Unable to import from STDIN. No data provided.' );
105+
continue;
106+
}
107+
108+
$stdin_handle = fopen( 'php://stdin', 'rb' );
109+
if ( false === $stdin_handle ) {
110+
WP_CLI::warning( 'Unable to import from STDIN. Could not open STDIN stream.' );
111+
continue;
112+
}
113+
114+
$temp_file = wp_tempnam( 'wp-import-stdin' );
115+
if ( ! $temp_file ) {
116+
fclose( $stdin_handle );
117+
WP_CLI::warning( 'Unable to import from STDIN. Could not create temporary file.' );
118+
continue;
119+
}
120+
121+
$temp_handle = fopen( $temp_file, 'wb' );
122+
if ( false === $temp_handle ) {
123+
fclose( $stdin_handle );
124+
unlink( $temp_file );
125+
WP_CLI::warning( 'Unable to import from STDIN. Could not open temporary file for writing.' );
126+
continue;
127+
}
128+
129+
$bytes_copied = stream_copy_to_stream( $stdin_handle, $temp_handle );
130+
fclose( $stdin_handle );
131+
fclose( $temp_handle );
132+
133+
if ( false === $bytes_copied || 0 === $bytes_copied ) {
134+
unlink( $temp_file );
135+
WP_CLI::warning( 'Unable to import from STDIN. No data provided.' );
136+
continue;
137+
}
138+
$new_args[] = $temp_file;
139+
$temp_files[ $temp_file ] = 'STDIN';
140+
continue;
141+
}
142+
143+
// Handle HTTP/HTTPS/FTP URLs
144+
$scheme = wp_parse_url( $arg, PHP_URL_SCHEME );
145+
if ( $scheme && in_array( strtolower( $scheme ), [ 'http', 'https', 'ftp', 'ftps' ], true ) ) {
146+
WP_CLI::log( "Downloading '{$arg}'..." );
147+
$temp_file = download_url( $arg );
148+
if ( is_wp_error( $temp_file ) ) {
149+
WP_CLI::warning( sprintf( "Unable to import from URL '%s'. %s", $arg, $temp_file->get_error_message() ) );
150+
continue;
151+
}
152+
$new_args[] = $temp_file;
153+
$temp_files[ $temp_file ] = $arg;
154+
continue;
155+
}
156+
80157
if ( is_dir( $arg ) ) {
81158
$dir = WP_CLI\Utils\trailingslashit( $arg );
82159
$files = glob( $dir . '*.wxr' );
@@ -114,22 +191,30 @@ public function __invoke( $args, $assoc_args ) {
114191
$args = $new_args;
115192

116193
foreach ( $args as $file ) {
117-
118-
$ret = $this->import_wxr( $file, $assoc_args );
194+
$display_name = isset( $temp_files[ $file ] ) ? $temp_files[ $file ] : null;
195+
$ret = $this->import_wxr( $file, $assoc_args, $display_name );
119196

120197
if ( is_wp_error( $ret ) ) {
198+
$this->cleanup_temp_files( $temp_files );
121199
WP_CLI::error( $ret );
122200
} else {
123201
WP_CLI::log( '' ); // WXR import ends with HTML, so make sure message is on next line
124-
WP_CLI::success( "Finished importing from '$file' file." );
202+
$source = null !== $display_name ? $display_name : $file;
203+
WP_CLI::success( "Finished importing from '$source' file." );
125204
}
126205
}
206+
207+
$this->cleanup_temp_files( $temp_files );
127208
}
128209

129210
/**
130211
* Imports a WXR file.
212+
*
213+
* @param string $file Path or URL to the WXR file being imported.
214+
* @param array{authors: string, skip: array<string>, rewrite_urls: ?bool, importer: class-string<WP_Import>} $args Arguments controlling the import behavior.
215+
* @param string|null $display_name Optional display name for the source (e.g. URL or 'STDIN').
131216
*/
132-
private function import_wxr( $file, $args ) {
217+
private function import_wxr( $file, $args, $display_name = null ) {
133218

134219
$importer_class = $args['importer'];
135220
/** @var WP_Import $wp_import */
@@ -218,7 +303,7 @@ private function import_wxr( $file, $args ) {
218303
add_filter( 'intermediate_image_sizes_advanced', array( $this, 'filter_set_image_sizes' ) );
219304
}
220305

221-
$GLOBALS['wpcli_import_current_file'] = basename( $file );
306+
$GLOBALS['wpcli_import_current_file'] = null !== $display_name ? basename( $display_name ) : basename( $file );
222307

223308
$reflection = new \ReflectionMethod( $wp_import, 'import' );
224309
$number_of_arguments = $reflection->getNumberOfParameters();
@@ -248,6 +333,20 @@ public function filter_set_image_sizes( $sizes ) {
248333
return null;
249334
}
250335

336+
/**
337+
* Removes temporary files created during import.
338+
*
339+
* @param array<string, string> $temp_files Map of temp_file_path => original source.
340+
*/
341+
private function cleanup_temp_files( array $temp_files ) {
342+
foreach ( $temp_files as $temp_file => $_ ) {
343+
if ( file_exists( $temp_file ) ) {
344+
// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink
345+
unlink( $temp_file );
346+
}
347+
}
348+
}
349+
251350
/**
252351
* Defines useful verbosity filters for the WXR importer.
253352
*/
@@ -405,10 +504,12 @@ private function process_author_mapping( $authors_arg, $author_data ) {
405504
private function read_author_mapping_file( $file ) {
406505
$author_mapping = [];
407506

507+
/**
508+
* @var array{old_user_login?: \WP_User, new_user_login?: \WP_User} $author
509+
*/
510+
// TODO: Fix type upstream.
511+
// @phpstan-ignore varTag.nativeType
408512
foreach ( new \WP_CLI\Iterators\CSV( $file ) as $i => $author ) {
409-
/**
410-
* @var array<string, \WP_User> $author
411-
*/
412513
if ( ! array_key_exists( 'old_user_login', $author ) || ! array_key_exists( 'new_user_login', $author ) ) {
413514
return new WP_Error( 'invalid-author-mapping', "Author mapping file isn't properly formatted." );
414515
}
@@ -440,8 +541,6 @@ private function create_author_mapping_file( $file, $author_data ) {
440541
return new WP_Error( 'author-mapping-error', "Couldn't create author mapping file." );
441542
}
442543

443-
// TODO: Fix $rows type upstream in write_csv()
444-
// @phpstan-ignore argument.type
445544
\WP_CLI\Utils\write_csv( $file_resource, $author_mapping, array( 'old_user_login', 'new_user_login' ) );
446545

447546
return new WP_Error( 'author-mapping-error', sprintf( 'Please update author mapping file before continuing: %s', $file ) );

0 commit comments

Comments
 (0)