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 ); + ?> +
+ +:
+ +
+ +