Skip to content

Conversation

LiamSarsfield
Copy link
Contributor

@LiamSarsfield LiamSarsfield commented Sep 5, 2025

Fixes HOG-336: Block Scanner: PHP Fatal TypeError in Widget Visibility Conditions

Proposed changes:

  • Normalize $instance['content'] to a string before calling has_blocks() in Jetpack_Widget_Conditions::filter_widget.
  • Guard serialize_blocks() to only run on parsed block arrays (checks for blockName), and bail safely on unknown/empty array shapes.
  • Avoids a PHP 8+ TypeError when has_blocks() is invoked with an array.

Jetpack product discussion

N/A

Does this pull request change what data or activity we track or use?

N/A

Testing instructions:

  • Prereqs:

    • PHP 8.1+ recommended.
    • Jetpack active with this branch installed.
    • Enable logging in wp-config.php if not already:
      • define( 'WP_DEBUG', true );
      • define( 'WP_DEBUG_LOG', true );
      • define( 'WP_DEBUG_DISPLAY', false );
    • Tail wp-content/debug.log while testing.
  • Manual verification:

    • Activate a classic theme that uses legacy widgets (e.g., Twenty Twenty or Twenty Twenty-One). This functionality does not apply to block-based themes.
    • Ensure the Widget Visibility module is active in Jetpack settings.
    • Navigate to Appearance > Widgets.
    • Add a block-based widget (e.g., “Latest Posts”) to a sidebar.
    • In the block controls → Advanced, set Widget Visibility to “Show if” → “Page” → “Front page”.
    • Visit:
      • Front page: widget is visible.
      • Another page/post: widget is hidden.
    • Confirm no errors in wp-content/debug.log.
  • Simulate "array content" code paths using a temporary MU plugin:

    • Create wp-content/mu-plugins/test-widget-visibility-content-shapes.php, or use an existing 01-snippets.php:
<?php
add_filter(
	'widget_display_callback',
	function ( $instance, $widget, $args ) {
		static $originals = array();

		// Only run when requested.
		$force_parsed_blocks = isset( $_GET['force_arr_content'] );
		$force_nested        = isset( $_GET['force_nested_content'] );

		if ( ! ( $force_parsed_blocks || $force_nested ) ) {
			return $instance;
		}

		// Only act on Block Widget instances, which carry block content.
		if ( ! ( $widget instanceof \WP_Widget_Block ) ) {
			return $instance;
		}

		// Must have string content to start with, or nothing to do.
		if ( empty( $instance['content'] ) || ! is_string( $instance['content'] ) ) {
			return $instance;
		}

		$widget_id = isset( $args['widget_id'] ) ? $args['widget_id'] : null;
		if ( ! $widget_id ) {
			return $instance;
		}

		// Store original string to restore at priority 11.
		$originals[ $widget_id ] = $instance['content'];

		// Present array shapes to Jetpack at priority 10.
		if ( $force_parsed_blocks ) {
			$blocks = parse_blocks( $instance['content'] );
			if ( is_array( $blocks ) && ! empty( $blocks ) ) {
				$instance['content'] = $blocks;
			}
		} elseif ( $force_nested ) {
			$instance['content'] = array( 'content' => $instance['content'] );
		}

		// Register a restoration callback once to revert to the original string after Jetpack runs.
		static $restorer_added = false;
		if ( ! $restorer_added ) {
			add_filter(
				'widget_display_callback',
				function ( $inst, $w, $a ) use ( &$originals ) {
					$wid = isset( $a['widget_id'] ) ? $a['widget_id'] : null;
					if ( $wid && isset( $originals[ $wid ] ) ) {
						$inst['content'] = $originals[ $wid ];
						unset( $originals[ $wid ] );
					}
					return $inst;
				},
				11,
				3
			);
			$restorer_added = true;
		}

		return $instance;
	},
	9,
	3
);
  • With your test widget in place:

    • Visit the front page with ?force_arr_content=1 → no errors; visibility rules respected.
    • Visit with ?force_nested_content=1 → no errors; visibility rules respected.
    • Visit with ?force_unknown_shape=1 → no errors; widget displays (safe fallback).
  • Check wp-content/debug.log for any TypeErrors/notices; expect none.

  • Unit tests:

    • Run, and verify all have passed.
jetpack docker phpunit jetpack -- --filter=Jetpack_Widget_Conditions_Test

Before / After:

  • Before: has_blocks() could be called with an array, causing a fatal error on PHP 8+ under certain block conditions.
  • After: content is normalized first; has_blocks() only receives strings; array shapes are handled safely or bailed out conservatively.

