diff --git a/docs/SETTINGS-EXPORT-IMPORT.md b/docs/SETTINGS-EXPORT-IMPORT.md new file mode 100644 index 00000000..1cec6749 --- /dev/null +++ b/docs/SETTINGS-EXPORT-IMPORT.md @@ -0,0 +1,171 @@ +# Settings Export and Import + +Copy the FrontBlocks configuration from one site to another with a JSON file. Open **FrontBlocks > Backup** in the admin menu. + +## Using it + +1. On the site you want to copy, open the **Backup** tab and click **Download settings file**. +2. On the other site, open the **Backup** tab, choose the file and click **Import settings**. +3. A summary lists how many settings were applied, which ones were skipped and why, and which ones were adjusted to fit the site. + +Only users with the `edit_theme_options` capability (the same as the settings screen) can export or import, and both requests are protected with nonces. + +## What is exported + +The `frontblocks_settings` option, limited to the settings that make sense on any site: + +| Group | Keys | +| --- | --- | +| Module toggles | Every checkbox of the settings screen (blocks, optional features, WooCommerce, PRO toggles such as `enable_popups` or `enable_language_banner`). A toggle that was never saved is exported as `false` (`image_max_upload_dimension_enabled`, which is on until it is saved off, is exported as `true`). Toggles of modules the site cannot use are left out, see below. | +| Options | `events_type`, `scroll_top_position`, `maintenance_title` | +| Image Management | `image_format_target`, `image_max_upload_dimension_enabled`, `image_max_upload_dimension`, `image_format_quality_webp`, `image_format_quality_avif`. When Image Management was never saved, the values it uses are exported: `none`, `true`, `2048`, `82` and `60`. | + +## Content from add-ons + +Settings are not the only thing an add-on may want to move. The file has an optional `content` section, filled by add-ons. FrontBlocks PRO uses it to move the **popups**, with their display settings (see its `docs/POPUPS-EXPORT-IMPORT.md`). + +- The export asks the add-ons for their content, and it is written under the id of each section. +- The import applies the settings first, then hands every section to the add-on that knows it. An add-on may depend on a toggle that was just imported. +- The result shows, for each section, how many items were created and updated, what was skipped and why, and what needs a review. +- A section that no add-on on this site can import is reported as skipped. Nothing is created for it. +- At most 20 sections are imported. Any section after that is not handed to the add-ons and is reported as one skipped entry. +- The `skipped` and `notes` lists of each section keep at most 50 entries in the summary, which says how many more there were. +- Each add-on checks what the current user may create, because the import only requires `edit_theme_options`. + +## What is not exported + +These belong to a single site or are secret, so they are never written to the file. Set them up again on each site. + +- Google Sign-In credentials (client ID and secret) and any license key. +- The maintenance image: it is a media library attachment ID. +- `enable_maintenance`, `enable_staging` and `staging_restrict_access`: they describe the state of one site, and importing them would put the destination in maintenance or staging mode. If a file has them, they are skipped and listed. +- `scroll_top_icon_url`: it usually points to the media library of the source site, so the destination would hotlink it. If a file has it, it is skipped and listed. +- The image size configuration (disabled, overridden and custom sizes) and the core size options it writes, because they depend on the sizes each theme registers. +- Activation dates, dismissed notices and other per-site state. +- Toggles of modules the exporting site cannot use: the PRO features (including custom post types) when FrontBlocks PRO is missing or has no valid license, and the WooCommerce features when WooCommerce is not active. They are off there only because the module is missing, so exporting them would turn the module off on a destination that uses it. An import leaves those settings as they are. Add-ons can change the list with the `frontblocks_export_unavailable_keys` filter. + +The file contains no credentials, so it is safe to keep in a repository. + +## File format + +```json +{ + "format": "frontblocks-settings", + "format_version": 1, + "plugin_version": "1.6.0", + "exported_at": "2026-11-11T10:00:00Z", + "source_site": "example.com", + "settings": { + "enable_back_button": true, + "enable_popups": false, + "scroll_top_position": "bottom-left" + }, + "content": { + "popups": [ + { "slug": "welcome", "title": "Welcome", "status": "publish", "content": "...", "settings": { "trigger": "delay" } } + ] + } +} +``` + +`content` is optional and only present when an add-on provides content. + +`format_version` lets a future version refuse or migrate a file it does not understand. A file with a newer version than the site supports is rejected with a message asking to update FrontBlocks. + +## How the import works + +- **It merges.** Only the keys present in the file change. Everything else on the destination site stays as it is, including the values that are never exported. +- **Every value is validated** against a schema (boolean, one of a list, http or https URL, text up to a length, whole number between two bounds). A value that does not match is skipped and listed, never stored. +- **Unknown keys are skipped** and listed, so a file cannot write arbitrary data into the option. The summary keeps at most 50 skipped entries (key names cut to 60 characters) and says how many more there were, so a file full of unknown keys cannot make a huge stored result. +- **Values that depend on the server are adjusted.** An image format target the server cannot produce, for example AVIF without support, is downgraded the same way the settings screen does, and the summary says so. +- **The two short description options exclude each other**, as they do on the settings screen. If an import would turn both on, one is turned off and the summary says which. +- **The `frontblocks_sanitize_settings` action runs** with the merged settings, right before they are stored, as it does when the settings screen is saved. +- **Limits.** The file must be valid JSON, declare `"format": "frontblocks-settings"`, be at most 2 MB and have the `.json` extension. The file is only decoded, never executed or included. A rejected file changes nothing. + +## Extending it + +Add-ons such as FrontBlocks PRO can contribute their own settings with two filters. Declare how a key is validated, then add its value to the export. + +```php +add_filter( + 'frontblocks_import_settings_schema', + function ( $schema ) { + $schema['my_addon_mode'] = array( + 'type' => 'enum', + 'values' => array( 'simple', 'advanced' ), + ); + return $schema; + } +); + +add_filter( + 'frontblocks_export_settings', + function ( $settings, $options ) { + if ( isset( $options['my_addon_mode'] ) ) { + $settings['my_addon_mode'] = $options['my_addon_mode']; + } + return $settings; + }, + 10, + 2 +); +``` + +Supported rule types: + +| `type` | Extra keys | Accepts | +| --- | --- | --- | +| `bool` | | `true`, `false`, `1`, `0`, `"1"`, `"0"` | +| `enum` | `values` | one of the listed strings | +| `url` | | an empty string or an `http` or `https` URL | +| `text` | `max` (default 255) | text up to `max` characters (counted with `mb_strlen()`, so multibyte text is not penalized), sanitized with `sanitize_text_field()` | +| `int` | `min`, `max` | a whole number between the bounds | + +### Content sections + +Add-ons move content with two more filters. Return the data under a section id (lowercase letters, numbers, hyphens and underscores) on export, and on import read that section, validate everything, and add a report. + +```php +add_filter( + 'frontblocks_export_content', + function ( $content ) { + $content['my-addon'] = array( array( 'slug' => 'one', 'title' => 'One' ) ); + return $content; + } +); + +add_filter( + 'frontblocks_import_content', + function ( $report, $sections ) { + if ( ! isset( $sections['my-addon'] ) ) { + return $report; + } + + // Check what the user may create, validate each item and save it. + $report['my-addon'] = array( + 'label' => __( 'My add-on', 'my-addon' ), + 'created' => 1, + 'updated' => 0, + 'skipped' => array( 'Two' => 'it has no title' ), + 'notes' => array( 'One' => 'check the image, it may not exist on this site' ), + ); + + return $report; + }, + 10, + 2 +); +``` + +- `created` and `updated` are counts. `skipped` and `notes` map a label to a short reason. Everything is escaped when shown. +- Replace IDs that only mean something on the source site (pages, media, forms) with something that can be found again, such as a path, and say in `notes` what the user has to review. +- Save through WordPress functions as the current user, so users without `unfiltered_html` keep getting their content filtered. + +Keys that are not in the schema are skipped on import, so an add-on must declare a key before it can travel. Never add credentials or values that only make sense on the source site to the export. + +## Code + +- `includes/Admin/SettingsTransfer.php`: schema, file validation, import, content sections and the Backup tab. +- `Settings::get_boolean_option_keys()` is the single list of toggles, shared with the settings form sanitizer. +- The tab is added through the `frontblocks_settings_tabs` filter and the `frontblocks_settings_tab_panels` action (see [Extending Settings Tabs](./SETTINGS-TAB-EXTENSIONS.md)). +- While an import writes the option, `SettingsTransfer::is_importing()` is true. The settings form sanitizer checks it, because it normally requires the form nonce, which an import does not have. diff --git a/includes/Admin/ImageManagement.php b/includes/Admin/ImageManagement.php index 38a4b599..504f53b9 100644 --- a/includes/Admin/ImageManagement.php +++ b/includes/Admin/ImageManagement.php @@ -60,6 +60,26 @@ public function __construct() { */ const JOB_TYPES = array( 'regenerate', 'convert', 'cleanup' ); + /** + * Max upload width/height, in pixels, until the module is saved. + */ + const DEFAULT_MAX_UPLOAD_DIMENSION = 2048; + + /** + * WebP quality until the module is saved. + */ + const DEFAULT_QUALITY_WEBP = 82; + + /** + * AVIF quality until the module is saved. + */ + const DEFAULT_QUALITY_AVIF = 60; + + /** + * Modern format target until the module is saved: no conversion. + */ + const DEFAULT_FORMAT_TARGET = 'none'; + /** * Register the settings section and fields. * @@ -101,7 +121,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' ) ); @@ -189,10 +209,10 @@ public function field_enable_image_management() { $disabled = (array) ( $options['image_sizes_disabled'] ?? array() ); $overrides = (array) ( $options['image_sizes_overrides'] ?? array() ); $custom = (array) ( $options['image_sizes_custom'] ?? array() ); - $format_target = (string) ( $options['image_format_target'] ?? 'none' ); + $format_target = (string) ( $options['image_format_target'] ?? self::DEFAULT_FORMAT_TARGET ); $quality_by_fmt = FrontendImageManagement::get_quality_settings( $options ); $max_upload_dimension_enabled = (bool) ( $options['image_max_upload_dimension_enabled'] ?? true ); - $max_upload_dimension = (int) ( $options['image_max_upload_dimension'] ?? 2048 ); + $max_upload_dimension = (int) ( $options['image_max_upload_dimension'] ?? self::DEFAULT_MAX_UPLOAD_DIMENSION ); $sizes_info = $this->get_registered_sizes_info(); $usage = FrontendImageManagement::estimate_disk_usage_by_size( wp_list_pluck( $sizes_info, 'name' ) ); @@ -333,20 +353,20 @@ public function sanitize_settings( $value, $option ) { $posted = wp_unslash( $_POST['frontblocks_settings'] ); // phpcs:ignore WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- nonce verified above; every value read from $posted below is sanitized individually. $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 ); + $posted_target = $posted['image_format_target'] ?? self::DEFAULT_FORMAT_TARGET; + $requested_target = in_array( $posted_target, $allowed_targets, true ) ? $posted_target : self::DEFAULT_FORMAT_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'] ); - $max_dimension = absint( $posted['image_max_upload_dimension'] ?? 2048 ); - $value['image_max_upload_dimension'] = $max_dimension >= 300 ? min( $max_dimension, 10000 ) : 2048; + $max_dimension = absint( $posted['image_max_upload_dimension'] ?? self::DEFAULT_MAX_UPLOAD_DIMENSION ); + $value['image_max_upload_dimension'] = $max_dimension >= 300 ? min( $max_dimension, 10000 ) : self::DEFAULT_MAX_UPLOAD_DIMENSION; - $webp_quality = absint( $posted['image_format_quality_webp'] ?? 82 ); - $value['image_format_quality_webp'] = $webp_quality > 0 ? min( $webp_quality, 100 ) : 82; + $webp_quality = absint( $posted['image_format_quality_webp'] ?? self::DEFAULT_QUALITY_WEBP ); + $value['image_format_quality_webp'] = $webp_quality > 0 ? min( $webp_quality, 100 ) : self::DEFAULT_QUALITY_WEBP; - $avif_quality = absint( $posted['image_format_quality_avif'] ?? 60 ); - $value['image_format_quality_avif'] = $avif_quality > 0 ? min( $avif_quality, 100 ) : 60; + $avif_quality = absint( $posted['image_format_quality_avif'] ?? self::DEFAULT_QUALITY_AVIF ); + $value['image_format_quality_avif'] = $avif_quality > 0 ? min( $avif_quality, 100 ) : self::DEFAULT_QUALITY_AVIF; $config = array(); if ( ! empty( $posted['image_sizes_config'] ) ) { diff --git a/includes/Admin/Settings.php b/includes/Admin/Settings.php index 05ee4518..fcaec0df 100644 --- a/includes/Admin/Settings.php +++ b/includes/Admin/Settings.php @@ -746,7 +746,7 @@ function activateTab(tabId) { }); if (saveBar) { - saveBar.hidden = found && 'google-signin' === tabId; + saveBar.hidden = found && ('google-signin' === tabId || 'backup' === tabId); } if (! found) { @@ -1032,15 +1032,29 @@ private static function get_tab_menu_page( $tab ) { * @return void */ public function move_license_entry_last() { + self::move_tab_entry_last( 'license' ); + } + + /** + * Move the menu entry of a tab to the end of the FrontBlocks menu. + * + * Tabs that belong at the end (Backup, License) use it once WordPress has added the + * entries of the post types shown in the menu, which would otherwise come after them. + * + * @since 1.6.0 + * @param string $tab_id Tab id. + * @return void + */ + public static function move_tab_entry_last( $tab_id ) { global $submenu; if ( empty( $submenu[ self::PAGE_SLUG ] ) || ! is_array( $submenu[ self::PAGE_SLUG ] ) ) { return; } - $license = self::get_page_slug( 'license' ); + $slug = self::get_page_slug( $tab_id ); foreach ( $submenu[ self::PAGE_SLUG ] as $position => $entry ) { - if ( isset( $entry[2] ) && $license === $entry[2] ) { + if ( isset( $entry[2] ) && $slug === $entry[2] ) { unset( $submenu[ self::PAGE_SLUG ][ $position ] ); $submenu[ self::PAGE_SLUG ][] = $entry; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Reorders the entries of this plugin's own menu. return; @@ -2473,30 +2487,50 @@ private function get_section_fields( $section_id ) { * @return bool */ private function is_pro_feature( $field_id ) { - return in_array( - $field_id, + return in_array( $field_id, self::get_pro_option_keys(), true ); + } + + /** + * Toggles of the WooCommerce features, which also need FrontBlocks PRO. + * + * @since 1.6.0 + * @return string[] + */ + public static function get_woocommerce_option_keys() { + return array( + 'enable_gutenberg', + 'enable_simple_prices_variable_products', + 'enable_after_add_to_cart', + 'deactivate_short_description', + 'move_content_to_short_description', + 'disable_zoom_images', + 'add_share_buttons', + 'deactivate_product_tabs', + 'horizontal_product_form', + 'enable_variant_display_mode', + 'checkout_inline', + 'disable_cart_coupon', + 'disable_cart_cross_sells', + 'disable_checkout_coupon', + 'disable_checkout_order_notes', + 'disable_checkout_login_prompt', + ); + } + + /** + * Toggles of the features that need FrontBlocks PRO with a valid license. + * + * @since 1.6.0 + * @return string[] + */ + public static function get_pro_option_keys() { + return array_merge( + self::get_woocommerce_option_keys(), array( - $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_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, - ), - true + 'enable_fullpage_scroll', + 'enable_language_banner', + 'enable_popups', + ) ); } @@ -3861,6 +3895,48 @@ 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_staging, - Staging::RESTRICT_ACCESS, - $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 ) { diff --git a/includes/Admin/SettingsTransfer.php b/includes/Admin/SettingsTransfer.php new file mode 100644 index 00000000..153d5147 --- /dev/null +++ b/includes/Admin/SettingsTransfer.php @@ -0,0 +1,1246 @@ + '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['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 ( mb_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, + ); + } + + /** + * Effective value of the settings that have a default when they were never saved. + * + * @return array Setting key => default. + */ + private static function get_unsaved_defaults() { + return array( + 'image_max_upload_dimension_enabled' => true, + 'image_max_upload_dimension' => ImageManagement::DEFAULT_MAX_UPLOAD_DIMENSION, + 'image_format_quality_webp' => ImageManagement::DEFAULT_QUALITY_WEBP, + 'image_format_quality_avif' => ImageManagement::DEFAULT_QUALITY_AVIF, + 'image_format_target' => ImageManagement::DEFAULT_FORMAT_TARGET, + ); + } + + /** + * Settings of the modules this site cannot use, which an export leaves out. + * + * Their toggles are off here only because the module is missing (no FrontBlocks + * PRO with a valid license, or no WooCommerce). Exporting them as off would turn + * the module off on a destination that uses it. + * + * @return string[] + */ + public static function get_unavailable_keys() { + $keys = array(); + + $has_pro = function_exists( 'frblp_is_license_valid' ) && frblp_is_license_valid(); + if ( ! $has_pro ) { + // Custom post types are a PRO module too, with a section of their own. + $keys = array_merge( Settings::get_pro_option_keys(), array( 'enable_custom_post_types' ) ); + } + + if ( ! class_exists( 'WooCommerce' ) ) { + $keys = array_merge( $keys, Settings::get_woocommerce_option_keys() ); + } + + /** + * Filters the settings an export leaves out because this site cannot use their module. + * + * @since 1.6.0 + * @param string[] $keys Setting keys. + */ + $keys = apply_filters( 'frontblocks_export_unavailable_keys', $keys ); + + return is_array( $keys ) ? array_values( array_unique( array_filter( $keys, 'is_string' ) ) ) : array(); + } + + /** + * 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(); + $defaults = self::get_unsaved_defaults(); + + $unavailable = self::get_unavailable_keys(); + + $settings = array(); + foreach ( $schema as $key => $rule ) { + // A module this site cannot use says nothing about the destination: leave it to that site. + if ( in_array( $key, $unavailable, true ) ) { + continue; + } + + if ( in_array( $key, $boolean, true ) ) { + // An unchecked toggle is never saved, so export its effective state. + $settings[ $key ] = ! empty( $options[ $key ] ); + continue; + } + + // A setting that was never saved would otherwise be missing, and the destination would keep its own value. + if ( ! array_key_exists( $key, $options ) && array_key_exists( $key, $defaults ) ) { + $settings[ $key ] = $defaults[ $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 ); + + $payload = 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(), + ); + + $content = self::collect_content(); + if ( ! empty( $content ) ) { + $payload['content'] = $content; + } + + return $payload; + } + + /** + * Whether a content section id is valid. + * + * @param mixed $id Section id. + * @return bool + */ + private static function is_valid_section_id( $id ) { + return is_string( $id ) && 1 === preg_match( '/^[a-z0-9_-]{1,40}$/', $id ); + } + + /** + * Ask the add-ons for the content that goes in the export. + * + * @return array Section id => data. + */ + private static function collect_content() { + /** + * Filters the content written to the `content` section of an export file. + * + * Add-ons return their data under their own section id (lowercase letters, + * numbers, hyphens and underscores). Use it for things that are not settings, + * such as the popups of FrontBlocks PRO. Never add credentials, and replace + * IDs that only mean something on this site (pages, media) with something + * that can be found again on another site, such as a path. + * + * @since 1.6.0 + * @param array $content Section id => data to export. + */ + $content = apply_filters( 'frontblocks_export_content', array() ); + if ( ! is_array( $content ) ) { + return array(); + } + + $clean = array(); + foreach ( $content as $id => $data ) { + if ( self::is_valid_section_id( $id ) && is_array( $data ) && array() !== $data ) { + $clean[ $id ] = $data; + } + } + + return $clean; + } + + /** + * 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, self::MAX_DEPTH ); + if ( JSON_ERROR_DEPTH === json_last_error() ) { + return new \WP_Error( 'frbl_transfer_too_deep', __( 'The file is nested too deeply to be a FrontBlocks settings export.', 'frontblocks' ) ); + } + 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' ) ); + } + + if ( isset( $data['content'] ) && ! is_array( $data['content'] ) ) { + return new \WP_Error( 'frbl_transfer_invalid_content', __( 'The content section of the file is not valid.', '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 ( in_array( $key, self::SITE_BOUND_KEYS, true ) ) { + $skipped[ $key ] = __( 'tied to the site it came from, so it is never imported', 'frontblocks' ); + continue; + } + + 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: %s: setting that stays on */ + $adjusted[ $turn_off ] = sprintf( __( 'turned off, it cannot be on together with "%s"', 'frontblocks' ), $keep ); + } + + // Listeners of the settings form sanitizer see the imported settings too, as on a form save. + do_action( 'frontblocks_sanitize_settings', $merged ); + + self::$importing = true; + self::$pending = $merged; + try { + update_option( self::OPTION, $merged ); + } finally { + self::$importing = false; + self::$pending = null; + } + + // A setting the exclusive rule just turned off was not applied as the file says. + $applied = array_keys( $valid ); + if ( isset( $turn_off ) ) { + $applied = array_values( array_diff( $applied, array( $turn_off ) ) ); + } + + return array( + 'applied' => $applied, + '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'] ); + + // Settings go first: an add-on may depend on a toggle that was just imported. + $content = self::import_content( isset( $data['content'] ) ? $data['content'] : array() ); + + $skipped = self::cap_skipped( $checked['skipped'] ); + + return array( + 'applied' => $applied['applied'], + 'skipped' => $skipped['list'], + 'skipped_more' => $skipped['more'], + 'adjusted' => $applied['adjusted'], + 'content' => $content, + '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'] ) : '', + ); + } + + /** + * Keep a list of the summary small enough to store: its keys come from the file. + * + * Used for the skipped settings and for the `skipped` and `notes` lists of the + * content sections. + * + * @param array $skipped Key => reason. + * @return array { + * @type array $list Key => reason, at most MAX_REPORTED_SKIPPED entries. + * @type int $more How many entries were left out. + * } + */ + private static function cap_skipped( $skipped ) { + $list = array(); + foreach ( array_slice( $skipped, 0, self::MAX_REPORTED_SKIPPED, true ) as $key => $reason ) { + $list[ mb_substr( sanitize_text_field( (string) $key ), 0, 60 ) ] = (string) $reason; + } + + return array( + 'list' => $list, + 'more' => max( 0, count( $skipped ) - count( $list ) ), + ); + } + + /** + * Hand the content sections of a file to the add-ons that know them. + * + * @param array $content Section id => data from the file. + * @return array Section id => report (label, created, updated, skipped and notes). + */ + public static function import_content( $content ) { + if ( ! is_array( $content ) || array() === $content ) { + return array(); + } + + $sections = array(); + $more = 0; + foreach ( $content as $id => $data ) { + if ( ! self::is_valid_section_id( $id ) || ! is_array( $data ) ) { + continue; + } + if ( count( $sections ) >= self::MAX_CONTENT_SECTIONS ) { + ++$more; + continue; + } + $sections[ $id ] = $data; + } + + /** + * Imports the content sections of a settings file. + * + * Each add-on handles the sections it exported, validates everything it + * reads, and adds a report under the section id: `label` (text), `created` and + * `updated` (counts), `skipped` (label => reason) and `notes` (label => what + * needs a review). It runs after the settings are applied, only for users who + * can import settings, and the add-on must still check what the user may create. + * + * @since 1.6.0 + * @param array $report Section id => report, filled by the handlers. + * @param array $sections Section id => data from the file. + */ + $report = apply_filters( 'frontblocks_import_content', array(), $sections ); + $report = is_array( $report ) ? $report : array(); + + $result = array(); + foreach ( array_keys( $sections ) as $id ) { + $result[ $id ] = isset( $report[ $id ] ) && is_array( $report[ $id ] ) + ? self::normalize_section_report( $id, $report[ $id ] ) + : array( + 'label' => $id, + 'created' => 0, + 'updated' => 0, + 'skipped' => array( $id => __( 'nothing on this site can import this content', 'frontblocks' ) ), + 'skipped_more' => 0, + 'notes' => array(), + 'notes_more' => 0, + ); + } + + if ( $more > 0 ) { + /* translators: %d: number of content sections that were not imported */ + $more_label = sprintf( _n( '%d more section', '%d more sections', $more, 'frontblocks' ), $more ); + + $result[ self::MORE_SECTIONS_ID ] = array( + 'label' => __( 'Content', 'frontblocks' ), + 'created' => 0, + 'updated' => 0, + /* translators: %d: maximum number of content sections */ + 'skipped' => array( $more_label => sprintf( __( 'a file can carry at most %d content sections, so the rest was not imported', 'frontblocks' ), self::MAX_CONTENT_SECTIONS ) ), + 'skipped_more' => 0, + 'notes' => array(), + 'notes_more' => 0, + ); + } + + return $result; + } + + /** + * Keep only the expected, plain values of an add-on report. + * + * @param string $id Section id. + * @param array $report Report returned by the add-on. + * @return array + */ + private static function normalize_section_report( $id, $report ) { + $lists = array(); + foreach ( array( 'skipped', 'notes' ) as $list ) { + $clean = array(); + foreach ( isset( $report[ $list ] ) && is_array( $report[ $list ] ) ? $report[ $list ] : array() as $label => $text ) { + if ( is_scalar( $text ) ) { + $clean[ sanitize_text_field( (string) $label ) ] = sanitize_text_field( (string) $text ); + } + } + // The labels often come from the file, so these lists are capped like the skipped settings. + $lists[ $list ] = self::cap_skipped( $clean ); + } + + return array( + 'label' => isset( $report['label'] ) && is_string( $report['label'] ) && '' !== $report['label'] ? sanitize_text_field( $report['label'] ) : $id, + 'created' => isset( $report['created'] ) ? absint( $report['created'] ) : 0, + 'updated' => isset( $report['updated'] ) ? absint( $report['updated'] ) : 0, + 'skipped' => $lists['skipped']['list'], + 'skipped_more' => $lists['skipped']['more'], + 'notes' => $lists['notes']['list'], + 'notes_more' => $lists['notes']['more'], + ); + } + + /** + * URL of the Backup tab. + * + * @param array $args Query arguments to add. + * @return string + */ + private static function settings_url( $args = array() ) { + return add_query_arg( $args, Settings::get_settings_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 ); + if ( false === $json ) { + wp_die( esc_html__( 'The settings could not be exported.', 'frontblocks' ), '', array( 'response' => 500 ) ); + } + + // A file that another site would refuse to import is no use: say so now. + if ( ! self::is_importable( $json ) ) { + wp_die( esc_html__( 'The settings could not be exported: the file would be larger than 2 MB or nested too deeply to be imported. This usually means an add-on adds too much content to it.', 'frontblocks' ), '', array( 'response' => 500 ) ); + } + + 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; + } + + /** + * Whether an exported document is within the limits an import accepts. + * + * @param string $json Encoded export. + * @return bool + */ + public static function is_importable( $json ) { + if ( ! is_string( $json ) || strlen( $json ) > self::MAX_FILE_SIZE ) { + return false; + } + + json_decode( $json, true, self::MAX_DEPTH ); + + return JSON_ERROR_NONE === json_last_error(); + } + + /** + * 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' ), isset( $result['skipped_more'] ) ? (int) $result['skipped_more'] : 0 ); + + foreach ( isset( $result['content'] ) ? (array) $result['content'] : array() as $section ) { + $this->render_content_section( (array) $section ); + } + } + + /** + * Show what an add-on did with its content, and what needs a review. + * + * @param array $section Normalized section report. + * @return void + */ + private function render_content_section( $section ) { + $label = isset( $section['label'] ) ? (string) $section['label'] : ''; + $created = isset( $section['created'] ) ? (int) $section['created'] : 0; + $updated = isset( $section['updated'] ) ? (int) $section['updated'] : 0; + + if ( $created > 0 || $updated > 0 ) { + ?> +
+ +
+ render_notes( + isset( $section['notes'] ) ? (array) $section['notes'] : array(), + /* translators: %s: kind of content, for example Popups */ + sprintf( __( '%s: needs a review', 'frontblocks' ), $label ), + isset( $section['notes_more'] ) ? (int) $section['notes_more'] : 0 + ); + $this->render_notes( + isset( $section['skipped'] ) ? (array) $section['skipped'] : array(), + /* translators: %s: kind of content, for example Popups */ + sprintf( __( '%s: skipped', 'frontblocks' ), $label ), + isset( $section['skipped_more'] ) ? (int) $section['skipped_more'] : 0 + ); + } + + /** + * List settings that were adjusted or skipped, with the reason. + * + * @param array $notes Setting key => reason. + * @param string $title Heading of the list. + * @param int $more Entries left out of the list. + * @return void + */ + private function render_notes( $notes, $title, $more = 0 ) { + if ( empty( $notes ) ) { + return; + } + ?> +
+

+ $reason ) : ?> +

