if ( str_starts_with( $css_property, '--wp--style--root--' ) && ( static::ROOT_BLOCK_SELECTOR !== $selector || ! $use_root_padding ) ) { continue; } /* * Root-level padding styles don't currently support strings with CSS shorthand values. * This may change: https://github.com/WordPress/gutenberg/issues/40132. */ if ( '--wp--style--root--padding' === $css_property && is_string( $value ) ) { continue; } if ( str_starts_with( $css_property, '--wp--style--root--' ) && $use_root_padding ) { $root_variable_duplicates[] = substr( $css_property, strlen( '--wp--style--root--' ) ); } /* * Look up protected properties, keyed by value path. * Skip protected properties that are explicitly set to `null`. */ if ( is_array( $value_path ) ) { $path_string = implode( '.', $value_path ); if ( isset( static::PROTECTED_PROPERTIES[ $path_string ] ) && _wp_array_get( $settings, static::PROTECTED_PROPERTIES[ $path_string ], null ) === null ) { continue; } } // Processes background styles. if ( 'background' === $value_path[0] && isset( $styles['background'] ) ) { $background_styles = wp_style_engine_get_styles( array( 'background' => $styles['background'] ) ); $value = isset( $background_styles['declarations'][ $css_property ] ) ? $background_styles['declarations'][ $css_property ] : $value; } // Skip if empty and not "0" or value represents array of longhand values. $has_missing_value = empty( $value ) && ! is_numeric( $value ); if ( $has_missing_value || is_array( $value ) ) { continue; } // Calculates fluid typography rules where available. if ( 'font-size' === $css_property ) { /* * wp_get_typography_font_size_value() will check * if fluid typography has been activated and also * whether the incoming value can be converted to a fluid value. * Values that already have a clamp() function will not pass the test, * and therefore the original $value will be returned. * Pass the current theme_json settings to override any global settings. */ $value = wp_get_typography_font_size_value( array( 'size' => $value ), $settings ); } if ( 'aspect-ratio' === $css_property ) { // For aspect ratio to work, other dimensions rules must be unset. // This ensures that a fixed height does not override the aspect ratio. $declarations[] = array( 'name' => 'min-height', 'value' => 'unset', ); } $declarations[] = array( 'name' => $css_property, 'value' => $value, ); } // If a variable value is added to the root, the corresponding property should be removed. foreach ( $root_variable_duplicates as $duplicate ) { $discard = array_search( $duplicate, array_column( $declarations, 'name' ), true ); if ( is_numeric( $discard ) ) { array_splice( $declarations, $discard, 1 ); } } return $declarations; } /** * Returns the style property for the given path. * * It also converts references to a path to the value * stored at that location, e.g. * { "ref": "style.color.background" } => "#fff". * * @since 5.8.0 * @since 5.9.0 Added support for values of array type, which are returned as is. * @since 6.1.0 Added the `$theme_json` parameter. * @since 6.3.0 It no longer converts the internal format "var:preset|color|secondary" * to the standard form "--wp--preset--color--secondary". * This is already done by the sanitize method, * so every property will be in the standard form. * * @param array $styles Styles subtree. * @param array $path Which property to process. * @param array $theme_json Theme JSON array. * @return string|array Style property value. */ protected static function get_property_value( $styles, $path, $theme_json = null ) { $value = _wp_array_get( $styles, $path, '' ); if ( '' === $value || null === $value ) { // No need to process the value further. return ''; } /* * This converts references to a path to the value at that path * where the values is an array with a "ref" key, pointing to a path. * For example: { "ref": "style.color.background" } => "#fff". */ if ( is_array( $value ) && isset( $value['ref'] ) ) { $value_path = explode( '.', $value['ref'] ); $ref_value = _wp_array_get( $theme_json, $value_path ); // Only use the ref value if we find anything. if ( ! empty( $ref_value ) && is_string( $ref_value ) ) { $value = $ref_value; } if ( is_array( $ref_value ) && isset( $ref_value['ref'] ) ) { $path_string = json_encode( $path ); $ref_value_string = json_encode( $ref_value ); _doing_it_wrong( 'get_property_value', sprintf( /* translators: 1: theme.json, 2: Value name, 3: Value path, 4: Another value name. */ __( 'Your %1$s file uses a dynamic value (%2$s) for the path at %3$s. However, the value at %3$s is also a dynamic value (pointing to %4$s) and pointing to another dynamic value is not supported. Please update %3$s to point directly to %4$s.' ), 'theme.json', $ref_value_string, $path_string, $ref_value['ref'] ), '6.1.0' ); } } if ( is_array( $value ) ) { return $value; } return $value; } /** * Builds metadata for the setting nodes, which returns in the form of: * * [ * [ * 'path' => ['path', 'to', 'some', 'node' ], * 'selector' => 'CSS selector for some node' * ], * [ * 'path' => [ 'path', 'to', 'other', 'node' ], * 'selector' => 'CSS selector for other node' * ], * ] * * @since 5.8.0 * * @param array $theme_json The tree to extract setting nodes from. * @param array $selectors List of selectors per block. * @return array An array of setting nodes metadata. */ protected static function get_setting_nodes( $theme_json, $selectors = array() ) { $nodes = array(); if ( ! isset( $theme_json['settings'] ) ) { return $nodes; } // Top-level. $nodes[] = array( 'path' => array( 'settings' ), 'selector' => static::ROOT_CSS_PROPERTIES_SELECTOR, ); // Calculate paths for blocks. if ( ! isset( $theme_json['settings']['blocks'] ) ) { return $nodes; } foreach ( $theme_json['settings']['blocks'] as $name => $node ) { $selector = null; if ( isset( $selectors[ $name ]['selector'] ) ) { $selector = $selectors[ $name ]['selector']; } $nodes[] = array( 'path' => array( 'settings', 'blocks', $name ), 'selector' => $selector, ); } return $nodes; } /** * Builds metadata for the style nodes, which returns in the form of: * * [ * [ * 'path' => [ 'path', 'to', 'some', 'node' ], * 'selector' => 'CSS selector for some node', * 'duotone' => 'CSS selector for duotone for some node' * ], * [ * 'path' => ['path', 'to', 'other', 'node' ], * 'selector' => 'CSS selector for other node', * 'duotone' => null * ], * ] * * @since 5.8.0 * @since 6.6.0 Added options array for modifying generated nodes. * * @param array $theme_json The tree to extract style nodes from. * @param array $selectors List of selectors per block. * @param array $options { * Optional. An array of options for now used for internal purposes only (may change without notice). * * @type bool $include_block_style_variations Includes style nodes for block style variations. Default false. * } * @return array An array of style nodes metadata. */ protected static function get_style_nodes( $theme_json, $selectors = array(), $options = array() ) { $nodes = array(); if ( ! isset( $theme_json['styles'] ) ) { return $nodes; } // Top-level. $nodes[] = array( 'path' => array( 'styles' ), 'selector' => static::ROOT_BLOCK_SELECTOR, ); if ( isset( $theme_json['styles']['elements'] ) ) { foreach ( self::ELEMENTS as $element => $selector ) { if ( ! isset( $theme_json['styles']['elements'][ $element ] ) ) { continue; } $nodes[] = array( 'path' => array( 'styles', 'elements', $element ), 'selector' => static::ELEMENTS[ $element ], ); // Handle any pseudo selectors for the element. if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) { foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) { if ( isset( $theme_json['styles']['elements'][ $element ][ $pseudo_selector ] ) ) { $nodes[] = array( 'path' => array( 'styles', 'elements', $element ), 'selector' => static::append_to_selector( static::ELEMENTS[ $element ], $pseudo_selector ), ); } } } } } // Blocks. if ( ! isset( $theme_json['styles']['blocks'] ) ) { return $nodes; } $block_nodes = static::get_block_nodes( $theme_json, $selectors, $options ); foreach ( $block_nodes as $block_node ) { $nodes[] = $block_node; } /** * Filters the list of style nodes with metadata. * * This allows for things like loading block CSS independently. * * @since 6.1.0 * * @param array $nodes Style nodes with metadata. */ return apply_filters( 'wp_theme_json_get_style_nodes', $nodes ); } /** * A public helper to get the block nodes from a theme.json file. * * @since 6.1.0 * * @return array The block nodes in theme.json. */ public function get_styles_block_nodes() { return static::get_block_nodes( $this->theme_json ); } /** * Returns a filtered declarations array if there is a separator block with only a background * style defined in theme.json by adding a color attribute to reflect the changes in the front. * * @since 6.1.1 * * @param array $declarations List of declarations. * @return array $declarations List of declarations filtered. */ private static function update_separator_declarations( $declarations ) { $background_color = ''; $border_color_matches = false; $text_color_matches = false; foreach ( $declarations as $declaration ) { if ( 'background-color' === $declaration['name'] && ! $background_color && isset( $declaration['value'] ) ) { $background_color = $declaration['value']; } elseif ( 'border-color' === $declaration['name'] ) { $border_color_matches = true; } elseif ( 'color' === $declaration['name'] ) { $text_color_matches = true; } if ( $background_color && $border_color_matches && $text_color_matches ) { break; } } if ( $background_color && ! $border_color_matches && ! $text_color_matches ) { $declarations[] = array( 'name' => 'color', 'value' => $background_color, ); } return $declarations; } /** * An internal method to get the block nodes from a theme.json file. * * @since 6.1.0 * @since 6.3.0 Refactored and stabilized selectors API. * @since 6.6.0 Added optional selectors and options for generating block nodes. * * @param array $theme_json The theme.json converted to an array. * @param array $selectors Optional list of selectors per block. * @param array $options { * Optional. An array of options for now used for internal purposes only (may change without notice). * * @type bool $include_block_style_variations Includes nodes for block style variations. Default false. * } * @return array The block nodes in theme.json. */ private static function get_block_nodes( $theme_json, $selectors = array(), $options = array() ) { $selectors = empty( $selectors ) ? static::get_blocks_metadata() : $selectors; $nodes = array(); if ( ! isset( $theme_json['styles'] ) ) { return $nodes; } // Blocks. if ( ! isset( $theme_json['styles']['blocks'] ) ) { return $nodes; } foreach ( $theme_json['styles']['blocks'] as $name => $node ) { $selector = null; if ( isset( $selectors[ $name ]['selector'] ) ) { $selector = $selectors[ $name ]['selector']; } $duotone_selector = null; if ( isset( $selectors[ $name ]['duotone'] ) ) { $duotone_selector = $selectors[ $name ]['duotone']; } $feature_selectors = null; if ( isset( $selectors[ $name ]['selectors'] ) ) { $feature_selectors = $selectors[ $name ]['selectors']; } $variation_selectors = array(); $include_variations = $options['include_block_style_variations'] ?? false; if ( $include_variations && isset( $node['variations'] ) ) { foreach ( $node['variations'] as $variation => $node ) { $variation_selectors[] = array( 'path' => array( 'styles', 'blocks', $name, 'variations', $variation ), 'selector' => $selectors[ $name ]['styleVariations'][ $variation ], ); } } $nodes[] = array( 'name' => $name, 'path' => array( 'styles', 'blocks', $name ), 'selector' => $selector, 'selectors' => $feature_selectors, 'duotone' => $duotone_selector, 'features' => $feature_selectors, 'variations' => $variation_selectors, ); if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'] ) ) { foreach ( $theme_json['styles']['blocks'][ $name ]['elements'] as $element => $node ) { $nodes[] = array( 'path' => array( 'styles', 'blocks', $name, 'elements', $element ), 'selector' => $selectors[ $name ]['elements'][ $element ], ); // Handle any pseudo selectors for the element. if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) { foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) { if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'][ $element ][ $pseudo_selector ] ) ) { $nodes[] = array( 'path' => array( 'styles', 'blocks', $name, 'elements', $element ), 'selector' => static::append_to_selector( $selectors[ $name ]['elements'][ $element ], $pseudo_selector ), ); } } } } } } return $nodes; } /** * Gets the CSS rules for a particular block from theme.json. * * @since 6.1.0 * @since 6.6.0 Setting a min-height of HTML when root styles have a background gradient or image. * Updated general global styles specificity to 0-1-0. * Fixed custom CSS output in block style variations. * * @param array $block_metadata Metadata about the block to get styles for. * * @return string Styles for the block. */ public function get_styles_for_block( $block_metadata ) { $node = _wp_array_get( $this->theme_json, $block_metadata['path'], array() ); $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments']; $selector = $block_metadata['selector']; $settings = isset( $this->theme_json['settings'] ) ? $this->theme_json['settings'] : array(); $feature_declarations = static::get_feature_declarations_for_node( $block_metadata, $node ); $is_root_selector = static::ROOT_BLOCK_SELECTOR === $selector; // If there are style variations, generate the declarations for them, including any feature selectors the block may have. $style_variation_declarations = array(); $style_variation_custom_css = array(); if ( ! empty( $block_metadata['variations'] ) ) { foreach ( $block_metadata['variations'] as $style_variation ) { $style_variation_node = _wp_array_get( $this->theme_json, $style_variation['path'], array() ); $clean_style_variation_selector = trim( $style_variation['selector'] ); // Generate any feature/subfeature style declarations for the current style variation. $variation_declarations = static::get_feature_declarations_for_node( $block_metadata, $style_variation_node ); // Combine selectors with style variation's selector and add to overall style variation declarations. foreach ( $variation_declarations as $current_selector => $new_declarations ) { // If current selector includes block classname, remove it but leave the whitespace in. $shortened_selector = str_replace( $block_metadata['selector'] . ' ', ' ', $current_selector ); // Prepend the variation selector to the current selector. $split_selectors = explode( ',', $shortened_selector ); $updated_selectors = array_map( static function ( $split_selector ) use ( $clean_style_variation_selector ) { return $clean_style_variation_selector . $split_selector; }, $split_selectors ); $combined_selectors = implode( ',', $updated_selectors ); // Add the new declarations to the overall results under the modified selector. $style_variation_declarations[ $combined_selectors ] = $new_declarations; } // Compute declarations for remaining styles not covered by feature level selectors. $style_variation_declarations[ $style_variation['selector'] ] = static::compute_style_properties( $style_variation_node, $settings, null, $this->theme_json ); // Store custom CSS for the style variation. if ( isset( $style_variation_node['css'] ) ) { $style_variation_custom_css[ $style_variation['selector'] ] = $this->process_blocks_custom_css( $style_variation_node['css'], $style_variation['selector'] ); } } } /* * Get a reference to element name from path. * $block_metadata['path'] = array( 'styles','elements','link' ); * Make sure that $block_metadata['path'] describes an element node, like [ 'styles', 'element', 'link' ]. * Skip non-element paths like just ['styles']. */ $is_processing_element = in_array( 'elements', $block_metadata['path'], true ); $current_element = $is_processing_element ? $block_metadata['path'][ count( $block_metadata['path'] ) - 1 ] : null; $element_pseudo_allowed = array(); if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) { $element_pseudo_allowed = static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ]; } /* * Check for allowed pseudo classes (e.g. ":hover") from the $selector ("a:hover"). * This also resets the array keys. */ $pseudo_matches = array_values( array_filter( $element_pseudo_allowed, static function ( $pseudo_selector ) use ( $selector ) { return str_contains( $selector, $pseudo_selector ); } ) ); $pseudo_selector = isset( $pseudo_matches[0] ) ? $pseudo_matches[0] : null; /* * If the current selector is a pseudo selector that's defined in the allow list for the current * element then compute the style properties for it. * Otherwise just compute the styles for the default selector as normal. */ if ( $pseudo_selector && isset( $node[ $pseudo_selector ] ) && isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) && in_array( $pseudo_selector, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ], true ) ) { $declarations = static::compute_style_properties( $node[ $pseudo_selector ], $settings, null, $this->theme_json, $selector, $use_root_padding ); } else { $declarations = static::compute_style_properties( $node, $settings, null, $this->theme_json, $selector, $use_root_padding ); } $block_rules = ''; /* * 1. Bespoke declaration modifiers: * - 'filter': Separate the declarations that use the general selector * from the ones using the duotone selector. * - 'background|background-image': set the html min-height to 100% * to ensure the background covers the entire viewport. */ $declarations_duotone = array(); $should_set_root_min_height = false; foreach ( $declarations as $index => $declaration ) { if ( 'filter' === $declaration['name'] ) { /* * 'unset' filters happen when a filter is unset * in the site-editor UI. Because the 'unset' value * in the user origin overrides the value in the * theme origin, we can skip rendering anything * here as no filter needs to be applied anymore. * So only add declarations to with values other * than 'unset'. */ if ( 'unset' !== $declaration['value'] ) { $declarations_duotone[] = $declaration; } unset( $declarations[ $index ] ); } if ( $is_root_selector && ( 'background-image' === $declaration['name'] || 'background' === $declaration['name'] ) ) { $should_set_root_min_height = true; } } /* * If root styles has a background-image or a background (gradient) set, * set the min-height to '100%'. Minus `--wp-admin--admin-bar--height` for logged-in view. * Setting the CSS rule on the HTML tag ensures background gradients and images behave similarly, * and matches the behavior of the site editor. */ if ( $should_set_root_min_height ) { $block_rules .= static::to_ruleset( 'html', array( array( 'name' => 'min-height', 'value' => 'calc(100% - var(--wp-admin--admin-bar--height, 0px))', ), ) ); } // Update declarations if there are separators with only background color defined. if ( '.wp-block-separator' === $selector ) { $declarations = static::update_separator_declarations( $declarations ); } /* * Top-level element styles using element-only specificity selectors should * not get wrapped in `:root :where()` to maintain backwards compatibility. * * Pseudo classes, e.g. :hover, :focus etc., are a class-level selector so * still need to be wrapped in `:root :where` to cap specificity for nested * variations etc. Pseudo selectors won't match the ELEMENTS selector exactly. */ $element_only_selector = $current_element && isset( static::ELEMENTS[ $current_element ] ) && // buttons, captions etc. still need `:root :where()` as they are class based selectors. ! isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $current_element ] ) && static::ELEMENTS[ $current_element ] === $selector; // 2. Generate and append the rules that use the general selector. $general_selector = $element_only_selector ? $selector : ":root :where($selector)"; $block_rules .= static::to_ruleset( $general_selector, $declarations ); // 3. Generate and append the rules that use the duotone selector. if ( isset( $block_metadata['duotone'] ) && ! empty( $declarations_duotone ) ) { $block_rules .= static::to_ruleset( $block_metadata['duotone'], $declarations_duotone ); } // 4. Generate Layout block gap styles. if ( ! $is_root_selector && ! empty( $block_metadata['name'] ) ) { $block_rules .= $this->get_layout_styles( $block_metadata ); } // 5. Generate and append the feature level rulesets. foreach ( $feature_declarations as $feature_selector => $individual_feature_declarations ) { $block_rules .= static::to_ruleset( ":root :where($feature_selector)", $individual_feature_declarations ); } // 6. Generate and append the style variation rulesets. foreach ( $style_variation_declarations as $style_variation_selector => $individual_style_variation_declarations ) { $block_rules .= static::to_ruleset( ":root :where($style_variation_selector)", $individual_style_variation_declarations ); if ( isset( $style_variation_custom_css[ $style_variation_selector ] ) ) { $block_rules .= $style_variation_custom_css[ $style_variation_selector ]; } } // 7. Generate and append any custom CSS rules pertaining to nested block style variations. if ( isset( $node['css'] ) && ! $is_root_selector ) { $block_rules .= $this->process_blocks_custom_css( $node['css'], $selector ); } return $block_rules; } /** * Outputs the CSS for layout rules on the root. * * @since 6.1.0 * @since 6.6.0 Use `ROOT_CSS_PROPERTIES_SELECTOR` for CSS custom properties and improved consistency of root padding rules. * Updated specificity of body margin reset and first/last child selectors. * * @param string $selector The root node selector. * @param array $block_metadata The metadata for the root block. * @return string The additional root rules CSS. */ public function get_root_layout_rules( $selector, $block_metadata ) { $css = ''; $settings = isset( $this->theme_json['settings'] ) ? $this->theme_json['settings'] : array(); $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments']; /* * If there are content and wide widths in theme.json, output them * as custom properties on the body element so all blocks can use them. */ if ( isset( $settings['layout']['contentSize'] ) || isset( $settings['layout']['wideSize'] ) ) { $content_size = isset( $settings['layout']['contentSize'] ) ? $settings['layout']['contentSize'] : $settings['layout']['wideSize']; $content_size = static::is_safe_css_declaration( 'max-width', $content_size ) ? $content_size : 'initial'; $wide_size = isset( $settings['layout']['wideSize'] ) ? $settings['layout']['wideSize'] : $settings['layout']['contentSize']; $wide_size = static::is_safe_css_declaration( 'max-width', $wide_size ) ? $wide_size : 'initial'; $css .= static::ROOT_CSS_PROPERTIES_SELECTOR . ' { --wp--style--global--content-size: ' . $content_size . ';'; $css .= '--wp--style--global--wide-size: ' . $wide_size . '; }'; } /* * Reset default browser margin on the body element. * This is set on the body selector **before** generating the ruleset * from the `theme.json`. This is to ensure that if the `theme.json` declares * `margin` in its `spacing` declaration for the `body` element then these * user-generated values take precedence in the CSS cascade. * @link https://github.com/WordPress/gutenberg/issues/36147. */ $css .= ':where(body) { margin: 0; }'; if ( $use_root_padding ) { // Top and bottom padding are applied to the outer block container. $css .= '.wp-site-blocks { padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom); }'; // Right and left padding are applied to the first container with `.has-global-padding` class. $css .= '.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }'; // Alignfull children of the container with left and right padding have negative margins so they can still be full width. $css .= '.has-global-padding > .alignfull { margin-right: calc(var(--wp--style--root--padding-right) * -1); margin-left: calc(var(--wp--style--root--padding-left) * -1); }'; // Nested children of the container with left and right padding that are not full aligned do not get padding, unless they are direct children of an alignfull flow container. $css .= '.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) { padding-right: 0; padding-left: 0; }'; // Alignfull direct children of the containers that are targeted by the rule above do not need negative margins. $css .= '.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) > .alignfull { margin-left: 0; margin-right: 0; }'; } $css .= '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }'; $css .= '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }'; $css .= '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }'; // Block gap styles will be output unless explicitly set to `null`. See static::PROTECTED_PROPERTIES. if ( isset( $this->theme_json['settings']['spacing']['blockGap'] ) ) { $block_gap_value = static::get_property_value( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ) ); $css .= ":where(.wp-site-blocks) > * { margin-block-start: $block_gap_value; margin-block-end: 0; }"; $css .= ':where(.wp-site-blocks) > :first-child { margin-block-start: 0; }'; $css .= ':where(.wp-site-blocks) > :last-child { margin-block-end: 0; }'; // For backwards compatibility, ensure the legacy block gap CSS variable is still available. $css .= static::ROOT_CSS_PROPERTIES_SELECTOR . " { --wp--style--block-gap: $block_gap_value; }"; } $css .= $this->get_layout_styles( $block_metadata ); return $css; } /** * For metadata values that can either be booleans or paths to booleans, gets the value. * * $data = array( * 'color' => array( * 'defaultPalette' => true * ) * ); * * static::get_metadata_boolean( $data, false ); * // => false * * static::get_metadata_boolean( $data, array( 'color', 'defaultPalette' ) ); * // => true * * @since 6.0.0 * * @param array $data The data to inspect. * @param bool|array $path Boolean or path to a boolean. * @param bool $default_value Default value if the referenced path is missing. * Default false. * @return bool Value of boolean metadata. */ protected static function get_metadata_boolean( $data, $path, $default_value = false ) { if ( is_bool( $path ) ) { return $path; } if ( is_array( $path ) ) { $value = _wp_array_get( $data, $path ); if ( null !== $value ) { return $value; } } return $default_value; } /** * Merges new incoming data. * * @since 5.8.0 * @since 5.9.0 Duotone preset also has origins. * * @param WP_Theme_JSON $incoming Data to merge. */ public function merge( $incoming ) { $incoming_data = $incoming->get_raw_data(); $this->theme_json = array_replace_recursive( $this->theme_json, $incoming_data ); /* * Recompute all the spacing sizes based on the new hierarchy of data. In the constructor * spacingScale and spacingSizes are both keyed by origin and VALID_ORIGINS is ordered, so * we can allow partial spacingScale data to inherit missing data from earlier layers when * computing the spacing sizes. * * This happens before the presets are merged to ensure that default spacing sizes can be * removed from the theme origin if $prevent_override is true. */ $flattened_spacing_scale = array(); foreach ( static::VALID_ORIGINS as $origin ) { $scale_path = array( 'settings', 'spacing', 'spacingScale', $origin ); // Apply the base spacing scale to the current layer. $base_spacing_scale = _wp_array_get( $this->theme_json, $scale_path, array() ); $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $base_spacing_scale ); $spacing_scale = _wp_array_get( $incoming_data, $scale_path, null ); if ( ! isset( $spacing_scale ) ) { continue; } // Allow partial scale settings by merging with lower layers. $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $spacing_scale ); // Generate and merge the scales for this layer. $sizes_path = array( 'settings', 'spacing', 'spacingSizes', $origin ); $spacing_sizes = _wp_array_get( $incoming_data, $sizes_path, array() ); $spacing_scale_sizes = static::compute_spacing_sizes( $flattened_spacing_scale ); $merged_spacing_sizes = static::merge_spacing_sizes( $spacing_scale_sizes, $spacing_sizes ); _wp_array_set( $incoming_data, $sizes_path, $merged_spacing_sizes ); } /* * The array_replace_recursive algorithm merges at the leaf level, * but we don't want leaf arrays to be merged, so we overwrite it. * * For leaf values that are sequential arrays it will use the numeric indexes for replacement. * We rather replace the existing with the incoming value, if it exists. * This is the case of spacing.units. * * For leaf values that are associative arrays it will merge them as expected. * This is also not the behavior we want for the current associative arrays (presets). * We rather replace the existing with the incoming value, if it exists. * This happens, for example, when we merge data from theme.json upon existing * theme supports or when we merge anything coming from the same source twice. * This is the case of color.palette, color.gradients, color.duotone, * typography.fontSizes, or typography.fontFamilies. * * Additionally, for some preset types, we also want to make sure the * values they introduce don't conflict with default values. We do so * by checking the incoming slugs for theme presets and compare them * with the equivalent default presets: if a slug is present as a default * we remove it from the theme presets. */ $nodes = static::get_setting_nodes( $incoming_data ); $slugs_global = static::get_default_slugs( $this->theme_json, array( 'settings' ) ); foreach ( $nodes as $node ) { // Replace the spacing.units. $path = $node['path']; $path[] = 'spacing'; $path[] = 'units'; $content = _wp_array_get( $incoming_data, $path, null ); if ( isset( $content ) ) { _wp_array_set( $this->theme_json, $path, $content ); } // Replace the presets. foreach ( static::PRESETS_METADATA as $preset_metadata ) { $prevent_override = $preset_metadata['prevent_override']; if ( is_array( $prevent_override ) ) { $prevent_override = _wp_array_get( $this->theme_json['settings'], $preset_metadata['prevent_override'] ); } foreach ( static::VALID_ORIGINS as $origin ) { $base_path = $node['path']; foreach ( $preset_metadata['path'] as $leaf ) { $base_path[] = $leaf; } $path = $base_path; $path[] = $origin; $content = _wp_array_get( $incoming_data, $path, null ); if ( ! isset( $content ) ) { continue; } // Set names for theme presets based on the slug if they are not set and can use default names. if ( 'theme' === $origin && $preset_metadata['use_default_names'] ) { foreach ( $content as $key => $item ) { if ( ! isset( $item['name'] ) ) { $name = static::get_name_from_defaults( $item['slug'], $base_path ); if ( null !== $name ) { $content[ $key ]['name'] = $name; } } } } // Filter out default slugs from theme presets when defaults should not be overridden. if ( 'theme' === $origin && $prevent_override ) { $slugs_node = static::get_default_slugs( $this->theme_json, $node['path'] ); $preset_global = _wp_array_get( $slugs_global, $preset_metadata['path'], array() ); $preset_node = _wp_array_get( $slugs_node, $preset_metadata['path'], array() ); $preset_slugs = array_merge_recursive( $preset_global, $preset_node ); $content = static::filter_slugs( $content, $preset_slugs ); } _wp_array_set( $this->theme_json, $path, $content ); } } } } /** * Converts all filter (duotone) presets into SVGs. * * @since 5.9.1 * * @param array $origins List of origins to process. * @return string SVG filters. */ public function get_svg_filters( $origins ) { $blocks_metadata = static::get_blocks_metadata(); $setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata ); $filters = ''; foreach ( $setting_nodes as $metadata ) { $node = _wp_array_get( $this->theme_json, $metadata['path'], array() ); if ( empty( $node['color']['duotone'] ) ) { continue; } $duotone_presets = $node['color']['duotone']; foreach ( $origins as $origin ) { if ( ! isset( $duotone_presets[ $origin ] ) ) { continue; } foreach ( $duotone_presets[ $origin ] as $duotone_preset ) { $filters .= wp_get_duotone_filter_svg( $duotone_preset ); } } } return $filters; } /** * Determines whether a presets should be overridden or not. * * @since 5.9.0 * @deprecated 6.0.0 Use {@see 'get_metadata_boolean'} instead. * * @param array $theme_json The theme.json like structure to inspect. * @param array $path Path to inspect. * @param bool|array $override Data to compute whether to override the preset. * @return bool */ protected static function should_override_preset( $theme_json, $path, $override ) { _deprecated_function( __METHOD__, '6.0.0', 'get_metadata_boolean' ); if ( is_bool( $override ) ) { return $override; } /* * The relationship between whether to override the defaults * and whether the defaults are enabled is inverse: * * - If defaults are enabled => theme presets should not be overridden * - If defaults are disabled => theme presets should be overridden * * For example, a theme sets defaultPalette to false, * making the default palette hidden from the user. * In that case, we want all the theme presets to be present, * so they should override the defaults. */ if ( is_array( $override ) ) { $value = _wp_array_get( $theme_json, array_merge( $path, $override ) ); if ( isset( $value ) ) { return ! $value; } // Search the top-level key if none was found for this node. $value = _wp_array_get( $theme_json, array_merge( array( 'settings' ), $override ) ); if ( isset( $value ) ) { return ! $value; } return true; } } /** * Returns the default slugs for all the presets in an associative array * whose keys are the preset paths and the leaves is the list of slugs. * * For example: * * array( * 'color' => array( * 'palette' => array( 'slug-1', 'slug-2' ), * 'gradients' => array( 'slug-3', 'slug-4' ), * ), * ) * * @since 5.9.0 * * @param array $data A theme.json like structure. * @param array $node_path The path to inspect. It's 'settings' by default. * @return array */ protected static function get_default_slugs( $data, $node_path ) { $slugs = array(); foreach ( static::PRESETS_METADATA as $metadata ) { $path = $node_path; foreach ( $metadata['path'] as $leaf ) { $path[] = $leaf; } $path[] = 'default'; $preset = _wp_array_get( $data, $path, null ); if ( ! isset( $preset ) ) { continue; } $slugs_for_preset = array(); foreach ( $preset as $item ) { if ( isset( $item['slug'] ) ) { $slugs_for_preset[] = $item['slug']; } } _wp_array_set( $slugs, $metadata['path'], $slugs_for_preset ); } return $slugs; } /** * Gets a `default`'s preset name by a provided slug. * * @since 5.9.0 * * @param string $slug The slug we want to find a match from default presets. * @param array $base_path The path to inspect. It's 'settings' by default. * @return string|null */ protected function get_name_from_defaults( $slug, $base_path ) { $path = $base_path; $path[] = 'default'; $default_content = _wp_array_get( $this->theme_json, $path, null ); if ( ! $default_content ) { return null; } foreach ( $default_content as $item ) { if ( $slug === $item['slug'] ) { return $item['name']; } } return null; } /** * Removes the preset values whose slug is equal to any of given slugs. * * @since 5.9.0 * * @param array $node The node with the presets to validate. * @param array $slugs The slugs that should not be overridden. * @return array The new node. */ protected static function filter_slugs( $node, $slugs ) { if ( empty( $slugs ) ) { return $node; } $new_node = array(); foreach ( $node as $value ) { if ( isset( $value['slug'] ) && ! in_array( $value['slug'], $slugs, true ) ) { $new_node[] = $value; } } return $new_node; } /** * Removes insecure data from theme.json. * * @since 5.9.0 * @since 6.3.2 Preserves global styles block variations when securing styles. * @since 6.6.0 Updated to allow variation element styles and $origin parameter. * * @param array $theme_json Structure to sanitize. * @param string $origin Optional. What source of data this object represents. * One of 'blocks', 'default', 'theme', or 'custom'. Default 'theme'. * @return array Sanitized structure. */ public static function remove_insecure_properties( $theme_json, $origin = 'theme' ) { if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) { $origin = 'theme'; } $sanitized = array(); $theme_json = WP_Theme_JSON_Schema::migrate( $theme_json, $origin ); $valid_block_names = array_keys( static::get_blocks_metadata() ); $valid_element_names = array_keys( static::ELEMENTS ); $valid_variations = static::get_valid_block_style_variations(); $theme_json = static::sanitize( $theme_json, $valid_block_names, $valid_element_names, $valid_variations ); $blocks_metadata = static::get_blocks_metadata(); $style_options = array( 'include_block_style_variations' => true ); // Allow variations data. $style_nodes = static::get_style_nodes( $theme_json, $blocks_metadata, $style_options ); foreach ( $style_nodes as $metadata ) { $input = _wp_array_get( $theme_json, $metadata['path'], array() ); if ( empty( $input ) ) { continue; } // The global styles custom CSS is not sanitized, but can only be edited by users with 'edit_css' capability. if ( isset( $input['css'] ) && current_user_can( 'edit_css' ) ) { $output = $input; } else { $output = static::remove_insecure_styles( $input ); } /* * Get a reference to element name from path. * $metadata['path'] = array( 'styles', 'elements', 'link' ); */ $current_element = $metadata['path'][ count( $metadata['path'] ) - 1 ]; /* * $output is stripped of pseudo selectors. Re-add and process them * or insecure styles here. */ if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) { foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] as $pseudo_selector ) { if ( isset( $input[ $pseudo_selector ] ) ) { $output[ $pseudo_selector ] = static::remove_insecure_styles( $input[ $pseudo_selector ] ); } } } if ( ! empty( $output ) ) { _wp_array_set( $sanitized, $metadata['path'], $output ); } if ( isset( $metadata['variations'] ) ) { foreach ( $metadata['variations'] as $variation ) { $variation_input = _wp_array_get( $theme_json, $variation['path'], array() ); if ( empty( $variation_input ) ) { continue; } $variation_output = static::remove_insecure_styles( $variation_input ); // Process a variation's elements and element pseudo selector styles. if ( isset( $variation_input['elements'] ) ) { foreach ( $valid_element_names as $element_name ) { $element_input = $variation_input['elements'][ $element_name ] ?? null; if ( $element_input ) { $element_output = static::remove_insecure_styles( $element_input ); if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) { foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) { if ( isset( $element_input[ $pseudo_selector ] ) ) { $element_output[ $pseudo_selector ] = static::remove_insecure_styles( $element_input[ $pseudo_selector ] ); } } } if ( ! empty( $element_output ) ) { _wp_array_set( $variation_output, array( 'elements', $element_name ), $element_output ); } } } } if ( ! empty( $variation_output ) ) { _wp_array_set( $sanitized, $variation['path'], $variation_output ); } } } } $setting_nodes = static::get_setting_nodes( $theme_json ); foreach ( $setting_nodes as $metadata ) { $input = _wp_array_get( $theme_json, $metadata['path'], array() ); if ( empty( $input ) ) { continue; } $output = static::remove_insecure_settings( $input ); if ( ! empty( $output ) ) { _wp_array_set( $sanitized, $metadata['path'], $output ); } } if ( empty( $sanitized['styles'] ) ) { unset( $theme_json['styles'] ); } else { $theme_json['styles'] = $sanitized['styles']; } if ( empty( $sanitized['settings'] ) ) { unset( $theme_json['settings'] ); } else { $theme_json['settings'] = $sanitized['settings']; } return $theme_json; } /** * Processes a setting node and returns the same node * without the insecure settings. * * @since 5.9.0 * * @param array $input Node to process. * @return array */ protected static function remove_insecure_settings( $input ) { $output = array(); foreach ( static::PRESETS_METADATA as $preset_metadata ) { foreach ( static::VALID_ORIGINS as $origin ) { $path_with_origin = $preset_metadata['path']; $path_with_origin[] = $origin; $presets = _wp_array_get( $input, $path_with_origin, null ); if ( null === $presets ) { continue; } $escaped_preset = array(); foreach ( $presets as $preset ) { if ( esc_attr( esc_html( $preset['name'] ) ) === $preset['name'] && sanitize_html_class( $preset['slug'] ) === $preset['slug'] ) { $value = null; if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) { $value = $preset[ $preset_metadata['value_key'] ]; } elseif ( isset( $preset_metadata['value_func'] ) && is_callable( $preset_metadata['value_func'] ) ) { $value = call_user_func( $preset_metadata['value_func'], $preset ); } $preset_is_valid = true; foreach ( $preset_metadata['properties'] as $property ) { if ( ! static::is_safe_css_declaration( $property, $value ) ) { $preset_is_valid = false; break; } } if ( $preset_is_valid ) { $escaped_preset[] = $preset; } } } if ( ! empty( $escaped_preset ) ) { _wp_array_set( $output, $path_with_origin, $escaped_preset ); } } } // Ensure indirect properties not included in any `PRESETS_METADATA` value are allowed. static::remove_indirect_properties( $input, $output ); return $output; } /** * Processes a style node and returns the same node * without the insecure styles. * * @since 5.9.0 * * @param array $input Node to process. * @return array */ protected static function remove_insecure_styles( $input ) { $output = array(); $declarations = static::compute_style_properties( $input ); foreach ( $declarations as $declaration ) { if ( static::is_safe_css_declaration( $declaration['name'], $declaration['value'] ) ) { $path = static::PROPERTIES_METADATA[ $declaration['name'] ]; /* * Check the value isn't an array before adding so as to not * double up shorthand and longhand styles. */ $value = _wp_array_get( $input, $path, array() ); if ( ! is_array( $value ) ) { _wp_array_set( $output, $path, $value ); } } } // Ensure indirect properties not handled by `compute_style_properties` are allowed. static::remove_indirect_properties( $input, $output ); return $output; } /** * Checks that a declaration provided by the user is safe. * * @since 5.9.0 * * @param string $property_name Property name in a CSS declaration, i.e. the `color` in `color: red`. * @param string $property_value Value in a CSS declaration, i.e. the `red` in `color: red`. * @return bool */ protected static function is_safe_css_declaration( $property_name, $property_value ) { $style_to_validate = $property_name . ': ' . $property_value; $filtered = esc_html( safecss_filter_attr( $style_to_validate ) ); return ! empty( trim( $filtered ) ); } /** * Removes indirect properties from the given input node and * sets in the given output node. * * @since 6.2.0 * * @param array $input Node to process. * @param array $output The processed node. Passed by reference. */ private static function remove_indirect_properties( $input, &$output ) { foreach ( static::INDIRECT_PROPERTIES_METADATA as $property => $paths ) { foreach ( $paths as $path ) { $value = _wp_array_get( $input, $path ); if ( is_string( $value ) && static::is_safe_css_declaration( $property, $value ) ) { _wp_array_set( $output, $path, $value ); } } } } /** * Returns the raw data. * * @since 5.8.0 * * @return array Raw data. */ public function get_raw_data() { return $this->theme_json; } /** * Transforms the given editor settings according the * add_theme_support format to the theme.json format. * * @since 5.8.0 * * @param array $settings Existing editor settings. * @return array Config that adheres to the theme.json schema. */ public static function get_from_editor_settings( $settings ) { $theme_settings = array( 'version' => static::LATEST_SCHEMA, 'settings' => array(), ); // Deprecated theme supports. if ( isset( $settings['disableCustomColors'] ) ) { $theme_settings['settings']['color']['custom'] = ! $settings['disableCustomColors']; } if ( isset( $settings['disableCustomGradients'] ) ) { $theme_settings['settings']['color']['customGradient'] = ! $settings['disableCustomGradients']; } if ( isset( $settings['disableCustomFontSizes'] ) ) { $theme_settings['settings']['typography']['customFontSize'] = ! $settings['disableCustomFontSizes']; } if ( isset( $settings['enableCustomLineHeight'] ) ) { $theme_settings['settings']['typography']['lineHeight'] = $settings['enableCustomLineHeight']; } if ( isset( $settings['enableCustomUnits'] ) ) { $theme_settings['settings']['spacing']['units'] = ( true === $settings['enableCustomUnits'] ) ? array( 'px', 'em', 'rem', 'vh', 'vw', '%' ) : $settings['enableCustomUnits']; } if ( isset( $settings['colors'] ) ) { $theme_settings['settings']['color']['palette'] = $settings['colors']; } if ( isset( $settings['gradients'] ) ) { $theme_settings['settings']['color']['gradients'] = $settings['gradients']; } if ( isset( $settings['fontSizes'] ) ) { $font_sizes = $settings['fontSizes']; // Back-compatibility for presets without units. foreach ( $font_sizes as $key => $font_size ) { if ( is_numeric( $font_size['size'] ) ) { $font_sizes[ $key ]['size'] = $font_size['size'] . 'px'; } } $theme_settings['settings']['typography']['fontSizes'] = $font_sizes; } if ( isset( $settings['enableCustomSpacing'] ) ) { $theme_settings['settings']['spacing']['padding'] = $settings['enableCustomSpacing']; } if ( isset( $settings['spacingSizes'] ) ) { $theme_settings['settings']['spacing']['spacingSizes'] = $settings['spacingSizes']; } return $theme_settings; } /** * Returns the current theme's wanted patterns(slugs) to be * registered from Pattern Directory. * * @since 6.0.0 * * @return string[] */ public function get_patterns() { if ( isset( $this->theme_json['patterns'] ) && is_array( $this->theme_json['patterns'] ) ) { return $this->theme_json['patterns']; } return array(); } /** * Returns a valid theme.json as provided by a theme. * * Unlike get_raw_data() this returns the presets flattened, as provided by a theme. * This also uses appearanceTools instead of their opt-ins if all of them are true. * * @since 6.0.0 * * @return array */ public function get_data() { $output = $this->theme_json; $nodes = static::get_setting_nodes( $output ); /** * Flatten the theme & custom origins into a single one. * * For example, the following: * * { * "settings": { * "color": { * "palette": { * "theme": [ {} ], * "custom": [ {} ] * } * } * } * } * * will be converted to: * * { * "settings": { * "color": { * "palette": [ {} ] * } * } * } */ foreach ( $nodes as $node ) { foreach ( static::PRESETS_METADATA as $preset_metadata ) { $path = $node['path']; foreach ( $preset_metadata['path'] as $preset_metadata_path ) { $path[] = $preset_metadata_path; } $preset = _wp_array_get( $output, $path, null ); if ( null === $preset ) { continue; } $items = array(); if ( isset( $preset['theme'] ) ) { foreach ( $preset['theme'] as $item ) { $slug = $item['slug']; unset( $item['slug'] ); $items[ $slug ] = $item; } } if ( isset( $preset['custom'] ) ) { foreach ( $preset['custom'] as $item ) { $slug = $item['slug']; unset( $item['slug'] ); $items[ $slug ] = $item; } } $flattened_preset = array(); foreach ( $items as $slug => $value ) { $flattened_preset[] = array_merge( array( 'slug' => (string) $slug ), $value ); } _wp_array_set( $output, $path, $flattened_preset ); } } /* * If all of the static::APPEARANCE_TOOLS_OPT_INS are true, * this code unsets them and sets 'appearanceTools' instead. */ foreach ( $nodes as $node ) { $all_opt_ins_are_set = true; foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) { $full_path = $node['path']; foreach ( $opt_in_path as $opt_in_path_item ) { $full_path[] = $opt_in_path_item; } /* * Use "unset prop" as a marker instead of "null" because * "null" can be a valid value for some props (e.g. blockGap). */ $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' ); if ( 'unset prop' === $opt_in_value ) { $all_opt_ins_are_set = false; break; } } if ( $all_opt_ins_are_set ) { $node_path_with_appearance_tools = $node['path']; $node_path_with_appearance_tools[] = 'appearanceTools'; _wp_array_set( $output, $node_path_with_appearance_tools, true ); foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) { $full_path = $node['path']; foreach ( $opt_in_path as $opt_in_path_item ) { $full_path[] = $opt_in_path_item; } /* * Use "unset prop" as a marker instead of "null" because * "null" can be a valid value for some props (e.g. blockGap). */ $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' ); if ( true !== $opt_in_value ) { continue; } /* * The following could be improved to be path independent. * At the moment it relies on a couple of assumptions: * * - all opt-ins having a path of size 2. * - there's two sources of settings: the top-level and the block-level. */ if ( ( 1 === count( $node['path'] ) ) && ( 'settings' === $node['path'][0] ) ) { // Top-level settings. unset( $output['settings'][ $opt_in_path[0] ][ $opt_in_path[1] ] ); if ( empty( $output['settings'][ $opt_in_path[0] ] ) ) { unset( $output['settings'][ $opt_in_path[0] ] ); } } elseif ( ( 3 === count( $node['path'] ) ) && ( 'settings' === $node['path'][0] ) && ( 'blocks' === $node['path'][1] ) ) { // Block-level settings. $block_name = $node['path'][2]; unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ][ $opt_in_path[1] ] ); if ( empty( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ) ) { unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ); } } } } } wp_recursive_ksort( $output ); return $output; } /** * Sets the spacingSizes array based on the spacingScale values from theme.json. * * @since 6.1.0 * @deprecated 6.6.0 No longer used as the spacingSizes are automatically * generated in the constructor and merge methods instead * of manually after instantiation. * * @return null|void */ public function set_spacing_sizes() { _deprecated_function( __METHOD__, '6.6.0' ); $spacing_scale = isset( $this->theme_json['settings']['spacing']['spacingScale'] ) ? $this->theme_json['settings']['spacing']['spacingScale'] : array(); if ( ! isset( $spacing_scale['steps'] ) || ! is_numeric( $spacing_scale['steps'] ) || ! isset( $spacing_scale['mediumStep'] ) || ! isset( $spacing_scale['unit'] ) || ! isset( $spacing_scale['operator'] ) || ! isset( $spacing_scale['increment'] ) || ! isset( $spacing_scale['steps'] ) || ! is_numeric( $spacing_scale['increment'] ) || ! is_numeric( $spacing_scale['mediumStep'] ) || ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ) { if ( ! empty( $spacing_scale ) ) { wp_trigger_error( __METHOD__, sprintf( /* translators: 1: theme.json, 2: settings.spacing.spacingScale */ __( 'Some of the %1$s %2$s values are invalid' ), 'theme.json', 'settings.spacing.spacingScale' ), E_USER_NOTICE ); } return null; } // If theme authors want to prevent the generation of the core spacing scale they can set their theme.json spacingScale.steps to 0. if ( 0 === $spacing_scale['steps'] ) { return null; } $spacing_sizes = static::compute_spacing_sizes( $spacing_scale ); // If there are 7 or fewer steps in the scale revert to numbers for labels instead of t-shirt sizes. if ( $spacing_scale['steps'] <= 7 ) { for ( $spacing_sizes_count = 0; $spacing_sizes_count < count( $spacing_sizes ); $spacing_sizes_count++ ) { $spacing_sizes[ $spacing_sizes_count ]['name'] = (string) ( $spacing_sizes_count + 1 ); } } _wp_array_set( $this->theme_json, array( 'settings', 'spacing', 'spacingSizes', 'default' ), $spacing_sizes ); } /** * Merges two sets of spacing size presets. * * @since 6.6.0 * * @param array $base The base set of spacing sizes. * @param array $incoming The set of spacing sizes to merge with the base. Duplicate slugs will override the base values. * @return array The merged set of spacing sizes. */ private static function merge_spacing_sizes( $base, $incoming ) { // Preserve the order if there are no base (spacingScale) values. if ( empty( $base ) ) { return $incoming; } $merged = array(); foreach ( $base as $item ) { $merged[ $item['slug'] ] = $item; } foreach ( $incoming as $item ) { $merged[ $item['slug'] ] = $item; } ksort( $merged, SORT_NUMERIC ); return array_values( $merged ); } /** * Generates a set of spacing sizes by starting with a medium size and * applying an operator with an increment value to generate the rest of the * sizes outward from the medium size. The medium slug is '50' with the rest * of the slugs being 10 apart. The generated names use t-shirt sizing. * * Example: * * $spacing_scale = array( * 'steps' => 4, * 'mediumStep' => 16, * 'unit' => 'px', * 'operator' => '+', * 'increment' => 2, * ); * $spacing_sizes = static::compute_spacing_sizes( $spacing_scale ); * // -> array( * // array( 'name' => 'Small', 'slug' => '40', 'size' => '14px' ), * // array( 'name' => 'Medium', 'slug' => '50', 'size' => '16px' ), * // array( 'name' => 'Large', 'slug' => '60', 'size' => '18px' ), * // array( 'name' => 'X-Large', 'slug' => '70', 'size' => '20px' ), * // ) * * @since 6.6.0 * * @param array $spacing_scale { * The spacing scale values. All are required. * * @type int $steps The number of steps in the scale. (up to 10 steps are supported.) * @type float $mediumStep The middle value that gets the slug '50'. (For even number of steps, this becomes the first middle value.) * @type string $unit The CSS unit to use for the sizes. * @type string $operator The mathematical operator to apply to generate the other sizes. Either '+' or '*'. * @type float $increment The value used with the operator to generate the other sizes. * } * @return array The spacing sizes presets or an empty array if some spacing scale values are missing or invalid. */ private static function compute_spacing_sizes( $spacing_scale ) { /* * This condition is intentionally missing some checks on ranges for the values in order to * keep backwards compatibility with the previous implementation. */ if ( ! isset( $spacing_scale['steps'] ) || ! is_numeric( $spacing_scale['steps'] ) || 0 === $spacing_scale['steps'] || ! isset( $spacing_scale['mediumStep'] ) || ! is_numeric( $spacing_scale['mediumStep'] ) || ! isset( $spacing_scale['unit'] ) || ! isset( $spacing_scale['operator'] ) || ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) || ! isset( $spacing_scale['increment'] ) || ! is_numeric( $spacing_scale['increment'] ) ) { return array(); } $unit = '%' === $spacing_scale['unit'] ? '%' : sanitize_title( $spacing_scale['unit'] ); $current_step = $spacing_scale['mediumStep']; $steps_mid_point = round( $spacing_scale['steps'] / 2, 0 ); $x_small_count = null; $below_sizes = array(); $slug = 40; $remainder = 0; for ( $below_midpoint_count = $steps_mid_point - 1; $spacing_scale['steps'] > 1 && $slug > 0 && $below_midpoint_count > 0; $below_midpoint_count-- ) { if ( '+' === $spacing_scale['operator'] ) { $current_step -= $spacing_scale['increment']; } elseif ( $spacing_scale['increment'] > 1 ) { $current_step /= $spacing_scale['increment']; } else { $current_step *= $spacing_scale['increment']; } if ( $current_step <= 0 ) { $remainder = $below_midpoint_count; break; } $below_sizes[] = array( /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Small. */ 'name' => $below_midpoint_count === $steps_mid_point - 1 ? __( 'Small' ) : sprintf( __( '%sX-Small' ), (string) $x_small_count ), 'slug' => (string) $slug, 'size' => round( $current_step, 2 ) . $unit, ); if ( $below_midpoint_count === $steps_mid_point - 2 ) { $x_small_count = 2; } if ( $below_midpoint_count < $steps_mid_point - 2 ) { ++$x_small_count; } $slug -= 10; } $below_sizes = array_reverse( $below_sizes ); $below_sizes[] = array( 'name' => __( 'Medium' ), 'slug' => '50', 'size' => $spacing_scale['mediumStep'] . $unit, ); $current_step = $spacing_scale['mediumStep']; $x_large_count = null; $above_sizes = array(); $slug = 60; $steps_above = ( $spacing_scale['steps'] - $steps_mid_point ) + $remainder; for ( $above_midpoint_count = 0; $above_midpoint_count < $steps_above; $above_midpoint_count++ ) { $current_step = '+' === $spacing_scale['operator'] ? $current_step + $spacing_scale['increment'] : ( $spacing_scale['increment'] >= 1 ? $current_step * $spacing_scale['increment'] : $current_step / $spacing_scale['increment'] ); $above_sizes[] = array( /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Large. */ 'name' => 0 === $above_midpoint_count ? __( 'Large' ) : sprintf( __( '%sX-Large' ), (string) $x_large_count ), 'slug' => (string) $slug, 'size' => round( $current_step, 2 ) . $unit, ); if ( 1 === $above_midpoint_count ) { $x_large_count = 2; } if ( $above_midpoint_count > 1 ) { ++$x_large_count; } $slug += 10; } $spacing_sizes = $below_sizes; foreach ( $above_sizes as $above_sizes_item ) { $spacing_sizes[] = $above_sizes_item; } return $spacing_sizes; } /** * This is used to convert the internal representation of variables to the CSS representation. * For example, `var:preset|color|vivid-green-cyan` becomes `var(--wp--preset--color--vivid-green-cyan)`. * * @since 6.3.0 * @param string $value The variable such as var:preset|color|vivid-green-cyan to convert. * @return string The converted variable. */ private static function convert_custom_properties( $value ) { $prefix = 'var:'; $prefix_len = strlen( $prefix ); $token_in = '|'; $token_out = '--'; if ( str_starts_with( $value, $prefix ) ) { $unwrapped_name = str_replace( $token_in, $token_out, substr( $value, $prefix_len ) ); $value = "var(--wp--$unwrapped_name)"; } return $value; } /** * Given a tree, converts the internal representation of variables to the CSS representation. * It is recursive and modifies the input in-place. * * @since 6.3.0 * @param array $tree Input to process. * @return array The modified $tree. */ private static function resolve_custom_css_format( $tree ) { $prefix = 'var:'; foreach ( $tree as $key => $data ) { if ( is_string( $data ) && str_starts_with( $data, $prefix ) ) { $tree[ $key ] = self::convert_custom_properties( $data ); } elseif ( is_array( $data ) ) { $tree[ $key ] = self::resolve_custom_css_format( $data ); } } return $tree; } /** * Returns the selectors metadata for a block. * * @since 6.3.0 * * @param object $block_type The block type. * @param string $root_selector The block's root selector. * * @return array The custom selectors set by the block. */ protected static function get_block_selectors( $block_type, $root_selector ) { if ( ! empty( $block_type->selectors ) ) { return $block_type->selectors; } $selectors = array( 'root' => $root_selector ); foreach ( static::BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS as $key => $feature ) { $feature_selector = wp_get_block_css_selector( $block_type, $key ); if ( null !== $feature_selector ) { $selectors[ $feature ] = array( 'root' => $feature_selector ); } } return $selectors; } /** * Generates all the element selectors for a block. * * @since 6.3.0 * * @param string $root_selector The block's root CSS selector. * @return array The block's element selectors. */ protected static function get_block_element_selectors( $root_selector ) { /* * Assign defaults, then override those that the block sets by itself. * If the block selector is compounded, will append the element to each * individual block selector. */ $block_selectors = explode( ',', $root_selector ); $element_selectors = array(); foreach ( static::ELEMENTS as $el_name => $el_selector ) { $element_selector = array(); foreach ( $block_selectors as $selector ) { if ( $selector === $el_selector ) { $element_selector = array( $el_selector ); break; } $element_selector[] = static::prepend_to_selector( $el_selector, $selector . ' ' ); } $element_selectors[ $el_name ] = implode( ',', $element_selector ); } return $element_selectors; } /** * Generates style declarations for a node's features e.g., color, border, * typography etc. that have custom selectors in their related block's * metadata. * * @since 6.3.0 * * @param object $metadata The related block metadata containing selectors. * @param object $node A merged theme.json node for block or variation. * * @return array The style declarations for the node's features with custom * selectors. */ protected function get_feature_declarations_for_node( $metadata, &$node ) { $declarations = array(); if ( ! isset( $metadata['selectors'] ) ) { return $declarations; } $settings = isset( $this->theme_json['settings'] ) ? $this->theme_json['settings'] : array(); foreach ( $metadata['selectors'] as $feature => $feature_selectors ) { /* * Skip if this is the block's root selector or the block doesn't * have any styles for the feature. */ if ( 'root' === $feature || empty( $node[ $feature ] ) ) { continue; } if ( is_array( $feature_selectors ) ) { foreach ( $feature_selectors as $subfeature => $subfeature_selector ) { if ( 'root' === $subfeature || empty( $node[ $feature ][ $subfeature ] ) ) { continue; } /* * Create temporary node containing only the subfeature data * to leverage existing `compute_style_properties` function. */ $subfeature_node = array( $feature => array( $subfeature => $node[ $feature ][ $subfeature ], ), ); // Generate style declarations. $new_declarations = static::compute_style_properties( $subfeature_node, $settings, null, $this->theme_json ); // Merge subfeature declarations into feature declarations. if ( isset( $declarations[ $subfeature_selector ] ) ) { foreach ( $new_declarations as $new_declaration ) { $declarations[ $subfeature_selector ][] = $new_declaration; } } else { $declarations[ $subfeature_selector ] = $new_declarations; } /* * Remove the subfeature from the block's node now its * styles will be included under its own selector not the * block's. */ unset( $node[ $feature ][ $subfeature ] ); } } /* * Now subfeatures have been processed and removed we can process * feature root selector or simple string selector. */ if ( is_string( $feature_selectors ) || ( isset( $feature_selectors['root'] ) && $feature_selectors['root'] ) ) { $feature_selector = is_string( $feature_selectors ) ? $feature_selectors : $feature_selectors['root']; /* * Create temporary node containing only the feature data * to leverage existing `compute_style_properties` function. */ $feature_node = array( $feature => $node[ $feature ] ); // Generate the style declarations. $new_declarations = static::compute_style_properties( $feature_node, $settings, null, $this->theme_json ); /* * Merge new declarations with any that already exist for * the feature selector. This may occur when multiple block * support features use the same custom selector. */ if ( isset( $declarations[ $feature_selector ] ) ) { foreach ( $new_declarations as $new_declaration ) { $declarations[ $feature_selector ][] = $new_declaration; } } else { $declarations[ $feature_selector ] = $new_declarations; } /* * Remove the feature from the block's node now its styles * will be included under its own selector not the block's. */ unset( $node[ $feature ] ); } } return $declarations; } /** * Replaces CSS variables with their values in place. * * @since 6.3.0 * @since 6.5.0 Check for empty style before processing its value. * * @param array $styles CSS declarations to convert. * @param array $values key => value pairs to use for replacement. * @return array */ private static function convert_variables_to_value( $styles, $values ) { foreach ( $styles as $key => $style ) { if ( empty( $style ) ) { continue; } if ( is_array( $style ) ) { $styles[ $key ] = self::convert_variables_to_value( $style, $values ); continue; } if ( 0 <= strpos( $style, 'var(' ) ) { // find all the variables in the string in the form of var(--variable-name, fallback), with fallback in the second capture group. $has_matches = preg_match_all( '/var\(([^),]+)?,?\s?(\S+)?\)/', $style, $var_parts ); if ( $has_matches ) { $resolved_style = $styles[ $key ]; foreach ( $var_parts[1] as $index => $var_part ) { $key_in_values = 'var(' . $var_part . ')'; $rule_to_replace = $var_parts[0][ $index ]; // the css rule to replace e.g. var(--wp--preset--color--vivid-green-cyan). $fallback = $var_parts[2][ $index ]; // the fallback value. $resolved_style = str_replace( array( $rule_to_replace, $fallback, ), array( isset( $values[ $key_in_values ] ) ? $values[ $key_in_values ] : $rule_to_replace, isset( $values[ $fallback ] ) ? $values[ $fallback ] : $fallback, ), $resolved_style ); } $styles[ $key ] = $resolved_style; } } } return $styles; } /** * Resolves the values of CSS variables in the given styles. * * @since 6.3.0 * @param WP_Theme_JSON $theme_json The theme json resolver. * * @return WP_Theme_JSON The $theme_json with resolved variables. */ public static function resolve_variables( $theme_json ) { $settings = $theme_json->get_settings(); $styles = $theme_json->get_raw_data()['styles']; $preset_vars = static::compute_preset_vars( $settings, static::VALID_ORIGINS ); $theme_vars = static::compute_theme_vars( $settings ); $vars = array_reduce( array_merge( $preset_vars, $theme_vars ), function ( $carry, $item ) { $name = $item['name']; $carry[ "var({$name})" ] = $item['value']; return $carry; }, array() ); $theme_json->theme_json['styles'] = self::convert_variables_to_value( $styles, $vars ); return $theme_json; } /** * Generates a selector for a block style variation. * * @since 6.5.0 * * @param string $variation_name Name of the block style variation. * @param string $block_selector CSS selector for the block. * @return string Block selector with block style variation selector added to it. */ protected static function get_block_style_variation_selector( $variation_name, $block_selector ) { $variation_class = ".is-style-$variation_name"; if ( ! $block_selector ) { return $variation_class; } $limit = 1; $selector_parts = explode( ',', $block_selector ); $result = array(); foreach ( $selector_parts as $part ) { $result[] = preg_replace_callback( '/((?::\([^)]+\))?\s*)([^\s:]+)/', function ( $matches ) use ( $variation_class ) { return $matches[1] . $matches[2] . $variation_class; }, $part, $limit ); } return implode( ',', $result ); } /** * Collects valid block style variations keyed by block type. * * @since 6.6.0 * * @return array Valid block style variations by block type. */ protected static function get_valid_block_style_variations() { $valid_variations = array(); foreach ( self::get_blocks_metadata() as $block_name => $block_meta ) { if ( ! isset( $block_meta['styleVariations'] ) ) { continue; } $valid_variations[ $block_name ] = array_keys( $block_meta['styleVariations'] ); } return $valid_variations; } } * @param int $comment_id Comment ID. */ $message_headers = apply_filters( 'comment_moderation_headers', $message_headers, $comment_id ); foreach ( $emails as $email ) { wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers ); } if ( $switched_locale ) { restore_previous_locale(); } return true; } endif; if ( ! function_exists( 'wp_password_change_notification' ) ) : /** * Notifies the blog admin of a user changing password, normally via email. * * @since 2.7.0 * * @param WP_User $user User object. */ function wp_password_change_notification( $user ) { /* * Send a copy of password change notification to the admin, * but check to see if it's the admin whose password we're changing, and skip this. */ if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) ) { /* translators: %s: User name. */ $message = sprintf( __( 'Password changed for user: %s' ), $user->user_login ) . "\r\n"; /* * The blogname option is escaped with esc_html() on the way into the database in sanitize_option(). * We want to reverse this for the plain text arena of emails. */ $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); $wp_password_change_notification_email = array( 'to' => get_option( 'admin_email' ), /* translators: Password change notification email subject. %s: Site title. */ 'subject' => __( '[%s] Password Changed' ), 'message' => $message, 'headers' => '', ); /** * Filters the contents of the password change notification email sent to the site admin. * * @since 4.9.0 * * @param array $wp_password_change_notification_email { * Used to build wp_mail(). * * @type string $to The intended recipient - site admin email address. * @type string $subject The subject of the email. * @type string $message The body of the email. * @type string $headers The headers of the email. * } * @param WP_User $user User object for user whose password was changed. * @param string $blogname The site title. */ $wp_password_change_notification_email = apply_filters( 'wp_password_change_notification_email', $wp_password_change_notification_email, $user, $blogname ); wp_mail( $wp_password_change_notification_email['to'], wp_specialchars_decode( sprintf( $wp_password_change_notification_email['subject'], $blogname ) ), $wp_password_change_notification_email['message'], $wp_password_change_notification_email['headers'] ); } } endif; if ( ! function_exists( 'wp_new_user_notification' ) ) : /** * Emails login credentials to a newly-registered user. * * A new user registration notification is also sent to admin email. * * @since 2.0.0 * @since 4.3.0 The `$plaintext_pass` parameter was changed to `$notify`. * @since 4.3.1 The `$plaintext_pass` parameter was deprecated. `$notify` added as a third parameter. * @since 4.6.0 The `$notify` parameter accepts 'user' for sending notification only to the user created. * * @param int $user_id User ID. * @param null $deprecated Not used (argument deprecated). * @param string $notify Optional. Type of notification that should happen. Accepts 'admin' or an empty * string (admin only), 'user', or 'both' (admin and user). Default empty. */ function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) { if ( null !== $deprecated ) { _deprecated_argument( __FUNCTION__, '4.3.1' ); } // Accepts only 'user', 'admin' , 'both' or default '' as $notify. if ( ! in_array( $notify, array( 'user', 'admin', 'both', '' ), true ) ) { return; } $user = get_userdata( $user_id ); /* * The blogname option is escaped with esc_html() on the way into the database in sanitize_option(). * We want to reverse this for the plain text arena of emails. */ $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); /** * Filters whether the admin is notified of a new user registration. * * @since 6.1.0 * * @param bool $send Whether to send the email. Default true. * @param WP_User $user User object for new user. */ $send_notification_to_admin = apply_filters( 'wp_send_new_user_notification_to_admin', true, $user ); if ( 'user' !== $notify && true === $send_notification_to_admin ) { $switched_locale = switch_to_locale( get_locale() ); /* translators: %s: Site title. */ $message = sprintf( __( 'New user registration on your site %s:' ), $blogname ) . "\r\n\r\n"; /* translators: %s: User login. */ $message .= sprintf( __( 'Username: %s' ), $user->user_login ) . "\r\n\r\n"; /* translators: %s: User email address. */ $message .= sprintf( __( 'Email: %s' ), $user->user_email ) . "\r\n"; $wp_new_user_notification_email_admin = array( 'to' => get_option( 'admin_email' ), /* translators: New user registration notification email subject. %s: Site title. */ 'subject' => __( '[%s] New User Registration' ), 'message' => $message, 'headers' => '', ); /** * Filters the contents of the new user notification email sent to the site admin. * * @since 4.9.0 * * @param array $wp_new_user_notification_email_admin { * Used to build wp_mail(). * * @type string $to The intended recipient - site admin email address. * @type string $subject The subject of the email. * @type string $message The body of the email. * @type string $headers The headers of the email. * } * @param WP_User $user User object for new user. * @param string $blogname The site title. */ $wp_new_user_notification_email_admin = apply_filters( 'wp_new_user_notification_email_admin', $wp_new_user_notification_email_admin, $user, $blogname ); wp_mail( $wp_new_user_notification_email_admin['to'], wp_specialchars_decode( sprintf( $wp_new_user_notification_email_admin['subject'], $blogname ) ), $wp_new_user_notification_email_admin['message'], $wp_new_user_notification_email_admin['headers'] ); if ( $switched_locale ) { restore_previous_locale(); } } /** * Filters whether the user is notified of their new user registration. * * @since 6.1.0 * * @param bool $send Whether to send the email. Default true. * @param WP_User $user User object for new user. */ $send_notification_to_user = apply_filters( 'wp_send_new_user_notification_to_user', true, $user ); // `$deprecated` was pre-4.3 `$plaintext_pass`. An empty `$plaintext_pass` didn't sent a user notification. if ( 'admin' === $notify || true !== $send_notification_to_user || ( empty( $deprecated ) && empty( $notify ) ) ) { return; } $key = get_password_reset_key( $user ); if ( is_wp_error( $key ) ) { return; } $switched_locale = switch_to_user_locale( $user_id ); /* translators: %s: User login. */ $message = sprintf( __( 'Username: %s' ), $user->user_login ) . "\r\n\r\n"; $message .= __( 'To set your password, visit the following address:' ) . "\r\n\r\n"; $message .= network_site_url( "wp-login.php?action=rp&key=$key&login=" . rawurlencode( $user->user_login ), 'login' ) . "\r\n\r\n"; $message .= wp_login_url() . "\r\n"; $wp_new_user_notification_email = array( 'to' => $user->user_email, /* translators: Login details notification email subject. %s: Site title. */ 'subject' => __( '[%s] Login Details' ), 'message' => $message, 'headers' => '', ); /** * Filters the contents of the new user notification email sent to the new user. * * @since 4.9.0 * * @param array $wp_new_user_notification_email { * Used to build wp_mail(). * * @type string $to The intended recipient - New user email address. * @type string $subject The subject of the email. * @type string $message The body of the email. * @type string $headers The headers of the email. * } * @param WP_User $user User object for new user. * @param string $blogname The site title. */ $wp_new_user_notification_email = apply_filters( 'wp_new_user_notification_email', $wp_new_user_notification_email, $user, $blogname ); wp_mail( $wp_new_user_notification_email['to'], wp_specialchars_decode( sprintf( $wp_new_user_notification_email['subject'], $blogname ) ), $wp_new_user_notification_email['message'], $wp_new_user_notification_email['headers'] ); if ( $switched_locale ) { restore_previous_locale(); } } endif; if ( ! function_exists( 'wp_nonce_tick' ) ) : /** * Returns the time-dependent variable for nonce creation. * * A nonce has a lifespan of two ticks. Nonces in their second tick may be * updated, e.g. by autosave. * * @since 2.5.0 * @since 6.1.0 Added `$action` argument. * * @param string|int $action Optional. The nonce action. Default -1. * @return float Float value rounded up to the next highest integer. */ function wp_nonce_tick( $action = -1 ) { /** * Filters the lifespan of nonces in seconds. * * @since 2.5.0 * @since 6.1.0 Added `$action` argument to allow for more targeted filters. * * @param int $lifespan Lifespan of nonces in seconds. Default 86,400 seconds, or one day. * @param string|int $action The nonce action, or -1 if none was provided. */ $nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS, $action ); return ceil( time() / ( $nonce_life / 2 ) ); } endif; if ( ! function_exists( 'wp_verify_nonce' ) ) : /** * Verifies that a correct security nonce was used with time limit. * * A nonce is valid for 24 hours (by default). * * @since 2.0.3 * * @param string $nonce Nonce value that was used for verification, usually via a form field. * @param string|int $action Should give context to what is taking place and be the same when nonce was created. * @return int|false 1 if the nonce is valid and generated between 0-12 hours ago, * 2 if the nonce is valid and generated between 12-24 hours ago. * False if the nonce is invalid. */ function wp_verify_nonce( $nonce, $action = -1 ) { $nonce = (string) $nonce; $user = wp_get_current_user(); $uid = (int) $user->ID; if ( ! $uid ) { /** * Filters whether the user who generated the nonce is logged out. * * @since 3.5.0 * * @param int $uid ID of the nonce-owning user. * @param string|int $action The nonce action, or -1 if none was provided. */ $uid = apply_filters( 'nonce_user_logged_out', $uid, $action ); } if ( empty( $nonce ) ) { return false; } $token = wp_get_session_token(); $i = wp_nonce_tick( $action ); // Nonce generated 0-12 hours ago. $expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 ); if ( hash_equals( $expected, $nonce ) ) { return 1; } // Nonce generated 12-24 hours ago. $expected = substr( wp_hash( ( $i - 1 ) . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 ); if ( hash_equals( $expected, $nonce ) ) { return 2; } /** * Fires when nonce verification fails. * * @since 4.4.0 * * @param string $nonce The invalid nonce. * @param string|int $action The nonce action. * @param WP_User $user The current user object. * @param string $token The user's session token. */ do_action( 'wp_verify_nonce_failed', $nonce, $action, $user, $token ); // Invalid nonce. return false; } endif; if ( ! function_exists( 'wp_create_nonce' ) ) : /** * Creates a cryptographic token tied to a specific action, user, user session, * and window of time. * * @since 2.0.3 * @since 4.0.0 Session tokens were integrated with nonce creation. * * @param string|int $action Scalar value to add context to the nonce. * @return string The token. */ function wp_create_nonce( $action = -1 ) { $user = wp_get_current_user(); $uid = (int) $user->ID; if ( ! $uid ) { /** This filter is documented in wp-includes/pluggable.php */ $uid = apply_filters( 'nonce_user_logged_out', $uid, $action ); } $token = wp_get_session_token(); $i = wp_nonce_tick( $action ); return substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 ); } endif; if ( ! function_exists( 'wp_salt' ) ) : /** * Returns a salt to add to hashes. * * Salts are created using secret keys. Secret keys are located in two places: * in the database and in the wp-config.php file. The secret key in the database * is randomly generated and will be appended to the secret keys in wp-config.php. * * The secret keys in wp-config.php should be updated to strong, random keys to maximize * security. Below is an example of how the secret key constants are defined. * Do not paste this example directly into wp-config.php. Instead, have a * {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just * for you. * * define('AUTH_KEY', ' XakmM%G4Yt>f`z]MON'); * define('SECURE_AUTH_KEY', 'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~'); * define('LOGGED_IN_KEY', '|i|Ux`9z7X>QYR0Z_XnZ@|'); * define('AUTH_SALT', 'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW'); * define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W*c(u`g~EJBf#8u#R{mUEZrozmm'); * define('NONCE_SALT', 'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT'); * * Salting passwords helps against tools which has stored hashed values of * common dictionary strings. The added values makes it harder to crack. * * @since 2.5.0 * * @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php * * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce). * @return string Salt value */ function wp_salt( $scheme = 'auth' ) { static $cached_salts = array(); if ( isset( $cached_salts[ $scheme ] ) ) { /** * Filters the WordPress salt. * * @since 2.5.0 * * @param string $cached_salt Cached salt for the given scheme. * @param string $scheme Authentication scheme. Values include 'auth', * 'secure_auth', 'logged_in', and 'nonce'. */ return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme ); } static $duplicated_keys; if ( null === $duplicated_keys ) { $duplicated_keys = array( 'put your unique phrase here' => true, ); /* * translators: This string should only be translated if wp-config-sample.php is localized. * You can check the localized release package or * https://i18n.svn.wordpress.org//branches//dist/wp-config-sample.php */ $duplicated_keys[ __( 'put your unique phrase here' ) ] = true; foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) { foreach ( array( 'KEY', 'SALT' ) as $second ) { if ( ! defined( "{$first}_{$second}" ) ) { continue; } $value = constant( "{$first}_{$second}" ); $duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] ); } } } $values = array( 'key' => '', 'salt' => '', ); if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) ) { $values['key'] = SECRET_KEY; } if ( 'auth' === $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) ) { $values['salt'] = SECRET_SALT; } if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ), true ) ) { foreach ( array( 'key', 'salt' ) as $type ) { $const = strtoupper( "{$scheme}_{$type}" ); if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) { $values[ $type ] = constant( $const ); } elseif ( ! $values[ $type ] ) { $values[ $type ] = get_site_option( "{$scheme}_{$type}" ); if ( ! $values[ $type ] ) { $values[ $type ] = wp_generate_password( 64, true, true ); update_site_option( "{$scheme}_{$type}", $values[ $type ] ); } } } } else { if ( ! $values['key'] ) { $values['key'] = get_site_option( 'secret_key' ); if ( ! $values['key'] ) { $values['key'] = wp_generate_password( 64, true, true ); update_site_option( 'secret_key', $values['key'] ); } } $values['salt'] = hash_hmac( 'md5', $scheme, $values['key'] ); } $cached_salts[ $scheme ] = $values['key'] . $values['salt']; /** This filter is documented in wp-includes/pluggable.php */ return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme ); } endif; if ( ! function_exists( 'wp_hash' ) ) : /** * Gets hash of given string. * * @since 2.0.3 * * @param string $data Plain text to hash. * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce). * @return string Hash of $data. */ function wp_hash( $data, $scheme = 'auth' ) { $salt = wp_salt( $scheme ); return hash_hmac( 'md5', $data, $salt ); } endif; if ( ! function_exists( 'wp_hash_password' ) ) : /** * Creates a hash (encrypt) of a plain text password. * * For integration with other applications, this function can be overwritten to * instead use the other package password checking algorithm. * * @since 2.5.0 * * @global PasswordHash $wp_hasher PHPass object. * * @param string $password Plain text user password to hash. * @return string The hash string of the password. */ function wp_hash_password( $password ) { global $wp_hasher; if ( empty( $wp_hasher ) ) { require_once ABSPATH . WPINC . '/class-phpass.php'; // By default, use the portable hash from phpass. $wp_hasher = new PasswordHash( 8, true ); } return $wp_hasher->HashPassword( trim( $password ) ); } endif; if ( ! function_exists( 'wp_check_password' ) ) : /** * Checks the plaintext password against the encrypted Password. * * Maintains compatibility between old version and the new cookie authentication * protocol using PHPass library. The $hash parameter is the encrypted password * and the function compares the plain text password when encrypted similarly * against the already encrypted password to see if they match. * * For integration with other applications, this function can be overwritten to * instead use the other package password checking algorithm. * * @since 2.5.0 * * @global PasswordHash $wp_hasher PHPass object used for checking the password * against the $hash + $password. * @uses PasswordHash::CheckPassword * * @param string $password Plaintext user's password. * @param string $hash Hash of the user's password to check against. * @param string|int $user_id Optional. User ID. * @return bool False, if the $password does not match the hashed password. */ function wp_check_password( $password, $hash, $user_id = '' ) { global $wp_hasher; // If the hash is still md5... if ( strlen( $hash ) <= 32 ) { $check = hash_equals( $hash, md5( $password ) ); if ( $check && $user_id ) { // Rehash using new hash. wp_set_password( $password, $user_id ); $hash = wp_hash_password( $password ); } /** * Filters whether the plaintext password matches the encrypted password. * * @since 2.5.0 * * @param bool $check Whether the passwords match. * @param string $password The plaintext password. * @param string $hash The hashed password. * @param string|int $user_id User ID. Can be empty. */ return apply_filters( 'check_password', $check, $password, $hash, $user_id ); } /* * If the stored hash is longer than an MD5, * presume the new style phpass portable hash. */ if ( empty( $wp_hasher ) ) { require_once ABSPATH . WPINC . '/class-phpass.php'; // By default, use the portable hash from phpass. $wp_hasher = new PasswordHash( 8, true ); } $check = $wp_hasher->CheckPassword( $password, $hash ); /** This filter is documented in wp-includes/pluggable.php */ return apply_filters( 'check_password', $check, $password, $hash, $user_id ); } endif; if ( ! function_exists( 'wp_generate_password' ) ) : /** * Generates a random password drawn from the defined set of characters. * * Uses wp_rand() to create passwords with far less predictability * than similar native PHP functions like `rand()` or `mt_rand()`. * * @since 2.5.0 * * @param int $length Optional. The length of password to generate. Default 12. * @param bool $special_chars Optional. Whether to include standard special characters. * Default true. * @param bool $extra_special_chars Optional. Whether to include other special characters. * Used when generating secret keys and salts. Default false. * @return string The random password. */ function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; if ( $special_chars ) { $chars .= '!@#$%^&*()'; } if ( $extra_special_chars ) { $chars .= '-_ []{}<>~`+=,.;:/?|'; } $password = ''; for ( $i = 0; $i < $length; $i++ ) { $password .= substr( $chars, wp_rand( 0, strlen( $chars ) - 1 ), 1 ); } /** * Filters the randomly-generated password. * * @since 3.0.0 * @since 5.3.0 Added the `$length`, `$special_chars`, and `$extra_special_chars` parameters. * * @param string $password The generated password. * @param int $length The length of password to generate. * @param bool $special_chars Whether to include standard special characters. * @param bool $extra_special_chars Whether to include other special characters. */ return apply_filters( 'random_password', $password, $length, $special_chars, $extra_special_chars ); } endif; if ( ! function_exists( 'wp_rand' ) ) : /** * Generates a random non-negative number. * * @since 2.6.2 * @since 4.4.0 Uses PHP7 random_int() or the random_compat library if available. * @since 6.1.0 Returns zero instead of a random number if both `$min` and `$max` are zero. * * @global string $rnd_value * * @param int $min Optional. Lower limit for the generated number. * Accepts positive integers or zero. Defaults to 0. * @param int $max Optional. Upper limit for the generated number. * Accepts positive integers. Defaults to 4294967295. * @return int A random non-negative number between min and max. */ function wp_rand( $min = null, $max = null ) { global $rnd_value; /* * Some misconfigured 32-bit environments (Entropy PHP, for example) * truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats. */ $max_random_number = 3000000000 === 2147483647 ? (float) '4294967295' : 4294967295; // 4294967295 = 0xffffffff if ( null === $min ) { $min = 0; } if ( null === $max ) { $max = $max_random_number; } // We only handle ints, floats are truncated to their integer value. $min = (int) $min; $max = (int) $max; // Use PHP's CSPRNG, or a compatible method. static $use_random_int_functionality = true; if ( $use_random_int_functionality ) { try { // wp_rand() can accept arguments in either order, PHP cannot. $_max = max( $min, $max ); $_min = min( $min, $max ); $val = random_int( $_min, $_max ); if ( false !== $val ) { return absint( $val ); } else { $use_random_int_functionality = false; } } catch ( Error $e ) { $use_random_int_functionality = false; } catch ( Exception $e ) { $use_random_int_functionality = false; } } /* * Reset $rnd_value after 14 uses. * 32 (md5) + 40 (sha1) + 40 (sha1) / 8 = 14 random numbers from $rnd_value. */ if ( strlen( $rnd_value ) < 8 ) { if ( defined( 'WP_SETUP_CONFIG' ) ) { static $seed = ''; } else { $seed = get_transient( 'random_seed' ); } $rnd_value = md5( uniqid( microtime() . mt_rand(), true ) . $seed ); $rnd_value .= sha1( $rnd_value ); $rnd_value .= sha1( $rnd_value . $seed ); $seed = md5( $seed . $rnd_value ); if ( ! defined( 'WP_SETUP_CONFIG' ) && ! defined( 'WP_INSTALLING' ) ) { set_transient( 'random_seed', $seed ); } } // Take the first 8 digits for our value. $value = substr( $rnd_value, 0, 8 ); // Strip the first eight, leaving the remainder for the next call to wp_rand(). $rnd_value = substr( $rnd_value, 8 ); $value = abs( hexdec( $value ) ); // Reduce the value to be within the min - max range. $value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 ); return abs( (int) $value ); } endif; if ( ! function_exists( 'wp_set_password' ) ) : /** * Updates the user's password with a new encrypted one. * * For integration with other applications, this function can be overwritten to * instead use the other package password checking algorithm. * * Please note: This function should be used sparingly and is really only meant for single-time * application. Leveraging this improperly in a plugin or theme could result in an endless loop * of password resets if precautions are not taken to ensure it does not execute on every page load. * * @since 2.5.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $password The plaintext new user password. * @param int $user_id User ID. */ function wp_set_password( $password, $user_id ) { global $wpdb; $hash = wp_hash_password( $password ); $wpdb->update( $wpdb->users, array( 'user_pass' => $hash, 'user_activation_key' => '', ), array( 'ID' => $user_id ) ); clean_user_cache( $user_id ); /** * Fires after the user password is set. * * @since 6.2.0 * * @param string $password The plaintext password just set. * @param int $user_id The ID of the user whose password was just set. */ do_action( 'wp_set_password', $password, $user_id ); } endif; if ( ! function_exists( 'get_avatar' ) ) : /** * Retrieves the avatar `` tag for a user, email address, MD5 hash, comment, or post. * * @since 2.5.0 * @since 4.2.0 Added the optional `$args` parameter. * @since 5.5.0 Added the `loading` argument. * @since 6.1.0 Added the `decoding` argument. * @since 6.3.0 Added the `fetchpriority` argument. * * @param mixed $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash, * user email, WP_User object, WP_Post object, or WP_Comment object. * @param int $size Optional. Height and width of the avatar in pixels. Default 96. * @param string $default_value URL for the default image or a default type. Accepts: * - '404' (return a 404 instead of a default image) * - 'retro' (a 8-bit arcade-style pixelated face) * - 'robohash' (a robot) * - 'monsterid' (a monster) * - 'wavatar' (a cartoon face) * - 'identicon' (the "quilt", a geometric pattern) * - 'mystery', 'mm', or 'mysteryman' (The Oyster Man) * - 'blank' (transparent GIF) * - 'gravatar_default' (the Gravatar logo) * Default is the value of the 'avatar_default' option, * with a fallback of 'mystery'. * @param string $alt Optional. Alternative text to use in the avatar image tag. * Default empty. * @param array $args { * Optional. Extra arguments to retrieve the avatar. * * @type int $height Display height of the avatar in pixels. Defaults to $size. * @type int $width Display width of the avatar in pixels. Defaults to $size. * @type bool $force_default Whether to always show the default image, never the Gravatar. * Default false. * @type string $rating What rating to display avatars up to. Accepts: * - 'G' (suitable for all audiences) * - 'PG' (possibly offensive, usually for audiences 13 and above) * - 'R' (intended for adult audiences above 17) * - 'X' (even more mature than above) * Default is the value of the 'avatar_rating' option. * @type string $scheme URL scheme to use. See set_url_scheme() for accepted values. * Default null. * @type array|string $class Array or string of additional classes to add to the img element. * Default null. * @type bool $force_display Whether to always show the avatar - ignores the show_avatars option. * Default false. * @type string $loading Value for the `loading` attribute. * Default null. * @type string $fetchpriority Value for the `fetchpriority` attribute. * Default null. * @type string $decoding Value for the `decoding` attribute. * Default null. * @type string $extra_attr HTML attributes to insert in the IMG element. Is not sanitized. * Default empty. * } * @return string|false `` tag for the user's avatar. False on failure. */ function get_avatar( $id_or_email, $size = 96, $default_value = '', $alt = '', $args = null ) { $defaults = array( // get_avatar_data() args. 'size' => 96, 'height' => null, 'width' => null, 'default' => get_option( 'avatar_default', 'mystery' ), 'force_default' => false, 'rating' => get_option( 'avatar_rating' ), 'scheme' => null, 'alt' => '', 'class' => null, 'force_display' => false, 'loading' => null, 'fetchpriority' => null, 'decoding' => null, 'extra_attr' => '', ); if ( empty( $args ) ) { $args = array(); } $args['size'] = (int) $size; $args['default'] = $default_value; $args['alt'] = $alt; $args = wp_parse_args( $args, $defaults ); if ( empty( $args['height'] ) ) { $args['height'] = $args['size']; } if ( empty( $args['width'] ) ) { $args['width'] = $args['size']; } // Update args with loading optimized attributes. $loading_optimization_attr = wp_get_loading_optimization_attributes( 'img', $args, 'get_avatar' ); $args = array_merge( $args, $loading_optimization_attr ); if ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) { $id_or_email = get_comment( $id_or_email ); } /** * Allows the HTML for a user's avatar to be returned early. * * Returning a non-null value will effectively short-circuit get_avatar(), passing * the value through the {@see 'get_avatar'} filter and returning early. * * @since 4.2.0 * * @param string|null $avatar HTML for the user's avatar. Default null. * @param mixed $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash, * user email, WP_User object, WP_Post object, or WP_Comment object. * @param array $args Arguments passed to get_avatar_url(), after processing. */ $avatar = apply_filters( 'pre_get_avatar', null, $id_or_email, $args ); if ( ! is_null( $avatar ) ) { /** This filter is documented in wp-includes/pluggable.php */ return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args ); } if ( ! $args['force_display'] && ! get_option( 'show_avatars' ) ) { return false; } $url2x = get_avatar_url( $id_or_email, array_merge( $args, array( 'size' => $args['size'] * 2 ) ) ); $args = get_avatar_data( $id_or_email, $args ); $url = $args['url']; if ( ! $url || is_wp_error( $url ) ) { return false; } $class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' ); if ( ! $args['found_avatar'] || $args['force_default'] ) { $class[] = 'avatar-default'; } if ( $args['class'] ) { if ( is_array( $args['class'] ) ) { $class = array_merge( $class, $args['class'] ); } else { $class[] = $args['class']; } } // Add `loading`, `fetchpriority`, and `decoding` attributes. $extra_attr = $args['extra_attr']; if ( in_array( $args['loading'], array( 'lazy', 'eager' ), true ) && ! preg_match( '/\bloading\s*=/', $extra_attr ) ) { if ( ! empty( $extra_attr ) ) { $extra_attr .= ' '; } $extra_attr .= "loading='{$args['loading']}'"; } if ( in_array( $args['fetchpriority'], array( 'high', 'low', 'auto' ), true ) && ! preg_match( '/\bfetchpriority\s*=/', $extra_attr ) ) { if ( ! empty( $extra_attr ) ) { $extra_attr .= ' '; } $extra_attr .= "fetchpriority='{$args['fetchpriority']}'"; } if ( in_array( $args['decoding'], array( 'async', 'sync', 'auto' ), true ) && ! preg_match( '/\bdecoding\s*=/', $extra_attr ) ) { if ( ! empty( $extra_attr ) ) { $extra_attr .= ' '; } $extra_attr .= "decoding='{$args['decoding']}'"; } $avatar = sprintf( "%s", esc_attr( $args['alt'] ), esc_url( $url ), esc_url( $url2x ) . ' 2x', esc_attr( implode( ' ', $class ) ), (int) $args['height'], (int) $args['width'], $extra_attr ); /** * Filters the HTML for a user's avatar. * * @since 2.5.0 * @since 4.2.0 Added the `$args` parameter. * * @param string $avatar HTML for the user's avatar. * @param mixed $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash, * user email, WP_User object, WP_Post object, or WP_Comment object. * @param int $size Height and width of the avatar in pixels. * @param string $default_value URL for the default image or a default type. Accepts: * - '404' (return a 404 instead of a default image) * - 'retro' (a 8-bit arcade-style pixelated face) * - 'robohash' (a robot) * - 'monsterid' (a monster) * - 'wavatar' (a cartoon face) * - 'identicon' (the "quilt", a geometric pattern) * - 'mystery', 'mm', or 'mysteryman' (The Oyster Man) * - 'blank' (transparent GIF) * - 'gravatar_default' (the Gravatar logo) * @param string $alt Alternative text to use in the avatar image tag. * @param array $args Arguments passed to get_avatar_data(), after processing. */ return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args ); } endif; if ( ! function_exists( 'wp_text_diff' ) ) : /** * Displays a human readable HTML representation of the difference between two strings. * * The Diff is available for getting the changes between versions. The output is * HTML, so the primary use is for displaying the changes. If the two strings * are equivalent, then an empty string will be returned. * * @since 2.6.0 * * @see wp_parse_args() Used to change defaults to user defined settings. * @uses Text_Diff * @uses WP_Text_Diff_Renderer_Table * * @param string $left_string "old" (left) version of string. * @param string $right_string "new" (right) version of string. * @param string|array $args { * Associative array of options to pass to WP_Text_Diff_Renderer_Table(). * * @type string $title Titles the diff in a manner compatible * with the output. Default empty. * @type string $title_left Change the HTML to the left of the title. * Default empty. * @type string $title_right Change the HTML to the right of the title. * Default empty. * @type bool $show_split_view True for split view (two columns), false for * un-split view (single column). Default true. * } * @return string Empty string if strings are equivalent or HTML with differences. */ function wp_text_diff( $left_string, $right_string, $args = null ) { $defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '', 'show_split_view' => true, ); $args = wp_parse_args( $args, $defaults ); if ( ! class_exists( 'WP_Text_Diff_Renderer_Table', false ) ) { require ABSPATH . WPINC . '/wp-diff.php'; } $left_string = normalize_whitespace( $left_string ); $right_string = normalize_whitespace( $right_string ); $left_lines = explode( "\n", $left_string ); $right_lines = explode( "\n", $right_string ); $text_diff = new Text_Diff( $left_lines, $right_lines ); $renderer = new WP_Text_Diff_Renderer_Table( $args ); $diff = $renderer->render( $text_diff ); if ( ! $diff ) { return ''; } $is_split_view = ! empty( $args['show_split_view'] ); $is_split_view_class = $is_split_view ? ' is-split-view' : ''; $r = "\n"; if ( $args['title'] ) { $r .= "\n"; } if ( $args['title_left'] || $args['title_right'] ) { $r .= ''; } if ( $args['title_left'] || $args['title_right'] ) { $th_or_td_left = empty( $args['title_left'] ) ? 'td' : 'th'; $th_or_td_right = empty( $args['title_right'] ) ? 'td' : 'th'; $r .= "\n"; $r .= "\t<$th_or_td_left>$args[title_left]\n"; if ( $is_split_view ) { $r .= "\t<$th_or_td_right>$args[title_right]\n"; } $r .= "\n"; } if ( $args['title_left'] || $args['title_right'] ) { $r .= "\n"; } $r .= "\n$diff\n\n"; $r .= '
$args[title]
'; return $r; } endif;