From a2dec73dd990d095e2237c117ee1f984db26b1e8 Mon Sep 17 00:00:00 2001 From: castellon Date: Wed, 11 Nov 2026 09:06:48 +0100 Subject: [PATCH 01/11] Prepare the settings screen for export and import - Move the list of boolean settings into Settings::get_boolean_option_keys() so the form sanitizer and the importer share one list of toggles. - Let the form sanitizer hand back a value untouched while a settings import is writing the option. It requires the settings form nonce, which an import does not have, so the saved option would otherwise be replaced by the previous one. - Make ImageManagement::downgrade_target_to_supported_formats() public and static, so an import can reuse the same server support check. - Hide the main save bar on the Backup tab, which has its own forms. --- includes/Admin/ImageManagement.php | 4 +- includes/Admin/Settings.php | 77 ++++++++++++++++++------------ 2 files changed, 49 insertions(+), 32 deletions(-) diff --git a/includes/Admin/ImageManagement.php b/includes/Admin/ImageManagement.php index d3fe7ebe..1e82c6ad 100644 --- a/includes/Admin/ImageManagement.php +++ b/includes/Admin/ImageManagement.php @@ -101,7 +101,7 @@ public function section_callback() { * @param string $target Requested target: 'none', 'webp', 'avif', or 'both'. * @return string A target the current server can produce, or 'none'. */ - private function downgrade_target_to_supported_formats( $target ) { + public static function downgrade_target_to_supported_formats( $target ) { $webp_supported = wp_image_editor_supports( array( 'mime_type' => 'image/webp' ) ); $avif_supported = wp_image_editor_supports( array( 'mime_type' => 'image/avif' ) ); @@ -335,7 +335,7 @@ public function sanitize_settings( $value, $option ) { $allowed_targets = array( 'none', 'webp', 'avif', 'both' ); $posted_target = $posted['image_format_target'] ?? 'none'; $requested_target = in_array( $posted_target, $allowed_targets, true ) ? $posted_target : 'none'; - $value['image_format_target'] = $this->downgrade_target_to_supported_formats( $requested_target ); + $value['image_format_target'] = self::downgrade_target_to_supported_formats( $requested_target ); $value['image_max_upload_dimension_enabled'] = ! empty( $posted['image_max_upload_dimension_enabled'] ); diff --git a/includes/Admin/Settings.php b/includes/Admin/Settings.php index 86bd5809..bf3b1834 100644 --- a/includes/Admin/Settings.php +++ b/includes/Admin/Settings.php @@ -656,7 +656,7 @@ function activateTab(tabId) { }); if (saveBar) { - saveBar.hidden = found && 'google-signin' === tabId; + saveBar.hidden = found && ('google-signin' === tabId || 'backup' === tabId); } if (! found) { @@ -3201,6 +3201,46 @@ private function render_pro_toggle( $option_key ) { option_enable_testimonials, - $this->option_enable_reading_progress, - $this->option_enable_back_button, - $this->option_enable_scroll_top, - $this->option_enable_events, - $this->option_enable_fluid_typography, - $this->option_enable_maintenance, - $this->option_enable_gutenberg, - $this->option_enable_simple_prices_variable_products, - $this->option_enable_after_add_to_cart, - $this->option_deactivate_short_description, - $this->option_move_content_to_short_description, - $this->option_disable_zoom_images, - $this->option_add_share_buttons, - $this->option_deactivate_product_tabs, - $this->option_horizontal_product_form, - $this->option_enable_variant_display_mode, - $this->option_enable_custom_post_types, - $this->option_enable_fullpage_scroll, - $this->option_enable_language_banner, - $this->option_enable_popups, - $this->option_checkout_inline, - $this->option_disable_cart_coupon, - $this->option_disable_cart_cross_sells, - $this->option_disable_checkout_coupon, - $this->option_disable_checkout_order_notes, - $this->option_disable_checkout_login_prompt, - ); + $boolean_options = self::get_boolean_option_keys(); // Initialize all boolean options to false (unchecked checkboxes are not submitted). foreach ( $boolean_options as $option ) { From cae6ecd6512e461538a793db9b5e5dbe08dff7db Mon Sep 17 00:00:00 2001 From: castellon Date: Wed, 11 Nov 2026 09:06:48 +0100 Subject: [PATCH 02/11] Add settings export and import in a new Backup tab The Backup tab downloads the FrontBlocks settings as a JSON file and imports one on another site, to clone a configuration between sites. - The file declares a format and a format version, and holds only settings that are safe to move: module toggles, simple options and the image format options that do not depend on the site. Credentials, license keys, the maintenance image and the image size configuration are never written. - The import merges: only the keys in the file change. Every value is validated against a schema, and unknown or invalid values are skipped and listed afterwards. An image format the server cannot produce is downgraded, and the two short description options stay exclusive. - Files must be valid JSON, declare the format, stay under 256 KB and have the .json extension. A rejected file changes nothing. - Export and import need the edit_theme_options capability and a nonce. - The frontblocks_import_settings_schema and frontblocks_export_settings filters let add-ons contribute their own settings. --- includes/Admin/SettingsTransfer.php | 821 ++++++++++++++++++++++++++++ includes/Plugin_Main.php | 5 + 2 files changed, 826 insertions(+) create mode 100644 includes/Admin/SettingsTransfer.php diff --git a/includes/Admin/SettingsTransfer.php b/includes/Admin/SettingsTransfer.php new file mode 100644 index 00000000..099bf629 --- /dev/null +++ b/includes/Admin/SettingsTransfer.php @@ -0,0 +1,821 @@ + 'bool' ); + } + + $schema['events_type'] = array( + 'type' => 'enum', + 'values' => array( 'cpt', 'posts' ), + ); + $schema['scroll_top_position'] = array( + 'type' => 'enum', + 'values' => array( 'bottom-right', 'bottom-left' ), + ); + $schema['scroll_top_icon_url'] = array( 'type' => 'url' ); + $schema['maintenance_title'] = array( + 'type' => 'text', + 'max' => 200, + ); + $schema['image_format_target'] = array( + 'type' => 'enum', + 'values' => array( 'none', 'webp', 'avif', 'both' ), + ); + $schema['image_max_upload_dimension_enabled'] = array( 'type' => 'bool' ); + $schema['image_max_upload_dimension'] = array( + 'type' => 'int', + 'min' => 300, + 'max' => 10000, + ); + $schema['image_format_quality_webp'] = array( + 'type' => 'int', + 'min' => 1, + 'max' => 100, + ); + $schema['image_format_quality_avif'] = array( + 'type' => 'int', + 'min' => 1, + 'max' => 100, + ); + + /** + * Filters the schema of the settings that can be exported and imported. + * + * Add-ons such as FrontBlocks PRO add their own keys here. Each rule needs a + * `type` of bool, enum (with `values`), url, text (with an optional `max`) + * or int (with optional `min` and `max`). + * + * @since 1.6.0 + * @param array $schema Setting key => rule. + */ + $schema = apply_filters( 'frontblocks_import_settings_schema', $schema ); + + return is_array( $schema ) ? $schema : array(); + } + + /** + * Validate and normalize one value against a schema rule. + * + * @param mixed $value Raw value. + * @param array $rule Schema rule. + * @return array { + * @type bool $ok Whether the value is valid. + * @type mixed $value The normalized value, when valid. + * @type string $reason Why the value was rejected, when invalid. + * } + */ + public static function sanitize_value( $value, $rule ) { + $type = isset( $rule['type'] ) ? $rule['type'] : ''; + + switch ( $type ) { + case 'bool': + if ( is_bool( $value ) ) { + return self::valid( $value ); + } + if ( in_array( $value, array( 0, 1, '0', '1' ), true ) ) { + return self::valid( (bool) (int) $value ); + } + return self::invalid( __( 'expected true or false', 'frontblocks' ) ); + + case 'enum': + $values = isset( $rule['values'] ) ? (array) $rule['values'] : array(); + if ( is_string( $value ) && in_array( $value, $values, true ) ) { + return self::valid( $value ); + } + /* translators: %s: comma separated list of allowed values */ + return self::invalid( sprintf( __( 'expected one of: %s', 'frontblocks' ), implode( ', ', $values ) ) ); + + case 'url': + if ( ! is_string( $value ) ) { + return self::invalid( __( 'expected a URL', 'frontblocks' ) ); + } + if ( '' === trim( $value ) ) { + return self::valid( '' ); + } + $url = esc_url_raw( trim( $value ), array( 'http', 'https' ) ); + if ( '' === $url ) { + return self::invalid( __( 'expected an http or https URL', 'frontblocks' ) ); + } + return self::valid( $url ); + + case 'text': + if ( ! is_string( $value ) ) { + return self::invalid( __( 'expected text', 'frontblocks' ) ); + } + $max = isset( $rule['max'] ) ? (int) $rule['max'] : 255; + if ( strlen( $value ) > $max ) { + /* translators: %d: maximum number of characters */ + return self::invalid( sprintf( __( 'longer than %d characters', 'frontblocks' ), $max ) ); + } + return self::valid( sanitize_text_field( $value ) ); + + case 'int': + if ( is_string( $value ) && preg_match( '/^-?\d+$/', $value ) ) { + $value = (int) $value; + } + $min = isset( $rule['min'] ) ? (int) $rule['min'] : PHP_INT_MIN; + $max = isset( $rule['max'] ) ? (int) $rule['max'] : PHP_INT_MAX; + if ( ! is_int( $value ) || $value < $min || $value > $max ) { + /* translators: 1: minimum value, 2: maximum value */ + return self::invalid( sprintf( __( 'expected a whole number between %1$d and %2$d', 'frontblocks' ), $min, $max ) ); + } + return self::valid( $value ); + } + + return self::invalid( __( 'unsupported setting type', 'frontblocks' ) ); + } + + /** + * Result of a value that passed validation. + * + * @param mixed $value Normalized value. + * @return array + */ + private static function valid( $value ) { + return array( + 'ok' => true, + 'value' => $value, + ); + } + + /** + * Result of a value that failed validation. + * + * @param string $reason Why it was rejected. + * @return array + */ + private static function invalid( $reason ) { + return array( + 'ok' => false, + 'reason' => $reason, + ); + } + + /** + * Build the document that an export downloads. + * + * @return array + */ + public static function build_export_payload() { + $options = get_option( self::OPTION, array() ); + $options = is_array( $options ) ? $options : array(); + $schema = self::get_schema(); + $boolean = Settings::get_boolean_option_keys(); + + $settings = array(); + foreach ( $schema as $key => $rule ) { + if ( in_array( $key, $boolean, true ) ) { + // An unchecked toggle is never saved, so export its effective state. + $settings[ $key ] = ! empty( $options[ $key ] ); + continue; + } + + if ( ! array_key_exists( $key, $options ) ) { + continue; + } + + $checked = self::sanitize_value( $options[ $key ], $rule ); + if ( $checked['ok'] ) { + $settings[ $key ] = $checked['value']; + } + } + + /** + * Filters the settings written to an export file. + * + * Add-ons can add the keys they declared on `frontblocks_import_settings_schema`. + * Never add credentials or values that only make sense on this site. + * + * @since 1.6.0 + * @param array $settings Setting key => value. + * @param array $options The stored `frontblocks_settings` option. + */ + $settings = apply_filters( 'frontblocks_export_settings', $settings, $options ); + + return array( + 'format' => self::FORMAT, + 'format_version' => self::FORMAT_VERSION, + 'plugin_version' => defined( 'FRBL_VERSION' ) ? FRBL_VERSION : '', + 'exported_at' => gmdate( 'Y-m-d\TH:i:s\Z' ), + 'source_site' => (string) wp_parse_url( home_url(), PHP_URL_HOST ), + 'settings' => is_array( $settings ) ? $settings : array(), + ); + } + + /** + * Name of the downloaded file. + * + * @return string + */ + public static function get_export_filename() { + $host = (string) wp_parse_url( home_url(), PHP_URL_HOST ); + + return sanitize_file_name( sprintf( 'frontblocks-settings-%s-%s.json', '' !== $host ? $host : 'site', gmdate( 'Y-m-d' ) ) ); + } + + /** + * Decode and check the contents of an import file. + * + * @param string $raw File contents. + * @return array|\WP_Error The decoded document, or an error describing what is wrong with it. + */ + public static function parse_file_contents( $raw ) { + if ( ! is_string( $raw ) || '' === trim( $raw ) ) { + return new \WP_Error( 'frbl_transfer_empty', __( 'The file is empty.', 'frontblocks' ) ); + } + + if ( strlen( $raw ) > self::MAX_FILE_SIZE ) { + return new \WP_Error( 'frbl_transfer_too_large', __( 'The file is too large to be a FrontBlocks settings export.', 'frontblocks' ) ); + } + + // Editors on Windows can add a byte order mark that JSON does not allow. + if ( 0 === strpos( $raw, "\xEF\xBB\xBF" ) ) { + $raw = substr( $raw, 3 ); + } + + $data = json_decode( $raw, true, 16 ); + if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $data ) ) { + return new \WP_Error( 'frbl_transfer_invalid_json', __( 'The file is not valid JSON.', 'frontblocks' ) ); + } + + if ( ! isset( $data['format'] ) || self::FORMAT !== $data['format'] ) { + return new \WP_Error( 'frbl_transfer_invalid_format', __( 'The file is not a FrontBlocks settings export.', 'frontblocks' ) ); + } + + $version = isset( $data['format_version'] ) ? $data['format_version'] : null; + if ( ! is_int( $version ) || $version < 1 ) { + return new \WP_Error( 'frbl_transfer_invalid_version', __( 'The file does not declare a valid format version.', 'frontblocks' ) ); + } + + if ( $version > self::FORMAT_VERSION ) { + return new \WP_Error( 'frbl_transfer_newer_version', __( 'The file was exported by a newer version of FrontBlocks. Update FrontBlocks on this site and try again.', 'frontblocks' ) ); + } + + if ( ! isset( $data['settings'] ) || ! is_array( $data['settings'] ) || array() === $data['settings'] ) { + return new \WP_Error( 'frbl_transfer_no_settings', __( 'The file does not contain any settings.', 'frontblocks' ) ); + } + + return $data; + } + + /** + * Check every incoming setting against the schema. + * + * @param array $incoming Setting key => raw value from the file. + * @return array { + * @type array $valid Setting key => normalized value, ready to store. + * @type array $skipped Setting key => reason it was not imported. + * @type array $adjusted Setting key => note about a value that was changed to fit this site. + * } + */ + public static function validate_settings( $incoming ) { + $schema = self::get_schema(); + $valid = array(); + $skipped = array(); + $adjusted = array(); + + foreach ( $incoming as $key => $value ) { + $key = is_string( $key ) ? $key : (string) $key; + + if ( ! isset( $schema[ $key ] ) ) { + $skipped[ $key ] = __( 'unknown setting', 'frontblocks' ); + continue; + } + + $checked = self::sanitize_value( $value, $schema[ $key ] ); + if ( ! $checked['ok'] ) { + $skipped[ $key ] = $checked['reason']; + continue; + } + + $valid[ $key ] = $checked['value']; + } + + // An image format the server cannot produce would break image delivery. + if ( isset( $valid['image_format_target'] ) && class_exists( __NAMESPACE__ . '\\ImageManagement' ) ) { + $supported = ImageManagement::downgrade_target_to_supported_formats( $valid['image_format_target'] ); + if ( $supported !== $valid['image_format_target'] ) { + /* translators: 1: requested format, 2: format applied instead */ + $adjusted['image_format_target'] = sprintf( __( 'this server cannot produce "%1$s", so "%2$s" was applied', 'frontblocks' ), $valid['image_format_target'], $supported ); + $valid['image_format_target'] = $supported; + } + } + + return array( + 'valid' => $valid, + 'skipped' => $skipped, + 'adjusted' => $adjusted, + ); + } + + /** + * Merge validated settings into the stored option. + * + * @param array $valid Setting key => validated value. + * @param array $adjusted Notes about values changed to fit this site. + * @return array { + * @type string[] $applied Keys that were written. + * @type array $adjusted Setting key => note. + * } + */ + public static function apply_settings( $valid, $adjusted = array() ) { + $current = get_option( self::OPTION, array() ); + $current = is_array( $current ) ? $current : array(); + $merged = array_merge( $current, $valid ); + + // The two short description options exclude each other, as on the settings screen. + $deactivate = 'deactivate_short_description'; + $move = 'move_content_to_short_description'; + if ( ! empty( $merged[ $deactivate ] ) && ! empty( $merged[ $move ] ) ) { + $turn_off = isset( $valid[ $deactivate ] ) && isset( $valid[ $move ] ) ? $move : ( isset( $valid[ $move ] ) ? $deactivate : $move ); + $keep = $turn_off === $move ? $deactivate : $move; + + $merged[ $turn_off ] = false; + /* translators: 1: setting turned off, 2: setting kept on */ + $adjusted[ $turn_off ] = sprintf( __( 'turned off, it cannot be on together with "%s"', 'frontblocks' ), $keep ); + } + + self::$importing = true; + try { + update_option( self::OPTION, $merged ); + } finally { + self::$importing = false; + } + + return array( + 'applied' => array_keys( $valid ), + 'adjusted' => $adjusted, + ); + } + + /** + * Import the contents of a settings file. + * + * @param string $raw File contents. + * @return array|\WP_Error Summary of what was applied and skipped, or the reason the file was rejected. + */ + public static function import_from_string( $raw ) { + $data = self::parse_file_contents( $raw ); + if ( is_wp_error( $data ) ) { + return $data; + } + + $checked = self::validate_settings( $data['settings'] ); + $applied = self::apply_settings( $checked['valid'], $checked['adjusted'] ); + + return array( + 'applied' => $applied['applied'], + 'skipped' => $checked['skipped'], + 'adjusted' => $applied['adjusted'], + 'source_site' => isset( $data['source_site'] ) && is_string( $data['source_site'] ) ? sanitize_text_field( $data['source_site'] ) : '', + 'source_version' => isset( $data['plugin_version'] ) && is_string( $data['plugin_version'] ) ? sanitize_text_field( $data['plugin_version'] ) : '', + ); + } + + /** + * URL of the Backup tab. + * + * @param array $args Query arguments to add. + * @return string + */ + private static function settings_url( $args = array() ) { + $url = add_query_arg( $args, admin_url( 'themes.php?page=' . self::PAGE_SLUG ) ); + + return $url . '#' . self::TAB_ID; + } + + /** + * Add the Backup tab, before the License tab. + * + * @param array $tabs Settings tabs. + * @return array + */ + public function add_tab( $tabs ) { + if ( ! is_array( $tabs ) ) { + $tabs = array(); + } + + $tab = array( + 'id' => self::TAB_ID, + 'label' => __( 'Backup', 'frontblocks' ), + ); + $position = count( $tabs ); + + foreach ( $tabs as $index => $existing ) { + if ( isset( $existing['id'] ) && 'license' === $existing['id'] ) { + $position = $index; + break; + } + } + + array_splice( $tabs, $position, 0, array( $tab ) ); + + return $tabs; + } + + /** + * Download the settings as a JSON file. + * + * @return void + */ + public function handle_export() { + if ( ! current_user_can( self::CAPABILITY ) ) { + wp_die( esc_html__( 'You are not allowed to export these settings.', 'frontblocks' ), '', array( 'response' => 403 ) ); + } + + check_admin_referer( self::EXPORT_ACTION ); + + $json = wp_json_encode( self::build_export_payload(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); + + nocache_headers(); + header( 'Content-Type: application/json; charset=utf-8' ); + header( 'Content-Disposition: attachment; filename="' . self::get_export_filename() . '"' ); + header( 'X-Content-Type-Options: nosniff' ); + + echo $json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON document sent as a download, not HTML. + exit; + } + + /** + * Read the uploaded file, import it and go back to the Backup tab with the result. + * + * @return void + */ + public function handle_import() { + if ( ! current_user_can( self::CAPABILITY ) ) { + wp_die( esc_html__( 'You are not allowed to import settings.', 'frontblocks' ), '', array( 'response' => 403 ) ); + } + + check_admin_referer( self::IMPORT_ACTION ); + + $result = $this->import_uploaded_file(); + + self::store_result( + is_wp_error( $result ) ? array( 'error' => $result->get_error_message() ) : $result + ); + + wp_safe_redirect( self::settings_url( array( 'frbl-transfer' => '1' ) ) ); + exit; + } + + /** + * Import the file that came with the request. + * + * @return array|\WP_Error + */ + private function import_uploaded_file() { + // The nonce is verified in handle_import(); every field is cast or sanitized as it is read. + // phpcs:disable WordPress.Security.NonceVerification.Missing + $field = self::FILE_FIELD; + $error = isset( $_FILES[ $field ]['error'] ) ? (int) $_FILES[ $field ]['error'] : UPLOAD_ERR_NO_FILE; + $size = isset( $_FILES[ $field ]['size'] ) ? (int) $_FILES[ $field ]['size'] : 0; + $name = isset( $_FILES[ $field ]['name'] ) ? sanitize_file_name( wp_unslash( $_FILES[ $field ]['name'] ) ) : ''; + $tmp_name = isset( $_FILES[ $field ]['tmp_name'] ) ? (string) $_FILES[ $field ]['tmp_name'] : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- checked with is_uploaded_file() below. + // phpcs:enable WordPress.Security.NonceVerification.Missing + + if ( UPLOAD_ERR_NO_FILE === $error ) { + return new \WP_Error( 'frbl_transfer_no_file', __( 'Choose a settings file to import.', 'frontblocks' ) ); + } + + if ( UPLOAD_ERR_OK !== $error ) { + return new \WP_Error( 'frbl_transfer_upload_failed', __( 'The file could not be uploaded. Try again.', 'frontblocks' ) ); + } + + if ( $size > self::MAX_FILE_SIZE ) { + return new \WP_Error( 'frbl_transfer_too_large', __( 'The file is too large to be a FrontBlocks settings export.', 'frontblocks' ) ); + } + + if ( 'json' !== strtolower( pathinfo( $name, PATHINFO_EXTENSION ) ) ) { + return new \WP_Error( 'frbl_transfer_wrong_extension', __( 'Choose a .json file.', 'frontblocks' ) ); + } + + if ( '' === $tmp_name || ! is_uploaded_file( $tmp_name ) ) { + return new \WP_Error( 'frbl_transfer_upload_failed', __( 'The file could not be uploaded. Try again.', 'frontblocks' ) ); + } + + $raw = file_get_contents( $tmp_name ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- reads the uploaded temporary file, not a remote URL. + if ( false === $raw ) { + return new \WP_Error( 'frbl_transfer_upload_failed', __( 'The file could not be read. Try again.', 'frontblocks' ) ); + } + + return self::import_from_string( $raw ); + } + + /** + * Keep the result of an import for the next page load of the current user. + * + * @param array $result Import summary or error. + * @return void + */ + private static function store_result( $result ) { + set_transient( self::result_key(), $result, 5 * MINUTE_IN_SECONDS ); + } + + /** + * Take the stored import result, so it is shown once. + * + * @return array|null + */ + private static function consume_result() { + $result = get_transient( self::result_key() ); + delete_transient( self::result_key() ); + + return is_array( $result ) ? $result : null; + } + + /** + * Transient that holds the import result of the current user. + * + * @return string + */ + private static function result_key() { + return 'frbl_transfer_result_' . get_current_user_id(); + } + + /** + * Render the Backup tab panel. + * + * @return void + */ + public function render_panel() { + if ( ! current_user_can( self::CAPABILITY ) ) { + return; + } + + $export_url = wp_nonce_url( admin_url( 'admin-post.php?action=' . self::EXPORT_ACTION ), self::EXPORT_ACTION ); + ?> + + + + +
+ +
+ render_notes( $adjusted, __( 'Adjusted to fit this site', 'frontblocks' ) ); + $this->render_notes( $skipped, __( 'Skipped', 'frontblocks' ) ); + } + + /** + * List settings that were adjusted or skipped, with the reason. + * + * @param array $notes Setting key => reason. + * @param string $title Heading of the list. + * @return void + */ + private function render_notes( $notes, $title ) { + if ( empty( $notes ) ) { + return; + } + ?> +
+

+ $reason ) : ?> +

:

+ +
+ Date: Wed, 11 Nov 2026 09:06:48 +0100 Subject: [PATCH 03/11] Add tests for settings export and import Cover the schema and value validation, the exported document, file validation, merging, the short description exclusion, the image format downgrade, the sanitizer bypass during an import, the Backup tab and its export and import requests (capability, nonce, bad uploads). --- tests/Unit/SettingsTransferTest.php | 861 ++++++++++++++++++++++++++++ 1 file changed, 861 insertions(+) create mode 100644 tests/Unit/SettingsTransferTest.php diff --git a/tests/Unit/SettingsTransferTest.php b/tests/Unit/SettingsTransferTest.php new file mode 100644 index 00000000..23c5d2de --- /dev/null +++ b/tests/Unit/SettingsTransferTest.php @@ -0,0 +1,861 @@ + value. + * @param array $extra Keys that replace those of the document. + * @return string + */ + private function document( array $settings, array $extra = array() ) { + return wp_json_encode( + array_merge( + array( + 'format' => 'frontblocks-settings', + 'format_version' => 1, + 'plugin_version' => '1.5.5', + 'source_site' => 'client-a.example', + 'settings' => $settings, + ), + $extra + ) + ); + } + + /** + * Route the nonce-bound sanitizers through update_option(), as on a real admin request. + * + * @return void + */ + private function register_settings_filters() { + $settings = new Settings(); + register_setting( + 'frontblocks_settings', + 'frontblocks_settings', + array( + 'type' => 'array', + 'sanitize_callback' => array( $settings, 'sanitize_settings' ), + 'default' => array(), + ) + ); + new ImageManagement(); + } + + /* + * --------------------------------------------------------------- + * Schema and value validation + * --------------------------------------------------------------- + */ + + public function test_schema_covers_every_boolean_setting_of_the_settings_screen() { + $schema = SettingsTransfer::get_schema(); + + foreach ( Settings::get_boolean_option_keys() as $key ) { + $this->assertArrayHasKey( $key, $schema, $key ); + $this->assertSame( 'bool', $schema[ $key ]['type'], $key ); + } + } + + public function test_boolean_keys_are_unique() { + $keys = Settings::get_boolean_option_keys(); + + $this->assertSame( count( $keys ), count( array_unique( $keys ) ) ); + } + + public function test_schema_never_includes_credentials_or_site_specific_values() { + $keys = array_keys( SettingsTransfer::get_schema() ); + + foreach ( array( 'client_id', 'client_secret', 'maintenance_image', 'image_sizes_disabled', 'image_sizes_overrides', 'image_sizes_custom' ) as $forbidden ) { + $this->assertNotContains( $forbidden, $keys, $forbidden ); + } + } + + public function test_schema_can_be_extended_by_add_ons() { + add_filter( + 'frontblocks_import_settings_schema', + function ( $schema ) { + $schema['pro_mode'] = array( 'type' => 'bool' ); + return $schema; + } + ); + + $this->assertArrayHasKey( 'pro_mode', SettingsTransfer::get_schema() ); + } + + public function test_bool_values() { + $rule = array( 'type' => 'bool' ); + + $this->assertTrue( SettingsTransfer::sanitize_value( true, $rule )['value'] ); + $this->assertFalse( SettingsTransfer::sanitize_value( false, $rule )['value'] ); + $this->assertTrue( SettingsTransfer::sanitize_value( 1, $rule )['value'] ); + $this->assertFalse( SettingsTransfer::sanitize_value( '0', $rule )['value'] ); + + foreach ( array( 'yes', 2, '', null, array( true ), 1.5 ) as $bad ) { + $this->assertFalse( SettingsTransfer::sanitize_value( $bad, $rule )['ok'], wp_json_encode( $bad ) ); + } + } + + public function test_enum_values() { + $rule = array( + 'type' => 'enum', + 'values' => array( 'cpt', 'posts' ), + ); + + $this->assertSame( 'posts', SettingsTransfer::sanitize_value( 'posts', $rule )['value'] ); + + foreach ( array( 'page', '', 'CPT', 0, array( 'cpt' ) ) as $bad ) { + $this->assertFalse( SettingsTransfer::sanitize_value( $bad, $rule )['ok'], wp_json_encode( $bad ) ); + } + } + + public function test_url_values_accept_http_and_https_only() { + $rule = array( 'type' => 'url' ); + + $this->assertSame( 'https://example.com/icon.svg', SettingsTransfer::sanitize_value( 'https://example.com/icon.svg', $rule )['value'] ); + $this->assertSame( '', SettingsTransfer::sanitize_value( '', $rule )['value'], 'An empty URL clears the setting.' ); + + foreach ( array( 'javascript:alert(1)', 'ftp://example.com/a.svg', 'data:text/html;base64,AAAA', 42, array( 'https://example.com' ) ) as $bad ) { + $this->assertFalse( SettingsTransfer::sanitize_value( $bad, $rule )['ok'], wp_json_encode( $bad ) ); + } + } + + public function test_text_values_are_sanitized_and_length_limited() { + $rule = array( + 'type' => 'text', + 'max' => 20, + ); + + $this->assertSame( 'Back soon', SettingsTransfer::sanitize_value( 'Back soon', $rule )['value'] ); + $this->assertTrue( SettingsTransfer::sanitize_value( str_repeat( 'a', 20 ), $rule )['ok'] ); + $this->assertFalse( SettingsTransfer::sanitize_value( str_repeat( 'a', 21 ), $rule )['ok'] ); + $this->assertFalse( SettingsTransfer::sanitize_value( 5, $rule )['ok'] ); + } + + public function test_int_values_are_bounded() { + $rule = array( + 'type' => 'int', + 'min' => 300, + 'max' => 10000, + ); + + $this->assertSame( 2048, SettingsTransfer::sanitize_value( 2048, $rule )['value'] ); + $this->assertSame( 2048, SettingsTransfer::sanitize_value( '2048', $rule )['value'] ); + + foreach ( array( 299, 10001, 20.5, '20.5', 'abc', true, null, array( 2048 ) ) as $bad ) { + $this->assertFalse( SettingsTransfer::sanitize_value( $bad, $rule )['ok'], wp_json_encode( $bad ) ); + } + } + + public function test_unsupported_rule_type_is_rejected() { + $this->assertFalse( SettingsTransfer::sanitize_value( 'x', array( 'type' => 'object' ) )['ok'] ); + $this->assertFalse( SettingsTransfer::sanitize_value( 'x', array() )['ok'] ); + } + + /* + * --------------------------------------------------------------- + * Export + * --------------------------------------------------------------- + */ + + public function test_export_declares_its_format_and_origin() { + $payload = SettingsTransfer::build_export_payload(); + + $this->assertSame( 'frontblocks-settings', $payload['format'] ); + $this->assertSame( 1, $payload['format_version'] ); + $this->assertSame( FRBL_VERSION, $payload['plugin_version'] ); + $this->assertSame( wp_parse_url( home_url(), PHP_URL_HOST ), $payload['source_site'] ); + $this->assertMatchesRegularExpression( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/', $payload['exported_at'] ); + } + + public function test_export_lists_every_toggle_even_when_never_saved() { + update_option( 'frontblocks_settings', array( 'enable_back_button' => true ) ); + + $settings = SettingsTransfer::build_export_payload()['settings']; + + $this->assertTrue( $settings['enable_back_button'] ); + foreach ( Settings::get_boolean_option_keys() as $key ) { + $this->assertArrayHasKey( $key, $settings, $key ); + } + $this->assertFalse( $settings['enable_popups'], 'An unchecked toggle is exported as off.' ); + } + + public function test_export_includes_simple_options_that_are_set() { + update_option( + 'frontblocks_settings', + array( + 'scroll_top_position' => 'bottom-left', + 'maintenance_title' => 'Back soon', + 'image_format_target' => 'webp', + 'image_format_quality_webp' => 70, + 'image_max_upload_dimension' => 2560, + ) + ); + + $settings = SettingsTransfer::build_export_payload()['settings']; + + $this->assertSame( 'bottom-left', $settings['scroll_top_position'] ); + $this->assertSame( 'Back soon', $settings['maintenance_title'] ); + $this->assertSame( 'webp', $settings['image_format_target'] ); + $this->assertSame( 70, $settings['image_format_quality_webp'] ); + $this->assertSame( 2560, $settings['image_max_upload_dimension'] ); + $this->assertArrayNotHasKey( 'events_type', $settings, 'A setting that was never saved is left out.' ); + } + + public function test_export_never_contains_site_specific_or_unknown_values() { + update_option( + 'frontblocks_settings', + array( + 'enable_back_button' => true, + 'maintenance_image' => 123, + 'image_sizes_disabled' => array( 'large' ), + 'image_sizes_overrides' => array( 'large' => array( 'width' => 10 ) ), + 'image_sizes_custom' => array( array( 'name' => 'x' ) ), + 'client_secret' => 'top-secret', + 'something_else' => 'value', + ) + ); + + $json = wp_json_encode( SettingsTransfer::build_export_payload() ); + + foreach ( array( 'maintenance_image', 'image_sizes', 'client_secret', 'top-secret', 'something_else' ) as $leak ) { + $this->assertStringNotContainsString( $leak, $json, $leak ); + } + } + + public function test_export_drops_stored_values_that_no_longer_validate() { + update_option( 'frontblocks_settings', array( 'scroll_top_position' => 'middle' ) ); + + $this->assertArrayNotHasKey( 'scroll_top_position', SettingsTransfer::build_export_payload()['settings'] ); + } + + public function test_export_can_be_extended_by_add_ons() { + update_option( 'frontblocks_settings', array( 'pro_mode' => true ) ); + add_filter( + 'frontblocks_export_settings', + function ( $settings, $options ) { + $settings['pro_mode'] = $options['pro_mode']; + return $settings; + }, + 10, + 2 + ); + + $this->assertTrue( SettingsTransfer::build_export_payload()['settings']['pro_mode'] ); + } + + public function test_export_filename_is_safe() { + $name = SettingsTransfer::get_export_filename(); + + $this->assertMatchesRegularExpression( '/^frontblocks-settings-[a-z0-9.\-]+-\d{4}-\d{2}-\d{2}\.json$/', $name ); + } + + /* + * --------------------------------------------------------------- + * File validation + * --------------------------------------------------------------- + */ + + public function test_rejects_an_empty_file() { + $this->assertWPError( SettingsTransfer::parse_file_contents( '' ) ); + $this->assertWPError( SettingsTransfer::parse_file_contents( " \n " ) ); + } + + public function test_rejects_a_file_over_the_size_limit() { + $error = SettingsTransfer::parse_file_contents( str_repeat( 'a', SettingsTransfer::MAX_FILE_SIZE + 1 ) ); + + $this->assertWPError( $error ); + $this->assertSame( 'frbl_transfer_too_large', $error->get_error_code() ); + } + + public function test_rejects_invalid_json() { + foreach ( array( '{not json', '[1,2', 'null', '"text"', '42' ) as $raw ) { + $error = SettingsTransfer::parse_file_contents( $raw ); + $this->assertWPError( $error, $raw ); + $this->assertSame( 'frbl_transfer_invalid_json', $error->get_error_code(), $raw ); + } + } + + public function test_rejects_a_document_that_is_not_a_frontblocks_export() { + $error = SettingsTransfer::parse_file_contents( wp_json_encode( array( 'settings' => array( 'a' => 1 ) ) ) ); + $this->assertSame( 'frbl_transfer_invalid_format', $error->get_error_code() ); + + $error = SettingsTransfer::parse_file_contents( $this->document( array( 'a' => 1 ), array( 'format' => 'another-plugin' ) ) ); + $this->assertSame( 'frbl_transfer_invalid_format', $error->get_error_code() ); + } + + public function test_rejects_a_missing_or_invalid_format_version() { + foreach ( array( null, 0, -1, '1', 1.5, 'one' ) as $version ) { + $error = SettingsTransfer::parse_file_contents( $this->document( array( 'a' => 1 ), array( 'format_version' => $version ) ) ); + $this->assertWPError( $error, wp_json_encode( $version ) ); + $this->assertSame( 'frbl_transfer_invalid_version', $error->get_error_code(), wp_json_encode( $version ) ); + } + } + + public function test_rejects_a_file_from_a_newer_format() { + $error = SettingsTransfer::parse_file_contents( $this->document( array( 'a' => 1 ), array( 'format_version' => 2 ) ) ); + + $this->assertSame( 'frbl_transfer_newer_version', $error->get_error_code() ); + } + + public function test_rejects_a_file_without_settings() { + foreach ( array( array(), 'text', null ) as $settings ) { + $error = SettingsTransfer::parse_file_contents( $this->document( array(), array( 'settings' => $settings ) ) ); + $this->assertSame( 'frbl_transfer_no_settings', $error->get_error_code(), wp_json_encode( $settings ) ); + } + } + + public function test_accepts_a_valid_file_and_a_byte_order_mark() { + $raw = $this->document( array( 'enable_back_button' => true ) ); + + $this->assertIsArray( SettingsTransfer::parse_file_contents( $raw ) ); + $this->assertIsArray( SettingsTransfer::parse_file_contents( "\xEF\xBB\xBF" . $raw ) ); + } + + public function test_rejects_deeply_nested_json() { + $raw = '{"format":"frontblocks-settings","format_version":1,"settings":' . str_repeat( '[', 40 ) . str_repeat( ']', 40 ) . '}'; + + $this->assertWPError( SettingsTransfer::parse_file_contents( $raw ) ); + } + + /* + * --------------------------------------------------------------- + * Validating the incoming settings + * --------------------------------------------------------------- + */ + + public function test_validate_keeps_valid_values_and_reports_the_rest() { + $result = SettingsTransfer::validate_settings( + array( + 'enable_back_button' => true, + 'scroll_top_position' => 'middle', + 'client_secret' => 'x', + 'enable_popups' => 'yes', + ) + ); + + $this->assertSame( array( 'enable_back_button' => true ), $result['valid'] ); + $this->assertSame( array( 'scroll_top_position', 'client_secret', 'enable_popups' ), array_keys( $result['skipped'] ) ); + $this->assertSame( 'unknown setting', $result['skipped']['client_secret'] ); + } + + public function test_validate_does_not_accept_numeric_keys_or_nested_values() { + $result = SettingsTransfer::validate_settings( + array( + 0 => true, + 'enable_back_button' => array( 'nested' => true ), + ) + ); + + $this->assertSame( array(), $result['valid'] ); + $this->assertCount( 2, $result['skipped'] ); + } + + public function test_validate_downgrades_an_image_format_the_server_cannot_produce() { + add_filter( 'wp_image_editors', '__return_empty_array' ); + wp_cache_delete( 'wp_image_editor_choose', 'image_editor' ); + + $result = SettingsTransfer::validate_settings( array( 'image_format_target' => 'avif' ) ); + + $this->assertSame( 'none', $result['valid']['image_format_target'] ); + $this->assertArrayHasKey( 'image_format_target', $result['adjusted'] ); + } + + public function test_validate_leaves_an_unneeded_image_format_alone() { + add_filter( 'wp_image_editors', '__return_empty_array' ); + wp_cache_delete( 'wp_image_editor_choose', 'image_editor' ); + + $result = SettingsTransfer::validate_settings( array( 'image_format_target' => 'none' ) ); + + $this->assertSame( 'none', $result['valid']['image_format_target'] ); + $this->assertSame( array(), $result['adjusted'] ); + } + + /* + * --------------------------------------------------------------- + * Applying + * --------------------------------------------------------------- + */ + + public function test_apply_merges_over_the_current_settings() { + update_option( + 'frontblocks_settings', + array( + 'enable_back_button' => false, + 'maintenance_image' => 123, + 'client_secret' => 'keep-me', + ) + ); + + $result = SettingsTransfer::apply_settings( array( 'enable_back_button' => true ) ); + + $stored = get_option( 'frontblocks_settings' ); + $this->assertTrue( $stored['enable_back_button'] ); + $this->assertSame( 123, $stored['maintenance_image'], 'Settings that are not in the file stay as they were.' ); + $this->assertSame( 'keep-me', $stored['client_secret'] ); + $this->assertSame( array( 'enable_back_button' ), $result['applied'] ); + } + + public function test_apply_reaches_the_option_through_the_form_sanitizers() { + $this->register_settings_filters(); + + SettingsTransfer::apply_settings( + array( + 'enable_back_button' => true, + 'image_format_quality_avif' => 55, + ) + ); + + $stored = get_option( 'frontblocks_settings' ); + $this->assertTrue( $stored['enable_back_button'] ); + $this->assertSame( 55, $stored['image_format_quality_avif'] ); + } + + public function test_form_sanitizers_still_ignore_saves_that_are_not_an_import() { + update_option( 'frontblocks_settings', array( 'enable_back_button' => false ) ); + $this->register_settings_filters(); + + // A save without the settings form nonce must still be refused. + update_option( 'frontblocks_settings', array( 'enable_back_button' => true ) ); + + $this->assertFalse( get_option( 'frontblocks_settings' )['enable_back_button'] ); + $this->assertFalse( SettingsTransfer::is_importing() ); + } + + public function test_import_flag_is_cleared_when_saving_fails() { + add_filter( + 'sanitize_option_frontblocks_settings', + function () { + throw new RuntimeException( 'boom' ); + } + ); + + try { + SettingsTransfer::apply_settings( array( 'enable_back_button' => true ) ); + $this->fail( 'The exception must reach the caller.' ); + } catch ( RuntimeException $e ) { + $this->assertFalse( SettingsTransfer::is_importing() ); + } + + remove_all_filters( 'sanitize_option_frontblocks_settings' ); + } + + public function test_apply_keeps_the_two_short_description_options_exclusive() { + update_option( 'frontblocks_settings', array( 'deactivate_short_description' => true ) ); + + $result = SettingsTransfer::apply_settings( array( 'move_content_to_short_description' => true ) ); + + $stored = get_option( 'frontblocks_settings' ); + $this->assertTrue( $stored['move_content_to_short_description'], 'The imported setting wins.' ); + $this->assertFalse( $stored['deactivate_short_description'] ); + $this->assertArrayHasKey( 'deactivate_short_description', $result['adjusted'] ); + } + + public function test_apply_turns_off_the_move_option_when_the_file_enables_both() { + $result = SettingsTransfer::apply_settings( + array( + 'deactivate_short_description' => true, + 'move_content_to_short_description' => true, + ) + ); + + $stored = get_option( 'frontblocks_settings' ); + $this->assertTrue( $stored['deactivate_short_description'] ); + $this->assertFalse( $stored['move_content_to_short_description'] ); + $this->assertArrayHasKey( 'move_content_to_short_description', $result['adjusted'] ); + } + + /* + * --------------------------------------------------------------- + * Whole import + * --------------------------------------------------------------- + */ + + public function test_import_applies_a_file_exported_from_another_site() { + $this->register_settings_filters(); + + $result = SettingsTransfer::import_from_string( + $this->document( + array( + 'enable_back_button' => true, + 'enable_popups' => true, + 'scroll_top_position' => 'bottom-left', + 'maintenance_title' => 'Back soon', + 'bogus' => 1, + ) + ) + ); + + $this->assertIsArray( $result ); + $this->assertSame( array( 'enable_back_button', 'enable_popups', 'scroll_top_position', 'maintenance_title' ), $result['applied'] ); + $this->assertSame( array( 'bogus' => 'unknown setting' ), $result['skipped'] ); + $this->assertSame( 'client-a.example', $result['source_site'] ); + $this->assertSame( '1.5.5', $result['source_version'] ); + + $stored = get_option( 'frontblocks_settings' ); + $this->assertTrue( $stored['enable_back_button'] ); + $this->assertTrue( $stored['enable_popups'] ); + $this->assertSame( 'bottom-left', $stored['scroll_top_position'] ); + $this->assertSame( 'Back soon', $stored['maintenance_title'] ); + $this->assertArrayNotHasKey( 'bogus', $stored ); + } + + public function test_import_of_an_invalid_file_changes_nothing() { + $before = array( 'enable_back_button' => true ); + update_option( 'frontblocks_settings', $before ); + $this->register_settings_filters(); + + foreach ( array( '', '{bad', $this->document( array( 'a' => 1 ), array( 'format' => 'x' ) ), $this->document( array( 'a' => 1 ), array( 'format_version' => 9 ) ) ) as $raw ) { + $this->assertWPError( SettingsTransfer::import_from_string( $raw ) ); + $this->assertSame( $before, get_option( 'frontblocks_settings' ) ); + } + } + + public function test_a_file_made_of_unknown_settings_applies_nothing() { + update_option( 'frontblocks_settings', array( 'enable_back_button' => true ) ); + + $result = SettingsTransfer::import_from_string( $this->document( array( 'client_secret' => 'x' ) ) ); + + $this->assertSame( array(), $result['applied'] ); + $this->assertSame( array( 'enable_back_button' => true ), get_option( 'frontblocks_settings' ) ); + } + + public function test_export_then_import_reproduces_the_configuration() { + update_option( + 'frontblocks_settings', + array( + 'enable_back_button' => true, + 'enable_fullpage_scroll' => true, + 'scroll_top_position' => 'bottom-left', + 'events_type' => 'posts', + 'image_format_quality_webp' => 64, + ) + ); + $exported = wp_json_encode( SettingsTransfer::build_export_payload() ); + + update_option( 'frontblocks_settings', array( 'enable_back_button' => false, 'enable_popups' => true ) ); + $this->register_settings_filters(); + SettingsTransfer::import_from_string( $exported ); + + $stored = get_option( 'frontblocks_settings' ); + $this->assertTrue( $stored['enable_back_button'] ); + $this->assertTrue( $stored['enable_fullpage_scroll'] ); + $this->assertFalse( $stored['enable_popups'], 'Every toggle in the file is applied, including the ones that are off.' ); + $this->assertSame( 'bottom-left', $stored['scroll_top_position'] ); + $this->assertSame( 'posts', $stored['events_type'] ); + $this->assertSame( 64, $stored['image_format_quality_webp'] ); + } + + /* + * --------------------------------------------------------------- + * Admin screen and requests + * --------------------------------------------------------------- + */ + + public function test_adds_the_backup_tab_before_the_license_tab() { + $transfer = new SettingsTransfer(); + $tabs = $transfer->add_tab( + array( + array( 'id' => 'blocks' ), + array( 'id' => 'license' ), + ) + ); + + $this->assertSame( array( 'blocks', 'backup', 'license' ), wp_list_pluck( $tabs, 'id' ) ); + } + + public function test_adds_the_backup_tab_at_the_end_when_there_is_no_license_tab() { + $transfer = new SettingsTransfer(); + $tabs = $transfer->add_tab( array( array( 'id' => 'blocks' ) ) ); + + $this->assertSame( array( 'blocks', 'backup' ), wp_list_pluck( $tabs, 'id' ) ); + } + + public function test_registers_its_hooks() { + $transfer = new SettingsTransfer(); + + $this->assertNotFalse( has_filter( 'frontblocks_settings_tabs', array( $transfer, 'add_tab' ) ) ); + $this->assertNotFalse( has_action( 'frontblocks_settings_tab_panels', array( $transfer, 'render_panel' ) ) ); + $this->assertNotFalse( has_action( 'admin_post_frbl_export_settings', array( $transfer, 'handle_export' ) ) ); + $this->assertNotFalse( has_action( 'admin_post_frbl_import_settings', array( $transfer, 'handle_import' ) ) ); + } + + public function test_panel_renders_export_link_and_import_form_for_administrators() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + ob_start(); + ( new SettingsTransfer() )->render_panel(); + $html = ob_get_clean(); + + $this->assertStringContainsString( 'data-tab-panel="backup"', $html ); + $this->assertStringContainsString( 'action=frbl_export_settings', $html ); + $this->assertStringContainsString( '_wpnonce=', $html ); + $this->assertStringContainsString( 'enctype="multipart/form-data"', $html ); + $this->assertStringContainsString( 'name="action" value="frbl_import_settings"', $html ); + $this->assertStringContainsString( 'name="frbl_settings_file"', $html ); + $this->assertStringContainsString( 'accept=".json,application/json"', $html ); + } + + public function test_panel_renders_nothing_without_the_capability() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'editor' ) ) ); + + ob_start(); + ( new SettingsTransfer() )->render_panel(); + + $this->assertSame( '', ob_get_clean() ); + } + + public function test_panel_shows_the_import_summary_once() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + set_transient( + 'frbl_transfer_result_' . get_current_user_id(), + array( + 'applied' => array( 'enable_back_button', 'enable_popups' ), + 'skipped' => array( 'bogus' => 'unknown setting' ), + 'adjusted' => array(), + 'source_site' => 'client-a.example', + ), + 60 + ); + $_GET['frbl-transfer'] = '1'; + + ob_start(); + ( new SettingsTransfer() )->render_panel(); + $first = ob_get_clean(); + + ob_start(); + ( new SettingsTransfer() )->render_panel(); + $second = ob_get_clean(); + + unset( $_GET['frbl-transfer'] ); + + $this->assertStringContainsString( '2 settings imported.', $first ); + $this->assertStringContainsString( 'client-a.example', $first ); + $this->assertStringNotContainsString( 'Reload', $first ); + $this->assertStringContainsString( 'bogus', $first ); + $this->assertStringNotContainsString( 'settings imported', $second, 'The summary is consumed after being shown.' ); + } + + public function test_panel_shows_why_a_file_was_rejected() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + set_transient( 'frbl_transfer_result_' . get_current_user_id(), array( 'error' => 'The file is not valid JSON.' ), 60 ); + $_GET['frbl-transfer'] = '1'; + + ob_start(); + ( new SettingsTransfer() )->render_panel(); + $html = ob_get_clean(); + + unset( $_GET['frbl-transfer'] ); + + $this->assertStringContainsString( 'Nothing was imported. The file is not valid JSON.', $html ); + } + + public function test_summary_values_are_escaped() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + set_transient( + 'frbl_transfer_result_' . get_current_user_id(), + array( + 'applied' => array(), + 'skipped' => array( '' => '' ), + 'adjusted' => array(), + 'source_site' => 'evil', + ), + 60 + ); + $_GET['frbl-transfer'] = '1'; + + ob_start(); + ( new SettingsTransfer() )->render_panel(); + $html = ob_get_clean(); + + unset( $_GET['frbl-transfer'] ); + + $this->assertStringNotContainsString( '' => '' ), + ), + ), + ), + 60 + ); + $_GET['frbl-transfer'] = '1'; + + ob_start(); + ( new SettingsTransfer() )->render_panel(); + $html = ob_get_clean(); + + unset( $_GET['frbl-transfer'] ); + + $this->assertStringContainsString( 'Popups: 2 created, 1 updated.', $html ); + $this->assertStringContainsString( 'Popups: needs a review', $html ); + $this->assertStringContainsString( 'Popups: skipped', $html ); + $this->assertStringContainsString( 'Old offer', $html ); + $this->assertStringNotContainsString( '' => '' ), + 'label' => 'Popups', + 'created' => 2, + 'updated' => 1, + 'skipped' => array( 'Old offer' => 'no permission' ), + 'skipped_more' => 7, + 'notes' => array( '' => '' ), ), ), ), @@ -1168,6 +1367,7 @@ public function test_panel_shows_what_an_add_on_imported_and_what_needs_a_review $this->assertStringContainsString( 'Popups: needs a review', $html ); $this->assertStringContainsString( 'Popups: skipped', $html ); $this->assertStringContainsString( 'Old offer', $html ); + $this->assertStringContainsString( 'and 7 more', $html ); $this->assertStringNotContainsString( '