:

+ + 0 ) : ?> +

+ +

+ +
+ 0 ? $max : $threshold; } @@ -191,7 +193,7 @@ public function filter_intermediate_sizes( $sizes ) { */ public function maybe_generate_modern_formats( $metadata, $attachment_id ) { $options = $this->get_options(); - $target = (string) ( $options['image_format_target'] ?? 'none' ); + $target = (string) ( $options['image_format_target'] ?? AdminImageManagement::DEFAULT_FORMAT_TARGET ); if ( 'none' === $target || empty( $metadata ) ) { return $metadata; @@ -209,8 +211,8 @@ public function maybe_generate_modern_formats( $metadata, $attachment_id ) { */ public static function get_quality_settings( $options ) { return array( - 'webp' => (int) ( $options['image_format_quality_webp'] ?? 82 ), - 'avif' => (int) ( $options['image_format_quality_avif'] ?? 60 ), + 'webp' => (int) ( $options['image_format_quality_webp'] ?? AdminImageManagement::DEFAULT_QUALITY_WEBP ), + 'avif' => (int) ( $options['image_format_quality_avif'] ?? AdminImageManagement::DEFAULT_QUALITY_AVIF ), ); } @@ -286,7 +288,7 @@ private static function generate_variant_files( $source_path, $formats, $quality continue; } - $editor->set_quality( $quality[ $format ] ?? 82 ); + $editor->set_quality( $quality[ $format ] ?? AdminImageManagement::DEFAULT_QUALITY_WEBP ); $target_path = preg_replace( '/\.[^.]+$/', '.' . $format, $source_path ); $saved = $editor->save( $target_path, $mime ); @@ -318,7 +320,7 @@ public static function convert_attachment( $attachment_id ) { } $options = get_option( 'frontblocks_settings', array() ); - $target = (string) ( $options['image_format_target'] ?? 'none' ); + $target = (string) ( $options['image_format_target'] ?? AdminImageManagement::DEFAULT_FORMAT_TARGET ); if ( 'none' === $target ) { return false; diff --git a/includes/Plugin_Main.php b/includes/Plugin_Main.php index 41af3d96..6943fdb4 100644 --- a/includes/Plugin_Main.php +++ b/includes/Plugin_Main.php @@ -75,6 +75,11 @@ private function load_modules() { } new Admin\Settings(); + if ( ! class_exists( 'FrontBlocks\Admin\SettingsTransfer' ) ) { + require_once FRBL_PLUGIN_PATH . 'includes/Admin/SettingsTransfer.php'; + } + new Admin\SettingsTransfer(); + if ( ! class_exists( 'FrontBlocks\Admin\ReviewNotice' ) ) { require_once FRBL_PLUGIN_PATH . 'includes/Admin/ReviewNotice.php'; } diff --git a/readme.md b/readme.md index 74ef8933..164585fe 100644 --- a/readme.md +++ b/readme.md @@ -37,6 +37,7 @@ Repository for FrontBlocks Site Tools, a WordPress plugin covering the everyday - **Google Sign-In** - "Sign in / Sign up with Google" button for wp-login.php, WooCommerce My Account and Checkout, plus a shortcode and block, with server-side ID token verification - **Table of Contents** - Accessible navigation block generated from the headings in the post, with collapsible and sticky options - **MCP Abilities** - Exposes maintenance mode as an ability via WordPress's Abilities API, so MCP/AI clients can read and toggle it (e.g. for a site go-live checklist), gated behind the `manage_options` capability. Also reports WooCommerce's own "Coming soon" site visibility independently +- **Settings Export / Import** - Download the FrontBlocks configuration as a JSON file and import it on another site to set it up in one step. Credentials, license keys and values tied to a site are never exported, and every imported value is validated. Add-ons can move content too, such as the popups of FrontBlocks PRO ### PRO Features (FrontBlocks PRO) - **Custom Post Types Builder** - Create and manage custom post types with advanced configuration options: @@ -81,6 +82,7 @@ Repository for FrontBlocks Site Tools, a WordPress plugin covering the everyday - [Redundant Plugins Notice](./docs/REDUNDANT-PLUGINS.md) - Detects plugins made unnecessary by FrontBlocks features and how to register new pairings - [Google Sign-In](./docs/GOOGLE-SIGNIN.md) - "Sign in / Sign up with Google" for wp-login.php and WooCommerce - [Extending Settings Tabs](./docs/SETTINGS-TAB-EXTENSIONS.md) - Add a companion-plugin tab and matching panel to FrontBlocks settings +- [Settings Export and Import](./docs/SETTINGS-EXPORT-IMPORT.md) - Clone the FrontBlocks configuration between sites with a JSON file, what is and is not included, and how add-ons extend it - [Table of Contents](./docs/TABLE-OF-CONTENTS.md) - Accessible, headings-based navigation block - [Column Link](./docs/COLUMN-LINK.md) - Make an entire native Column block clickable diff --git a/readme.txt b/readme.txt index aa7a1240..3df5fda3 100644 --- a/readme.txt +++ b/readme.txt @@ -224,6 +224,7 @@ More information in the [FrontBlocks PRO](https://close.technology/en/wordpress- == Changelog == = Unreleased = +* Added: Export and import the FrontBlocks settings as a JSON file from the new Backup tab, to clone a configuration between sites. Credentials, license keys and values tied to a site are never exported, every imported value is validated, and add-ons can extend it with the `frontblocks_import_settings_schema` and `frontblocks_export_settings` filters, and move content such as the popups of FrontBlocks PRO with `frontblocks_export_content` and `frontblocks_import_content`. * Changed: FrontBlocks has a menu of its own in the admin sidebar, with a submenu entry for each settings tab, instead of a page under Appearance. Testimonials and Events (with their categories) move into the same menu. The old Appearance URL redirects to the new menu, keeping its arguments and tab. Companion plugins can link to a tab with `Settings::get_settings_url()` and recognize its screens with `Settings::is_settings_screen()`. * Added: Staging Mode. It is activated automatically on domains starting with `beta.` (filterable), when the environment type is `staging` or `development`, with a manual toggle in the Maintenance tab, or with the `FRBL_STAGING` constant (`false` forces it off). It blocks indexing (noindex, X-Robots-Tag, closed robots.txt, no sitemaps), blocks outgoing email with a log (or redirects it to one address), can restrict the frontend to logged-in users, adds a STAGING admin bar node, a [STAGING] title prefix and notices, adds WooCommerce safety (test site notice, manual Subscriptions renewals, paused webhooks), can pause WP-Cron and Action Scheduler, block requests to selected hosts and remove Google Analytics/Tag Manager snippets. Add-ons can check `frontblocks_is_staging()`. * Changed: Removed the legacy Cookie Notice runtime (banner, AJAX consent endpoints, and GTM/GA4/other tracking integrations) from FrontBlocks — a hard cutover, not a transition. Cookie consent now lives entirely in the standalone FrontConsent plugin; the Cookie Notice settings tab remains as a promo panel pointing to it. diff --git a/tests/Unit/SettingsTransferTest.php b/tests/Unit/SettingsTransferTest.php new file mode 100644 index 00000000..c0f8d859 --- /dev/null +++ b/tests/Unit/SettingsTransferTest.php @@ -0,0 +1,1568 @@ + 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 ( array_diff( Settings::get_boolean_option_keys(), SettingsTransfer::SITE_BOUND_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_text_length_is_counted_in_characters_not_bytes() { + $rule = array( + 'type' => 'text', + 'max' => 20, + ); + + $japanese = str_repeat( '日', 20 ); + $greek = str_repeat( 'λ', 20 ); + $this->assertGreaterThan( 20, strlen( $japanese ), 'The text takes more bytes than the limit.' ); + + $this->assertSame( $japanese, SettingsTransfer::sanitize_value( $japanese, $rule )['value'] ); + $this->assertSame( $greek, SettingsTransfer::sanitize_value( $greek, $rule )['value'] ); + $this->assertFalse( SettingsTransfer::sanitize_value( $japanese . '日', $rule )['ok'] ); + } + + public function test_a_multibyte_maintenance_title_travels_between_sites() { + $title = str_repeat( 'メンテナンス中', 28 ); + $this->assertSame( 196, mb_strlen( $title ) ); + + update_option( 'frontblocks_settings', array( 'maintenance_title' => $title ) ); + $this->assertSame( $title, SettingsTransfer::build_export_payload()['settings']['maintenance_title'], 'It is not dropped on export.' ); + + delete_option( 'frontblocks_settings' ); + $result = SettingsTransfer::import_from_string( $this->document( array( 'maintenance_title' => $title ) ) ); + + $this->assertContains( 'maintenance_title', $result['applied'] ); + $this->assertSame( $title, get_option( 'frontblocks_settings' )['maintenance_title'] ); + } + + 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() { + // A source site with every module: FrontBlocks PRO with a license and WooCommerce. + add_filter( 'frontblocks_export_unavailable_keys', '__return_empty_array' ); + update_option( 'frontblocks_settings', array( 'enable_back_button' => true ) ); + + $settings = SettingsTransfer::build_export_payload()['settings']; + + $this->assertTrue( $settings['enable_back_button'] ); + foreach ( array_diff( Settings::get_boolean_option_keys(), SettingsTransfer::SITE_BOUND_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_leaves_out_values_that_belong_to_one_site() { + update_option( + 'frontblocks_settings', + array( + 'enable_maintenance' => true, + 'enable_staging' => true, + 'staging_restrict_access' => true, + 'scroll_top_icon_url' => 'https://source.example/wp-content/uploads/icon.svg', + ) + ); + + $settings = SettingsTransfer::build_export_payload()['settings']; + + foreach ( SettingsTransfer::SITE_BOUND_KEYS as $key ) { + $this->assertArrayNotHasKey( $key, $settings, $key ); + $this->assertArrayNotHasKey( $key, SettingsTransfer::get_schema(), $key ); + } + } + + public function test_export_includes_the_upload_dimension_toggle_even_when_never_saved() { + update_option( 'frontblocks_settings', array() ); + $this->assertTrue( SettingsTransfer::build_export_payload()['settings']['image_max_upload_dimension_enabled'], 'It is on until it is saved off.' ); + + update_option( 'frontblocks_settings', array( 'image_max_upload_dimension_enabled' => false ) ); + $this->assertFalse( SettingsTransfer::build_export_payload()['settings']['image_max_upload_dimension_enabled'] ); + } + + public function test_export_includes_the_image_values_in_effect_when_image_management_was_never_saved() { + update_option( 'frontblocks_settings', array( 'enable_back_button' => true ) ); + $settings = SettingsTransfer::build_export_payload()['settings']; + + $this->assertSame( 2048, $settings['image_max_upload_dimension'] ); + $this->assertSame( 82, $settings['image_format_quality_webp'] ); + $this->assertSame( 60, $settings['image_format_quality_avif'] ); + $this->assertSame( 'none', $settings['image_format_target'] ); + $this->assertSame( ImageManagement::DEFAULT_MAX_UPLOAD_DIMENSION, $settings['image_max_upload_dimension'] ); + $this->assertSame( ImageManagement::DEFAULT_QUALITY_WEBP, $settings['image_format_quality_webp'] ); + $this->assertSame( ImageManagement::DEFAULT_QUALITY_AVIF, $settings['image_format_quality_avif'] ); + $this->assertSame( ImageManagement::DEFAULT_FORMAT_TARGET, $settings['image_format_target'] ); + } + + public function test_export_prefers_saved_image_values_over_the_defaults() { + update_option( + 'frontblocks_settings', + array( + 'image_max_upload_dimension' => 3000, + 'image_format_quality_webp' => 70, + 'image_format_quality_avif' => 45, + 'image_format_target' => 'webp', + ) + ); + $settings = SettingsTransfer::build_export_payload()['settings']; + + $this->assertSame( 3000, $settings['image_max_upload_dimension'] ); + $this->assertSame( 70, $settings['image_format_quality_webp'] ); + $this->assertSame( 45, $settings['image_format_quality_avif'] ); + $this->assertSame( 'webp', $settings['image_format_target'] ); + } + + public function test_the_image_defaults_are_valid_against_the_schema() { + $schema = SettingsTransfer::get_schema(); + $values = array( + 'image_max_upload_dimension' => ImageManagement::DEFAULT_MAX_UPLOAD_DIMENSION, + 'image_format_quality_webp' => ImageManagement::DEFAULT_QUALITY_WEBP, + 'image_format_quality_avif' => ImageManagement::DEFAULT_QUALITY_AVIF, + 'image_format_target' => ImageManagement::DEFAULT_FORMAT_TARGET, + ); + + foreach ( $values as $key => $value ) { + $this->assertTrue( SettingsTransfer::sanitize_value( $value, $schema[ $key ] )['ok'], $key ); + } + } + + 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_import_skips_values_that_belong_to_one_site_and_says_why() { + $result = SettingsTransfer::validate_settings( + array( + 'enable_maintenance' => true, + 'enable_staging' => true, + 'scroll_top_icon_url' => 'https://source.example/icon.svg', + 'enable_popups' => true, + ) + ); + + $this->assertSame( array( 'enable_popups' => true ), $result['valid'] ); + $this->assertSame( array( 'enable_maintenance', 'enable_staging', 'scroll_top_icon_url' ), array_keys( $result['skipped'] ) ); + $this->assertStringContainsString( 'never imported', $result['skipped']['enable_maintenance'] ); + } + + public function test_import_does_not_turn_maintenance_on_at_the_destination() { + update_option( 'frontblocks_settings', array( 'enable_maintenance' => false ) ); + + SettingsTransfer::import_from_string( $this->document( array( 'enable_maintenance' => true, 'enable_popups' => true ) ) ); + + $stored = get_option( 'frontblocks_settings' ); + $this->assertFalse( $stored['enable_maintenance'] ); + $this->assertTrue( $stored['enable_popups'] ); + } + + public function test_the_skipped_list_of_the_summary_is_capped() { + $settings = array( 'enable_popups' => true ); + for ( $i = 0; $i < 80; $i++ ) { + $settings[ 'unknown_' . $i . '_' . str_repeat( 'x', 100 ) ] = 1; + } + + $result = SettingsTransfer::import_from_string( $this->document( $settings ) ); + + $this->assertCount( SettingsTransfer::MAX_REPORTED_SKIPPED, $result['skipped'] ); + $this->assertSame( 30, $result['skipped_more'] ); + foreach ( array_keys( $result['skipped'] ) as $key ) { + $this->assertLessThanOrEqual( 60, strlen( $key ) ); + } + } + + public function test_site_bound_keys_use_the_staging_constant() { + $this->assertContains( \FrontBlocks\Frontend\Staging::RESTRICT_ACCESS, SettingsTransfer::SITE_BOUND_KEYS ); + } + + public function test_the_skipped_list_is_not_capped_when_it_is_short() { + $result = SettingsTransfer::import_from_string( $this->document( array( 'enable_popups' => true, 'bogus' => 1 ) ) ); + + $this->assertSame( array( 'bogus' => 'unknown setting' ), $result['skipped'] ); + $this->assertSame( 0, $result['skipped_more'] ); + } + + public function test_a_file_that_touches_neither_short_description_option_turns_move_off_when_both_are_on() { + update_option( + 'frontblocks_settings', + array( + 'deactivate_short_description' => true, + 'move_content_to_short_description' => true, + ) + ); + + $result = SettingsTransfer::apply_settings( array( 'enable_popups' => 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'] ); + } + + 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() { + add_filter( 'frontblocks_export_unavailable_keys', '__return_empty_array' ); + 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'] ); + } + + public function test_export_leaves_out_the_modules_this_site_cannot_use() { + // The test site has no FrontBlocks PRO, so its modules are off only because they are missing. + update_option( 'frontblocks_settings', array( 'enable_back_button' => true ) ); + + $unavailable = SettingsTransfer::get_unavailable_keys(); + $settings = SettingsTransfer::build_export_payload()['settings']; + + foreach ( array_merge( Settings::get_pro_option_keys(), array( 'enable_custom_post_types' ) ) as $key ) { + $this->assertContains( $key, $unavailable, $key ); + $this->assertArrayNotHasKey( $key, $settings, $key ); + } + $this->assertTrue( $settings['enable_back_button'], 'Modules of FrontBlocks itself still travel.' ); + $this->assertArrayHasKey( 'enable_testimonials', $settings ); + } + + public function test_woocommerce_toggles_are_left_out_without_woocommerce() { + add_filter( + 'frontblocks_export_unavailable_keys', + function ( $keys ) { + // Keep only what WooCommerce decides, as on a site with a PRO license. + return array_values( array_diff( $keys, array( 'enable_fullpage_scroll', 'enable_language_banner', 'enable_popups', 'enable_custom_post_types' ) ) ); + } + ); + + $unavailable = SettingsTransfer::get_unavailable_keys(); + + foreach ( Settings::get_woocommerce_option_keys() as $key ) { + if ( class_exists( 'WooCommerce' ) ) { + $this->assertNotContains( $key, $unavailable, $key ); + } else { + $this->assertContains( $key, $unavailable, $key ); + } + } + } + + public function test_an_import_from_a_site_without_a_module_leaves_it_alone() { + // Source site: no FrontBlocks PRO. + update_option( 'frontblocks_settings', array( 'enable_back_button' => true ) ); + $exported = wp_json_encode( SettingsTransfer::build_export_payload() ); + + // Destination site: uses popups and a WooCommerce feature. + update_option( + 'frontblocks_settings', + array( + 'enable_back_button' => false, + 'enable_popups' => true, + 'disable_cart_coupon' => true, + ) + ); + $this->register_settings_filters(); + $result = SettingsTransfer::import_from_string( $exported ); + remove_all_filters( 'sanitize_option_frontblocks_settings' ); + + $stored = get_option( 'frontblocks_settings' ); + $this->assertTrue( $stored['enable_back_button'] ); + $this->assertTrue( $stored['enable_popups'], 'A module the source site does not have stays as it was.' ); + $this->assertTrue( $stored['disable_cart_coupon'] ); + $this->assertNotContains( 'enable_popups', $result['applied'] ); + } + + public function test_pro_features_of_the_screen_match_the_pro_keys() { + $settings = new Settings(); + $method = new ReflectionMethod( Settings::class, 'is_pro_feature' ); + $method->setAccessible( true ); + + foreach ( Settings::get_pro_option_keys() as $key ) { + $this->assertTrue( $method->invoke( $settings, $key ), $key ); + } + $this->assertFalse( $method->invoke( $settings, 'enable_back_button' ) ); + } + + /* + * --------------------------------------------------------------- + * 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->assertStringContainsString( 'and 7 more', $html ); + $this->assertStringNotContainsString( '