feat: guard admin package imports

This commit is contained in:
Keith Solomon
2026-04-26 20:32:04 -05:00
parent a9f719c408
commit 76b614e9e3
3 changed files with 303 additions and 1 deletions
+69
View File
@@ -0,0 +1,69 @@
<?php
/**
* Admin file import controller.
*
* @package WPContentSync
*/
namespace WPContentSync\Admin;
use WPContentSync\Logging\LoggerInterface;
use WPContentSync\Transport\FileTransportInterface;
final class FileImportController {
private FileTransportInterface $transport;
private LoggerInterface $logger;
public function __construct( FileTransportInterface $transport, LoggerInterface $logger ) {
$this->transport = $transport;
$this->logger = $logger;
}
public function register(): void {
add_action( 'admin_post_wpcs_import_package', array( $this, 'handleImport' ) );
}
public function handleImport(): void {
if ( ! current_user_can( 'manage_options' ) ) {
throw new \RuntimeException( 'You do not have permission to import content packages.' );
}
if ( ! check_admin_referer( 'wpcs_import_package', 'wpcs_import_package_nonce' ) ) {
throw new \RuntimeException( 'The import request could not be verified.' );
}
if ( ! isset( $_FILES['wpcs_package_file']['tmp_name'], $_FILES['wpcs_package_file']['error'] ) ) {
throw new \RuntimeException( 'Choose a package JSON file before importing.' );
}
if ( UPLOAD_ERR_OK !== (int) $_FILES['wpcs_package_file']['error'] ) {
throw new \RuntimeException( 'The package file could not be uploaded.' );
}
$uploaded_file = sanitize_text_field( (string) $_FILES['wpcs_package_file']['tmp_name'] );
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading a validated local upload temp file.
$contents = file_get_contents( $uploaded_file );
if ( false === $contents ) {
throw new \RuntimeException( 'The package file could not be read.' );
}
$package = $this->transport->import( $contents );
$this->logger->info(
'Validated imported content package.',
array(
'schema_version' => $package->schemaVersion(),
'manifest' => $package->manifest(),
)
);
wp_safe_redirect(
add_query_arg(
array( 'wpcs_imported' => '1' ),
admin_url( 'admin.php?page=wp-content-sync' )
)
);
}
}