…ck (#45080)

* Added logic to process $instance['content'] as an array, ensuring compatibility with nested structures and serialization of block arrays.
* Improved validation to return early if content is not a valid string after processing.
@github-actions github-actions bot added [Feature] Widget Visibility [Plugin] Jetpack Issues about the Jetpack plugin. https://wordpress.org/plugins/jetpack/ [Status] In Progress labels Sep 5, 2025
Copy link
Contributor

github-actions bot commented Sep 5, 2025

Thank you for your PR!

When contributing to Jetpack, we have a few suggestions that can help us test and review your patch:

  • ✅ Include a description of your PR changes.
  • ✅ Add a "[Status]" label (In Progress, Needs Review, ...).
  • ✅ Add a "[Type]" label (Bug, Enhancement, Janitorial, Task).
  • ✅ Add testing instructions.
  • ✅ Specify whether this PR includes any changes to data or privacy.
  • ✅ Add changelog entries to affected projects

This comment will be updated as you work on your PR and make changes. If you think that some of those checks are not needed for your PR, please explain why you think so. Thanks for cooperation 🤖


Follow this PR Review Process:

  1. Ensure all required checks appearing at the bottom of this PR are passing.
  2. Make sure to test your changes on all platforms that it applies to. You're responsible for the quality of the code you ship.
  3. You can use GitHub's Reviewers functionality to request a review.
  4. When it's reviewed and merged, you will be pinged in Slack to deploy the changes to WordPress.com simple once the build is done.

If you have questions about anything, reach out in #jetpack-developers for guidance!


Jetpack plugin:

No scheduled milestone found for this plugin.

If you have any questions about the release process, please ask in the #jetpack-releases channel on Slack.

@github-actions github-actions bot added the [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. label Sep 5, 2025
Copy link
Contributor

github-actions bot commented Sep 5, 2025

Are you an Automattician? Please test your changes on all WordPress.com environments to help mitigate accidental explosions.

  • To test on WoA, go to the Plugins menu on a WoA dev site. Click on the "Upload" button and follow the upgrade flow to be able to upload, install, and activate the Jetpack Beta plugin. Once the plugin is active, go to Jetpack > Jetpack Beta, select your plugin (Jetpack), and enable the fix/widget-visibility/array-string-conversion-error-hog-336 branch.
  • To test on Simple, run the following command on your sandbox:
bin/jetpack-downloader test jetpack fix/widget-visibility/array-string-conversion-error-hog-336

Interested in more tips and information?

  • In your local development environment, use the jetpack rsync command to sync your changes to a WoA dev blog.
  • Read more about our development workflow here: PCYsg-eg0-p2
  • Figure out when your changes will be shipped to customers here: PCYsg-eg5-p2

@LiamSarsfield LiamSarsfield added [Type] Bug When a feature is broken and / or not performing as intended and removed [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. labels Sep 5, 2025
Copy link

jp-launch-control bot commented Sep 5, 2025

Code Coverage Summary

Coverage changed in 1 file.

File Coverage Δ% Δ Uncovered
projects/plugins/jetpack/modules/widget-visibility/widget-conditions.php 59/625 (9.44%) 1.32% 0 💚

Full summary · PHP report · JS report

* Updated logic to ensure proper processing of $instance['content'], including normalization to string and improved validation for block visibility.
* Enhanced comments for clarity on content structure handling.
* Updated the visibility condition to check for empty content more effectively, ensuring that the logic correctly identifies invalid content scenarios.
* Improved overall robustness of content handling in widget visibility checks.
* Updated assertions in Jetpack_Widget_Conditions_Test to utilize PHPUnit\Framework\Assert for consistency.
* Added new test cases to verify handling of parsed blocks arrays and unknown array shapes in filter_widget method.
* Enhanced test coverage for visibility rules with various block configurations.
@LiamSarsfield LiamSarsfield requested review from kraftbj, dilirity and a team September 5, 2025 16:27
@LiamSarsfield LiamSarsfield marked this pull request as ready for review September 5, 2025 16:27
Copy link
Contributor

@tbradsha tbradsha left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't test, but the code looks like it should address the issue. Thanks!

@@ -826,8 +826,29 @@ public static function filter_widget( $instance ) {
return $instance;
}
return false;
} elseif ( ! empty( $instance['content'] ) && has_blocks( $instance['content'] ) ) {
$scanner = Block_Scanner::create( $instance['content'] );
} elseif ( ! empty( $instance['content'] ) ) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could invert this and return early, de-nesting the rest of the block.

@tbradsha
Copy link
Contributor

tbradsha commented Sep 5, 2025

Also, thanks for adding test coverage!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Feature] Widget Visibility [Plugin] Jetpack Issues about the Jetpack plugin. https://wordpress.org/plugins/jetpack/ [Status] In Progress [Tests] Includes Tests [Type] Bug When a feature is broken and / or not performing as intended
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants