From 567ce64051cb98c38ac2c01959f20cc99aa5285f Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Tue, 17 Nov 2026 22:46:56 +0000 Subject: [PATCH 01/85] Tests: Remove empty REST icons test placeholders. Rename the existing GET tests to satisfy the required `test_get_item()` and `test_get_items()` methods. Remove the empty placeholders while preserving their behavioral coverage. Developed in: https://github.com/WordPress/wordpress-develop/pull/15919 Props rejaulalomkhan, rcwpdev. See #40538. git-svn-id: https://develop.svn.wordpress.org/trunk@65565 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/icons/wpRestIconsController.php | 24 ++++--------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/tests/phpunit/tests/icons/wpRestIconsController.php b/tests/phpunit/tests/icons/wpRestIconsController.php index bdd04bc16555a..225aed0768c94 100644 --- a/tests/phpunit/tests/icons/wpRestIconsController.php +++ b/tests/phpunit/tests/icons/wpRestIconsController.php @@ -221,24 +221,6 @@ public function test_delete_item() { $this->assertSame( 404, $response->get_status() ); } - /** - * @ticket 64651 - * - * @covers ::get_item - * - * @doesNotPerformAssertions - */ - public function test_get_item() { - // see methods test_get_item_* - } - - /** - * @doesNotPerformAssertions - */ - public function test_get_items() { - // see methods test_get_items_* - } - /** * @ticket 64651 * @@ -283,11 +265,12 @@ public function test_get_item_schema() { /** * Test that GET /wp/v2/icons returns a list of icons for users with edit_posts capability. * + * @ticket 40538 * @ticket 64651 * * @covers ::get_items */ - public function test_get_items_returns_icons_list() { + public function test_get_items() { wp_set_current_user( self::$editor_id ); $request = new WP_REST_Request( 'GET', '/wp/v2/icons' ); @@ -350,11 +333,12 @@ public function test_get_items_contributor_has_access() { /** * Test that GET /wp/v2/icons/core/arrow-left returns specific icon data. * + * @ticket 40538 * @ticket 64651 * * @covers ::get_item */ - public function test_get_item_returns_specific_icon() { + public function test_get_item() { wp_set_current_user( self::$editor_id ); /* From 19379c816819a77e55a2f2f577ac9809340cc407 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Tue, 17 Nov 2026 23:13:13 +0000 Subject: [PATCH 02/85] Build/Test Tools: Include PHPStan baselines via a PHP loader. The per-identifier baselines were listed one by one in `phpstan.neon.dist`, between markers that `composer phpstan:baselines` rewrote whenever a baseline was added or deleted, so every change that retired a baseline edited the same lines and two such changes conflicted. They are now included through `tests/phpstan/baselines/loader.php`, a PHP configuration that returns the baselines found in its directory, since NEON can only include files by name. A baseline takes effect when it is added and stops when it is deleted, with no edit of the configuration. When regenerating, only the baselines being rewritten are suppressed: the generator passes their directory in the `WP_PHPSTAN_GENERATING_BASELINES` environment variable, and the loader there returns nothing. This works even when the configuration is included by another, such as a local `phpstan.neon`, which previously left every baseline in force and got them deleted. Baselines in other directories stay in force, so a stricter configuration with baselines of its own records only the errors the default ones do not cover. Developed in https://github.com/WordPress/wordpress-develop/pull/16049. Follow-up to r63019, r63294, r65372. Props westonruter, apermo. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65566 602fd350-edb4-49c9-b593-d223f7449a82 --- .../reusable-phpstan-static-analysis-v1.yml | 4 +- phpstan.neon.dist | 40 +- tests/phpstan/README.md | 6 +- tests/phpstan/baseline-includes.php | 105 +++++ tests/phpstan/baselines/argument.type.neon | 6 +- .../baselines/argument.unresolvableType.neon | 6 +- .../baselines/assign.propertyType.neon | 6 +- tests/phpstan/baselines/binaryOp.invalid.neon | 6 +- .../baselines/booleanAnd.leftAlwaysTrue.neon | 6 +- .../baselines/booleanNot.alwaysTrue.neon | 6 +- tests/phpstan/baselines/class.notFound.neon | 6 +- .../baselines/deadCode.unreachable.neon | 6 +- tests/phpstan/baselines/empty.property.neon | 6 +- tests/phpstan/baselines/empty.variable.neon | 6 +- .../function.alreadyNarrowedType.neon | 6 +- .../baselines/function.resultUnused.neon | 6 +- .../baselines/identical.alwaysFalse.neon | 6 +- tests/phpstan/baselines/if.alwaysFalse.neon | 6 +- tests/phpstan/baselines/if.alwaysTrue.neon | 6 +- tests/phpstan/baselines/isset.property.neon | 6 +- tests/phpstan/baselines/loader.php | 16 + .../baselines/method.childParameterType.neon | 6 +- tests/phpstan/baselines/method.unused.neon | 6 +- .../baselines/notIdentical.alwaysTrue.neon | 6 +- .../offsetAccess.nonOffsetAccessible.neon | 6 +- .../baselines/offsetAccess.notFound.neon | 6 +- .../baselines/offsetAssign.valueType.neon | 6 +- .../baselines/parameterByRef.type.neon | 6 +- .../baselines/parameterByRef.unusedType.neon | 6 +- .../baselines/property.defaultValue.neon | 6 +- .../phpstan/baselines/property.nonObject.neon | 6 +- .../phpstan/baselines/property.notFound.neon | 6 +- tests/phpstan/baselines/property.private.neon | 6 +- tests/phpstan/baselines/return.type.neon | 6 +- .../phpstan/baselines/varTag.noVariable.neon | 6 +- .../phpstan/baselines/variable.undefined.neon | 6 +- tests/phpstan/generate-baselines.php | 431 ++++++++---------- 37 files changed, 412 insertions(+), 376 deletions(-) create mode 100644 tests/phpstan/baseline-includes.php create mode 100644 tests/phpstan/baselines/loader.php diff --git a/.github/workflows/reusable-phpstan-static-analysis-v1.yml b/.github/workflows/reusable-phpstan-static-analysis-v1.yml index 9a80af539ae13..5474a810164cd 100644 --- a/.github/workflows/reusable-phpstan-static-analysis-v1.yml +++ b/.github/workflows/reusable-phpstan-static-analysis-v1.yml @@ -283,9 +283,9 @@ jobs: composer phpstan:fix ``` - That runs PHPStan with `--fix`, which lowers the counts in the files under [`tests/phpstan/baselines`][baselines], removes the entries that no longer match, and removes any `@phpstan-ignore` annotation in the code that no longer ignores anything. It then deletes any baseline left with no entries, and updates the list of them in `phpstan.neon.dist`. + That runs PHPStan with `--fix`, which lowers the counts in the files under [`tests/phpstan/baselines`][baselines], removes the entries that no longer match, and removes any `@phpstan-ignore` annotation in the code that no longer ignores anything. It then deletes any baseline left with no entries. - Alternatively, regenerate the baselines with `npm run typecheck:php:baselines` or `composer phpstan:baselines`. That also deletes any baseline whose errors are now all fixed, and updates the list of them in `phpstan.neon.dist`, but it does not clear an `@phpstan-ignore` annotation. + Alternatively, regenerate the baselines with `npm run typecheck:php:baselines` or `composer phpstan:baselines`. That also deletes any baseline whose errors are now all fixed, but it does not clear an `@phpstan-ignore` annotation. See [`tests/phpstan/README.md`][readme] for details. diff --git a/phpstan.neon.dist b/phpstan.neon.dist index cbaa19f3e8db1..260afa934953f 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -18,44 +18,12 @@ includes: # Preexisting errors that should be ignored, one baseline per error identifier # so that the remaining work on each is visible as a single shrinking file. - # Each is meant to reach zero and be deleted, taking its line below with it. + # Each is meant to reach zero and be deleted. # https://phpstan.org/user-guide/baseline # - # Regenerate with `composer phpstan:baselines`, which rewrites both the files - # and the list between the markers. Do not edit that list by hand. - # phpstan:baselines start - - tests/phpstan/baselines/argument.type.neon - - tests/phpstan/baselines/argument.unresolvableType.neon - - tests/phpstan/baselines/assign.propertyType.neon - - tests/phpstan/baselines/binaryOp.invalid.neon - - tests/phpstan/baselines/booleanAnd.leftAlwaysTrue.neon - - tests/phpstan/baselines/booleanNot.alwaysTrue.neon - - tests/phpstan/baselines/class.notFound.neon - - tests/phpstan/baselines/deadCode.unreachable.neon - - tests/phpstan/baselines/empty.property.neon - - tests/phpstan/baselines/empty.variable.neon - - tests/phpstan/baselines/function.alreadyNarrowedType.neon - - tests/phpstan/baselines/function.resultUnused.neon - - tests/phpstan/baselines/identical.alwaysFalse.neon - - tests/phpstan/baselines/if.alwaysFalse.neon - - tests/phpstan/baselines/if.alwaysTrue.neon - - tests/phpstan/baselines/isset.property.neon - - tests/phpstan/baselines/method.childParameterType.neon - - tests/phpstan/baselines/method.unused.neon - - tests/phpstan/baselines/notIdentical.alwaysTrue.neon - - tests/phpstan/baselines/offsetAccess.nonOffsetAccessible.neon - - tests/phpstan/baselines/offsetAccess.notFound.neon - - tests/phpstan/baselines/offsetAssign.valueType.neon - - tests/phpstan/baselines/parameterByRef.type.neon - - tests/phpstan/baselines/parameterByRef.unusedType.neon - - tests/phpstan/baselines/property.defaultValue.neon - - tests/phpstan/baselines/property.nonObject.neon - - tests/phpstan/baselines/property.notFound.neon - - tests/phpstan/baselines/property.private.neon - - tests/phpstan/baselines/return.type.neon - - tests/phpstan/baselines/varTag.noVariable.neon - - tests/phpstan/baselines/variable.undefined.neon - # phpstan:baselines end + # The loader includes every baseline in its directory, so adding or deleting one + # needs no edit here. Regenerate them with `composer phpstan:baselines`. + - tests/phpstan/baselines/loader.php # Rules from phpstan-strict-rules which core already complies with, or which enforce the # WordPress Coding Standards. The others are not enabled until the code complies with them, diff --git a/tests/phpstan/README.md b/tests/phpstan/README.md index 62003ca812d6a..7dd1df431d4a9 100644 --- a/tests/phpstan/README.md +++ b/tests/phpstan/README.md @@ -204,6 +204,8 @@ PHPStan errors can be ignored in the following ways: The baselines live in [`baselines/`](baselines), one file per error identifier, such as `variable.undefined.neon`. Splitting them this way keeps each kind of error visible as a single file that should shrink to nothing and then be deleted, rather than as part of one large file in which every kind is mixed together. +[`phpstan.neon.dist`](../../phpstan.neon.dist) does not list the baselines one by one. It includes [`baselines/loader.php`](baselines/loader.php), which includes every `.neon` file in that directory named for an error identifier, so a baseline takes effect as soon as it is added, and stops as soon as it is deleted, without an edit of the configuration. + Every entry is scoped to the file the error occurs in and carries an exact occurrence count: ```neon @@ -235,7 +237,7 @@ composer phpstan:fix This runs three steps, each only when the one before it succeeds: 1. PHPStan with its `--fix` option, which lowers the count of the entry, or removes the entry, leaving the rest of the baseline as it was. It is usually much faster than regenerating, since it reuses the result cache of the run that reported the errors. Unlike regenerating, it also removes an `@phpstan-ignore` comment that no longer matches. -2. `composer phpstan:baselines -- --prune`, which deletes any baseline left with no entries, along with its `includes` entry in `phpstan.neon.dist`. Removing the last entry of a baseline leaves the file behind, as `ignoreErrors: []`. Pruning analyzes nothing, so it can also be run on its own. +2. `composer phpstan:baselines -- --prune`, which deletes any baseline left with no entries. Removing the last entry of a baseline leaves the file behind, as `ignoreErrors: []`. Pruning analyzes nothing, so it can also be run on its own. 3. The analysis once more, which reuses the result cache and so is quick. PHPStan's `--fix` reports only what it fixed, and succeeds even when other errors remain, so this is what shows the errors that are left. Keep in mind: @@ -290,7 +292,7 @@ composer phpstan:baselines -- --help Note the `--` in each of those. Composer needs it in order to pass the flags on to the script rather than reading them as its own, and without it they are discarded silently, so `composer phpstan:baselines --identifier=variable.undefined` regenerates every baseline rather than that one. The npm script supplies it, which is why only one is needed there. -A run also deletes any baseline whose identifier no longer reports anything, and rewrites the list of them between the `# phpstan:baselines` markers in the `includes` of [`phpstan.neon.dist`](../../phpstan.neon.dist) to match. Adding a newly split out baseline, and retiring one that has reached zero, therefore need no edit of the configuration. +A run also deletes any baseline whose identifier no longer reports anything. Since the baselines are included through [`baselines/loader.php`](baselines/loader.php), adding a newly split out baseline, and retiring one that has reached zero, need no edit of the configuration. PHPStan's own `--generate-baseline` is deliberately not used directly. It captures every error a run reports, with no way to restrict it to one identifier, so it cannot refresh a single baseline without sweeping every other kind of error into it. diff --git a/tests/phpstan/baseline-includes.php b/tests/phpstan/baseline-includes.php new file mode 100644 index 0000000000000..5086ffab34017 --- /dev/null +++ b/tests/phpstan/baseline-includes.php @@ -0,0 +1,105 @@ + File names, sorted. + * + * @throws RuntimeException When the directory cannot be listed. + */ +function find_baselines( string $directory ): array { + $entries = is_dir( $directory ) ? scandir( $directory ) : false; + + if ( false === $entries ) { + throw new RuntimeException( "Could not list the PHPStan baselines in $directory." ); + } + + $names = array(); + foreach ( $entries as $name ) { + if ( '' !== $name && 1 === preg_match( BASELINE_FILE_PATTERN, $name ) ) { + $names[] = $name; + } + } + + return $names; +} + +/** + * Returns the configuration a baselines loader hands to PHPStan. + * + * Each baseline is included by its bare file name, which PHPStan resolves against + * the loader's path as the configuration reached it. A loader's __DIR__ is the + * real path, with any symbolic link resolved, so an absolute path built from it + * would place the baselines, and the paths their entries name relative to + * themselves, outside a checkout reached through a link, where they match none + * of the analyzed files. + * + * @param non-empty-string $directory The loader's directory, as its __DIR__. + * @return array{includes: list} Configuration. + * + * @throws RuntimeException When the directory cannot be listed. + */ +function get_baseline_includes( string $directory ): array { + if ( getenv( GENERATING_BASELINES_ENV ) === $directory ) { + return array( 'includes' => array() ); + } + + return array( 'includes' => find_baselines( $directory ) ); +} diff --git a/tests/phpstan/baselines/argument.type.neon b/tests/phpstan/baselines/argument.type.neon index aece929f18751..dd184d5a12924 100644 --- a/tests/phpstan/baselines/argument.type.neon +++ b/tests/phpstan/baselines/argument.type.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=argument.type # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/argument.unresolvableType.neon b/tests/phpstan/baselines/argument.unresolvableType.neon index 3e8cdcb76c85d..8bee3995f6ac5 100644 --- a/tests/phpstan/baselines/argument.unresolvableType.neon +++ b/tests/phpstan/baselines/argument.unresolvableType.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=argument.unresolvableType # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/assign.propertyType.neon b/tests/phpstan/baselines/assign.propertyType.neon index 80b4b8b9b43c1..4afc274001850 100644 --- a/tests/phpstan/baselines/assign.propertyType.neon +++ b/tests/phpstan/baselines/assign.propertyType.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=assign.propertyType # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/binaryOp.invalid.neon b/tests/phpstan/baselines/binaryOp.invalid.neon index 167f159cffb34..57b8bf343662e 100644 --- a/tests/phpstan/baselines/binaryOp.invalid.neon +++ b/tests/phpstan/baselines/binaryOp.invalid.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=binaryOp.invalid # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/booleanAnd.leftAlwaysTrue.neon b/tests/phpstan/baselines/booleanAnd.leftAlwaysTrue.neon index 10ed28f6b433d..23523d7b66739 100644 --- a/tests/phpstan/baselines/booleanAnd.leftAlwaysTrue.neon +++ b/tests/phpstan/baselines/booleanAnd.leftAlwaysTrue.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=booleanAnd.leftAlwaysTrue # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/booleanNot.alwaysTrue.neon b/tests/phpstan/baselines/booleanNot.alwaysTrue.neon index b61a98cef358e..066ee954ba210 100644 --- a/tests/phpstan/baselines/booleanNot.alwaysTrue.neon +++ b/tests/phpstan/baselines/booleanNot.alwaysTrue.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=booleanNot.alwaysTrue # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/class.notFound.neon b/tests/phpstan/baselines/class.notFound.neon index 560ceafb56573..423a42dd3aca5 100644 --- a/tests/phpstan/baselines/class.notFound.neon +++ b/tests/phpstan/baselines/class.notFound.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=class.notFound # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/deadCode.unreachable.neon b/tests/phpstan/baselines/deadCode.unreachable.neon index ef8ca56577602..3dccb140aacc0 100644 --- a/tests/phpstan/baselines/deadCode.unreachable.neon +++ b/tests/phpstan/baselines/deadCode.unreachable.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=deadCode.unreachable # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/empty.property.neon b/tests/phpstan/baselines/empty.property.neon index 5bc6d4e3cbdd3..869cadbf2fea7 100644 --- a/tests/phpstan/baselines/empty.property.neon +++ b/tests/phpstan/baselines/empty.property.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=empty.property # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/empty.variable.neon b/tests/phpstan/baselines/empty.variable.neon index c9a94ecd02d9f..fe2adb8dec11e 100644 --- a/tests/phpstan/baselines/empty.variable.neon +++ b/tests/phpstan/baselines/empty.variable.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=empty.variable # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/function.alreadyNarrowedType.neon b/tests/phpstan/baselines/function.alreadyNarrowedType.neon index a7c36b7d7d0b8..467991720b5a7 100644 --- a/tests/phpstan/baselines/function.alreadyNarrowedType.neon +++ b/tests/phpstan/baselines/function.alreadyNarrowedType.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=function.alreadyNarrowedType # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/function.resultUnused.neon b/tests/phpstan/baselines/function.resultUnused.neon index 1ad6a84dbfa4c..442b207fe196d 100644 --- a/tests/phpstan/baselines/function.resultUnused.neon +++ b/tests/phpstan/baselines/function.resultUnused.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=function.resultUnused # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/identical.alwaysFalse.neon b/tests/phpstan/baselines/identical.alwaysFalse.neon index d8d766d45827f..5bd777f130a40 100644 --- a/tests/phpstan/baselines/identical.alwaysFalse.neon +++ b/tests/phpstan/baselines/identical.alwaysFalse.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=identical.alwaysFalse # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/if.alwaysFalse.neon b/tests/phpstan/baselines/if.alwaysFalse.neon index 15f01b77b4cf4..30fb317dec4c4 100644 --- a/tests/phpstan/baselines/if.alwaysFalse.neon +++ b/tests/phpstan/baselines/if.alwaysFalse.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=if.alwaysFalse # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/if.alwaysTrue.neon b/tests/phpstan/baselines/if.alwaysTrue.neon index 6f5169ee0b1e6..1d3af11e446fb 100644 --- a/tests/phpstan/baselines/if.alwaysTrue.neon +++ b/tests/phpstan/baselines/if.alwaysTrue.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=if.alwaysTrue # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/isset.property.neon b/tests/phpstan/baselines/isset.property.neon index 5278005df2869..327cd1c76aa43 100644 --- a/tests/phpstan/baselines/isset.property.neon +++ b/tests/phpstan/baselines/isset.property.neon @@ -7,14 +7,14 @@ # silently. Fixing an occurrence therefore means decrementing or removing its # entry here as part of the same change. # -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. +# The goal is to empty this file and delete it. # # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with # # composer phpstan:baselines -- --identifier=isset.property # -# which reruns the analysis with this file suppressed so the errors surface again. +# which reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: diff --git a/tests/phpstan/baselines/loader.php b/tests/phpstan/baselines/loader.php new file mode 100644 index 0000000000000..829e4ac4880d4 --- /dev/null +++ b/tests/phpstan/baselines/loader.php @@ -0,0 +1,16 @@ + $entries ) { - file_put_contents( + $written = file_put_contents( $output_dir . '/' . $identifier . '.neon', - build_baseline( $entries, $output_dir, build_baseline_header( $identifier, $config_option ) ) + build_baseline( $entries, $output_dir, build_baseline_header( $identifier, $regenerate_options ) ) ); + if ( false === $written ) { + fwrite( STDERR, "Could not write $output_option/$identifier.neon\n" ); + exit( 1 ); + } + printf( "%s: %d entries, %d errors\n", $output_option . '/' . $identifier . '.neon', @@ -359,8 +436,8 @@ static function () use ( $temp_config, $temp_stripped, $temp_baseline ): void { $retired = $only_identifiers; if ( ! $only_identifiers ) { - foreach ( find_baselines( $output_dir ) as $file ) { - $retired[] = basename( $file, '.neon' ); + foreach ( find_baselines( $output_dir ) as $name ) { + $retired[] = basename( $name, '.neon' ); } } @@ -377,8 +454,6 @@ static function () use ( $temp_config, $temp_stripped, $temp_baseline ): void { } } -update_config_includes( $config_path, $config_option, $output_dir ); - /** * Returns the usage message. * @@ -388,10 +463,10 @@ function get_usage(): string { return <<<'TEXT' Generates PHPStan baselines split by error identifier. - Writes one baseline per identifier, retires any whose identifier no longer - reports anything, and rewrites the list of them between the - `# phpstan:baselines` markers in the configuration's `includes`, so that - neither addition nor removal has to be done by hand. + Writes one baseline per identifier, and retires any whose identifier no + longer reports anything. The configuration includes every baseline through + tests/phpstan/baselines/loader.php, so neither addition nor removal needs an + edit of it. Usage: composer phpstan:baselines [-- ] @@ -406,14 +481,16 @@ function get_usage(): string { root. Default: phpstan.neon.dist --output-dir= Where the per-identifier baselines are written, relative to the repository root. Paths inside them are written - relative to this directory. + relative to this directory. A loader is written there + too, which the configuration has to include. Baselines + in other directories stay in force, so only the errors + they leave are written. Default: tests/phpstan/baselines --combined Print one combined baseline to stdout instead of writing per-identifier files. Nothing is written to disk. --prune Without analyzing anything, delete the baselines that no longer list any entries, such as one emptied by running - PHPStan with --fix, and update the configuration's - `includes` to match. With --identifier, only those + PHPStan with --fix. With --identifier, only those baselines are considered. --memory-limit= Passed through to PHPStan. Default: 2G -h, --help Show this message. @@ -470,6 +547,15 @@ function read_file( string $path ): string { function read_baseline( string $path ): array { $data = require $path; + /* + * PHPStan writes a baseline of no errors as an empty array, without the + * `parameters` it otherwise has. That is the usual outcome for a directory + * whose errors the baselines elsewhere already cover. + */ + if ( array() === $data ) { + return array(); + } + $parameters = is_array( $data ) ? ( $data['parameters'] ?? null ) : null; $ignore_errors = is_array( $parameters ) ? ( $parameters['ignoreErrors'] ?? null ) : null; @@ -516,95 +602,52 @@ function read_baseline( string $path ): array { } /** - * Returns the configuration with the baseline `includes` removed. - * - * Those files suppress the very errors being regenerated, so they have to be out - * of the way for the analysis to report anything. + * Builds the loader for a baselines directory. * - * Two kinds of include are dropped. Everything between the `# phpstan:baselines` - * markers goes, whatever it points at, because that region is generated and every - * baseline in force is listed there. Any other include resolving inside the output - * directory goes as well, so that a baseline listed by hand outside the markers is - * still suppressed when it is about to be rewritten. + * The loader holds no logic of its own. It requires `baseline-includes.php`, by a + * path relative to its directory, and returns what get_baseline_includes() finds + * there, so a fix to that reaches every directory's loader alike. + * `baselines/loader.php` is the one this builds for the default directory. * - * The distinction matters to `--output-dir`. Were only the output directory - * considered, writing somewhere other than the default would leave the baselines - * already in force active, and the analysis would report just the errors they do - * not cover: a differential baseline rather than a complete one. + * The relative path is worked out between the real paths, since that is how the + * loader's __DIR__ is resolved when the path is followed. Worked out from the + * directory as given, a symbolic link in it would send the loader looking + * somewhere else. * - * @param non-falsy-string $config_path Absolute path to the configuration file. - * @param non-falsy-string $output_dir Absolute path to the baseline directory. - * @return string Configuration contents. + * @param non-empty-string $output_dir Absolute path to the baseline directory, which exists. + * @return non-falsy-string Loader contents. */ -function strip_baseline_includes( string $config_path, string $output_dir ): string { - $config_dir = dirname( $config_path ); - $in_block = false; - $in_managed = false; - $kept = array(); - - foreach ( explode( "\n", read_file( $config_path ) ) as $line ) { - if ( 1 === preg_match( '/^includes:/', $line ) ) { - $in_block = true; - $kept[] = $line; - continue; - } - - // A non-indented, non-blank line ends the block. - if ( $in_block && '' !== trim( $line ) && 1 !== preg_match( '/^\s/', $line ) ) { - $in_block = false; - $in_managed = false; - } - - if ( $in_block ) { - if ( BASELINES_START_MARKER === trim( $line ) ) { - $in_managed = true; - } elseif ( BASELINES_END_MARKER === trim( $line ) ) { - $in_managed = false; - } - } - - if ( $in_block && 1 === preg_match( '/^\s*-\s*(\S+)\s*$/', $line, $matches ) ) { - if ( $in_managed ) { - continue; - } - - $included = $matches[1]; - $absolute = ( '/' === $included[0] ) ? $included : $config_dir . '/' . $included; - - if ( 0 === strpos( normalize_path( $absolute ), normalize_path( $output_dir ) . '/' ) ) { - continue; - } - } +function build_loader( string $output_dir ): string { + $from = realpath( $output_dir ); + $to = realpath( __DIR__ . '/baseline-includes.php' ); - $kept[] = $line; + if ( false === $from || false === $to ) { + fwrite( STDERR, "Could not resolve $output_dir or the shared baseline includes.\n" ); + exit( 1 ); } - return implode( "\n", $kept ); -} - -/** - * Lists the per-identifier baselines present on disk. - * - * @param non-empty-string $output_dir Absolute path to the baseline directory. - * @return list Absolute paths, sorted by name. - */ -function find_baselines( string $output_dir ): array { - $found = glob( $output_dir . '/*.neon' ); - - if ( false === $found ) { - return array(); - } + return sprintf( + <<<'PHP' + $line ) { - if ( $start_marker === trim( $line ) ) { - $start = $i; - } - if ( $end_marker === trim( $line ) ) { - $end = $i; - } - } - - $region = array( "\t" . $start_marker ); - foreach ( find_baselines( $output_dir ) as $file ) { - $region[] = "\t- " . get_relative_path( dirname( $config_path ), $file ); - } - $region[] = "\t" . $end_marker; - - if ( null !== $start && null !== $end && $start < $end ) { - $updated = array_merge( - array_slice( $lines, 0, $start ), - $region, - array_slice( $lines, $end + 1 ) - ); - } else { - $insert = find_includes_end( $lines ); - - if ( null === $insert ) { - fwrite( STDERR, "No `includes` block found in $config_option, left untouched.\n" ); - return; - } - - $updated = array_merge( - array_slice( $lines, 0, $insert ), - array( '' ), - $region, - array_slice( $lines, $insert ) - ); - } - - $after = implode( "\n", $updated ); - - if ( $before === $after ) { - return; - } - - file_put_contents( $config_path, $after ); - printf( "%s: `includes` updated.\n", $config_option ); -} - -/** - * Finds where the `includes` block ends. - * - * @param list $lines Configuration lines. - * @return int|null Index of the first line after the block, or null when there is none. - */ -function find_includes_end( array $lines ): ?int { - $in_block = false; - $last = null; - - foreach ( $lines as $i => $line ) { - if ( 1 === preg_match( '/^includes:/', $line ) ) { - $in_block = true; - $last = $i; - continue; - } - - if ( ! $in_block || '' === trim( $line ) ) { - continue; - } - - // A non-indented line ends the block. - if ( 1 !== preg_match( '/^\s/', $line ) ) { - break; - } - - $last = $i; - } - - return null === $last ? null : $last + 1; -} - /** * Resolves ".." segments in a path without requiring it to exist. * @@ -861,10 +804,12 @@ function quote_neon_value( string $value ): string { * Builds the header comment for a per-identifier baseline. * * @param non-falsy-string $identifier Error identifier, a group followed by a code. - * @param non-empty-string $config Configuration path, as passed on the command line. + * @param string $options Options other than `--identifier` the + * regenerate command needs, each preceded + * by a space. Default empty. * @return non-falsy-string Comment block. */ -function build_baseline_header( string $identifier, string $config ): string { +function build_baseline_header( string $identifier, string $options = '' ): string { return << Date: Wed, 18 Nov 2026 13:05:26 +0000 Subject: [PATCH 03/85] REST API: Return no terms when a term search resolves to no taxonomy. Props xknown, dmsnell, jonsurrell, jeremyfelt. git-svn-id: https://develop.svn.wordpress.org/trunk@65567 602fd350-edb4-49c9-b593-d223f7449a82 --- .../rest-api/search/class-wp-rest-term-search-handler.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/wp-includes/rest-api/search/class-wp-rest-term-search-handler.php b/src/wp-includes/rest-api/search/class-wp-rest-term-search-handler.php index 6527697208bbb..2ece2ceed7cfb 100644 --- a/src/wp-includes/rest-api/search/class-wp-rest-term-search-handler.php +++ b/src/wp-includes/rest-api/search/class-wp-rest-term-search-handler.php @@ -90,6 +90,13 @@ public function search_items( WP_REST_Request $request ) { */ $query_args = apply_filters( 'rest_term_search_query', $query_args, $request ); + if ( empty( $query_args['taxonomy'] ) ) { + return array( + self::RESULT_IDS => array(), + self::RESULT_TOTAL => 0, + ); + } + $query = new WP_Term_Query(); $found_terms = $query->query( $query_args ); $found_ids = wp_list_pluck( $found_terms, 'term_id' ); From a89133782588b3bc5d9e2cc1719c6cb83a063aa4 Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:10:29 +0000 Subject: [PATCH 04/85] Customize: Sanitize option settings with sanitize_option() when previewing. Props westonruter, lancewillett, johnbillion, xknown. git-svn-id: https://develop.svn.wordpress.org/trunk@65568 602fd350-edb4-49c9-b593-d223f7449a82 --- .../class-wp-customize-manager.php | 6 +- .../class-wp-customize-setting.php | 261 ++++++++++++++++-- src/wp-includes/formatting.php | 8 + 3 files changed, 251 insertions(+), 24 deletions(-) diff --git a/src/wp-includes/class-wp-customize-manager.php b/src/wp-includes/class-wp-customize-manager.php index ad787986b75de..26d251ec42b5b 100644 --- a/src/wp-includes/class-wp-customize-manager.php +++ b/src/wp-includes/class-wp-customize-manager.php @@ -5220,8 +5220,9 @@ public function register_controls() { $this->add_setting( 'custom_logo', array( - 'theme_supports' => array( 'custom-logo' ), - 'transport' => 'postMessage', + 'theme_supports' => array( 'custom-logo' ), + 'transport' => 'postMessage', + 'sanitize_callback' => 'absint', ) ); @@ -5985,7 +5986,6 @@ public function handle_load_themes_request() { wp_send_json_success( $themes ); } - /** * Callback for validating the header_textcolor value. * diff --git a/src/wp-includes/class-wp-customize-setting.php b/src/wp-includes/class-wp-customize-setting.php index 2658eb20fd02d..c8272651b85df 100644 --- a/src/wp-includes/class-wp-customize-setting.php +++ b/src/wp-includes/class-wp-customize-setting.php @@ -152,6 +152,28 @@ class WP_Customize_Setting { */ protected $is_multidimensional_aggregated = false; + /** + * Whether the setting is being saved. + * + * When saving, the value of an option setting is not sanitized with `sanitize_option()` + * by {@see WP_Customize_Setting::sanitize()} since `update_option()` sanitizes it. + * + * @since 7.1.5 + * @var bool + */ + private $is_saving = false; + + /** + * Number of times that previewing has been suspended for each option, keyed by option name. + * + * While previewing an option is suspended, its preview filters pass through the original value. + * + * @since 7.1.5 + * @see WP_Customize_Setting::suspend_option_preview() + * @var array + */ + private static $suspended_option_previews = array(); + /** * Constructor. * @@ -436,6 +458,62 @@ final public function _clear_aggregated_multidimensional_preview_applied_flag() unset( self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['preview_applied_instances'][ $this->id ] ); } + /** + * Suspends previewing the setting's option, so that its preview filters pass through the original value. + * + * This is done while the option is being sanitized or saved. Every call must be paired with a call to + * {@see WP_Customize_Setting::resume_option_preview()}, including when an exception or error is thrown. + * + * @since 7.1.5 + */ + private function suspend_option_preview() { + /** @var string $id_base */ + $id_base = $this->id_data['base']; + + if ( ! isset( self::$suspended_option_previews[ $id_base ] ) ) { + self::$suspended_option_previews[ $id_base ] = 1; + } else { + ++self::$suspended_option_previews[ $id_base ]; + } + } + + /** + * Resumes previewing the setting's option, once each suspension has been resumed. + * + * @since 7.1.5 + * + * @see WP_Customize_Setting::suspend_option_preview() + */ + private function resume_option_preview() { + /** @var string $id_base */ + $id_base = $this->id_data['base']; + + if ( ! isset( self::$suspended_option_previews[ $id_base ] ) ) { + return; + } + + if ( self::$suspended_option_previews[ $id_base ] > 1 ) { + --self::$suspended_option_previews[ $id_base ]; + } else { + unset( self::$suspended_option_previews[ $id_base ] ); + } + } + + /** + * Determines whether previewing the setting's option is suspended. + * + * @since 7.1.5 + * + * @see WP_Customize_Setting::suspend_option_preview() + * + * @return bool Whether previewing the option is suspended. + */ + private function is_option_preview_suspended() { + /** @var string $id_base */ + $id_base = $this->id_data['base']; + return 'option' === $this->type && isset( self::$suspended_option_previews[ $id_base ] ); + } + /** * Callback function to filter non-multidimensional theme mods and options. * @@ -449,7 +527,7 @@ final public function _clear_aggregated_multidimensional_preview_applied_flag() * @return mixed New or old value. */ public function _preview_filter( $original ) { - if ( ! $this->is_current_blog_previewed() ) { + if ( ! $this->is_current_blog_previewed() || $this->is_option_preview_suspended() ) { return $original; } @@ -481,7 +559,7 @@ public function _preview_filter( $original ) { * @return mixed New or old value. */ final public function _multidimensional_preview_filter( $original ) { - if ( ! $this->is_current_blog_previewed() ) { + if ( ! $this->is_current_blog_previewed() || $this->is_option_preview_suspended() ) { return $original; } @@ -521,27 +599,68 @@ final public function _multidimensional_preview_filter( $original ) { * or value isn't set or is invalid. */ final public function save() { - $value = $this->post_value(); - - if ( ! $this->check_capabilities() || ! isset( $value ) ) { - return false; + /* + * While saving an option setting, its preview filters pass through the persisted value. Otherwise, + * update_option() would skip the update when the new value is the same as the previewed value, and + * hooks which read the option while saving would get a value not sanitized with sanitize_option(). + */ + if ( 'option' === $this->type ) { + $this->suspend_option_preview(); } - $id_base = $this->id_data['base']; - - /** - * Fires when the WP_Customize_Setting::save() method is called. - * - * The dynamic portion of the hook name, `$id_base` refers to - * the base slug of the setting name. - * - * @since 3.4.0 - * - * @param WP_Customize_Setting $setting WP_Customize_Setting instance. + /* + * Since a `finally` block requires PHP 5.5, the state is restored in each `catch` block before + * rethrowing. Exceptions are caught for PHP 5, and errors such as TypeError for PHP 7+. */ - do_action( "customize_save_{$id_base}", $this ); + try { + $this->is_saving = true; + $value = $this->post_value(); + $this->is_saving = false; + + if ( ! $this->check_capabilities() || ! isset( $value ) ) { + $this->end_saving(); + return false; + } - $this->update( $value ); + /** @var string $id_base */ + $id_base = $this->id_data['base']; + + /** + * Fires when the WP_Customize_Setting::save() method is called. + * + * The dynamic portion of the hook name, `$id_base` refers to + * the base slug of the setting name. + * + * @since 3.4.0 + * + * @param WP_Customize_Setting $setting WP_Customize_Setting instance. + */ + do_action( "customize_save_{$id_base}", $this ); + + $this->update( $value ); + } catch ( Exception $e ) { + $this->end_saving(); + throw $e; + } catch ( Throwable $e ) { + $this->end_saving(); + throw $e; + } + + $this->end_saving(); + } + + /** + * Restores the state changed while saving the setting. + * + * @since 7.1.5 + * + * @see WP_Customize_Setting::save() + */ + private function end_saving() { + $this->is_saving = false; + if ( 'option' === $this->type ) { + $this->resume_option_preview(); + } } /** @@ -562,12 +681,12 @@ final public function post_value( $default_value = null ) { * Sanitize an input. * * @since 3.4.0 + * @since 7.1.5 The value of an option setting is additionally sanitized with `sanitize_option()`. * * @param string|array $value The value to sanitize. * @return string|array|null|WP_Error Sanitized value, or `null`/`WP_Error` if invalid. */ public function sanitize( $value ) { - /** * Filters a Customize setting value in un-slashed form. * @@ -576,7 +695,101 @@ public function sanitize( $value ) { * @param mixed $value Value of the setting. * @param WP_Customize_Setting $setting WP_Customize_Setting instance. */ - return apply_filters( "customize_sanitize_{$this->id}", $value, $this ); + $value = apply_filters( "customize_sanitize_{$this->id}", $value, $this ); + + /* + * The value of an option setting is previewed via the option filters, bypassing the + * sanitize_option() call in update_option(). So the value is sanitized here to ensure + * that the previewed value is sanitized in the same way as the value which would be + * persisted. When saving, this is skipped since update_option() sanitizes the value. + */ + if ( 'option' === $this->type && ! $this->is_saving && ! is_null( $value ) && ! is_wp_error( $value ) ) { + $value = $this->sanitize_option_value( $value ); + } + + return $value; + } + + /** + * Sanitizes the value of an option setting with `sanitize_option()`. + * + * This applies the sanitization for core options as well as for options sanitized via the + * {@see 'sanitize_option_$option'} filter, such as by the `sanitize_callback` passed to + * `register_setting()`. The value of a multidimensional setting is sanitized as part of + * the root option value. + * + * Any errors added via `add_settings_error()` during sanitization are returned as a `WP_Error`. + * + * @since 7.1.5 + * + * @global array|null $wp_settings_errors Storage array of errors registered during this pageload. + * + * @param mixed $value Value which has already been sanitized by the setting's sanitize callback. + * @return mixed|WP_Error Sanitized value, or `WP_Error` if invalid. + */ + private function sanitize_option_value( $value ) { + global $wp_settings_errors; + + /** @var string $id_base */ + $id_base = $this->id_data['base']; + + /** @var string[] $keys */ + $keys = $this->id_data['keys']; + + // Callbacks for the "sanitize_option_{$option}" filter may call add_settings_error() without checking whether it exists. + if ( ! function_exists( 'add_settings_error' ) ) { + require_once ABSPATH . 'wp-admin/includes/template.php'; + } + + if ( $this->is_multidimensional_aggregated ) { + $root = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value']; + $value = $this->multidimensional_replace( $root, $keys, $value ); + } + + // Capture only the errors added while sanitizing, and leave the existing errors untouched. + $previous_settings_errors = $wp_settings_errors; + $previous_settings_errors_count = is_array( $wp_settings_errors ) ? count( $wp_settings_errors ) : 0; + + /* + * While sanitizing, the preview filters for the option pass through the original value. This + * prevents infinite recursion when sanitize_option() calls get_option() for the same option, + * for example to fall back to the existing value when the value is invalid. + * + * Since a `finally` block requires PHP 5.5, the state is restored in each `catch` block before + * rethrowing. Exceptions are caught for PHP 5, and errors such as TypeError for PHP 7+. + */ + $this->suspend_option_preview(); + try { + $value = sanitize_option( $id_base, $value ); + } catch ( Exception $e ) { + $this->resume_option_preview(); + $wp_settings_errors = $previous_settings_errors; + throw $e; + } catch ( Throwable $e ) { + $this->resume_option_preview(); + $wp_settings_errors = $previous_settings_errors; + throw $e; + } + $this->resume_option_preview(); + + $settings_errors = is_array( $wp_settings_errors ) ? array_slice( $wp_settings_errors, $previous_settings_errors_count ) : array(); + $wp_settings_errors = $previous_settings_errors; + + $validity = new WP_Error(); + foreach ( $settings_errors as $settings_error ) { + if ( 'error' === $settings_error['type'] ) { + $validity->add( $settings_error['code'], $settings_error['message'] ); + } + } + if ( array() !== $validity->get_error_codes() ) { + return $validity; + } + + if ( $this->is_multidimensional_aggregated ) { + $value = $this->multidimensional_get( $value, $keys ); + } + + return $value; } /** @@ -850,6 +1063,7 @@ final public function check_capabilities() { * Multidimensional helper function. * * @since 3.4.0 + * @since 7.1.5 When creating, a non-array value is overridden with an array at every level, not only the last. * * @param array $root * @param array $keys @@ -869,6 +1083,11 @@ final protected function multidimensional( &$root, $keys, $create = false ) { $node = &$root; foreach ( $keys as $key ) { + if ( $create && ! is_array( $node ) ) { + // Account for an array overriding a string or object value. + $node = array(); + } + if ( $create && ! isset( $node[ $key ] ) ) { $node[ $key ] = array(); } diff --git a/src/wp-includes/formatting.php b/src/wp-includes/formatting.php index ecae45083a6ca..ad12579fdafa1 100644 --- a/src/wp-includes/formatting.php +++ b/src/wp-includes/formatting.php @@ -4965,6 +4965,7 @@ function wp_make_link_relative( $link ) { * of functions depending on the $option. * * @since 2.0.5 + * @since 7.1.5 The `show_on_front` option is sanitized. * * @global wpdb $wpdb WordPress database abstraction object. * @@ -5205,6 +5206,13 @@ function sanitize_option( $option, $value ) { } break; + case 'show_on_front': + // Any value other than 'page' is treated as 'posts'. + if ( 'page' !== $value ) { + $value = 'posts'; + } + break; + case 'default_role': if ( ! get_role( $value ) && get_role( 'subscriber' ) ) { $value = 'subscriber'; From 45c4c458be4e0ba01f910f18103d3ddd46d097ad Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:10:56 +0000 Subject: [PATCH 05/85] REST API: Escape a hyphen in `wp_is_json_media_type()`. Props batmoo, xknown, jonsurrell. git-svn-id: https://develop.svn.wordpress.org/trunk@65569 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/load.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/load.php b/src/wp-includes/load.php index ce309d2ecd2ae..909a4ed98f66f 100644 --- a/src/wp-includes/load.php +++ b/src/wp-includes/load.php @@ -2007,7 +2007,7 @@ function wp_is_json_media_type( $media_type ) { static $cache = array(); if ( ! isset( $cache[ $media_type ] ) ) { - $cache[ $media_type ] = (bool) preg_match( '/(^|\s|,)application\/([\w!#\$&-\^\.\+]+\+)?json(\+oembed)?($|\s|;|,)/i', $media_type ); + $cache[ $media_type ] = (bool) preg_match( '/(^|\s|,)application\/([\w!#\$&\-\^\.\+]+\+)?json(\+oembed)?($|\s|;|,)/i', $media_type ); } return $cache[ $media_type ]; From 1b7a7bccf54f98a606d1206049af900eeeb24ffb Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:11:22 +0000 Subject: [PATCH 06/85] REST API: Harden comment author handling. Props xknown, jonsurrell, andrewserong. git-svn-id: https://develop.svn.wordpress.org/trunk@65570 602fd350-edb4-49c9-b593-d223f7449a82 --- .../class-wp-rest-comments-controller.php | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php index f5739e6b3a3f3..490bd7659ea59 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php @@ -586,7 +586,7 @@ public function create_item_permissions_check( $request ) { } // Limit who can set comment `author`, `author_ip` or `status` to anything other than the default. - if ( isset( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( 'moderate_comments' ) ) { + if ( isset( $request['author'] ) && get_current_user_id() !== $request['author'] && ! $this->check_assign_author_permission( $request['author'] ) ) { return new WP_Error( 'rest_comment_invalid_author', /* translators: %s: Request parameter. */ @@ -1168,6 +1168,24 @@ public function update_item_permissions_check( $request ) { ); } + /* + * Reassigning a comment copies the new author's email address onto it, + * which is then returned in the response. + */ + if ( + isset( $request['author'] ) && + (int) $request['author'] !== (int) $comment->user_id && + get_current_user_id() !== (int) $request['author'] && + ! $this->check_assign_author_permission( $request['author'] ) + ) { + return new WP_Error( + 'rest_comment_invalid_author', + /* translators: %s: Request parameter. */ + sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + /* * check_edit_permission() above only establishes that the comment may be * edited where it currently sits, because 'edit_comment' maps to 'edit_post' @@ -1215,6 +1233,15 @@ public function update_item( $request ) { ); } + /* + * Re-sending the current author is a no-op. Otherwise the author's details + * would be refreshed from their user account, exposing any change to their + * email address to whoever can edit the comment. + */ + if ( isset( $request['author'] ) && (int) $request['author'] === (int) $comment->user_id ) { + unset( $request['author'] ); + } + $prepared_args = $this->prepare_item_for_database( $request ); if ( is_wp_error( $prepared_args ) ) { @@ -2459,6 +2486,18 @@ protected function check_edit_permission( $comment ) { return current_user_can( 'edit_comment', $comment->comment_ID ); } + /** + * Checks whether the current user can attribute a comment to another user. + * + * @since 7.1.5 + * + * @param int $author_id ID of the user the comment is being attributed to. + * @return bool Whether the comment can be attributed to the user. + */ + protected function check_assign_author_permission( $author_id ) { + return current_user_can( 'moderate_comments' ) && is_user_member_of_blog( $author_id ); + } + /** * Checks a comment author email for validity. * From 0e5a0eea6e2c4efdb5de21f522ac4a7439dbbf92 Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:11:52 +0000 Subject: [PATCH 07/85] XML-RPC: Only return comments the user can read from `wp.getComments`. Props villanovachile, peterwilsoncc, westonruter, johnbillion, jonsurrell, jeremyfelt. git-svn-id: https://develop.svn.wordpress.org/trunk@65571 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-xmlrpc-server.php | 46 ++++++++++++++++++---- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/src/wp-includes/class-wp-xmlrpc-server.php b/src/wp-includes/class-wp-xmlrpc-server.php index 4ac680065f036..3a4db2f5f1641 100644 --- a/src/wp-includes/class-wp-xmlrpc-server.php +++ b/src/wp-includes/class-wp-xmlrpc-server.php @@ -1243,6 +1243,9 @@ protected function _prepare_comment( $comment ) { } else { $comment_status = $comment->comment_approved; } + + $can_moderate_or_edit = current_user_can( 'moderate_comments' ) || current_user_can( 'edit_comment', $comment->comment_ID ); + $_comment = array( 'date_created_gmt' => $comment_date_gmt, 'user_id' => $comment->user_id, @@ -1255,8 +1258,8 @@ protected function _prepare_comment( $comment ) { 'post_title' => get_the_title( $comment->comment_post_ID ), 'author' => $comment->comment_author, 'author_url' => $comment->comment_author_url, - 'author_email' => $comment->comment_author_email, - 'author_ip' => $comment->comment_author_IP, + 'author_email' => $can_moderate_or_edit ? $comment->comment_author_email : '', + 'author_ip' => $can_moderate_or_edit ? $comment->comment_author_IP : '', 'type' => $comment->comment_type, ); @@ -3784,7 +3787,9 @@ public function wp_getComments( $args ) { $status = $struct['status'] ?? ''; - if ( ! current_user_can( 'moderate_comments' ) && 'approve' !== $status ) { + $can_moderate = current_user_can( 'moderate_comments' ); + + if ( ! $can_moderate && 'approve' !== $status ) { return new IXR_Error( 401, __( 'Invalid comment status.' ) ); } @@ -3793,6 +3798,17 @@ public function wp_getComments( $args ) { $post_id = absint( $struct['post_id'] ); } + $has_public_status = static function ( $post ) { + $status = get_post_status( $post ); + $status_object = $status ? get_post_status_object( $status ) : null; + + return $status_object && $status_object->public; + }; + + if ( $post_id && ! $can_moderate && ! $has_public_status( $post_id ) && ! current_user_can( 'read_post', $post_id ) ) { + return new IXR_Error( 401, __( 'Invalid post ID.' ) ); + } + $post_type = ''; if ( isset( $struct['post_type'] ) ) { $post_type_object = get_post_type_object( $struct['post_type'] ); @@ -3814,17 +3830,31 @@ public function wp_getComments( $args ) { $comments = get_comments( array( - 'status' => $status, - 'post_id' => $post_id, - 'offset' => $offset, - 'number' => $number, - 'post_type' => $post_type, + 'status' => $status, + 'post_id' => $post_id, + 'offset' => $offset, + 'number' => $number, + 'post_type' => $post_type, + 'update_comment_post_cache' => true, ) ); $comments_struct = array(); if ( is_array( $comments ) ) { foreach ( $comments as $comment ) { + if ( ! $can_moderate && ! current_user_can( 'edit_comment', $comment->comment_ID ) ) { + $post = get_post( $comment->comment_post_ID ); + + if ( + ! $post + || ! is_post_type_viewable( $post->post_type ) + || post_password_required( $post ) + || ( ! $has_public_status( $post ) && ! current_user_can( 'read_post', $post->ID ) ) + ) { + continue; + } + } + $comments_struct[] = $this->_prepare_comment( $comment ); } } From cc42ef4e307bd37fc43a21659bdfe224c4c21ccc Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:12:18 +0000 Subject: [PATCH 08/85] Embeds: Return scripts from the oEmbed proxy only for embed handlers. Props jonsurrell, jsnajdr, jeryj. git-svn-id: https://develop.svn.wordpress.org/trunk@65572 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-oembed-controller.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/wp-includes/class-wp-oembed-controller.php b/src/wp-includes/class-wp-oembed-controller.php index d78a76d885a24..65e131f390749 100644 --- a/src/wp-includes/class-wp-oembed-controller.php +++ b/src/wp-includes/class-wp-oembed-controller.php @@ -176,6 +176,10 @@ public function get_proxy_item( $request ) { $cache_key = 'oembed_' . md5( serialize( $args ) ); $data = get_transient( $cache_key ); if ( ! empty( $data ) ) { + // Only embed handlers return scripts, and their responses are not cached. + if ( is_object( $data ) ) { + unset( $data->scripts ); + } return $data; } @@ -222,6 +226,11 @@ public function get_proxy_item( $request ) { return new WP_Error( 'oembed_invalid_url', get_status_header_desc( 404 ), array( 'status' => 404 ) ); } + // Only embed handlers return scripts. + if ( is_object( $data ) ) { + unset( $data->scripts ); + } + /** This filter is documented in wp-includes/class-wp-oembed.php */ $data->html = apply_filters( 'oembed_result', _wp_oembed_get_object()->data2html( (object) $data, $url ), $url, $args ); From e9acd04896337ea8fc67ba9c74379915a572a025 Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:12:47 +0000 Subject: [PATCH 09/85] Shortcodes: Prevent attribute escape sequences from forming HTML. Props jonsurrell, ntsekouras, westonruter, xknown, rfaile313, jorbin, jeremyfelt, ehtis. git-svn-id: https://develop.svn.wordpress.org/trunk@65573 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/shortcodes.php | 43 +++++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/src/wp-includes/shortcodes.php b/src/wp-includes/shortcodes.php index d6bb8db1e6b91..bc946676bd81c 100644 --- a/src/wp-includes/shortcodes.php +++ b/src/wp-includes/shortcodes.php @@ -616,6 +616,7 @@ function get_shortcode_atts_regex() { * @since 2.5.0 * @since 6.5.0 The function now always returns an array, * even if the original arguments string cannot be parsed or is empty. + * @since 7.1.5 A hex or octal escape that decodes to <, >, " or ' produces a character reference. * * @param string $text Shortcode arguments list. * @return array Array of attribute values keyed by attribute name. @@ -623,23 +624,53 @@ function get_shortcode_atts_regex() { * or if the original arguments string cannot be parsed. */ function shortcode_parse_atts( $text ) { + // Decodes like stripcslashes(), except that a hex or octal escape that decodes + // to `<`, `>`, `"` or `'` produces `<`, `>`, `"` or `'`. + $decode = static function ( $value ) { + if ( ! str_contains( $value, '\\' ) ) { + return $value; + } + + return preg_replace_callback( + '/\\\\(?:x[0-9A-Fa-f]{1,2}|[0-7]{1,3}|.)/s', + static function ( $matches ) { + $decoded = stripcslashes( $matches[0] ); + + // A two-byte escape cannot decode to a structural character that the raw value lacks. + if ( 2 === strlen( $matches[0] ) ) { + return $decoded; + } + + $structural = array( + '<' => '<', + '>' => '>', + '"' => '"', + "'" => ''', + ); + + return $structural[ $decoded ] ?? $decoded; + }, + $value + ); + }; + $atts = array(); $pattern = get_shortcode_atts_regex(); $text = preg_replace( "/[\x{00a0}\x{200b}]+/u", ' ', $text ); if ( preg_match_all( $pattern, $text, $match, PREG_SET_ORDER ) ) { foreach ( $match as $m ) { if ( ! empty( $m[1] ) ) { - $atts[ strtolower( $m[1] ) ] = stripcslashes( $m[2] ); + $atts[ strtolower( $m[1] ) ] = $decode( $m[2] ); } elseif ( ! empty( $m[3] ) ) { - $atts[ strtolower( $m[3] ) ] = stripcslashes( $m[4] ); + $atts[ strtolower( $m[3] ) ] = $decode( $m[4] ); } elseif ( ! empty( $m[5] ) ) { - $atts[ strtolower( $m[5] ) ] = stripcslashes( $m[6] ); + $atts[ strtolower( $m[5] ) ] = $decode( $m[6] ); } elseif ( isset( $m[7] ) && strlen( $m[7] ) ) { - $atts[] = stripcslashes( $m[7] ); + $atts[] = $decode( $m[7] ); } elseif ( isset( $m[8] ) && strlen( $m[8] ) ) { - $atts[] = stripcslashes( $m[8] ); + $atts[] = $decode( $m[8] ); } elseif ( isset( $m[9] ) ) { - $atts[] = stripcslashes( $m[9] ); + $atts[] = $decode( $m[9] ); } } From 0ed3c9e8667902913d64292efd0258cdbd44c08d Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:13:14 +0000 Subject: [PATCH 10/85] Meta API: Validate the `relation` argument in `WP_Meta_Query`. Props xknown, westonruter, jeremyfelt. git-svn-id: https://develop.svn.wordpress.org/trunk@65574 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-meta-query.php | 40 ++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/src/wp-includes/class-wp-meta-query.php b/src/wp-includes/class-wp-meta-query.php index 67e2d3d27ee0b..07bf07702027b 100644 --- a/src/wp-includes/class-wp-meta-query.php +++ b/src/wp-includes/class-wp-meta-query.php @@ -36,6 +36,7 @@ class WP_Meta_Query { * * @since 3.2.0 * @var string + * @phpstan-var 'AND'|'OR'|null */ public $relation; @@ -170,8 +171,8 @@ public function __construct( $meta_query = array() ) { return; } - if ( isset( $meta_query['relation'] ) && 'OR' === strtoupper( $meta_query['relation'] ) ) { - $this->relation = 'OR'; + if ( isset( $meta_query['relation'] ) ) { + $this->relation = $this->sanitize_relation( $meta_query['relation'] ); } else { $this->relation = 'AND'; } @@ -209,6 +210,19 @@ public function sanitize_query( $queries ) { unset( $query['value'] ); } + /* + * Dropping an empty value can leave a clause that is no longer + * first-order, so sanitize it as a nested query instead. Otherwise + * it would be stored unsanitized and later treated as a nested + * query when the SQL is generated. + */ + if ( ! $this->is_first_order_clause( $query ) ) { + $query = $this->sanitize_query( $query ); + } elseif ( array_key_exists( 'relation', $query ) ) { + // A first-order clause has no relation of its own, but never store an unvalidated one. + $query['relation'] = $this->sanitize_relation( $query['relation'] ); + } + $clean_queries[ $key ] = $query; // Otherwise, it's a nested query, so we recurse. @@ -226,7 +240,7 @@ public function sanitize_query( $queries ) { } // Sanitize the 'relation' key provided in the query. - if ( isset( $relation ) && 'OR' === strtoupper( $relation ) ) { + if ( isset( $relation ) && 'OR' === $this->sanitize_relation( $relation ) ) { $clean_queries['relation'] = 'OR'; $this->has_or_relation = true; @@ -246,6 +260,23 @@ public function sanitize_query( $queries ) { return $clean_queries; } + /** + * Sanitizes a 'relation' operator. + * + * @since 7.1.5 + * + * @param mixed $relation Raw relation key from the query argument. Typically the string 'AND' or 'OR'. + * @return string Sanitized relation. Either 'AND' or 'OR'. + * @phpstan-return 'AND'|'OR' + */ + public function sanitize_relation( $relation ) { + if ( is_string( $relation ) && 'OR' === strtoupper( $relation ) ) { + return 'OR'; + } else { + return 'AND'; + } + } + /** * Determines whether a query clause is first-order. * @@ -461,7 +492,8 @@ protected function get_sql_for_query( &$query, $depth = 0 ) { foreach ( $query as $key => &$clause ) { if ( 'relation' === $key ) { - $relation = $query['relation']; + // Clauses that bypassed sanitize_query() may carry an unvalidated relation. + $relation = $this->sanitize_relation( $query['relation'] ); } elseif ( is_array( $clause ) ) { // This is a first-order clause. From 75aab487b79da13762e4be7b8111cfb161738b84 Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:13:40 +0000 Subject: [PATCH 11/85] Customize: Harden nav menu args handling. Props xknown, jonsurrell, jeremyfelt. git-svn-id: https://develop.svn.wordpress.org/trunk@65575 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-customize-nav-menus.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/class-wp-customize-nav-menus.php b/src/wp-includes/class-wp-customize-nav-menus.php index b093509f2f5c2..8df0392bf2406 100644 --- a/src/wp-includes/class-wp-customize-nav-menus.php +++ b/src/wp-includes/class-wp-customize-nav-menus.php @@ -1530,13 +1530,17 @@ public function filter_wp_nav_menu( $nav_menu_content, $args ) { * * Note that the array is expected to be pre-sorted. * + * The serialized arguments are prefixed so that the resulting hash cannot + * collide with other `wp_hash()` values computed over serialized data. + * * @since 4.3.0 + * @since 7.1.5 The hash is now domain-separated from other hashes. * * @param array $args The arguments to hash. * @return string Hashed nav menu arguments. */ public function hash_nav_menu_args( $args ) { - return wp_hash( serialize( $args ) ); + return wp_hash( 'customize_nav_menu_args|' . serialize( $args ) ); } /** From 1fdfb3998d97a692e320057335adcd280f86dbf2 Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:14:06 +0000 Subject: [PATCH 12/85] Query: Use prepared statements for more `WP_Query` clauses. Props rfaile313, westonruter, tyxla, lancewillett, xknown, jeremyfelt. git-svn-id: https://develop.svn.wordpress.org/trunk@65576 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-query.php | 54 ++++++++++++++++++------------ 1 file changed, 32 insertions(+), 22 deletions(-) diff --git a/src/wp-includes/class-wp-query.php b/src/wp-includes/class-wp-query.php index 44220d06c9b3c..c5e048efe3806 100644 --- a/src/wp-includes/class-wp-query.php +++ b/src/wp-includes/class-wp-query.php @@ -2097,25 +2097,26 @@ public function get_posts() { } if ( '' !== $query_vars['menu_order'] ) { - $where .= " AND {$wpdb->posts}.menu_order = " . $query_vars['menu_order']; + // The value is wrapped in an array so that an array value is queried as 0 instead of dropping the condition. + $where .= $wpdb->prepare( " AND {$wpdb->posts}.menu_order = %d", array( $query_vars['menu_order'] ) ); } // The "m" parameter is meant for months but accepts datetimes of varying specificity. if ( $query_vars['m'] ) { - $where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr( $query_vars['m'], 0, 4 ); + $where .= $wpdb->prepare( " AND YEAR({$wpdb->posts}.post_date)=%d", substr( $query_vars['m'], 0, 4 ) ); if ( strlen( $query_vars['m'] ) > 5 ) { - $where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr( $query_vars['m'], 4, 2 ); + $where .= $wpdb->prepare( " AND MONTH({$wpdb->posts}.post_date)=%02d", substr( $query_vars['m'], 4, 2 ) ); } if ( strlen( $query_vars['m'] ) > 7 ) { - $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr( $query_vars['m'], 6, 2 ); + $where .= $wpdb->prepare( " AND DAYOFMONTH({$wpdb->posts}.post_date)=%02d", substr( $query_vars['m'], 6, 2 ) ); } if ( strlen( $query_vars['m'] ) > 9 ) { - $where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr( $query_vars['m'], 8, 2 ); + $where .= $wpdb->prepare( " AND HOUR({$wpdb->posts}.post_date)=%02d", substr( $query_vars['m'], 8, 2 ) ); } if ( strlen( $query_vars['m'] ) > 11 ) { - $where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr( $query_vars['m'], 10, 2 ); + $where .= $wpdb->prepare( " AND MINUTE({$wpdb->posts}.post_date)=%02d", substr( $query_vars['m'], 10, 2 ) ); } if ( strlen( $query_vars['m'] ) > 13 ) { - $where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr( $query_vars['m'], 12, 2 ); + $where .= $wpdb->prepare( " AND SECOND({$wpdb->posts}.post_date)=%02d", substr( $query_vars['m'], 12, 2 ) ); } } @@ -2224,8 +2225,9 @@ public function get_posts() { if ( ( 'page' !== get_option( 'show_on_front' ) ) || empty( $page_for_posts ) || ( $reqpage != $page_for_posts ) ) { $query_vars['pagename'] = sanitize_title_for_query( wp_basename( $query_vars['pagename'] ) ); $query_vars['name'] = $query_vars['pagename']; - $where .= " AND ({$wpdb->posts}.ID = '$reqpage')"; - $reqpage_obj = get_post( $reqpage ); + // The value is wrapped in an array so that an array value is queried as 0 instead of dropping the condition. + $where .= $wpdb->prepare( " AND ({$wpdb->posts}.ID = '%d')", array( $reqpage ) ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.QuotedSimplePlaceholder -- Quoted to keep the SQL unchanged for filters. + $reqpage_obj = get_post( $reqpage ); if ( is_object( $reqpage_obj ) && 'attachment' === $reqpage_obj->post_type ) { $this->is_attachment = true; $post_type = 'attachment'; @@ -2254,7 +2256,8 @@ public function get_posts() { // If a post number is specified, load that post. if ( $query_vars['p'] ) { - $where .= " AND {$wpdb->posts}.ID = " . $query_vars['p']; + // The value is wrapped in an array so that an array value is queried as 0 instead of dropping the condition. + $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID = %d", array( $query_vars['p'] ) ); } elseif ( $query_vars['post__in'] ) { // Duplicate array before sorting to allow for the orderby clause. $post__in_for_where = $query_vars['post__in']; @@ -2286,7 +2289,8 @@ public function get_posts() { if ( $query_vars['page_id'] ) { if ( ( 'page' !== get_option( 'show_on_front' ) ) || ( get_option( 'page_for_posts' ) != $query_vars['page_id'] ) ) { $query_vars['p'] = $query_vars['page_id']; - $where = " AND {$wpdb->posts}.ID = " . $query_vars['page_id']; + // The value is wrapped in an array so that an array value is queried as 0 instead of dropping the condition. + $where = $wpdb->prepare( " AND {$wpdb->posts}.ID = %d", array( $query_vars['page_id'] ) ); } } @@ -2677,16 +2681,16 @@ public function get_posts() { if ( in_array( 'any', $q_status, true ) ) { foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) { if ( ! in_array( $status, $q_status, true ) ) { - $e_status[] = "{$wpdb->posts}.post_status <> '$status'"; + $e_status[] = $wpdb->prepare( "{$wpdb->posts}.post_status <> %s", $status ); } } } else { foreach ( get_post_stati() as $status ) { if ( in_array( $status, $q_status, true ) ) { if ( 'private' === $status ) { - $p_status[] = "{$wpdb->posts}.post_status = '$status'"; + $p_status[] = $wpdb->prepare( "{$wpdb->posts}.post_status = %s", $status ); } else { - $r_status[] = "{$wpdb->posts}.post_status = '$status'"; + $r_status[] = $wpdb->prepare( "{$wpdb->posts}.post_status = %s", $status ); } } } @@ -2702,14 +2706,14 @@ public function get_posts() { } if ( ! empty( $r_status ) ) { if ( ! empty( $query_vars['perm'] ) && 'editable' === $query_vars['perm'] && ! current_user_can( $edit_others_cap ) ) { - $statuswheres[] = "({$wpdb->posts}.post_author = $user_id " . 'AND (' . implode( ' OR ', $r_status ) . '))'; + $statuswheres[] = $wpdb->prepare( "({$wpdb->posts}.post_author = %d ", $user_id ) . 'AND (' . implode( ' OR ', $r_status ) . '))'; } else { $statuswheres[] = '(' . implode( ' OR ', $r_status ) . ')'; } } if ( ! empty( $p_status ) ) { if ( ! empty( $query_vars['perm'] ) && 'readable' === $query_vars['perm'] && ! current_user_can( $read_private_cap ) ) { - $statuswheres[] = "({$wpdb->posts}.post_author = $user_id " . 'AND (' . implode( ' OR ', $p_status ) . '))'; + $statuswheres[] = $wpdb->prepare( "({$wpdb->posts}.post_author = %d ", $user_id ) . 'AND (' . implode( ' OR ', $p_status ) . '))'; } else { $statuswheres[] = '(' . implode( ' OR ', $p_status ) . ')'; } @@ -2749,7 +2753,7 @@ public function get_posts() { $public_statuses = get_post_stati( array( 'public' => true ) ); $status_clauses = array(); foreach ( $public_statuses as $public_status ) { - $status_clauses[] = "{$wpdb->posts}.post_status = '$public_status'"; + $status_clauses[] = $wpdb->prepare( "{$wpdb->posts}.post_status = %s", $public_status ); } $type_where .= implode( ' OR ', $status_clauses ); @@ -2762,7 +2766,7 @@ public function get_posts() { ) ); foreach ( $admin_all_statuses as $admin_all_status ) { - $type_where .= " OR {$wpdb->posts}.post_status = '$admin_all_status'"; + $type_where .= $wpdb->prepare( " OR {$wpdb->posts}.post_status = %s", $admin_all_status ); } } @@ -2771,7 +2775,7 @@ public function get_posts() { $read_private_cap = $queried_post_type_object->cap->read_private_posts; $private_statuses = get_post_stati( array( 'private' => true ) ); foreach ( $private_statuses as $private_status ) { - $type_where .= current_user_can( $read_private_cap ) ? " \nOR {$wpdb->posts}.post_status = '$private_status'" : " \nOR ({$wpdb->posts}.post_author = $user_id AND {$wpdb->posts}.post_status = '$private_status')"; + $type_where .= current_user_can( $read_private_cap ) ? $wpdb->prepare( " \nOR {$wpdb->posts}.post_status = %s", $private_status ) : $wpdb->prepare( " \nOR ({$wpdb->posts}.post_author = %d AND {$wpdb->posts}.post_status = %s)", $user_id, $private_status ); } } @@ -2886,6 +2890,9 @@ public function get_posts() { */ $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) ); + // The value is wrapped in an array so that an array value is queried as 0 instead of dropping the condition. + $climits = $wpdb->prepare( 'LIMIT %d', array( get_option( 'posts_per_rss' ) ) ); + /** * Filters the LIMIT clause of the comments feed query before sending. * @@ -2894,7 +2901,7 @@ public function get_posts() { * @param string $climits The JOIN clause of the query. * @param WP_Query $query The WP_Query instance (passed by reference). */ - $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option( 'posts_per_rss' ), &$this ) ); + $climits = apply_filters_ref_array( 'comment_feed_limits', array( $climits, &$this ) ); } $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : ''; @@ -3558,7 +3565,7 @@ public function get_posts() { $cjoin = apply_filters_ref_array( 'comment_feed_join', array( '', &$this ) ); /** This filter is documented in wp-includes/class-wp-query.php */ - $cwhere = apply_filters_ref_array( 'comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1' AND {$wpdb->comments}.comment_type NOT IN ( 'note', 'reaction' )", &$this ) ); + $cwhere = apply_filters_ref_array( 'comment_feed_where', array( $wpdb->prepare( "WHERE comment_post_ID = '%d' AND comment_approved = '1' AND {$wpdb->comments}.comment_type NOT IN ( 'note', 'reaction' )", $this->posts[0]->ID ), &$this ) ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.QuotedSimplePlaceholder -- Quoted to keep the SQL unchanged for filters. /** This filter is documented in wp-includes/class-wp-query.php */ $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( '', &$this ) ); @@ -3568,8 +3575,11 @@ public function get_posts() { $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) ); $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : ''; + // The value is wrapped in an array so that an array value is queried as 0 instead of dropping the condition. + $climits = $wpdb->prepare( 'LIMIT %d', array( get_option( 'posts_per_rss' ) ) ); + /** This filter is documented in wp-includes/class-wp-query.php */ - $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option( 'posts_per_rss' ), &$this ) ); + $climits = apply_filters_ref_array( 'comment_feed_limits', array( $climits, &$this ) ); $comments_request = "SELECT {$wpdb->comments}.comment_ID FROM {$wpdb->comments} $cjoin $cwhere $cgroupby $corderby $climits"; From ba9a93c4dc4ceecc6258216ce6e6385daad619ed Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:14:32 +0000 Subject: [PATCH 13/85] REST API: Only serve `rest_route` requests outside of the admin. Props xknown, jonsurrell, jeremyfelt. git-svn-id: https://develop.svn.wordpress.org/trunk@65577 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/rest-api.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/rest-api.php b/src/wp-includes/rest-api.php index f8d5e0a383e81..d61bb4fe31ee5 100644 --- a/src/wp-includes/rest-api.php +++ b/src/wp-includes/rest-api.php @@ -454,7 +454,11 @@ function create_initial_rest_routes() { * @global WP $wp Current WordPress environment instance. */ function rest_api_loaded() { - if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) { + /* + * Admin screens call wp() for list queries; they are never REST entry points. + * Check WP_ADMIN rather than is_admin(), which follows the current screen. + */ + if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) || defined( 'WP_ADMIN' ) ) { return; } From 86d0d8a3bf44a6b14dcc611a4048b3aae1c8b17a Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:14:58 +0000 Subject: [PATCH 14/85] Comments: Check permissions before moving a comment to another post in the admin. Props jorbin, ramonopoly, westonruter, adamsilverstein, jeremyfelt, rfaile313. git-svn-id: https://develop.svn.wordpress.org/trunk@65578 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/includes/comment.php | 111 ++++++++++++++++++++++++++++-- 1 file changed, 107 insertions(+), 4 deletions(-) diff --git a/src/wp-admin/includes/comment.php b/src/wp-admin/includes/comment.php index 1cfc93144e978..5f46be6a5cdfa 100644 --- a/src/wp-admin/includes/comment.php +++ b/src/wp-admin/includes/comment.php @@ -47,6 +47,8 @@ function comment_exists( $comment_author, $comment_date, $timezone = 'blog' ) { * @since 2.0.0 * @since 5.5.0 A return value was added. * @since 7.1.0 The comment parent can be updated via `$_POST['comment_parent']`. + * @since 7.1.5 Moving a comment to another post is checked against the user's capabilities, + * and the comment type can no longer be changed. * * @return int|WP_Error The value 1 if the comment was updated, 0 if not updated. * A WP_Error object on failure. @@ -75,14 +77,50 @@ function edit_comment() { $_POST['comment_ID'] = (int) $_POST['comment_ID']; } + $comment_id = (int) $_POST['comment_ID']; + $comment = get_comment( $comment_id ); + + /* + * The comment type is not editable from the Edit Comment screen. Changing it + * would turn a private note into a public comment or vice versa, and would + * break the rule that replies share their parent's type. + */ + if ( $comment && isset( $_POST['comment_type'] ) && $_POST['comment_type'] !== $comment->comment_type ) { + return new WP_Error( 'comment_type_invalid', __( 'The comment type cannot be changed.' ) ); + } + + /* + * The capability check above only establishes that the comment may be edited + * where it currently sits, because 'edit_comment' maps to 'edit_post' on the + * comment's current post. Moving the comment to another post has to be + * authorized separately, otherwise a user who can edit a comment on their own + * post could attach it to any post, including posts they can neither read nor + * edit. + */ + + $comment_post_id = $comment ? (int) $comment->comment_post_ID : 0; + + if ( $comment && isset( $_POST['comment_post_ID'] ) ) { + $target_post_id = (int) $_POST['comment_post_ID']; + + $_POST['comment_post_ID'] = $target_post_id; + + if ( $target_post_id !== $comment_post_id ) { + $target_post_check = _wp_check_comment_target_post( $comment, $target_post_id ); + + if ( is_wp_error( $target_post_check ) ) { + return $target_post_check; + } + + $comment_post_id = $target_post_id; + } + } + if ( isset( $_POST['comment_parent'] ) ) { - $comment_id = (int) $_POST['comment_ID']; $comment_parent = (int) $_POST['comment_parent']; $_POST['comment_parent'] = $comment_parent; - $comment = get_comment( $comment_id ); - if ( $comment && $comment_parent && $comment_parent !== (int) $comment->comment_parent ) { if ( ! get_option( 'thread_comments' ) ) { return new WP_Error( 'comment_parent_invalid', __( 'The comment parent cannot be changed because threaded comments are disabled.' ) ); @@ -100,7 +138,7 @@ function edit_comment() { // The parent must be a comment of the same type, on the same post, and publicly visible if the comment is approved. if ( ! $parent - || (int) $parent->comment_post_ID !== (int) $comment->comment_post_ID + || (int) $parent->comment_post_ID !== $comment_post_id || $parent->comment_type !== $comment->comment_type || in_array( $parent_status, array( 'spam', 'trash' ), true ) || ( $comment_is_approved && 'approved' !== $parent_status ) @@ -183,6 +221,71 @@ function edit_comment() { return wp_update_comment( $_POST, true ); } +/** + * Checks that the current user may move a comment to another post. + * + * Mirrors the checks applied by the REST API comments controller when the + * parent post of a comment or note is changed. + * + * @since 7.1.5 + * @access private + * + * @param WP_Comment $comment The comment being moved. + * @param int $post_id ID of the post the comment is being moved to. + * @return true|WP_Error True if the comment may be moved to the post, WP_Error otherwise. + */ +function _wp_check_comment_target_post( WP_Comment $comment, int $post_id ) { + $post = $post_id ? get_post( $post_id ) : null; + + if ( ! $post ) { + return new WP_Error( 'comment_post_invalid', __( 'Invalid post ID.' ) ); + } + + /* + * Notes are editorial content, so they may only be attached to a post the + * user can edit. Any other comment needs either comment moderation rights + * or edit access to the post, matching what 'edit_comment' requires on the + * post the comment is moving away from. + */ + $is_note = 'note' === strtolower( $comment->comment_type ); + + if ( $is_note ) { + $can_target_post = current_user_can( 'edit_post', $post->ID ); + } else { + $can_target_post = current_user_can( 'moderate_comments' ) || current_user_can( 'edit_post', $post->ID ); + } + + if ( ! $can_target_post ) { + return new WP_Error( 'comment_post_invalid', __( 'Sorry, you are not allowed to move this comment to that post.' ) ); + } + + if ( ! $is_note ) { + return true; + } + + $supports_notes = false; + $supports = get_all_post_type_supports( $post->post_type ); + + if ( isset( $supports['editor'] ) && is_array( $supports['editor'] ) ) { + $supports_notes = array_any( + $supports['editor'], + static function ( $item ) { + return is_array( $item ) && ! empty( $item['notes'] ); + } + ); + } + + if ( ! $supports_notes ) { + return new WP_Error( 'comment_post_invalid', __( 'Sorry, this post type does not support notes.' ) ); + } + + if ( 'trash' === $post->post_status || ! current_user_can( 'read_post', $post->ID ) ) { + return new WP_Error( 'comment_post_invalid', __( 'Sorry, you are not allowed to move this comment to that post.' ) ); + } + + return true; +} + /** * Returns a WP_Comment object based on comment ID. * From c2ee32bbe1872347b0eb392ad800e11fe527cf5e Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:15:24 +0000 Subject: [PATCH 15/85] XML-RPC: Process only one pingback per request. Props johnbillion, batmoo, jonsurrell, jeremyfelt, jorbin, xknown, rfaile313. git-svn-id: https://develop.svn.wordpress.org/trunk@65579 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-xmlrpc-server.php | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/wp-includes/class-wp-xmlrpc-server.php b/src/wp-includes/class-wp-xmlrpc-server.php index 3a4db2f5f1641..515a2458f9e38 100644 --- a/src/wp-includes/class-wp-xmlrpc-server.php +++ b/src/wp-includes/class-wp-xmlrpc-server.php @@ -50,6 +50,17 @@ class wp_xmlrpc_server extends IXR_Server { */ protected $auth_failed = false; + /** + * Flags that a pingback has already been processed in this instance of wp_xmlrpc_server. + * + * Prevents a single `system.multicall` request from processing an unbounded number of pingbacks. + * + * @since 7.1.5 + * + * @var bool + */ + protected $pingback_processed = false; + /** * Flags that XML-RPC is enabled * @@ -7097,6 +7108,16 @@ public function mt_publishPost( $args ) { public function pingback_ping( $args ) { global $wpdb; + /* + * Checked before the `xmlrpc_call` action and any database or network work, so repeated + * calls in a multicall cost nothing, including in plugins that check each pingback. + */ + if ( $this->pingback_processed ) { + return $this->pingback_error( 49, __( 'Only one pingback can be processed per request.' ) ); + } + + $this->pingback_processed = true; + /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */ do_action( 'xmlrpc_call', 'pingback.ping', $args, $this ); From 6b74030aa3a78f8b1033a9aff424044102e59d78 Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:15:52 +0000 Subject: [PATCH 16/85] Interactivity API: Escape the store namespace in `wp_interactivity_data_wp_context()`. Props jrf, gziolo, luisherranz, jonsurrell, lancewillett. git-svn-id: https://develop.svn.wordpress.org/trunk@65580 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/interactivity-api/interactivity-api.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/interactivity-api/interactivity-api.php b/src/wp-includes/interactivity-api/interactivity-api.php index 81c6362b94a39..b08e14191602a 100644 --- a/src/wp-includes/interactivity-api/interactivity-api.php +++ b/src/wp-includes/interactivity-api/interactivity-api.php @@ -103,7 +103,7 @@ function wp_interactivity_config( string $store_namespace, array $config = array */ function wp_interactivity_data_wp_context( array $context, string $store_namespace = '' ): string { return 'data-wp-context=\'' . - ( $store_namespace ? $store_namespace . '::' : '' ) . + ( $store_namespace ? esc_attr( $store_namespace ) . '::' : '' ) . ( empty( $context ) ? '{}' : wp_json_encode( $context, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP ) ) . '\''; } From 750136d3ec3023d77eb4488f4a07b81049cfbdcf Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 13:16:28 +0000 Subject: [PATCH 17/85] REST API: Restrict post and template author assignment to site members. Props jsnajdr, johnbillion, jeryj, xknown. git-svn-id: https://develop.svn.wordpress.org/trunk@65581 602fd350-edb4-49c9-b593-d223f7449a82 --- .../endpoints/class-wp-rest-posts-controller.php | 9 ++++----- .../endpoints/class-wp-rest-templates-controller.php | 9 ++++----- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php index 0c24925ff9245..a333b55845410 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php @@ -1392,12 +1392,11 @@ protected function prepare_item_for_database( $request ) { // Author. if ( ! empty( $schema['properties']['author'] ) && ! empty( $request['author'] ) ) { - $post_author = (int) $request['author']; + $post_author = (int) $request['author']; + $current_author = isset( $existing_post ) ? (int) $existing_post->post_author : 0; - if ( get_current_user_id() !== $post_author ) { - $user_obj = get_userdata( $post_author ); - - if ( ! $user_obj ) { + if ( get_current_user_id() !== $post_author && $current_author !== $post_author ) { + if ( ! is_user_member_of_blog( $post_author ) ) { return new WP_Error( 'rest_invalid_author', __( 'Invalid author ID.' ), diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php index b2429f1f482cb..93e38bb0950d2 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php @@ -640,12 +640,11 @@ protected function prepare_item_for_database( $request ) { } if ( ! empty( $request['author'] ) ) { - $post_author = (int) $request['author']; + $post_author = (int) $request['author']; + $current_author = $template instanceof WP_Block_Template ? (int) $template->author : 0; - if ( get_current_user_id() !== $post_author ) { - $user_obj = get_userdata( $post_author ); - - if ( ! $user_obj ) { + if ( get_current_user_id() !== $post_author && $current_author !== $post_author ) { + if ( ! is_user_member_of_blog( $post_author ) ) { return new WP_Error( 'rest_invalid_author', __( 'Invalid author ID.' ), From ca8e4ca246a29e1bf550efe923daeea7e404690a Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 14:02:11 +0000 Subject: [PATCH 18/85] Tests: Update the expected error for an invalid comment author. Follow-up to [65570]. Props jeremyfelt. git-svn-id: https://develop.svn.wordpress.org/trunk@65582 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/rest-api/rest-comments-controller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/phpunit/tests/rest-api/rest-comments-controller.php b/tests/phpunit/tests/rest-api/rest-comments-controller.php index 898b344842f9a..7cb9f647063d9 100644 --- a/tests/phpunit/tests/rest-api/rest-comments-controller.php +++ b/tests/phpunit/tests/rest-api/rest-comments-controller.php @@ -2345,7 +2345,7 @@ public function test_create_item_invalid_author() { $request->set_body( wp_json_encode( $params ) ); $response = rest_get_server()->dispatch( $request ); - $this->assertErrorResponse( 'rest_comment_author_invalid', $response, 400 ); + $this->assertErrorResponse( 'rest_comment_invalid_author', $response, 403 ); } public function test_create_item_pull_author_info() { From f276d60cbbec44eba4683d251b2af90ea982e527 Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 14:39:30 +0000 Subject: [PATCH 19/85] General: Bump the pinned hash for Gutenberg to `efd7722`. This updates the pinned commit hash of the Gutenberg repository from `61aba5422836aeed76a794f98d3fe0da3eb5f5d1` to `efd7722f89ebb8abfc3607fffdd86f5e34afbd9c`. A full list of changes included in this commit can be found on GitHub: https://github.com/WordPress/gutenberg/compare/61aba5422836aeed76a794f98d3fe0da3eb5f5d1...efd7722f89ebb8abfc3607fffdd86f5e34afbd9c. git-svn-id: https://develop.svn.wordpress.org/trunk@65583 602fd350-edb4-49c9-b593-d223f7449a82 --- package.json | 2 +- src/wp-includes/assets/script-loader-packages.php | 6 +++--- src/wp-includes/blocks/comment-date.php | 4 +++- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 269b8d3a9cfdf..12a90c83b077b 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "url": "https://develop.svn.wordpress.org/trunk" }, "gutenberg": { - "sha": "61aba5422836aeed76a794f98d3fe0da3eb5f5d1", + "sha": "efd7722f89ebb8abfc3607fffdd86f5e34afbd9c", "ghcrRepo": "WordPress/gutenberg/gutenberg-wp-develop-build" }, "engines": { diff --git a/src/wp-includes/assets/script-loader-packages.php b/src/wp-includes/assets/script-loader-packages.php index 9512d25d2c5ce..e33f77b5f7755 100644 --- a/src/wp-includes/assets/script-loader-packages.php +++ b/src/wp-includes/assets/script-loader-packages.php @@ -151,7 +151,7 @@ 'import' => 'dynamic' ) ), - 'version' => '8118001470fde50b42fe' + 'version' => '58156d96a4c9fdf86645' ), 'block-serialization-default-parser.js' => array( 'dependencies' => array( @@ -282,7 +282,7 @@ 'wp-url', 'wp-warning' ), - 'version' => '089f1cc441f999d491af' + 'version' => '26d8066a55a711f6eed8' ), 'customize-widgets.js' => array( 'dependencies' => array( @@ -549,7 +549,7 @@ 'import' => 'static' ) ), - 'version' => '3427e50f718f7602341b' + 'version' => '33deefc6545abe93022a' ), 'element.js' => array( 'dependencies' => array( diff --git a/src/wp-includes/blocks/comment-date.php b/src/wp-includes/blocks/comment-date.php index 7856e132404a8..b14559b3cd336 100644 --- a/src/wp-includes/blocks/comment-date.php +++ b/src/wp-includes/blocks/comment-date.php @@ -37,7 +37,9 @@ function render_block_core_comment_date( $attributes, $content, $block ) { $link = get_comment_link( $comment ); if ( ! empty( $attributes['isLink'] ) ) { - $formatted_date = sprintf( '%2$s', esc_url( $link ), $formatted_date ); + $formatted_date = sprintf( '%2$s', esc_url( $link ), esc_html( $formatted_date ) ); + } else { + $formatted_date = esc_html( $formatted_date ); } return sprintf( From a2c645986d9a662b5f595e604dca6f7b95d830db Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 16:41:53 +0000 Subject: [PATCH 20/85] WordPress 7.2 RC 2. git-svn-id: https://develop.svn.wordpress.org/trunk@65604 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/version.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/version.php b/src/wp-includes/version.php index bfb37d9220880..69e799eb719ea 100644 --- a/src/wp-includes/version.php +++ b/src/wp-includes/version.php @@ -16,7 +16,7 @@ * * @global string $wp_version */ -$wp_version = '7.2-RC1-65559-src'; +$wp_version = '7.2-RC2-src'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. From bb6f370ee308b91c8a7edb82d323353e47f227a1 Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Wed, 18 Nov 2026 17:08:47 +0000 Subject: [PATCH 21/85] Post WordPress 7.2-RC2 version bump. git-svn-id: https://develop.svn.wordpress.org/trunk@65606 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/version.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/version.php b/src/wp-includes/version.php index 69e799eb719ea..6bc5d15fb0437 100644 --- a/src/wp-includes/version.php +++ b/src/wp-includes/version.php @@ -16,7 +16,7 @@ * * @global string $wp_version */ -$wp_version = '7.2-RC2-src'; +$wp_version = '7.2-RC2-65605-src'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. From 689cb3301342862af0ca35604e48406aae1a0357 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Wed, 18 Nov 2026 22:32:16 +0000 Subject: [PATCH 22/85] Tests: Cover `wp_strict_cross_origin_referrer()`. Verify the expected output of `` tag. Developed in https://github.com/WordPress/wordpress-develop/pull/15355. Props devmuhib, huzaifaalmesbah, lancewillett. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65667 602fd350-edb4-49c9-b593-d223f7449a82 --- .../general/wpStrictCrossOriginReferrer.php | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 tests/phpunit/tests/general/wpStrictCrossOriginReferrer.php diff --git a/tests/phpunit/tests/general/wpStrictCrossOriginReferrer.php b/tests/phpunit/tests/general/wpStrictCrossOriginReferrer.php new file mode 100644 index 0000000000000..f09e2f7952c70 --- /dev/null +++ b/tests/phpunit/tests/general/wpStrictCrossOriginReferrer.php @@ -0,0 +1,27 @@ +"; + + ob_start(); + wp_strict_cross_origin_referrer(); + $actual = trim( ob_get_clean() ); + + $this->assertSame( $expected, $actual ); + } +} From a21fd678f87eafeaf6bc9aafdd11b7f314707ebe Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Wed, 18 Nov 2026 23:06:14 +0000 Subject: [PATCH 23/85] Build/Test Tools: Hold a project subset to PHPStan rule level 10. PHPStan analyzes all of core at rule level 5, but much of the code added in recent releases, such as the Abilities API and the AI client, already meets or nearly meets level 10. A second analysis now holds a selected set of paths to level 10, so that they cannot regress, and so that the set can grow as more files are brought up to that level, without raising the level for the entire project. PHPStan has no per-path rule levels, so the strict paths have a configuration of their own, `phpstan-strict.neon.dist`, which includes `phpstan.neon.dist`, replaces its paths with the strict ones, and scans the rest of core so that its symbols are known. Its baselines in `tests/phpstan/baselines-strict/` hold only what level 10 adds in the strict paths, since it includes the default baselines too. The two analyses are named "default" and "strict" rather than after their levels, since either level can be raised. The narrowed analysis relies on PHPStan 2.3.6, which no longer reports an ignored error as unmatched when its file is not analyzed. `composer phpstan` now runs both analyses. Also, `composer phpstan:baselines` and `composer phpstan:fix` handle both baseline directories. In CI, the two analyses run as parallel jobs, whose results are merged into the pull request comment. The headers of the default baselines change only to name the configuration they are regenerated with. Developed in https://github.com/WordPress/wordpress-develop/pull/16021. Follow-up to r61699, r64539, r65372, r65537, r65566. Props westonruter, apermo. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65668 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpstan-pull-request-comments.yml | 100 ++++++- .github/workflows/phpstan-static-analysis.yml | 2 + .../reusable-phpstan-static-analysis-v1.yml | 99 ++++++- .gitignore | 1 + composer.json | 6 +- phpstan-strict.neon.dist | 91 ++++++ phpstan.neon.dist | 3 + tests/phpstan/README.md | 38 ++- tests/phpstan/analyse.php | 276 ++++++++++++++++++ .../baselines-strict/argument.type.neon | 60 ++++ tests/phpstan/baselines-strict/cast.int.neon | 25 ++ tests/phpstan/baselines-strict/loader.php | 16 + .../baselines-strict/method.notFound.neon | 25 ++ .../missingType.iterableValue.neon | 55 ++++ .../baselines-strict/missingType.return.neon | 40 +++ .../offsetAccess.nonOffsetAccessible.neon | 35 +++ .../phpstan/baselines-strict/return.type.neon | 25 ++ tests/phpstan/baselines/argument.type.neon | 6 +- .../baselines/argument.unresolvableType.neon | 6 +- .../baselines/assign.propertyType.neon | 6 +- tests/phpstan/baselines/binaryOp.invalid.neon | 6 +- .../baselines/booleanAnd.leftAlwaysTrue.neon | 6 +- .../baselines/booleanNot.alwaysTrue.neon | 6 +- tests/phpstan/baselines/class.notFound.neon | 6 +- .../baselines/deadCode.unreachable.neon | 6 +- tests/phpstan/baselines/empty.property.neon | 6 +- tests/phpstan/baselines/empty.variable.neon | 6 +- .../function.alreadyNarrowedType.neon | 6 +- .../baselines/function.resultUnused.neon | 6 +- .../baselines/identical.alwaysFalse.neon | 6 +- tests/phpstan/baselines/if.alwaysFalse.neon | 6 +- tests/phpstan/baselines/if.alwaysTrue.neon | 6 +- tests/phpstan/baselines/isset.property.neon | 6 +- .../baselines/method.childParameterType.neon | 6 +- tests/phpstan/baselines/method.unused.neon | 6 +- .../baselines/notIdentical.alwaysTrue.neon | 6 +- .../offsetAccess.nonOffsetAccessible.neon | 6 +- .../baselines/offsetAccess.notFound.neon | 6 +- .../baselines/offsetAssign.valueType.neon | 6 +- .../baselines/parameterByRef.type.neon | 6 +- .../baselines/parameterByRef.unusedType.neon | 6 +- .../baselines/property.defaultValue.neon | 6 +- .../phpstan/baselines/property.nonObject.neon | 6 +- .../phpstan/baselines/property.notFound.neon | 6 +- tests/phpstan/baselines/property.private.neon | 6 +- tests/phpstan/baselines/return.type.neon | 6 +- .../phpstan/baselines/varTag.noVariable.neon | 6 +- .../phpstan/baselines/variable.undefined.neon | 6 +- tests/phpstan/generate-baselines.php | 208 +++++++++---- 49 files changed, 1114 insertions(+), 177 deletions(-) create mode 100644 phpstan-strict.neon.dist create mode 100644 tests/phpstan/analyse.php create mode 100644 tests/phpstan/baselines-strict/argument.type.neon create mode 100644 tests/phpstan/baselines-strict/cast.int.neon create mode 100644 tests/phpstan/baselines-strict/loader.php create mode 100644 tests/phpstan/baselines-strict/method.notFound.neon create mode 100644 tests/phpstan/baselines-strict/missingType.iterableValue.neon create mode 100644 tests/phpstan/baselines-strict/missingType.return.neon create mode 100644 tests/phpstan/baselines-strict/offsetAccess.nonOffsetAccessible.neon create mode 100644 tests/phpstan/baselines-strict/return.type.neon diff --git a/.github/workflows/phpstan-pull-request-comments.yml b/.github/workflows/phpstan-pull-request-comments.yml index d1c38cc83fd10..170d770cd880b 100644 --- a/.github/workflows/phpstan-pull-request-comments.yml +++ b/.github/workflows/phpstan-pull-request-comments.yml @@ -57,6 +57,20 @@ jobs: run-id: ${{ github.event.workflow_run.id }} github-token: ${{ github.token }} + # The results of the analysis holding selected paths to a stricter rule level. A pull request whose branch does + # not have that analysis yet uploads none, which is fine. Whether they were expected is decided from the results + # above. + - name: Download the results of the strict analysis + id: download-strict + if: ${{ steps.download.outcome == 'success' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + continue-on-error: true + with: + name: phpstan-results-strict + path: ${{ runner.temp }}/phpstan-results-strict + run-id: ${{ github.event.workflow_run.id }} + github-token: ${{ github.token }} + - name: Create, update, or resolve the PHPStan comment if: ${{ steps.download.outcome == 'success' }} uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -74,7 +88,7 @@ jobs: // anything at all. They are therefore checked for shape, and only accepted for the pull request whose // current head is the commit that the run analyzed. That also discards the results of a run that was // overtaken by a newer push. - const results = JSON.parse( fs.readFileSync( `${ process.env.RUNNER_TEMP }/phpstan-results/results.json`, 'utf8' ) ); + const results = JSON.parse( fs.readFileSync( `${ process.env.RUNNER_TEMP }/phpstan-results/results.json`, { encoding: 'utf8' } ) ); const issue_number = results.pull_request; if ( ! Number.isSafeInteger( issue_number ) || issue_number <= 0 || ! Array.isArray( results.errors ) ) { core.setFailed( 'The analysis results are malformed.' ); @@ -93,12 +107,62 @@ jobs: const asString = ( value ) => ( typeof value === 'string' ? value : null ); const asSha = ( value ) => ( typeof value === 'string' && /^[0-9a-f]{40}$/.test( value ) ? value : null ); + // A rule level is a number, or `max`. Results from a branch that does not report the level have none. + const asLevel = ( value ) => ( ( Number.isSafeInteger( value ) && value >= 0 ) || value === 'max' ? value : null ); const normalize = ( error ) => ( { file: asString( error.file ), line: Number.isSafeInteger( error.line ) && error.line > 0 ? error.line : null, message: ( asString( error.message ) ?? '' ).slice( 0, 1000 ), identifier: /^[A-Za-z0-9.]+$/.test( error.identifier ) ? error.identifier : null, ignorable: error.ignorable === true, + // The analysis that reported the error, and the rule level it analyzed at. Neither is reported per error: + // they are those of the results the error was read from, and are kept in the history from there. + analysis: error.analysis === 'strict' ? 'strict' : 'default', + level: asLevel( error.level ), + } ); + + // The paths held to a stricter rule level are analyzed a second time, and that analysis uploads its results + // separately. The results above list the analyses the run made, and when the strict one is among them but + // its results are missing, the comment is left as it is: every error that only analysis reported would + // otherwise be shown as resolved. A run from a branch that does not have that analysis yet lists none, and + // has only these results. + const expectsStrict = Array.isArray( results.analyses ) && results.analyses.includes( 'strict' ); + let strictErrors = []; + let strictLevel = null; + let strictChangedInBase = []; + if ( expectsStrict ) { + let strictResults = null; + try { + strictResults = JSON.parse( fs.readFileSync( `${ process.env.RUNNER_TEMP }/phpstan-results-strict/results.json`, { encoding: 'utf8' } ) ); + } catch ( error ) { + core.info( `The results of the strict analysis are missing, so the comment is left as it is: ${ error.message }` ); + return; + } + if ( strictResults?.pull_request !== issue_number || ! Array.isArray( strictResults.errors ) ) { + core.setFailed( 'The results of the strict analysis are malformed.' ); + return; + } + strictLevel = asLevel( strictResults.level ); + strictErrors = strictResults.errors.map( ( error ) => normalize( { ...error, analysis: 'strict', level: strictLevel } ) ); + strictChangedInBase = Array.isArray( strictResults.changed_in_base ) ? strictResults.changed_in_base : []; + } + + // The strict analysis includes everything the default one does, so an error it reports at a lower level is + // reported by both. Such an error is listed once, as found by the analysis of the whole codebase, and the + // strict one only adds what is left over. Errors are matched as they are below, apart from their line. + const errorKey = ( error ) => JSON.stringify( [ error.file, error.identifier, error.message ] ); + const defaultCounts = new Map(); + const defaultErrors = results.errors.map( ( error ) => normalize( { ...error, analysis: 'default', level: results.level } ) ); + for ( const error of defaultErrors ) { + defaultCounts.set( errorKey( error ), ( defaultCounts.get( errorKey( error ) ) ?? 0 ) + 1 ); + } + const strictOnly = strictErrors.filter( ( error ) => { + const count = defaultCounts.get( errorKey( error ) ) ?? 0; + if ( count > 0 ) { + defaultCounts.set( errorKey( error ), count - 1 ); + return false; + } + return true; } ); // An error is recognized from one run to the next by its file, identifier and message, but not its line, @@ -107,10 +171,10 @@ jobs: // is fixed or added, those after it shift to the history of the one before or after, so their first reports // can be off, and the one shown as resolved or new is the last rather than the one that was. That is rarer // than lines being added or removed above them, which would throw off matching them by line. - const errors = results.errors.map( normalize ); + const errors = [ ...defaultErrors, ...strictOnly ]; const occurrences = new Map(); for ( const error of [ ...errors ].sort( ( a, b ) => ( a.line ?? 0 ) - ( b.line ?? 0 ) ) ) { - const key = JSON.stringify( [ error.file, error.identifier, error.message ] ); + const key = errorKey( error ); const occurrence = occurrences.get( key ) ?? 0; occurrences.set( key, occurrence + 1 ); error.key = `${ key }#${ occurrence }`; @@ -164,7 +228,11 @@ jobs: // Files the base branch has changed since the pull request branched from it, in which the line numbers // reported can be off in the head commit, since the analysis ran on the head commit merged into the base. - const changedInBase = new Set( Array.isArray( results.changed_in_base ) ? results.changed_in_base.filter( ( file ) => typeof file === 'string' ) : [] ); + // Each analysis only lists those among the files it reported errors in, so the lists of both are combined. + const changedInBase = new Set( + [ ...( Array.isArray( results.changed_in_base ) ? results.changed_in_base : [] ), ...strictChangedInBase ] + .filter( ( file ) => typeof file === 'string' ) + ); const lineMayBeOff = ( error ) => ! error.fixed && Boolean( error.line ) && changedInBase.has( error.file ); const filesWithLinesOff = new Set( active.filter( lineMayBeOff ).map( ( error ) => error.file ) ); @@ -206,7 +274,10 @@ jobs: // GitHub shows only the first few annotations of each kind from a step on the page of the workflow run, so // errors left out of a table are pointed to in the log of the step that reported them, which has them all. - const where = `the log of the [workflow run](${ run.html_url }), in the “Report the analysis results” step`; + // Each analysis runs in a job of its own, and an error found only by the strict one is only in that job's log. + const where = strictOnly.length > 0 + ? `the log of the [workflow run](${ run.html_url }), in the “Report the analysis results” step of each of its jobs (errors in strict paths are only in the “strict paths” job)` + : `the log of the [workflow run](${ run.html_url }), in the “Report the analysis results” step`; const table = ( rows, rowLimit, { withResolution = false } = {} ) => { const shown = rows.slice( 0, rowLimit ); if ( shown.length === 0 ) { @@ -215,10 +286,14 @@ jobs: : `The ${ rows.length } errors are not listed here, to keep this comment short. They are listed in ${ where }.`; } const more = `…and ${ rows.length - shown.length } more, which are listed in ${ where }.`; + // The rule level is only shown in a table listing an error from the strict analysis, so that one listing + // only errors from the analysis of the whole codebase looks as it did before there were two. A level + // that was not reported, as by a branch from before it was, is left blank. + const withLevel = shown.some( ( error ) => error.analysis === 'strict' ); const lines = [ - `| Location | Error | Identifier | First reported |${ withResolution ? ' Resolved |' : '' }`, - `| --- | --- | --- | --- |${ withResolution ? ' --- |' : '' }`, - ...shown.map( ( error ) => `| ${ location( error ) } | ${ code( error.message ) } | ${ identifier( error ) } | ${ commit( error.introduced ) } |${ withResolution ? ` ${ commit( error.fixed ) } |` : '' }` ), + `| Location | Error | Identifier |${ withLevel ? ' Level |' : '' } First reported |${ withResolution ? ' Resolved |' : '' }`, + `| --- | --- | --- |${ withLevel ? ' --- |' : '' } --- |${ withResolution ? ' --- |' : '' }`, + ...shown.map( ( error ) => `| ${ location( error ) } | ${ code( error.message ) } | ${ identifier( error ) } |${ withLevel ? ` ${ error.level ?? '' } |` : '' } ${ commit( error.introduced ) } |${ withResolution ? ` ${ commit( error.fixed ) } |` : '' }` ), ]; if ( shown.length < rows.length ) { lines.push( '', more ); @@ -248,6 +323,11 @@ jobs: `> ${ filesWithLinesOff.size === 1 ? 'A file with errors has' : `${ filesWithLinesOff.size } files with errors have` } changed in ${ code( pr.base.ref ) } since this branch was last updated, so the line numbers reported in ${ filesWithLinesOff.size === 1 ? 'it' : 'them' } may be off and are not linked. Merge the latest ${ code( pr.base.ref ) } into this branch for accurate links.`, ].join( '\n' ) ); } + if ( active.some( ( error ) => error.analysis === 'strict' ) ) { + const strictError = strictLevel === null ? 'An error found by the strict analysis' : `An error at level ${ strictLevel }`; + const stricterLevel = strictLevel === null ? 'a stricter rule level' : `rule level ${ strictLevel }`; + sections.push( `${ strictError } is in a path that ${ code( 'phpstan-strict.neon.dist' ) } holds to ${ stricterLevel }, which the rest of the codebase is not yet held to. See [Stricter analysis of selected paths](${ readmeUrl }#stricter-analysis-of-selected-paths).` ); + } } else { // Resolved by the last commit that resolved anything, so that later commits do not change the comment. const resolvedBy = resolved.at( -1 )?.fixed ?? run.head_sha; @@ -316,8 +396,8 @@ jobs: // The errors tracked are taken in the order they are listed, so that each one listed keeps its history. const tracked = [ ...unignorable, ...ignorable ].slice( 0, trackedLimit ).concat( resolved ).map( ( error ) => { - const { key, file, line, message, identifier, ignorable, introduced, seen, fixed } = error; - return { key, file, line: lineMayBeOff( error ) ? null : line, message, identifier, ignorable, introduced, seen, fixed }; + const { key, file, line, message, identifier, ignorable, analysis, level, introduced, seen, fixed } = error; + return { key, file, line: lineMayBeOff( error ) ? null : line, message, identifier, ignorable, analysis, level, introduced, seen, fixed }; } ); sections.push( `` ); diff --git a/.github/workflows/phpstan-static-analysis.yml b/.github/workflows/phpstan-static-analysis.yml index f0eaad6d015f3..3d855296e0e0a 100644 --- a/.github/workflows/phpstan-static-analysis.yml +++ b/.github/workflows/phpstan-static-analysis.yml @@ -17,8 +17,10 @@ on: - 'composer.*' # These files configure PHPStan. Changes could affect the outcome. - 'phpstan.neon.dist' + - 'phpstan-strict.neon.dist' - 'tests/phpstan/base.neon' - 'tests/phpstan/baselines/**' + - 'tests/phpstan/baselines-strict/**' # Confirm any changes to relevant workflow files. - '.github/workflows/phpstan-static-analysis.yml' - '.github/workflows/reusable-phpstan-static-analysis-v1.yml' diff --git a/.github/workflows/reusable-phpstan-static-analysis-v1.yml b/.github/workflows/reusable-phpstan-static-analysis-v1.yml index 5474a810164cd..aba7162bb2a05 100644 --- a/.github/workflows/reusable-phpstan-static-analysis-v1.yml +++ b/.github/workflows/reusable-phpstan-static-analysis-v1.yml @@ -21,8 +21,11 @@ permissions: {} jobs: # Runs PHP static analysis tests. # - # Violations are reported inline with annotations. For pull requests, the results are also uploaded - # as an artifact, which the PHPStan Pull Request Comments workflow summarizes in a comment. + # Core is analyzed twice, in parallel: the whole codebase with phpstan.neon.dist, and the paths held to a stricter rule + # level with phpstan-strict.neon.dist. See tests/phpstan/README.md. + # + # Violations are reported inline with annotations. For pull requests, the results of each analysis are also uploaded + # as an artifact, and the PHPStan Pull Request Comments workflow combines them in a comment. # # Performs the following steps: # - Checks out the repository. @@ -39,11 +42,33 @@ jobs: # - Saves the PHPStan result cache. # - Ensures version-controlled files are not modified or deleted. phpstan: - name: Run PHP static analysis + name: Run PHP static analysis (${{ matrix.label }}) runs-on: ubuntu-26.04 permissions: contents: read timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + # The artifact of the analysis of the whole codebase keeps the name it had before there were two, which is + # the name the PHPStan Pull Request Comments workflow on trunk requires. That way the comment is kept up to + # date for a pull request whose branch does not have the second analysis yet. + # + # The analyses are named for their role rather than their rule level, which is read from the configuration + # when the results are reported, so that raising either level is an edit of its configuration alone. + - analysis: default + label: all paths + config: phpstan.neon.dist + baselines: tests/phpstan/baselines + script: phpstan:default + artifact: phpstan-results + - analysis: strict + label: strict paths + config: phpstan-strict.neon.dist + baselines: tests/phpstan/baselines-strict + script: phpstan:strict + artifact: phpstan-results-strict steps: # For a pull request, the parents of the merge commit are fetched too, to find the files that the base branch @@ -92,16 +117,21 @@ jobs: # merged this commit yet runs the workflow it has, and that workflow would prefix-match the # caches written here: it would analyse without the extensions against reflection derived with # them. A name of its own leaves those runs restoring only their own caches. + # + # Each analysis caches separately. Its result cache records the rule level, and is discarded + # by a run at another level, so restoring the other analysis's cache would gain nothing. - name: Cache PHP Static Analysis scan cache uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 with: path: .cache # This is defined in the base.neon file. - key: "phpstan-analysis-cache-${{ hashFiles('phpstan.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}-${{ github.run_id }}" + key: "phpstan-analysis-cache-${{ matrix.analysis }}-${{ hashFiles('phpstan.neon.dist', 'phpstan-strict.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}-${{ github.run_id }}" restore-keys: | - phpstan-analysis-cache-${{ hashFiles('phpstan.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}- + phpstan-analysis-cache-${{ matrix.analysis }}-${{ hashFiles('phpstan.neon.dist', 'phpstan-strict.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}- - name: Run PHP static analysis tests id: phpstan + env: + SCRIPT: ${{ matrix.script }} run: | # The report is written to a file for the steps below, which turn it into annotations, # the pull request comment, and a check for errors that cannot be reported as warnings. @@ -111,7 +141,7 @@ jobs: # The step shell exits on the first failing command, which would also end the step on # the status of 1 that PHPStan uses for reporting errors. Capture the status instead. status=0 - composer run phpstan -- -vvv --error-format=json > "${RUNNER_TEMP}/phpstan-report.json" || status=$? + composer run "${SCRIPT}" -- -vvv --error-format=json > "${RUNNER_TEMP}/phpstan-report.json" || status=$? # PHPStan exits 1 when it has errors to report, which is the expected case here and # is what the annotations are for. Anything higher means it did not finish at all. @@ -132,11 +162,36 @@ jobs: - name: Report the analysis results id: report uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + ANALYSIS: ${{ matrix.analysis }} + CONFIG: ${{ matrix.config }} with: script: | const fs = require( 'fs' ); - const report = JSON.parse( fs.readFileSync( `${ process.env.RUNNER_TEMP }/phpstan-report.json`, 'utf8' ) ); + // The rule level the configuration analyzes at, as a number, or `max`. Only the line of the parameter is + // matched, rather than decoding the whole dump, because the JSON PHPStan prints can be invalid: it writes + // the `\<` in a message pattern as is, which is not a valid JSON escape. + let level = null; + try { + const parameters = require( 'child_process' ).execFileSync( + `${ process.env.GITHUB_WORKSPACE }/vendor/bin/phpstan`, + [ 'dump-parameters', `--configuration=${ process.env.CONFIG }`, '--json' ], + { encoding: 'utf8' } + ); + const match = parameters.match( /^\s*"level":\s*"?(max|\d+)"?,?$/m ); + if ( match ) { + level = match[ 1 ] === 'max' ? 'max' : Number( match[ 1 ] ); + } + } catch ( error ) { + core.warning( `The rule level of ${ process.env.CONFIG } could not be read: ${ error.message }` ); + } + + // Annotations from the stricter analysis say so, since the same code can pass the other one. + const analysis = process.env.ANALYSIS; + const titlePrefix = analysis === 'strict' ? `PHPStan (strict${ level === null ? '' : `, level ${ level }` })` : 'PHPStan'; + + const report = JSON.parse( fs.readFileSync( `${ process.env.RUNNER_TEMP }/phpstan-report.json`, { encoding: 'utf8' } ) ); const workspace = `${ process.env.GITHUB_WORKSPACE }/`; const errors = []; @@ -165,7 +220,7 @@ jobs: const fixHint = 'This can be fixed automatically by running `composer phpstan:fix` (or `npm run typecheck:php:fix`).'; for ( const error of errors ) { - const properties = { title: error.identifier ? `PHPStan: ${ error.identifier }` : 'PHPStan' }; + const properties = { title: error.identifier ? `${ titlePrefix }: ${ error.identifier }` : titlePrefix }; if ( error.file ) { properties.file = error.file; } @@ -186,6 +241,10 @@ jobs: // The commit analyzed is the pull request merged into its base branch, whose second parent is the head // commit. The files with errors that differ between the two are those the base branch has changed, in // which the line numbers reported can be off in the head commit. + // + // Each analysis writes its own results. Those of the analysis of the whole codebase also list every + // analysis the run makes, so that the comment is not updated from only some of them: an error missing + // because its analysis did not upload results would otherwise be shown as resolved. if ( context.eventName === 'pull_request' ) { let changedInBase = []; try { @@ -200,6 +259,10 @@ jobs: fs.mkdirSync( `${ process.env.RUNNER_TEMP }/phpstan-results`, { recursive: true } ); fs.writeFileSync( `${ process.env.RUNNER_TEMP }/phpstan-results/results.json`, JSON.stringify( { pull_request: context.payload.pull_request.number, + analysis, + level, + // Keep this list in step with the `analysis` values of the job's matrix. + ...( analysis === 'default' ? { analyses: [ 'default', 'strict' ] } : {} ), changed_in_base: changedInBase, errors: errors.map( ( { tip, fixable, ...error } ) => error ), } ) ); @@ -211,7 +274,7 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 if: ${{ github.event_name == 'pull_request' && steps.report.outcome == 'success' }} with: - name: phpstan-results + name: ${{ matrix.artifact }} path: ${{ runner.temp }}/phpstan-results/ # Some errors cannot be ignored, so they cannot be reported as warnings either. Most often @@ -229,7 +292,8 @@ jobs: - name: Check for errors that cannot be reported as warnings if: ${{ !cancelled() }} env: - BASELINES_URL: ${{ github.server_url }}/${{ github.repository }}/tree/${{ github.sha }}/tests/phpstan/baselines + BASELINES_URL: ${{ github.server_url }}/${{ github.repository }}/tree/${{ github.sha }}/${{ matrix.baselines }} + LABEL: ${{ matrix.label }} README_URL: ${{ github.server_url }}/${{ github.repository }}/blob/${{ github.sha }}/tests/phpstan/README.md run: | # This step runs even when the analysis above it failed, in which case the report may @@ -264,8 +328,11 @@ jobs: # # A newline renders as a line break rather than a space, so each paragraph is one # line however long that makes it, and the rendered summary wraps to its own width. + # + # The heading names the analysis whose baselines are out of date, which is filled in for + # the LABEL placeholder when the summary is written, since the heredoc expands nothing. baselines_summary=$( cat <<'SUMMARY' - ## PHPStan baselines are out of date + ## PHPStan baselines are out of date (LABEL) An ignored error no longer occurs, or occurs a different number of times, so PHPStan reported it under an `ignore.unmatched` or `ignore.count` identifier. @@ -283,7 +350,7 @@ jobs: composer phpstan:fix ``` - That runs PHPStan with `--fix`, which lowers the counts in the files under [`tests/phpstan/baselines`][baselines], removes the entries that no longer match, and removes any `@phpstan-ignore` annotation in the code that no longer ignores anything. It then deletes any baseline left with no entries. + That runs PHPStan with `--fix`, which lowers the counts in [the baselines][baselines], removes the entries that no longer match, and removes any `@phpstan-ignore` annotation in the code that no longer ignores anything. It then deletes any baseline left with no entries. Alternatively, regenerate the baselines with `npm run typecheck:php:baselines` or `composer phpstan:baselines`. That also deletes any baseline whose errors are now all fixed, but it does not clear an `@phpstan-ignore` annotation. @@ -294,14 +361,14 @@ jobs: if [ "${ignore_errors}" -gt 0 ]; then { - printf '%s\n\n' "${baselines_summary}" + printf '%s\n\n' "${baselines_summary/LABEL/${LABEL}}" echo "[baselines]: ${BASELINES_URL}" echo "[readme]: ${README_URL}" } >> "${GITHUB_STEP_SUMMARY}" - echo "::error title=PHPStan baselines are out of date::An ignored error no longer occurs, or occurs a different number of times. If you fixed it, that is expected: run \`npm run typecheck:php:fix\` or \`composer phpstan:fix\` and commit the updated baselines. See ${README_URL}" + echo "::error title=PHPStan baselines are out of date (${LABEL})::An ignored error no longer occurs, or occurs a different number of times. If you fixed it, that is expected: run \`npm run typecheck:php:fix\` or \`composer phpstan:fix\` and commit the updated baselines. See ${README_URL}" else - echo "::error title=PHPStan reported errors that cannot be ignored::PHPStan reported ${unignorable} error(s) that cannot be ignored or reported as warnings. See the error annotations for details, and ${README_URL} for how to run the analysis locally." + echo "::error title=PHPStan reported errors that cannot be ignored (${LABEL})::PHPStan reported ${unignorable} error(s) that cannot be ignored or reported as warnings. See the error annotations for details, and ${README_URL} for how to run the analysis locally." fi exit 1 @@ -311,7 +378,7 @@ jobs: if: ${{ !cancelled() }} with: path: .cache - key: "phpstan-analysis-cache-${{ hashFiles('phpstan.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}-${{ github.run_id }}" + key: "phpstan-analysis-cache-${{ matrix.analysis }}-${{ hashFiles('phpstan.neon.dist', 'phpstan-strict.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}-${{ github.run_id }}" - name: Ensure version-controlled files are not modified or deleted run: git diff --exit-code diff --git a/.gitignore b/.gitignore index 2d0178f495120..24b4282326304 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,7 @@ wp-tests-config.php /tests/phpunit/build /wp-cli.local.yml /phpstan.neon +/phpstan-strict.neon /*.tsbuildinfo /jsdoc /composer.lock diff --git a/composer.json b/composer.json index dd7f57d5b6313..f17e0922e00d1 100644 --- a/composer.json +++ b/composer.json @@ -75,9 +75,11 @@ } }, "scripts": { - "phpstan": "@php ./vendor/bin/phpstan analyse --memory-limit=2G", + "phpstan": [ "Composer\\Config::disableProcessTimeout", "@php ./tests/phpstan/analyse.php --memory-limit=2G" ], + "phpstan:default": [ "Composer\\Config::disableProcessTimeout", "@php ./vendor/bin/phpstan analyse --configuration=phpstan.neon.dist --memory-limit=2G" ], + "phpstan:strict": [ "Composer\\Config::disableProcessTimeout", "@php ./vendor/bin/phpstan analyse --configuration=phpstan-strict.neon.dist --memory-limit=2G" ], "phpstan:baselines": [ "Composer\\Config::disableProcessTimeout", "@php ./tests/phpstan/generate-baselines.php" ], - "phpstan:fix": [ "Composer\\Config::disableProcessTimeout", "@phpstan --configuration=phpstan.neon.dist --fix", "@phpstan:baselines --prune", "@phpstan --configuration=phpstan.neon.dist" ], + "phpstan:fix": [ "Composer\\Config::disableProcessTimeout", "@php ./tests/phpstan/analyse.php --memory-limit=2G --fix" ], "compat": "@php ./vendor/squizlabs/php_codesniffer/bin/phpcs --standard=phpcompat.xml.dist --report=summary,source", "format": "@php ./vendor/squizlabs/php_codesniffer/bin/phpcbf --report=summary,source", "lint": "@php ./vendor/squizlabs/php_codesniffer/bin/phpcs --report=summary,source", diff --git a/phpstan-strict.neon.dist b/phpstan-strict.neon.dist new file mode 100644 index 0000000000000..ffa58a226d576 --- /dev/null +++ b/phpstan-strict.neon.dist @@ -0,0 +1,91 @@ +# PHPStan configuration holding selected parts of WordPress Core to a stricter rule level. +# +# phpstan.neon.dist analyzes the whole codebase at a lower rule level. This analyzes only the paths listed under +# `paths!` below, at the `level` set below, so that code which already meets that stricter level, mostly code added in +# recent releases, keeps meeting it. `composer phpstan` runs both analyses. +# +# The rest of core is scanned rather than analyzed, so that what the strict paths use is known. A scanned file is read +# with the same WordPress-specific parser node visitors as an analyzed one (see the redefinition of +# `currentPhpVersionSimpleParser` in tests/phpstan/base.neon), so a function outside the strict paths has the same +# types here, such as the array shapes from hash notation, as in the analysis of the whole codebase. +# +# To override this configuration, create a phpstan-strict.neon which includes this file, in the same way as +# phpstan.neon overrides phpstan.neon.dist. +# +# https://phpstan.org/config-reference + +includes: + # Everything phpstan.neon.dist enforces: the base configuration, the strict rules, the errors ignored as not + # actionable, and its baselines. An error that both analyses report is baselined once, by phpstan.neon.dist. The + # entries for files this does not analyze are not reported as unmatched, since PHPStan only reports an entry when + # what it ignores is within the analysis. + - phpstan.neon.dist + + # Preexisting errors at this level in the strict paths, beyond those baselined by phpstan.neon.dist. They are + # organized and regenerated the same way, by `composer phpstan:baselines`, and included the same way, through the + # loader in their directory. + - tests/phpstan/baselines-strict/loader.php + +parameters: + # The level is set explicitly rather than as `max`, so that a PHPStan update that adds a level does not raise it. + # https://phpstan.org/user-guide/rule-levels + level: 10 + + # The two analyses share the cache of what PHPStan reads from each file, since both read every file the same way, + # but each needs its own result cache. Its metadata includes the rule level and the paths analyzed, so a shared one + # would be discarded by every run of the other analysis. + resultCachePath: %tmpDir%/resultCache-strict.php + + # The paths held to this rule level, replacing those analyzed by phpstan.neon.dist. A directory covers every file + # below it. + # + # Before adding a path, fix the errors this analysis reports in it, or baseline those that cannot be fixed yet. + paths!: + - src/wp-admin/includes/class-wp-filesystem-base.php + - src/wp-admin/includes/class-wp-filesystem-direct.php + - src/wp-admin/includes/class-wp-filesystem-ssh2.php + - src/wp-includes/abilities-api + - src/wp-includes/abilities-api.php + - src/wp-includes/ai-client + - src/wp-includes/ai-client.php + - src/wp-includes/class-wp-block-styles-registry.php + - src/wp-includes/class-wp-block-template.php + - src/wp-includes/class-wp-comment.php + - src/wp-includes/class-wp-connector-registry.php + - src/wp-includes/class-wp-error.php + - src/wp-includes/class-wp-post.php + - src/wp-includes/class-wp-url-pattern-prefixer.php + - src/wp-includes/html-api/class-wp-html-attribute-token.php + - src/wp-includes/html-api/class-wp-html-decoder.php + - src/wp-includes/html-api/class-wp-html-doctype-info.php + - src/wp-includes/html-api/class-wp-html-processor-state.php + - src/wp-includes/html-api/class-wp-html-span.php + - src/wp-includes/html-api/class-wp-html-stack-event.php + - src/wp-includes/html-api/class-wp-html-text-replacement.php + - src/wp-includes/html-api/class-wp-html-token.php + - src/wp-includes/html-api/class-wp-html-unsupported-exception.php + - src/wp-includes/l10n/class-wp-translations.php + - src/wp-includes/sitemaps.php + - src/wp-includes/speculative-loading.php + - src/wp-includes/style-engine + - tests/phpstan + + # The code outside the strict paths that they can use. The bundled themes are left out, since nothing in core uses + # them. The files in the root are scanned for the constants they define, such as WPINC in wp-settings.php. + scanDirectories: + - src/wp-admin + - src/wp-includes + scanFiles: + - src/index.php + - src/wp-activate.php + - src/wp-blog-header.php + - src/wp-comments-post.php + - src/wp-cron.php + - src/wp-links-opml.php + - src/wp-load.php + - src/wp-login.php + - src/wp-mail.php + - src/wp-settings.php + - src/wp-signup.php + - src/wp-trackback.php + - src/xmlrpc.php diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 260afa934953f..796646255ada6 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -1,5 +1,8 @@ # PHPStan configuration for WordPress Core. # +# This analyzes the whole codebase. phpstan-strict.neon.dist includes it, and holds selected +# paths to a stricter rule level. `composer phpstan` runs both. +# # To override this configuration, create a phpstan.neon which includes this file and adjusts # its parameters as needed, rather than copying it, so that the copy does not go stale. See # tests/phpstan/README.md for examples. diff --git a/tests/phpstan/README.md b/tests/phpstan/README.md index 7dd1df431d4a9..056c4acdfb077 100644 --- a/tests/phpstan/README.md +++ b/tests/phpstan/README.md @@ -16,6 +16,8 @@ npm run typecheck:php which will run PHPStan in the Docker container. +This runs two analyses, one after the other: the whole codebase with [`phpstan.neon.dist`](../../phpstan.neon.dist), and then the paths held to a stricter rule level with [`phpstan-strict.neon.dist`](../../phpstan-strict.neon.dist), as described in [Stricter analysis of selected paths](#stricter-analysis-of-selected-paths). The command fails when either of them reports an error. + Additional flags supported by PHPStan can be passed by passing `--` followed by the flags themselves. For example, ```bash @@ -41,14 +43,16 @@ composer run phpstan -- -vvv --debug Note the `--` in each of those. Composer needs it in order to pass the flags on to PHPStan rather than reading them as its own, and without it they are discarded silently. The npm script supplies it, which is why only one is needed there. +The flags are passed to both analyses, except that paths, `--configuration`, `--level`, `--error-format`, `--generate-baseline`, and `--fix-ignored` run only the first, since each only makes sense for one. To run only one of them, as CI does, use `composer phpstan:default` or `composer phpstan:strict`. Those always use the `.dist` configurations, ignoring a local override. + For available flags, see https://phpstan.org/user-guide/command-line-usage. ## Results on pull requests -The analysis also runs on every pull request that changes PHP files or the PHPStan configuration. The errors it reports are shown in two places: +Both analyses also run on every pull request that changes PHP files or the PHPStan configuration, as two jobs. The errors they report are shown in two places: - As annotations on the changed files. Most errors are annotated as warnings, which do not fail the check. -- In a comment on the pull request, which lists every error in a table along with the commit it was first reported for. The comment is updated as new commits are pushed, moving each error that a commit resolves into a collapsed list of resolved errors, which also names that commit. Once all of the errors are resolved, the comment is marked as resolved and collapsed. +- In a comment on the pull request, which lists every error in a table along with the commit it was first reported for. The comment is updated as new commits are pushed, moving each error that a commit resolves into a collapsed list of resolved errors, which also names that commit. Once all of the errors are resolved, the comment is marked as resolved and collapsed. The comment combines both analyses: an error reported by both is listed once, and when an error is only reported by the analysis of the strict paths, the table gains a Level column giving the rule level of each error. Some errors cannot be ignored, and so cannot be reported as warnings either. These fail the check. The most common is an [out-of-date baseline](#removing-stale-entries-with---fix), which is reported when an error recorded in a baseline was fixed without the baseline being updated. Such an error is reported against a file rather than a line in it, so its annotation does not appear alongside the changes, and it would easily go unnoticed if the check passed. @@ -104,6 +108,25 @@ parameters: ignoreErrors!: [] ``` +### Stricter analysis of selected paths + +`phpstan.neon.dist` holds the whole codebase to a low rule level, since most of it does not yet meet a higher one. Some of it already does, mostly code added in recent releases, such as the AI client and the Abilities API. [`phpstan-strict.neon.dist`](../../phpstan-strict.neon.dist) holds those paths to a stricter rule level, currently 10, so that they keep meeting it. The level is set as a number rather than `max`, so that it is only raised deliberately, not by a PHPStan update adding a level. + +`phpstan-strict.neon.dist` includes `phpstan.neon.dist`, so everything `phpstan.neon.dist` enforces still applies, and replaces the paths analyzed with the ones it lists under `paths!`. The rest of core is scanned instead, so that what those paths use is known. A scanned file gets the same [WordPress-specific extensions](#wordpress-specific-extensions) as an analyzed one, because `base.neon` has every parse run them, so the types of the code outside the strict paths are the same as in the analysis of the whole codebase. + +Errors are baselined in two layers. An error that the analysis of the whole codebase reports is baselined in [`baselines/`](baselines), as usual, and stays baselined there for the strict analysis. What the stricter level adds in the strict paths is baselined in [`baselines-strict/`](baselines-strict), in the same way, and included through its own [`loader.php`](baselines-strict/loader.php). `composer phpstan:baselines` and `composer phpstan:fix` maintain both. + +To hold another path to the stricter level: + +1. Make sure no entry in [`baselines/`](baselines) is for a file in the path. Both analyses enforce those entries, but each may report a different number of the errors one ignores, and then no count satisfies both. Fix those errors first. +2. Add the path to `paths!` in `phpstan-strict.neon.dist`. +3. Run `composer phpstan:strict`, and fix the errors it reports. +4. Baseline any that cannot be fixed yet with `composer phpstan:baselines`. + +In the strict paths, **do not add an `@phpstan-ignore` comment for an error that only the stricter level reports**. The analysis of the whole codebase does not report that error, so it reports the comment as ignoring nothing, and `composer phpstan:fix` would remove it. Fix the error, or baseline it instead. + +A local `phpstan-strict.neon` overrides `phpstan-strict.neon.dist`, the same way `phpstan.neon` overrides `phpstan.neon.dist`. When a local `phpstan.neon` analyzes at the strict level or above, `composer phpstan` skips the second analysis, since it could only repeat part of the first. Only the levels are compared, so if the local `phpstan.neon` also narrows the paths analyzed, leaving out some of the strict paths, run `composer phpstan:strict` as well. + For more information about configuring PHPStan, see the [PHPStan documentation's Config reference](https://phpstan.org/config-reference). ## WordPress-specific extensions @@ -234,16 +257,15 @@ or, outside the Docker environment: composer phpstan:fix ``` -This runs three steps, each only when the one before it succeeds: +This runs three steps: -1. PHPStan with its `--fix` option, which lowers the count of the entry, or removes the entry, leaving the rest of the baseline as it was. It is usually much faster than regenerating, since it reuses the result cache of the run that reported the errors. Unlike regenerating, it also removes an `@phpstan-ignore` comment that no longer matches. +1. PHPStan with its `--fix` option, once with `phpstan.neon.dist` and once with `phpstan-strict.neon.dist`. It lowers the count of the entry, or removes the entry, leaving the rest of the baseline as it was. It is usually much faster than regenerating, since it reuses the result cache of the run that reported the errors. Unlike regenerating, it also removes an `@phpstan-ignore` comment that no longer matches. PHPStan says `No fixable errors found` for a configuration with nothing to fix, which does not stop the other steps. 2. `composer phpstan:baselines -- --prune`, which deletes any baseline left with no entries. Removing the last entry of a baseline leaves the file behind, as `ignoreErrors: []`. Pruning analyzes nothing, so it can also be run on its own. -3. The analysis once more, which reuses the result cache and so is quick. PHPStan's `--fix` reports only what it fixed, and succeeds even when other errors remain, so this is what shows the errors that are left. +3. Both analyses once more, which reuse the result cache and so are quick. PHPStan's `--fix` reports only what it fixed, and succeeds even when other errors remain, so this is what shows the errors that are left. Keep in mind: -- **It fails when nothing is fixable.** PHPStan then says `No fixable errors found` and stops the script there, so run `composer phpstan` to see whether any errors remain. -- **It always analyzes the whole tree with `phpstan.neon.dist`**, whatever a local `phpstan.neon` says. PHPStan only reports stale ignores when it analyzes every path, and a configuration at another rule level can report a baselined error with a different message, in which case `--fix` would remove an entry that the default configuration still needs. +- **It always analyzes with the two `.dist` configurations**, whatever a local `phpstan.neon` or `phpstan-strict.neon` says. A configuration at another rule level can report a baselined error with a different message, in which case `--fix` would remove an entry that the default configuration still needs. - **It fixes every fixable error the run reports**, not only stale ignores. A few other errors can also be fixed automatically, such as a [useless cast](https://phpstan.org/error-identifiers/cast.useless), so check the diff before committing it. - PHPStan's `--fix-ignored`, run as `composer phpstan -- --fix-ignored`, goes further and also fixes the fixable errors which a baseline currently ignores. That is a way to work through a baseline, but expect larger diffs, and follow it with `composer phpstan:baselines -- --prune`. @@ -294,6 +316,8 @@ Note the `--` in each of those. Composer needs it in order to pass the flags on A run also deletes any baseline whose identifier no longer reports anything. Since the baselines are included through [`baselines/loader.php`](baselines/loader.php), adding a newly split out baseline, and retiring one that has reached zero, need no edit of the configuration. +Each run regenerates both sets of baselines: those of `phpstan.neon.dist` in [`baselines/`](baselines), and then those of `phpstan-strict.neon.dist` in [`baselines-strict/`](baselines-strict). The order matters, since the strict configuration includes the other one along with its baselines, so its own are only what is left over. The options apply to both, except `--combined`, which only prints the baseline of `phpstan.neon.dist`. To regenerate one set, name its configuration with `--config`, such as `--config=phpstan-strict.neon.dist`. + PHPStan's own `--generate-baseline` is deliberately not used directly. It captures every error a run reports, with no way to restrict it to one identifier, so it cannot refresh a single baseline without sweeping every other kind of error into it. ## Performance and troubleshooting diff --git a/tests/phpstan/analyse.php b/tests/phpstan/analyse.php new file mode 100644 index 0000000000000..884db73d3ac02 --- /dev/null +++ b/tests/phpstan/analyse.php @@ -0,0 +1,276 @@ + 1 ) { + exit( $status ); + } + } + + $status = run( 'Deleting the baselines left without entries', __DIR__ . '/generate-baselines.php', array( '--prune' ) ); + if ( 0 !== $status ) { + exit( $status ); + } + + $exit_code = 0; + foreach ( array( PROJECT_CONFIG, STRICT_CONFIG ) as $config ) { + $exit_code = max( $exit_code, analyse( "Analyzing with $config", $phpstan, array( "--configuration=$config", ...$args ) ) ); + } + exit( $exit_code ); +} + +$local_config = $repo_root . '/phpstan.neon'; +$strict_config = is_file( $repo_root . '/phpstan-strict.neon' ) ? 'phpstan-strict.neon' : STRICT_CONFIG; + +// PHPStan reads phpstan.neon in place of phpstan.neon.dist by itself, so the first analysis names neither. +$exit_code = analyse( 'Analyzing with ' . ( is_file( $local_config ) ? 'phpstan.neon' : PROJECT_CONFIG ), $phpstan, $args ); + +if ( is_file( $local_config ) ) { + $local_level = get_level( $phpstan, $local_config ); + $strict_level = get_level( $phpstan, $repo_root . '/' . $strict_config ); + + if ( null !== $local_level && null !== $strict_level && is_level_at_least( $local_level, $strict_level ) ) { + fwrite( STDERR, "\nSkipping $strict_config: phpstan.neon analyzes at level $local_level, and the strict paths are held to $strict_level. If phpstan.neon leaves any of them out, run `composer phpstan:strict` too.\n" ); + exit( $exit_code ); + } +} + +exit( max( $exit_code, analyse( "Analyzing the strict paths with $strict_config", $phpstan, array( "--configuration=$strict_config", ...$args ) ) ) ); + +/** + * Runs a command with a heading, passing its output through. + * + * The heading goes to stderr, so that what the command writes to stdout, such as + * a report in a machine-readable format, is left as it is. + * + * The script runs on the PHP running this one, which Composer's `@php` chose, + * rather than on whichever `php` the script's shebang finds first. + * + * @param string $heading Heading describing the run. + * @param string $script Path to the PHP script to run. + * @param string[] $args Arguments, which are escaped for the shell here. + * @return int Exit status of the script. + */ +function run( string $heading, string $script, array $args ): int { + fwrite( STDERR, "\n== $heading ==\n\n" ); + + $parts = array( escapeshellarg( PHP_BINARY ), escapeshellarg( $script ) ); + foreach ( $args as $arg ) { + $parts[] = escapeshellarg( $arg ); + } + + $exit_code = 0; + passthru( implode( ' ', $parts ), $exit_code ); + + return $exit_code; +} + +/** + * Runs PHPStan's `analyse` command with a heading, passing its output through. + * + * @param string $heading Heading describing the run. + * @param string $phpstan Path to the PHPStan executable. + * @param list $args Arguments to the command, which are escaped for the shell. + * @return int Exit status of PHPStan. + */ +function analyse( string $heading, string $phpstan, array $args ): int { + return run( $heading, $phpstan, array( 'analyse', ...$args ) ); +} + +/** + * Gets the rule level a configuration analyzes at. + * + * Only the line of the parameter is matched, rather than decoding the whole dump, + * because the JSON PHPStan prints can be invalid: it writes the `\<` in a message + * pattern as is, which is not a valid JSON escape. + * + * @param string $phpstan Path to the PHPStan executable. + * @param string $config Absolute path to the configuration file. + * @return string|null The rule level, as digits or `max`, or null if it could not be read. + */ +function get_level( string $phpstan, string $config ): ?string { + $output = array(); + $exit_code = 0; + exec( sprintf( '%s %s dump-parameters --configuration=%s --json 2>/dev/null', escapeshellarg( PHP_BINARY ), escapeshellarg( $phpstan ), escapeshellarg( $config ) ), $output, $exit_code ); + + // A configuration PHPStan cannot load, for one, leaves no parameters to read. + if ( 0 !== $exit_code ) { + return null; + } + + foreach ( $output as $line ) { + if ( 1 === preg_match( '/^\s*"level":\s*("max"|"?\d+"?),?$/', $line, $matches ) ) { + return trim( $matches[1], '"' ); + } + } + + return null; +} + +/** + * Determines whether a rule level is at least as strict as another. + * + * `max` is the highest level of whichever PHPStan version is installed, so it is + * at least any other. A numbered level is not taken to be at least `max`, since + * that would only hold until PHPStan adds a level above it. + * + * @param string $level Rule level, as digits or `max`. + * @param string $minimum Rule level to compare it with, as digits or `max`. + * @return bool Whether the level is at least the minimum. + */ +function is_level_at_least( string $level, string $minimum ): bool { + if ( 'max' === $level ) { + return true; + } + if ( 'max' === $minimum ) { + return false; + } + return (int) $level >= (int) $minimum; +} + +/** + * Finds an argument that only makes sense for a single analysis. + * + * Those are a configuration, a level, a report format, a baseline to generate, + * `--fix-ignored`, and the paths to analyze. An option's value can follow it as the + * next argument, so that is skipped rather than taken for a path. + * + * @param list $args Arguments. + * @return string|null Description of the first such argument, or null if there is none. + */ +function get_single_analysis_reason( array $args ): ?string { + // The options whose value can be given as the next argument rather than after `=`. + $takes_value = array( '-c', '--configuration', '-l', '--level', '-a', '--autoload-file', '--error-format', '--memory-limit', '--tmp-file', '--instead-of' ); + $single = array( '-c', '--configuration', '-l', '--level', '--error-format', '--generate-baseline', '-b', '--fix-ignored' ); + + $is_value = false; + foreach ( $args as $i => $arg ) { + // The value of the option before, given as an argument of its own. + if ( $is_value ) { + $is_value = false; + continue; + } + + if ( '--' === $arg ) { + return $i + 1 < count( $args ) ? 'the paths given' : null; + } + + if ( '' === $arg || '-' !== $arg[0] ) { + return 'the paths given'; + } + + // A long option's value follows `=`, and a short option's follows its letter directly, as in `-l6`. + if ( 0 === strpos( $arg, '--' ) ) { + $name = explode( '=', $arg, 2 )[0]; + $has_value = false !== strpos( $arg, '=' ); + } else { + $name = substr( $arg, 0, 2 ); + $has_value = strlen( $arg ) > 2; + } + + if ( in_array( $name, $single, true ) ) { + return $name; + } + + if ( ! $has_value && in_array( $name, $takes_value, true ) ) { + $is_value = true; + } + } + + return null; +} diff --git a/tests/phpstan/baselines-strict/argument.type.neon b/tests/phpstan/baselines-strict/argument.type.neon new file mode 100644 index 0000000000000..dd83b950de430 --- /dev/null +++ b/tests/phpstan/baselines-strict/argument.type.neon @@ -0,0 +1,60 @@ +# PHPStan baseline for the `argument.type` errors in WordPress core. +# +# https://phpstan.org/error-identifiers/argument.type +# +# Each entry is scoped to a single file and carries an exact occurrence count, +# so that a new instance is reported as a new error rather than being absorbed +# silently. Fixing an occurrence therefore means decrementing or removing its +# entry here as part of the same change. +# +# The goal is to empty this file and delete it. +# +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: +# +# composer phpstan:baselines -- --identifier=argument.type --config=phpstan-strict.neon.dist +# +# This reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. + +parameters: + ignoreErrors: + - + message: '#^Parameter \#1 \$object_or_string of function is_a expects object\|string, mixed given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-includes/abilities-api/class-wp-abilities-registry.php + - + message: '#^Parameter \#1 \$args of function wp_parse_args expects array\\|object\|string, mixed given\.$#' + identifier: argument.type + count: 2 + path: ../../../src/wp-includes/abilities-api/class-wp-ability.php + - + message: '#^Parameter \#1 \$name of method WordPress\\AiClientDependencies\\Psr\\Http\\Message\\MessageInterface\:\:withHeader\(\) expects string, mixed given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-includes/ai-client/adapters/class-wp-ai-client-http-client.php + - + message: '#^Parameter \#1 \$wp_response of method WP_AI_Client_HTTP_Client\:\:create_psr_response\(\) expects array\, array given\.$#' + identifier: argument.type + count: 2 + path: ../../../src/wp-includes/ai-client/adapters/class-wp-ai-client-http-client.php + - + message: '#^Parameter \#2 \$value of method WordPress\\AiClientDependencies\\Psr\\Http\\Message\\MessageInterface\:\:withHeader\(\) expects array\\|string, mixed given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-includes/ai-client/adapters/class-wp-ai-client-http-client.php + - + message: '#^Parameter \#4 \$options of static method WP_Style_Engine_CSS_Declarations\:\:filter_declaration\(\) expects array\{important\?\: bool, \.\.\.\}, mixed given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-includes/style-engine/class-wp-style-engine-css-declarations.php + - + message: '#^Parameter \#3 \$options of method WP_Style_Engine_CSS_Declarations\:\:add_declaration\(\) expects array\{important\?\: bool, \.\.\.\}, mixed given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-includes/style-engine/class-wp-style-engine-css-rule.php + - + message: '#^Parameter \#1 \$should_prettify of method WP_Style_Engine_CSS_Rule\:\:get_css\(\) expects bool, mixed given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-includes/style-engine/class-wp-style-engine-processor.php diff --git a/tests/phpstan/baselines-strict/cast.int.neon b/tests/phpstan/baselines-strict/cast.int.neon new file mode 100644 index 0000000000000..afa3e42a72b97 --- /dev/null +++ b/tests/phpstan/baselines-strict/cast.int.neon @@ -0,0 +1,25 @@ +# PHPStan baseline for the `cast.int` errors in WordPress core. +# +# https://phpstan.org/error-identifiers/cast.int +# +# Each entry is scoped to a single file and carries an exact occurrence count, +# so that a new instance is reported as a new error rather than being absorbed +# silently. Fixing an occurrence therefore means decrementing or removing its +# entry here as part of the same change. +# +# The goal is to empty this file and delete it. +# +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: +# +# composer phpstan:baselines -- --identifier=cast.int --config=phpstan-strict.neon.dist +# +# This reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. + +parameters: + ignoreErrors: + - + message: '#^Cannot cast mixed to int\.$#' + identifier: cast.int + count: 1 + path: ../../../src/wp-includes/class-wp-post.php diff --git a/tests/phpstan/baselines-strict/loader.php b/tests/phpstan/baselines-strict/loader.php new file mode 100644 index 0000000000000..829e4ac4880d4 --- /dev/null +++ b/tests/phpstan/baselines-strict/loader.php @@ -0,0 +1,16 @@ + but returns array\\.$#' + identifier: return.type + count: 1 + path: ../../../src/wp-includes/abilities-api/class-wp-ability-categories-registry.php diff --git a/tests/phpstan/baselines/argument.type.neon b/tests/phpstan/baselines/argument.type.neon index dd184d5a12924..bd6828d096b11 100644 --- a/tests/phpstan/baselines/argument.type.neon +++ b/tests/phpstan/baselines/argument.type.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=argument.type +# composer phpstan:baselines -- --identifier=argument.type --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/argument.unresolvableType.neon b/tests/phpstan/baselines/argument.unresolvableType.neon index 8bee3995f6ac5..f6ca492a525ce 100644 --- a/tests/phpstan/baselines/argument.unresolvableType.neon +++ b/tests/phpstan/baselines/argument.unresolvableType.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=argument.unresolvableType +# composer phpstan:baselines -- --identifier=argument.unresolvableType --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/assign.propertyType.neon b/tests/phpstan/baselines/assign.propertyType.neon index 4afc274001850..a9a89163f9df1 100644 --- a/tests/phpstan/baselines/assign.propertyType.neon +++ b/tests/phpstan/baselines/assign.propertyType.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=assign.propertyType +# composer phpstan:baselines -- --identifier=assign.propertyType --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/binaryOp.invalid.neon b/tests/phpstan/baselines/binaryOp.invalid.neon index 57b8bf343662e..bfcd43d16d874 100644 --- a/tests/phpstan/baselines/binaryOp.invalid.neon +++ b/tests/phpstan/baselines/binaryOp.invalid.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=binaryOp.invalid +# composer phpstan:baselines -- --identifier=binaryOp.invalid --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/booleanAnd.leftAlwaysTrue.neon b/tests/phpstan/baselines/booleanAnd.leftAlwaysTrue.neon index 23523d7b66739..1f55c01be4124 100644 --- a/tests/phpstan/baselines/booleanAnd.leftAlwaysTrue.neon +++ b/tests/phpstan/baselines/booleanAnd.leftAlwaysTrue.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=booleanAnd.leftAlwaysTrue +# composer phpstan:baselines -- --identifier=booleanAnd.leftAlwaysTrue --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/booleanNot.alwaysTrue.neon b/tests/phpstan/baselines/booleanNot.alwaysTrue.neon index 066ee954ba210..7db8291d66e7c 100644 --- a/tests/phpstan/baselines/booleanNot.alwaysTrue.neon +++ b/tests/phpstan/baselines/booleanNot.alwaysTrue.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=booleanNot.alwaysTrue +# composer phpstan:baselines -- --identifier=booleanNot.alwaysTrue --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/class.notFound.neon b/tests/phpstan/baselines/class.notFound.neon index 423a42dd3aca5..97a6745e87a0d 100644 --- a/tests/phpstan/baselines/class.notFound.neon +++ b/tests/phpstan/baselines/class.notFound.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=class.notFound +# composer phpstan:baselines -- --identifier=class.notFound --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/deadCode.unreachable.neon b/tests/phpstan/baselines/deadCode.unreachable.neon index 3dccb140aacc0..1a688f51c78a1 100644 --- a/tests/phpstan/baselines/deadCode.unreachable.neon +++ b/tests/phpstan/baselines/deadCode.unreachable.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=deadCode.unreachable +# composer phpstan:baselines -- --identifier=deadCode.unreachable --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/empty.property.neon b/tests/phpstan/baselines/empty.property.neon index 869cadbf2fea7..29c45b3128ea4 100644 --- a/tests/phpstan/baselines/empty.property.neon +++ b/tests/phpstan/baselines/empty.property.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=empty.property +# composer phpstan:baselines -- --identifier=empty.property --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/empty.variable.neon b/tests/phpstan/baselines/empty.variable.neon index fe2adb8dec11e..47f6187fd5310 100644 --- a/tests/phpstan/baselines/empty.variable.neon +++ b/tests/phpstan/baselines/empty.variable.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=empty.variable +# composer phpstan:baselines -- --identifier=empty.variable --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/function.alreadyNarrowedType.neon b/tests/phpstan/baselines/function.alreadyNarrowedType.neon index 467991720b5a7..3c1a44fe8f871 100644 --- a/tests/phpstan/baselines/function.alreadyNarrowedType.neon +++ b/tests/phpstan/baselines/function.alreadyNarrowedType.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=function.alreadyNarrowedType +# composer phpstan:baselines -- --identifier=function.alreadyNarrowedType --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/function.resultUnused.neon b/tests/phpstan/baselines/function.resultUnused.neon index 442b207fe196d..045ad4b731459 100644 --- a/tests/phpstan/baselines/function.resultUnused.neon +++ b/tests/phpstan/baselines/function.resultUnused.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=function.resultUnused +# composer phpstan:baselines -- --identifier=function.resultUnused --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/identical.alwaysFalse.neon b/tests/phpstan/baselines/identical.alwaysFalse.neon index 5bd777f130a40..0d305bff88893 100644 --- a/tests/phpstan/baselines/identical.alwaysFalse.neon +++ b/tests/phpstan/baselines/identical.alwaysFalse.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=identical.alwaysFalse +# composer phpstan:baselines -- --identifier=identical.alwaysFalse --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/if.alwaysFalse.neon b/tests/phpstan/baselines/if.alwaysFalse.neon index 30fb317dec4c4..ed8b9f60e0c1c 100644 --- a/tests/phpstan/baselines/if.alwaysFalse.neon +++ b/tests/phpstan/baselines/if.alwaysFalse.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=if.alwaysFalse +# composer phpstan:baselines -- --identifier=if.alwaysFalse --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/if.alwaysTrue.neon b/tests/phpstan/baselines/if.alwaysTrue.neon index 1d3af11e446fb..a86c1b801ab98 100644 --- a/tests/phpstan/baselines/if.alwaysTrue.neon +++ b/tests/phpstan/baselines/if.alwaysTrue.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=if.alwaysTrue +# composer phpstan:baselines -- --identifier=if.alwaysTrue --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/isset.property.neon b/tests/phpstan/baselines/isset.property.neon index 327cd1c76aa43..4cf68462ad846 100644 --- a/tests/phpstan/baselines/isset.property.neon +++ b/tests/phpstan/baselines/isset.property.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=isset.property +# composer phpstan:baselines -- --identifier=isset.property --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/method.childParameterType.neon b/tests/phpstan/baselines/method.childParameterType.neon index 4c68bab982fab..5faf12a73aa86 100644 --- a/tests/phpstan/baselines/method.childParameterType.neon +++ b/tests/phpstan/baselines/method.childParameterType.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=method.childParameterType +# composer phpstan:baselines -- --identifier=method.childParameterType --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/method.unused.neon b/tests/phpstan/baselines/method.unused.neon index 054dc94542241..ced0e2372a23f 100644 --- a/tests/phpstan/baselines/method.unused.neon +++ b/tests/phpstan/baselines/method.unused.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=method.unused +# composer phpstan:baselines -- --identifier=method.unused --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/notIdentical.alwaysTrue.neon b/tests/phpstan/baselines/notIdentical.alwaysTrue.neon index 1a6284b361ec2..642d685217d02 100644 --- a/tests/phpstan/baselines/notIdentical.alwaysTrue.neon +++ b/tests/phpstan/baselines/notIdentical.alwaysTrue.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=notIdentical.alwaysTrue +# composer phpstan:baselines -- --identifier=notIdentical.alwaysTrue --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/offsetAccess.nonOffsetAccessible.neon b/tests/phpstan/baselines/offsetAccess.nonOffsetAccessible.neon index 6ea0acc46ac2b..ed021ec794760 100644 --- a/tests/phpstan/baselines/offsetAccess.nonOffsetAccessible.neon +++ b/tests/phpstan/baselines/offsetAccess.nonOffsetAccessible.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=offsetAccess.nonOffsetAccessible +# composer phpstan:baselines -- --identifier=offsetAccess.nonOffsetAccessible --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/offsetAccess.notFound.neon b/tests/phpstan/baselines/offsetAccess.notFound.neon index ed127f9ed48cd..9f61db04aba25 100644 --- a/tests/phpstan/baselines/offsetAccess.notFound.neon +++ b/tests/phpstan/baselines/offsetAccess.notFound.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=offsetAccess.notFound +# composer phpstan:baselines -- --identifier=offsetAccess.notFound --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/offsetAssign.valueType.neon b/tests/phpstan/baselines/offsetAssign.valueType.neon index 6764804f6d4f1..8077ca9892ff4 100644 --- a/tests/phpstan/baselines/offsetAssign.valueType.neon +++ b/tests/phpstan/baselines/offsetAssign.valueType.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=offsetAssign.valueType +# composer phpstan:baselines -- --identifier=offsetAssign.valueType --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/parameterByRef.type.neon b/tests/phpstan/baselines/parameterByRef.type.neon index 40c8748b45974..0a99ae46d6d27 100644 --- a/tests/phpstan/baselines/parameterByRef.type.neon +++ b/tests/phpstan/baselines/parameterByRef.type.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=parameterByRef.type +# composer phpstan:baselines -- --identifier=parameterByRef.type --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/parameterByRef.unusedType.neon b/tests/phpstan/baselines/parameterByRef.unusedType.neon index 0704b43af2e54..4738b39636023 100644 --- a/tests/phpstan/baselines/parameterByRef.unusedType.neon +++ b/tests/phpstan/baselines/parameterByRef.unusedType.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=parameterByRef.unusedType +# composer phpstan:baselines -- --identifier=parameterByRef.unusedType --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/property.defaultValue.neon b/tests/phpstan/baselines/property.defaultValue.neon index 6cda21d8d6b20..5c7ebe5274920 100644 --- a/tests/phpstan/baselines/property.defaultValue.neon +++ b/tests/phpstan/baselines/property.defaultValue.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=property.defaultValue +# composer phpstan:baselines -- --identifier=property.defaultValue --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/property.nonObject.neon b/tests/phpstan/baselines/property.nonObject.neon index e9f1ae8ec3d98..2acecd3a68838 100644 --- a/tests/phpstan/baselines/property.nonObject.neon +++ b/tests/phpstan/baselines/property.nonObject.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=property.nonObject +# composer phpstan:baselines -- --identifier=property.nonObject --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/property.notFound.neon b/tests/phpstan/baselines/property.notFound.neon index a3f3247ffce3e..6686c06ba9431 100644 --- a/tests/phpstan/baselines/property.notFound.neon +++ b/tests/phpstan/baselines/property.notFound.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=property.notFound +# composer phpstan:baselines -- --identifier=property.notFound --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/property.private.neon b/tests/phpstan/baselines/property.private.neon index 20fdc0268cef3..6d08652de08d5 100644 --- a/tests/phpstan/baselines/property.private.neon +++ b/tests/phpstan/baselines/property.private.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=property.private +# composer phpstan:baselines -- --identifier=property.private --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/return.type.neon b/tests/phpstan/baselines/return.type.neon index f0f524e3f0dbd..9143cbd2bbad7 100644 --- a/tests/phpstan/baselines/return.type.neon +++ b/tests/phpstan/baselines/return.type.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=return.type +# composer phpstan:baselines -- --identifier=return.type --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/varTag.noVariable.neon b/tests/phpstan/baselines/varTag.noVariable.neon index 2593db2cafcd1..5078f4df8beb9 100644 --- a/tests/phpstan/baselines/varTag.noVariable.neon +++ b/tests/phpstan/baselines/varTag.noVariable.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=varTag.noVariable +# composer phpstan:baselines -- --identifier=varTag.noVariable --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/baselines/variable.undefined.neon b/tests/phpstan/baselines/variable.undefined.neon index b1eec349cd4d0..a46e0e5fa2283 100644 --- a/tests/phpstan/baselines/variable.undefined.neon +++ b/tests/phpstan/baselines/variable.undefined.neon @@ -9,11 +9,11 @@ # # The goal is to empty this file and delete it. # -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with +# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # -# composer phpstan:baselines -- --identifier=variable.undefined +# composer phpstan:baselines -- --identifier=variable.undefined --config=phpstan.neon.dist # -# which reruns the analysis with the baselines in this directory suppressed, so +# This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. parameters: diff --git a/tests/phpstan/generate-baselines.php b/tests/phpstan/generate-baselines.php index 5a4ee33d9d5f9..f59ae0331c3b3 100644 --- a/tests/phpstan/generate-baselines.php +++ b/tests/phpstan/generate-baselines.php @@ -17,6 +17,11 @@ * includes every baseline in that directory, so adding a newly split out baseline, * and retiring one that has reached zero, need no edit of the configuration. * + * Unless a configuration is named, this is done for each of DEFAULT_CONFIGS in + * turn: phpstan.neon.dist, which analyzes the whole codebase, and then + * phpstan-strict.neon.dist, which holds selected paths to a stricter rule level + * and includes the former along with its baselines. + * * With `--prune`, nothing is analyzed: the baselines that no longer list any * entries are deleted. That completes running PHPStan with `--fix`, which removes * the entries of fixed errors in place but leaves a baseline it has emptied @@ -57,6 +62,21 @@ */ const DEFAULT_CONFIG = 'phpstan.neon.dist'; +/** + * The configurations processed when neither `--config` nor `--output-dir` is given, + * each with the directory its baselines are written to. + * + * They are processed in this order, which matters: phpstan-strict.neon.dist + * includes phpstan.neon.dist along with its baselines, so its own are only what is + * left over once those are up to date. + * + * Relative to the repository root. + */ +const DEFAULT_CONFIGS = array( + DEFAULT_CONFIG => DEFAULT_OUTPUT_DIR, + 'phpstan-strict.neon.dist' => 'tests/phpstan/baselines-strict', +); + if ( 'cli' !== PHP_SAPI ) { fwrite( STDERR, "This script must be run from the command line.\n" ); exit( 1 ); @@ -74,7 +94,8 @@ array_shift( $args ); $config_option = DEFAULT_CONFIG; -$output_option = DEFAULT_OUTPUT_DIR; +$output_option = null; +$config_given = false; $memory_limit = '2G'; $only_identifiers = array(); $combined = false; @@ -121,11 +142,13 @@ if ( 1 === preg_match( '/^--config=(.+)$/', $arg, $matches ) ) { $config_option = $matches[1]; + $config_given = true; continue; } if ( 1 === preg_match( '/^--output-dir=(.+)$/', $arg, $matches ) ) { $output_option = $matches[1]; + $config_given = true; continue; } @@ -138,6 +161,58 @@ exit( 1 ); } +/* + * Without a configuration named, every default configuration is processed in turn, + * each by a run of this script naming it, so that each run is the same as one asked + * for directly. The first failure stops the rest, since each configuration after it + * depends on the baselines of those before it. + * + * `--combined` prints a single baseline, so it keeps to the first configuration. + */ +if ( ! $config_given && ! $combined ) { + foreach ( DEFAULT_CONFIGS as $config => $output ) { + $command = implode( + ' ', + array_map( + 'escapeshellarg', + array( + PHP_BINARY, + __FILE__, + ...$args, + "--config=$config", + "--output-dir=$output", + ) + ) + ); + + fwrite( STDERR, "\n== $config ==\n\n" ); + + $exit_code = 0; + passthru( $command, $exit_code ); + + if ( 0 !== $exit_code ) { + exit( $exit_code ); + } + } + exit( 0 ); +} + +/* + * A default configuration named without an output directory writes to its own, + * so that naming phpstan-strict.neon.dist alone cannot write its baselines over + * those of phpstan.neon.dist. So does a local override of one, such as + * phpstan-strict.neon, named as the `.dist` file is but without the suffix. + * Written to the default directory instead, the stricter analysis of only the + * strict paths, with the baselines there suppressed, would retire every baseline of + * the whole codebase it does not report again. + */ +$config_relative = trim( normalize_path( $config_option ), '/' ); +$config_output_dir = DEFAULT_CONFIGS[ $config_relative ] ?? DEFAULT_CONFIGS[ $config_relative . '.dist' ] ?? DEFAULT_OUTPUT_DIR; + +if ( null === $output_option ) { + $output_option = $config_output_dir; +} + $config_path = $repo_root . '/' . ltrim( $config_option, '/' ); $output_dir = $repo_root . '/' . trim( $output_option, '/' ); @@ -258,8 +333,6 @@ static function () use ( $temp_config, $temp_baseline ): void { * readings of everything it does not cover. Keying the directory on the * configuration keeps each one's reflection to itself. */ -$config_relative = trim( normalize_path( $config_option ), '/' ); - if ( DEFAULT_CONFIG !== $config_relative ) { $analysis_tmp_dir .= '-' . (string) preg_replace( '/[^A-Za-z0-9._]+/', '-', $config_relative ); } @@ -301,14 +374,55 @@ static function () use ( $temp_config, $temp_baseline ): void { escapeshellarg( $memory_limit ) ); +/* + * The baselines only take effect through a loader in their own directory. It is + * written on every run, so that the committed loader of the default directory, and + * that of any other, stay what build_loader() makes rather than drifting from it + * unnoticed. A directory given with `--output-dir` that had none is not included + * by anything yet, so say so. + * + * It is written before the analysis rather than after, since a configuration may + * already include it, and PHPStan refuses to run with an include that is missing. + * That is how the baselines of a new configuration are first generated: add the + * loader of its directory to its `includes`, then run this with `--config` and + * `--output-dir` naming them. With the directory suppressed, the loader includes + * nothing during the analysis either way. + * + * `--combined` writes nothing to disk, so a missing loader stays missing then. + */ +if ( ! $combined ) { + if ( ! is_dir( $output_dir ) && ! mkdir( $output_dir, 0755, true ) ) { + fwrite( STDERR, "Could not create $output_option\n" ); + exit( 1 ); + } + + $loader_path = $output_dir . '/loader.php'; + $loader = build_loader( $output_dir ); + $loader_existed = is_file( $loader_path ); + $loader_contents = $loader_existed ? file_get_contents( $loader_path ) : false; + + if ( $loader !== $loader_contents ) { + if ( false === file_put_contents( $loader_path, $loader ) ) { + fwrite( STDERR, "Could not write $output_option/loader.php\n" ); + exit( 1 ); + } + + printf( + $loader_existed ? "%s: rewritten.\n" : "%s: written. The configuration has to include it for these baselines to take effect.\n", + $output_option . '/loader.php' + ); + } +} + fwrite( STDERR, "Analyzing with $config_option, baselines in $output_option suppressed...\n" ); /* * PHPStan inherits it, as do the worker processes it starts. It is the real path, - * since that is what the loader's __DIR__ is. An output directory not created yet - * holds no loader to match, so it is not set at all then. It is cleared first - * either way, so that a value exported in the shell, perhaps naming another - * directory, cannot switch off baselines this run means to keep. + * since that is what the loader's __DIR__ is. An output directory that does not + * exist, which only `--combined` leaves uncreated, holds no loader to match, so it + * is not set at all then. It is cleared first either way, so that a value + * exported in the shell, perhaps naming another directory, cannot switch off + * baselines this run means to keep. */ putenv( GENERATING_BASELINES_ENV ); $resolved_output_dir = realpath( $output_dir ); @@ -363,46 +477,17 @@ static function () use ( $temp_config, $temp_baseline ): void { exit( 0 ); } -if ( ! is_dir( $output_dir ) && ! mkdir( $output_dir, 0755, true ) ) { - fwrite( STDERR, "Could not create $output_option\n" ); - exit( 1 ); -} - -/* - * The baselines only take effect through a loader in their own directory. It is - * written on every run, so that the committed loader of the default directory, and - * that of any other, stay what build_loader() makes rather than drifting from it - * unnoticed. A directory given with `--output-dir` that had none is not included - * by anything yet, so say so. - */ -$loader_path = $output_dir . '/loader.php'; -$loader = build_loader( $output_dir ); -$loader_existed = is_file( $loader_path ); -$loader_contents = $loader_existed ? file_get_contents( $loader_path ) : false; - -if ( $loader !== $loader_contents ) { - if ( false === file_put_contents( $loader_path, $loader ) ) { - fwrite( STDERR, "Could not write $output_option/loader.php\n" ); - exit( 1 ); - } - - printf( - $loader_existed ? "%s: rewritten.\n" : "%s: written. Include it in the configuration for these baselines to take effect.\n", - $output_option . '/loader.php' - ); -} - /* * The command each header gives for regenerating its baseline has to name the - * configuration and the directory this run used, where they are not the - * defaults. Without them, it would regenerate the default directory instead. + * configuration this run used, even the default one, since without a + * configuration named, every one in DEFAULT_CONFIGS is processed, and the + * baselines of the same identifier in each of their directories are rewritten. + * The directory is only named where it is not the configuration's own, since + * naming the configuration alone writes there. */ -$regenerate_options = ''; -if ( DEFAULT_CONFIG !== $config_relative ) { - $regenerate_options .= ' --config=' . $config_option; -} -if ( ! $is_default_output_dir ) { - $regenerate_options .= ' --output-dir=' . $output_option; +$regenerate_options = ' --config=' . quote_shell_value( $config_option ); +if ( $config_output_dir !== trim( normalize_path( $output_option ), '/' ) ) { + $regenerate_options .= ' --output-dir=' . quote_shell_value( $output_option ); } foreach ( $grouped as $identifier => $entries ) { @@ -468,6 +553,10 @@ function get_usage(): string { tests/phpstan/baselines/loader.php, so neither addition nor removal needs an edit of it. + Without --config or --output-dir, this is done for phpstan.neon.dist into + tests/phpstan/baselines, and then for phpstan-strict.neon.dist into + tests/phpstan/baselines-strict. The other options apply to both. + Usage: composer phpstan:baselines [-- ] @@ -478,16 +567,21 @@ function get_usage(): string { rather than left behind empty. Default: every identifier reported. --config= Configuration to analyze with, relative to the repository - root. Default: phpstan.neon.dist + root. Naming one processes only that configuration. + Default: both of the above. --output-dir= Where the per-identifier baselines are written, relative to the repository root. Paths inside them are written relative to this directory. A loader is written there too, which the configuration has to include. Baselines in other directories stay in force, so only the errors they leave are written. - Default: tests/phpstan/baselines + Default: the directory of the configuration named + above, or of the one it overrides locally, such as + phpstan-strict.neon, or else tests/phpstan/baselines --combined Print one combined baseline to stdout instead of writing - per-identifier files. Nothing is written to disk. + per-identifier files. Nothing is written to disk. Only + phpstan.neon.dist is analyzed, unless --config names + another configuration. --prune Without analyzing anything, delete the baselines that no longer list any entries, such as one emptied by running PHPStan with --fix. With --identifier, only those @@ -800,6 +894,22 @@ function quote_neon_value( string $value ): string { return "'" . str_replace( "'", "''", $value ) . "'"; } +/** + * Quotes a value for a command shown to be run in a shell, where it needs it. + * + * The command is only written into a baseline's header, to be copied from there, + * so a value is left as it is when the shell would read it that way, as the paths + * of the default configurations and their directories are. Any other value, such + * as a path with a space in it, is quoted, so the copied command still passes it + * as one argument. + * + * @param string $value Value to quote. + * @return string Value, quoted if the shell would otherwise split or expand it. + */ +function quote_shell_value( string $value ): string { + return 1 === preg_match( '#^[\w./-]+$#', $value ) ? $value : escapeshellarg( $value ); +} + /** * Builds the header comment for a per-identifier baseline. * @@ -822,11 +932,11 @@ function build_baseline_header( string $identifier, string $options = '' ): stri # # The goal is to empty this file and delete it. # - # Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with + # Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: # # composer phpstan:baselines -- --identifier=$identifier$options # - # which reruns the analysis with the baselines in this directory suppressed, so + # This reruns the analysis with the baselines in this directory suppressed, so # that their errors surface again, and rewrites only this file. TEXT; From 96c60f01f6c076a45c13995e40e687192a5d9133 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Wed, 18 Nov 2026 23:55:10 +0000 Subject: [PATCH 24/85] Build/Test Tools: Run the mu-plugin E2E specs in parallel. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Give each test plugin a unique filename and limit its effects to requests carrying the test’s query parameter. Publish each plugin with an atomic rename and remove test plugins during global setup. Move the fatal error handler and login script localization specs to the parallel Playwright project. Developed in: https://github.com/WordPress/wordpress-develop/pull/16037 Props adrianmoldovanwp, lucatume. See #66392. git-svn-id: https://develop.svn.wordpress.org/trunk@65669 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/e2e/README.md | 2 +- tests/e2e/config/global-setup.js | 11 ++-- tests/e2e/fixtures/site.js | 64 ++++++++++++++----- tests/e2e/playwright.config.js | 2 - tests/e2e/specs/fatal-error-handler.test.js | 17 ++++- tests/e2e/specs/login-localize-script.test.js | 34 ++++++---- 6 files changed, 91 insertions(+), 39 deletions(-) diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 8ac40c53af75f..62601d8760797 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -93,7 +93,7 @@ To create posts, pages or users, to upload attachments, or to change a setting, * `siteSettings`: reads and changes the settings of `/wp/v2/settings` through REST, with `get()`, `remember( keys )` and `set( patch )`. It restores only the keys passed to `remember` or `set`. See `specs/privacy.test.js`. * `siteOptions`: reads and changes options through WP-CLI, with `get( names )`, `remember( names )` and `set( values )`. It reads and restores the stored `gmt_offset`, not the value calculated for a named timezone. It restores only the keys passed to `remember` or `set`. See `specs/general-settings-invalid-timezone.test.js`. -* `muPlugin`: writes a must-use plugin with `write( fileName, php )`, and deletes the file when the test ends. Call `write` before the test visits a page. See `specs/fatal-error-handler.test.js`. +* `muPlugin`: writes a must-use plugin with `write( fileName, php )`. Unlike the other fixtures, it does not delete the file when the test ends, because a request from another worker can fail if a file goes away while WordPress loads it. Global setup deletes the files before the next run, so a plugin must not change requests from other tests. Call `write` before the test visits a page. See `specs/fatal-error-handler.test.js`. * `postFactory`: creates posts with `create( data )` and pages with `createPage( data )`, and force-deletes them when the test ends. `uniqueTitle( prefix )` adds a UUID to the prefix. See `specs/edit-posts.test.js`. * `attachments`: uploads a file with `upload( absolutePath )`, records an attachment that the browser uploaded with `track( id )`, and deletes them when the test ends. See `specs/media-new-client-side-upload.test.js`. * `userFactory`: creates users with `create( { roles, ...data } )`, which returns `{ user, username, password }`. For a user that the test creates through a form, call `adopt( username )` before the form is submitted. When the test ends, it deletes each user and the user's auto-drafts. To log in as the user, import `signIn( page, username, password )` from `../fixtures/user`. See `specs/users.test.js`. diff --git a/tests/e2e/config/global-setup.js b/tests/e2e/config/global-setup.js index 407e7ba32e0e1..be45c9fb22a21 100644 --- a/tests/e2e/config/global-setup.js +++ b/tests/e2e/config/global-setup.js @@ -10,6 +10,11 @@ import { request } from '@playwright/test'; */ import { RequestUtils } from '@wordpress/e2e-test-utils-playwright'; +/** + * Internal dependencies + */ +import { removeMuPlugins } from '../fixtures/site'; + /** * * @param {import('@playwright/test').FullConfig} config @@ -20,12 +25,10 @@ async function globalSetup( config ) { const storageStatePath = typeof storageState === 'string' ? storageState : undefined; - // An interrupted run can leave these behind, and each one breaks the whole site. + // An interrupted run can leave this behind, and it breaks the whole site. const documentRoot = join( process.cwd(), process.env.LOCAL_DIR ?? 'src' ); rmSync( join( documentRoot, '.maintenance' ), { force: true } ); - rmSync( join( documentRoot, 'wp-content/mu-plugins/fatal-error.php' ), { - force: true, - } ); + removeMuPlugins(); const requestContext = await request.newContext( { baseURL, diff --git a/tests/e2e/fixtures/site.js b/tests/e2e/fixtures/site.js index b6ecce28ffef6..a8502b94152a7 100644 --- a/tests/e2e/fixtures/site.js +++ b/tests/e2e/fixtures/site.js @@ -1,7 +1,9 @@ /** * External dependencies */ -import { mkdir, rm, writeFile } from 'node:fs/promises'; +import { randomUUID } from 'node:crypto'; +import { readdirSync, rmSync } from 'node:fs'; +import { mkdir, rename, rm, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; /** @@ -134,28 +136,56 @@ export const siteOptions = async ( { baseURL }, use ) => { } }; +const muPluginDirectory = join( + process.cwd(), + process.env.LOCAL_DIR ?? 'src', + 'wp-content/mu-plugins' +); +const MU_PLUGIN_PREFIX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}-/; + /** - * Writes must-use plugins. Teardown deletes each file that `write` wrote. + * Deletes the must-use plugins that `muPlugin` wrote. Global setup calls this, while no + * test runs. */ -export const muPlugin = async ( {}, use ) => { - const directory = join( - process.cwd(), - process.env.LOCAL_DIR ?? 'src', - 'wp-content/mu-plugins' - ); - const files = new Set(); +export function removeMuPlugins() { + let names; + try { + names = readdirSync( muPluginDirectory ); + } catch { + return; + } + for ( const name of names ) { + if ( MU_PLUGIN_PREFIX.test( name ) ) { + rmSync( join( muPluginDirectory, name ), { force: true } ); + } + } +} +/** + * Writes must-use plugins. Each file name gets a unique prefix, so that tests in other workers + * cannot overwrite it. + * + * The files stay until the next run's global setup deletes them. A request from another worker + * can list a file and then include it, so deleting the file between the two makes that request + * fail. Each plugin must therefore not change requests from other tests. + */ +export const muPlugin = async ( {}, use ) => { await use( { write: async ( fileName, php ) => { - const file = join( directory, fileName ); - files.add( file ); - await mkdir( directory, { recursive: true } ); - await writeFile( file, php ); + const file = join( + muPluginDirectory, + `${ randomUUID() }-${ fileName }` + ); + await mkdir( muPluginDirectory, { recursive: true } ); + // WordPress loads only `*.php` files, so it never includes a half-written file. + const temporary = `${ file }.tmp`; + try { + await writeFile( temporary, php ); + await rename( temporary, file ); + } finally { + await rm( temporary, { force: true } ); + } return file; }, } ); - - await settleRestores( - [ ...files ].map( ( file ) => rm( file, { force: true } ) ) - ); }; diff --git a/tests/e2e/playwright.config.js b/tests/e2e/playwright.config.js index d6fad8f51c4a3..0db4d5c44e525 100644 --- a/tests/e2e/playwright.config.js +++ b/tests/e2e/playwright.config.js @@ -18,8 +18,6 @@ process.env.STORAGE_STATE_PATH ??= path.join( const SERIAL_SPECS = [ 'install.test.js', 'maintenance-mode.test.js', - 'fatal-error-handler.test.js', - 'login-localize-script.test.js', 'gutenberg-plugin.test.js', 'plugins.test.js', 'themes.test.js', diff --git a/tests/e2e/specs/fatal-error-handler.test.js b/tests/e2e/specs/fatal-error-handler.test.js index 3d1e320f57f4f..047d39eb8d292 100644 --- a/tests/e2e/specs/fatal-error-handler.test.js +++ b/tests/e2e/specs/fatal-error-handler.test.js @@ -1,3 +1,8 @@ +/** + * External dependencies + */ +import { randomUUID } from 'node:crypto'; + /** * Internal dependencies */ @@ -5,9 +10,17 @@ import { test, expect } from '../fixtures'; test.describe( 'Fatal error handler', () => { test( 'should display fatal error notice', async ( { admin, page, muPlugin } ) => { - await muPlugin.write( 'fatal-error.php', ` { test( 'should localize script', async ( { page, muPlugin } ) => { + const trigger = randomUUID(); await muPlugin.write( 'login-test.php', ` 42, - ] - ); - } - );` + if ( isset( $_GET['${ trigger }'] ) ) { + add_action( + 'login_enqueue_scripts', + function() { + wp_localize_script( + 'wp-util', + 'testData', + [ + 'answerToTheUltimateQuestionOfLifeTheUniverseAndEverything' => 42, + ] + ); + } + ); + }` ); - await page.goto( '/wp-login.php' ); + await page.goto( `/wp-login.php?${ trigger }` ); await expect( page.getByRole( 'button', { name: 'Log In', exact: true } ) ).toBeVisible(); From 12824a98a51a70dce80a622e574edb8715863b3b Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Thu, 19 Nov 2026 00:04:58 +0000 Subject: [PATCH 25/85] Tests: Avoid attachment ID collisions in media widget tests. Use `REST_TESTS_IMPOSSIBLY_HIGH_NUMBER` for the missing attachment in the audio and video widget tests. The test fixture itself can receive ID `777` and render media where the tests expect empty output. Developed in: https://github.com/WordPress/wordpress-develop/pull/16092 Props johnbillion. See #66736. git-svn-id: https://develop.svn.wordpress.org/trunk@65670 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/widgets/wpWidgetMediaAudio.php | 2 +- tests/phpunit/tests/widgets/wpWidgetMediaVideo.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/phpunit/tests/widgets/wpWidgetMediaAudio.php b/tests/phpunit/tests/widgets/wpWidgetMediaAudio.php index cb555fb5285a5..52388224c201b 100644 --- a/tests/phpunit/tests/widgets/wpWidgetMediaAudio.php +++ b/tests/phpunit/tests/widgets/wpWidgetMediaAudio.php @@ -239,7 +239,7 @@ public function test_render_media() { ob_start(); $widget->render_media( array( - 'attachment_id' => 777, + 'attachment_id' => REST_TESTS_IMPOSSIBLY_HIGH_NUMBER, ) ); $output = ob_get_clean(); diff --git a/tests/phpunit/tests/widgets/wpWidgetMediaVideo.php b/tests/phpunit/tests/widgets/wpWidgetMediaVideo.php index 98c86ec4865fd..39ce60d7cb3f3 100644 --- a/tests/phpunit/tests/widgets/wpWidgetMediaVideo.php +++ b/tests/phpunit/tests/widgets/wpWidgetMediaVideo.php @@ -241,7 +241,7 @@ public function test_render_media() { ob_start(); $widget->render_media( array( - 'attachment_id' => 777, + 'attachment_id' => REST_TESTS_IMPOSSIBLY_HIGH_NUMBER, ) ); $output = ob_get_clean(); From ba75b6ea844c49e7e26e6970d4df945ea2a8f5c2 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Thu, 19 Nov 2026 13:13:51 +0000 Subject: [PATCH 26/85] Build/Test Tools: Check where tracked CSS and JavaScript files live. Check the CSS and JavaScript directories in `wp-admin` and `wp-includes` for misplaced files. Allow the admin color scheme SCSS sources and the generated files under `wp-includes/build/`. Developed in: https://github.com/WordPress/wordpress-develop/pull/13684 Props adrianmoldovanwp, mohamedahamed, lucatume, jorbin. See #65279. git-svn-id: https://develop.svn.wordpress.org/trunk@65673 602fd350-edb4-49c9-b593-d223f7449a82 --- .github/workflows/file-type-check.yml | 182 ++++++++++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 .github/workflows/file-type-check.yml diff --git a/.github/workflows/file-type-check.yml b/.github/workflows/file-type-check.yml new file mode 100644 index 0000000000000..e2773384a8009 --- /dev/null +++ b/.github/workflows/file-type-check.yml @@ -0,0 +1,182 @@ +name: File Type Check + +on: + push: + branches: + - trunk + - '6.[8-9]' + - '[7-9].[0-9]' + paths: + # Inward check: files added to CSS/JS directories. + - 'src/wp-includes/css/**' + - 'src/wp-includes/js/**' + - 'src/wp-admin/css/**' + - 'src/wp-admin/js/**' + # Outward check: CSS/JS files placed outside designated directories. + - 'src/wp-includes/**.css' + - 'src/wp-includes/**.js' + - 'src/wp-admin/**.css' + - 'src/wp-admin/**.js' + # Confirm any changes to the workflow file itself. + - '.github/workflows/file-type-check.yml' + pull_request: + branches: + - trunk + - '6.[8-9]' + - '[7-9].[0-9]' + paths: + - 'src/wp-includes/css/**' + - 'src/wp-includes/js/**' + - 'src/wp-admin/css/**' + - 'src/wp-admin/js/**' + - 'src/wp-includes/**.css' + - 'src/wp-includes/**.js' + - 'src/wp-admin/**.css' + - 'src/wp-admin/**.js' + - '.github/workflows/file-type-check.yml' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }} + cancel-in-progress: true + +permissions: {} + +jobs: + # Verifies that CSS and JS files live in the directories intended for them. + # + # The JS sources in src/js/ are out of scope. The build system decides where + # those are placed, so only its output is checked. + check-file-types: + name: Verify file types in CSS/JS directories + runs-on: ubuntu-26.04 + permissions: + contents: read + if: | + github.repository == 'WordPress/wordpress-develop' || ( + github.event_name == 'pull_request' && ( + ! github.event.repository.private || + ! github.event.pull_request.draft || + contains( github.event.pull_request.labels.*.name, 'Draft Workflow Runs' ) + ) + ) + timeout-minutes: 5 + + steps: + - name: Checkout repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + show-progress: ${{ runner.debug == '1' && 'true' || 'false' }} + persist-credentials: false + + - name: Check for misplaced CSS and JS files + run: | + # Git does the filtering, so no path is ever matched as text. Shell + # patterns break on names holding a tab, a newline or a quote: Git + # C-quotes those, and core.quotePath=false does not stop it. + # + # Each check is a bare assignment, so `set -e` sees a failure from Git. + # + # Every exclude starts with src/, the directory the positive pathspecs share. + # git ls-files strips that shared directory from every pathspec, excludes + # included, without checking that it is there. An exclude such as *.js is + # then cut down to a pattern that can match every file. + # + # Only tracked files are checked. The PHP that Gutenberg generates + # into css/dist and js/dist is untracked, so it never appears here. + # Whether it should be tracked, moved, or not copied at all is still + # open in #65278. If it becomes tracked, this check will flag it. + + # Git exits 0 when a pathspec matches nothing. + if [ -z "$( git ls-files -- src/wp-includes src/wp-admin )" ]; then + echo "::error::No tracked files found under src/wp-includes or src/wp-admin." + exit 1 + fi + + # The SCSS sources for the admin color schemes are the only tracked + # non-CSS files in these directories. + inward_css=$( git ls-files -- src/wp-includes/css src/wp-admin/css \ + ':(exclude,glob)src/wp-includes/css/**/*.css' \ + ':(exclude,glob)src/wp-admin/css/**/*.css' \ + ':(exclude,glob)src/wp-admin/css/colors/**/*.scss' ) + + # Both directories are gitignored in full, so this only catches a file + # committed with `git add -f`. + inward_js=$( git ls-files -- src/wp-includes/js src/wp-admin/js \ + ':(exclude,glob)src/wp-includes/js/**/*.js' \ + ':(exclude,glob)src/wp-admin/js/**/*.js' ) + + # src/wp-includes/build/ is tracked, not gitignored: it holds the + # generated routes and pages. + outward=$( git ls-files -- \ + ':(glob)src/wp-includes/**/*.css' ':(glob)src/wp-includes/**/*.js' \ + ':(glob)src/wp-admin/**/*.css' ':(glob)src/wp-admin/**/*.js' \ + ':(exclude,glob)src/wp-includes/css/**' \ + ':(exclude,glob)src/wp-includes/js/**' \ + ':(exclude,glob)src/wp-admin/css/**' \ + ':(exclude,glob)src/wp-admin/js/**' \ + ':(exclude,glob)src/wp-includes/build/**' ) + + violations=$( printf '%s\n%s\n%s' "$inward_css" "$inward_js" "$outward" | grep -v '^$' || true ) + + if [ -n "$violations" ]; then + echo "::error::Misplaced files found." + echo + echo "$violations" + echo + echo "CSS directories should contain only .css files and JS directories only .js files." + echo ".css and .js files belong in those directories, not elsewhere in wp-includes/ or wp-admin/." + echo "If a file is a legitimate exception, update .github/workflows/file-type-check.yml." + exit 1 + fi + + echo "All tracked CSS and JS files are correctly placed." + + slack-notifications: + name: Slack Notifications + uses: ./.github/workflows/slack-notifications.yml + permissions: + actions: read + contents: read + needs: [ check-file-types ] + if: ${{ github.repository == 'WordPress/wordpress-develop' && github.event_name != 'pull_request' && always() }} + with: + calling_status: ${{ contains( needs.*.result, 'cancelled' ) && 'cancelled' || contains( needs.*.result, 'failure' ) && 'failure' || 'success' }} + secrets: + SLACK_GHA_SUCCESS_WEBHOOK: ${{ secrets.SLACK_GHA_SUCCESS_WEBHOOK }} + SLACK_GHA_CANCELLED_WEBHOOK: ${{ secrets.SLACK_GHA_CANCELLED_WEBHOOK }} + SLACK_GHA_FIXED_WEBHOOK: ${{ secrets.SLACK_GHA_FIXED_WEBHOOK }} + SLACK_GHA_FAILURE_WEBHOOK: ${{ secrets.SLACK_GHA_FAILURE_WEBHOOK }} + + failed-workflow: + name: Failed workflow tasks + runs-on: ubuntu-26.04 + permissions: + actions: write + needs: [ check-file-types, slack-notifications ] + if: | + always() && + github.repository == 'WordPress/wordpress-develop' && + github.event_name != 'pull_request' && + github.run_attempt < 2 && + ( + contains( needs.*.result, 'cancelled' ) || + contains( needs.*.result, 'failure' ) + ) + + steps: + - name: Dispatch workflow run + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + retries: 2 + retry-exempt-status-codes: 418 + script: | + github.rest.actions.createWorkflowDispatch({ + owner: context.repo.owner, + repo: context.repo.repo, + workflow_id: 'failed-workflow.yml', + ref: 'trunk', + inputs: { + run_id: `${context.runId}`, + } + }); From 2162cd6933dee4096080446806fb6a2612dce94b Mon Sep 17 00:00:00 2001 From: Jonathan Desrosiers Date: Thu, 19 Nov 2026 14:53:30 +0000 Subject: [PATCH 27/85] Docs: Remove repeated word within `WP_Error` property. Props kimclow. See #65860. git-svn-id: https://develop.svn.wordpress.org/trunk@65691 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-error.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/class-wp-error.php b/src/wp-includes/class-wp-error.php index d5b3dc729a0c1..c694828d84870 100644 --- a/src/wp-includes/class-wp-error.php +++ b/src/wp-includes/class-wp-error.php @@ -34,7 +34,7 @@ class WP_Error { public $error_data = array(); /** - * Stores previously added data added for error codes, oldest-to-newest by code. + * Stores previously added data for error codes, oldest-to-newest by code. * * @since 5.6.0 * @var array From 6883e5015ff0701c6a432b2ff0d21a609ab3b814 Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Thu, 19 Nov 2026 18:58:46 +0000 Subject: [PATCH 28/85] Docs: Correct the indentation of closing braces in hash notation. See #65860 git-svn-id: https://develop.svn.wordpress.org/trunk@65692 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-customize-setting.php | 2 +- src/wp-includes/nav-menu-template.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-customize-setting.php b/src/wp-includes/class-wp-customize-setting.php index c8272651b85df..77a544bfbae0e 100644 --- a/src/wp-includes/class-wp-customize-setting.php +++ b/src/wp-includes/class-wp-customize-setting.php @@ -200,7 +200,7 @@ class WP_Customize_Setting { * @type callable $sanitize_js_callback Callback to convert a Customize PHP setting value to a value that is * JSON serializable. * @type bool $dirty Whether or not the setting is initially dirty when created. - * } + * } */ public function __construct( $manager, $id, $args = array() ) { $keys = array_keys( get_object_vars( $this ) ); diff --git a/src/wp-includes/nav-menu-template.php b/src/wp-includes/nav-menu-template.php index c11f00855cf0d..09990fd0d21e0 100644 --- a/src/wp-includes/nav-menu-template.php +++ b/src/wp-includes/nav-menu-template.php @@ -55,7 +55,7 @@ * numbered placeholders. Default is a ul with an id and class. * @type string $item_spacing Whether to preserve whitespace within the menu's HTML. * Accepts 'preserve' or 'discard'. Default 'preserve'. - * } + * } * @return void|string|false Void if 'echo' argument is true, menu output if 'echo' is false. * False if there are no items or no menu was found. */ From c27ffa2898df5bef56570863055824f0d7047d58 Mon Sep 17 00:00:00 2001 From: Jonathan Desrosiers Date: Thu, 19 Nov 2026 19:14:38 +0000 Subject: [PATCH 29/85] Build/Test Tools: Split the PHPStan reusable workflow into -v1 and -v2. The 7.0 and 7.1 branches call `reusable-phpstan-static-analysis-v1.yml` from `trunk`. In r65668, that workflow began running `composer phpstan:default` and `composer phpstan:strict`, which only exist in `trunk`'s `composer.json`. Because of this, both of its jobs now fail immediately on those branches. This copies the current version of the workflow to `reusable-phpstan-static-analysis-v2.yml`, which `trunk` now calls, and restores `reusable-phpstan-static-analysis-v1.yml` to its state before r65668 for those branches. Follow-up to r65668. Reviewed by westonruter. Props desrosj, westonruter. Fixes #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65693 602fd350-edb4-49c9-b593-d223f7449a82 --- .github/workflows/phpstan-static-analysis.yml | 4 +- .../reusable-phpstan-static-analysis-v1.yml | 101 +---- .../reusable-phpstan-static-analysis-v2.yml | 384 ++++++++++++++++++ tests/phpstan/README.md | 2 +- 4 files changed, 404 insertions(+), 87 deletions(-) create mode 100644 .github/workflows/reusable-phpstan-static-analysis-v2.yml diff --git a/.github/workflows/phpstan-static-analysis.yml b/.github/workflows/phpstan-static-analysis.yml index 3d855296e0e0a..386a71cece831 100644 --- a/.github/workflows/phpstan-static-analysis.yml +++ b/.github/workflows/phpstan-static-analysis.yml @@ -23,7 +23,7 @@ on: - 'tests/phpstan/baselines-strict/**' # Confirm any changes to relevant workflow files. - '.github/workflows/phpstan-static-analysis.yml' - - '.github/workflows/reusable-phpstan-static-analysis-v1.yml' + - '.github/workflows/reusable-phpstan-static-analysis-v2.yml' workflow_dispatch: # Cancels all previous workflow runs for pull requests that have not completed. @@ -41,7 +41,7 @@ jobs: # Runs PHPStan Static Analysis. phpstan: name: PHP static analysis - uses: ./.github/workflows/reusable-phpstan-static-analysis-v1.yml + uses: ./.github/workflows/reusable-phpstan-static-analysis-v2.yml permissions: contents: read if: | diff --git a/.github/workflows/reusable-phpstan-static-analysis-v1.yml b/.github/workflows/reusable-phpstan-static-analysis-v1.yml index aba7162bb2a05..cda319835e645 100644 --- a/.github/workflows/reusable-phpstan-static-analysis-v1.yml +++ b/.github/workflows/reusable-phpstan-static-analysis-v1.yml @@ -1,7 +1,7 @@ ## # A reusable workflow that runs PHP Static Analysis tests. # -# This workflow is used by `trunk` and branches >= 7.0. +# This workflow is used by branches 7.0 and 7.1. ## name: PHP Static Analysis @@ -21,11 +21,8 @@ permissions: {} jobs: # Runs PHP static analysis tests. # - # Core is analyzed twice, in parallel: the whole codebase with phpstan.neon.dist, and the paths held to a stricter rule - # level with phpstan-strict.neon.dist. See tests/phpstan/README.md. - # - # Violations are reported inline with annotations. For pull requests, the results of each analysis are also uploaded - # as an artifact, and the PHPStan Pull Request Comments workflow combines them in a comment. + # Violations are reported inline with annotations. For pull requests, the results are also uploaded + # as an artifact, which the PHPStan Pull Request Comments workflow summarizes in a comment. # # Performs the following steps: # - Checks out the repository. @@ -42,33 +39,11 @@ jobs: # - Saves the PHPStan result cache. # - Ensures version-controlled files are not modified or deleted. phpstan: - name: Run PHP static analysis (${{ matrix.label }}) + name: Run PHP static analysis runs-on: ubuntu-26.04 permissions: contents: read timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - include: - # The artifact of the analysis of the whole codebase keeps the name it had before there were two, which is - # the name the PHPStan Pull Request Comments workflow on trunk requires. That way the comment is kept up to - # date for a pull request whose branch does not have the second analysis yet. - # - # The analyses are named for their role rather than their rule level, which is read from the configuration - # when the results are reported, so that raising either level is an edit of its configuration alone. - - analysis: default - label: all paths - config: phpstan.neon.dist - baselines: tests/phpstan/baselines - script: phpstan:default - artifact: phpstan-results - - analysis: strict - label: strict paths - config: phpstan-strict.neon.dist - baselines: tests/phpstan/baselines-strict - script: phpstan:strict - artifact: phpstan-results-strict steps: # For a pull request, the parents of the merge commit are fetched too, to find the files that the base branch @@ -117,21 +92,16 @@ jobs: # merged this commit yet runs the workflow it has, and that workflow would prefix-match the # caches written here: it would analyse without the extensions against reflection derived with # them. A name of its own leaves those runs restoring only their own caches. - # - # Each analysis caches separately. Its result cache records the rule level, and is discarded - # by a run at another level, so restoring the other analysis's cache would gain nothing. - name: Cache PHP Static Analysis scan cache uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 with: path: .cache # This is defined in the base.neon file. - key: "phpstan-analysis-cache-${{ matrix.analysis }}-${{ hashFiles('phpstan.neon.dist', 'phpstan-strict.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}-${{ github.run_id }}" + key: "phpstan-analysis-cache-${{ hashFiles('phpstan.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}-${{ github.run_id }}" restore-keys: | - phpstan-analysis-cache-${{ matrix.analysis }}-${{ hashFiles('phpstan.neon.dist', 'phpstan-strict.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}- + phpstan-analysis-cache-${{ hashFiles('phpstan.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}- - name: Run PHP static analysis tests id: phpstan - env: - SCRIPT: ${{ matrix.script }} run: | # The report is written to a file for the steps below, which turn it into annotations, # the pull request comment, and a check for errors that cannot be reported as warnings. @@ -141,7 +111,7 @@ jobs: # The step shell exits on the first failing command, which would also end the step on # the status of 1 that PHPStan uses for reporting errors. Capture the status instead. status=0 - composer run "${SCRIPT}" -- -vvv --error-format=json > "${RUNNER_TEMP}/phpstan-report.json" || status=$? + composer run phpstan -- -vvv --error-format=json > "${RUNNER_TEMP}/phpstan-report.json" || status=$? # PHPStan exits 1 when it has errors to report, which is the expected case here and # is what the annotations are for. Anything higher means it did not finish at all. @@ -162,36 +132,11 @@ jobs: - name: Report the analysis results id: report uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - ANALYSIS: ${{ matrix.analysis }} - CONFIG: ${{ matrix.config }} with: script: | const fs = require( 'fs' ); - // The rule level the configuration analyzes at, as a number, or `max`. Only the line of the parameter is - // matched, rather than decoding the whole dump, because the JSON PHPStan prints can be invalid: it writes - // the `\<` in a message pattern as is, which is not a valid JSON escape. - let level = null; - try { - const parameters = require( 'child_process' ).execFileSync( - `${ process.env.GITHUB_WORKSPACE }/vendor/bin/phpstan`, - [ 'dump-parameters', `--configuration=${ process.env.CONFIG }`, '--json' ], - { encoding: 'utf8' } - ); - const match = parameters.match( /^\s*"level":\s*"?(max|\d+)"?,?$/m ); - if ( match ) { - level = match[ 1 ] === 'max' ? 'max' : Number( match[ 1 ] ); - } - } catch ( error ) { - core.warning( `The rule level of ${ process.env.CONFIG } could not be read: ${ error.message }` ); - } - - // Annotations from the stricter analysis say so, since the same code can pass the other one. - const analysis = process.env.ANALYSIS; - const titlePrefix = analysis === 'strict' ? `PHPStan (strict${ level === null ? '' : `, level ${ level }` })` : 'PHPStan'; - - const report = JSON.parse( fs.readFileSync( `${ process.env.RUNNER_TEMP }/phpstan-report.json`, { encoding: 'utf8' } ) ); + const report = JSON.parse( fs.readFileSync( `${ process.env.RUNNER_TEMP }/phpstan-report.json`, 'utf8' ) ); const workspace = `${ process.env.GITHUB_WORKSPACE }/`; const errors = []; @@ -220,7 +165,7 @@ jobs: const fixHint = 'This can be fixed automatically by running `composer phpstan:fix` (or `npm run typecheck:php:fix`).'; for ( const error of errors ) { - const properties = { title: error.identifier ? `${ titlePrefix }: ${ error.identifier }` : titlePrefix }; + const properties = { title: error.identifier ? `PHPStan: ${ error.identifier }` : 'PHPStan' }; if ( error.file ) { properties.file = error.file; } @@ -241,10 +186,6 @@ jobs: // The commit analyzed is the pull request merged into its base branch, whose second parent is the head // commit. The files with errors that differ between the two are those the base branch has changed, in // which the line numbers reported can be off in the head commit. - // - // Each analysis writes its own results. Those of the analysis of the whole codebase also list every - // analysis the run makes, so that the comment is not updated from only some of them: an error missing - // because its analysis did not upload results would otherwise be shown as resolved. if ( context.eventName === 'pull_request' ) { let changedInBase = []; try { @@ -259,10 +200,6 @@ jobs: fs.mkdirSync( `${ process.env.RUNNER_TEMP }/phpstan-results`, { recursive: true } ); fs.writeFileSync( `${ process.env.RUNNER_TEMP }/phpstan-results/results.json`, JSON.stringify( { pull_request: context.payload.pull_request.number, - analysis, - level, - // Keep this list in step with the `analysis` values of the job's matrix. - ...( analysis === 'default' ? { analyses: [ 'default', 'strict' ] } : {} ), changed_in_base: changedInBase, errors: errors.map( ( { tip, fixable, ...error } ) => error ), } ) ); @@ -274,7 +211,7 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 if: ${{ github.event_name == 'pull_request' && steps.report.outcome == 'success' }} with: - name: ${{ matrix.artifact }} + name: phpstan-results path: ${{ runner.temp }}/phpstan-results/ # Some errors cannot be ignored, so they cannot be reported as warnings either. Most often @@ -292,8 +229,7 @@ jobs: - name: Check for errors that cannot be reported as warnings if: ${{ !cancelled() }} env: - BASELINES_URL: ${{ github.server_url }}/${{ github.repository }}/tree/${{ github.sha }}/${{ matrix.baselines }} - LABEL: ${{ matrix.label }} + BASELINES_URL: ${{ github.server_url }}/${{ github.repository }}/tree/${{ github.sha }}/tests/phpstan/baselines README_URL: ${{ github.server_url }}/${{ github.repository }}/blob/${{ github.sha }}/tests/phpstan/README.md run: | # This step runs even when the analysis above it failed, in which case the report may @@ -328,11 +264,8 @@ jobs: # # A newline renders as a line break rather than a space, so each paragraph is one # line however long that makes it, and the rendered summary wraps to its own width. - # - # The heading names the analysis whose baselines are out of date, which is filled in for - # the LABEL placeholder when the summary is written, since the heredoc expands nothing. baselines_summary=$( cat <<'SUMMARY' - ## PHPStan baselines are out of date (LABEL) + ## PHPStan baselines are out of date An ignored error no longer occurs, or occurs a different number of times, so PHPStan reported it under an `ignore.unmatched` or `ignore.count` identifier. @@ -350,7 +283,7 @@ jobs: composer phpstan:fix ``` - That runs PHPStan with `--fix`, which lowers the counts in [the baselines][baselines], removes the entries that no longer match, and removes any `@phpstan-ignore` annotation in the code that no longer ignores anything. It then deletes any baseline left with no entries. + That runs PHPStan with `--fix`, which lowers the counts in the files under [`tests/phpstan/baselines`][baselines], removes the entries that no longer match, and removes any `@phpstan-ignore` annotation in the code that no longer ignores anything. It then deletes any baseline left with no entries. Alternatively, regenerate the baselines with `npm run typecheck:php:baselines` or `composer phpstan:baselines`. That also deletes any baseline whose errors are now all fixed, but it does not clear an `@phpstan-ignore` annotation. @@ -361,14 +294,14 @@ jobs: if [ "${ignore_errors}" -gt 0 ]; then { - printf '%s\n\n' "${baselines_summary/LABEL/${LABEL}}" + printf '%s\n\n' "${baselines_summary}" echo "[baselines]: ${BASELINES_URL}" echo "[readme]: ${README_URL}" } >> "${GITHUB_STEP_SUMMARY}" - echo "::error title=PHPStan baselines are out of date (${LABEL})::An ignored error no longer occurs, or occurs a different number of times. If you fixed it, that is expected: run \`npm run typecheck:php:fix\` or \`composer phpstan:fix\` and commit the updated baselines. See ${README_URL}" + echo "::error title=PHPStan baselines are out of date::An ignored error no longer occurs, or occurs a different number of times. If you fixed it, that is expected: run \`npm run typecheck:php:fix\` or \`composer phpstan:fix\` and commit the updated baselines. See ${README_URL}" else - echo "::error title=PHPStan reported errors that cannot be ignored (${LABEL})::PHPStan reported ${unignorable} error(s) that cannot be ignored or reported as warnings. See the error annotations for details, and ${README_URL} for how to run the analysis locally." + echo "::error title=PHPStan reported errors that cannot be ignored::PHPStan reported ${unignorable} error(s) that cannot be ignored or reported as warnings. See the error annotations for details, and ${README_URL} for how to run the analysis locally." fi exit 1 @@ -378,7 +311,7 @@ jobs: if: ${{ !cancelled() }} with: path: .cache - key: "phpstan-analysis-cache-${{ matrix.analysis }}-${{ hashFiles('phpstan.neon.dist', 'phpstan-strict.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}-${{ github.run_id }}" + key: "phpstan-analysis-cache-${{ hashFiles('phpstan.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}-${{ github.run_id }}" - name: Ensure version-controlled files are not modified or deleted run: git diff --exit-code diff --git a/.github/workflows/reusable-phpstan-static-analysis-v2.yml b/.github/workflows/reusable-phpstan-static-analysis-v2.yml new file mode 100644 index 0000000000000..2973de0ca40a2 --- /dev/null +++ b/.github/workflows/reusable-phpstan-static-analysis-v2.yml @@ -0,0 +1,384 @@ +## +# A reusable workflow that runs PHP Static Analysis tests. +# +# This workflow is used by `trunk` and branches >= 7.2. +## +name: PHP Static Analysis + +on: + workflow_call: + inputs: + php-version: + description: 'The PHP version to use.' + required: false + type: 'string' + default: 'latest' + +# Disable permissions for all available scopes by default. +# Any needed permissions should be configured at the job level. +permissions: {} + +jobs: + # Runs PHP static analysis tests. + # + # Core is analyzed twice, in parallel: the whole codebase with phpstan.neon.dist, and the paths held to a stricter rule + # level with phpstan-strict.neon.dist. See tests/phpstan/README.md. + # + # Violations are reported inline with annotations. For pull requests, the results of each analysis are also uploaded + # as an artifact, and the PHPStan Pull Request Comments workflow combines them in a comment. + # + # Performs the following steps: + # - Checks out the repository. + # - Sets up PHP. + # - Logs debug information. + # - Installs Composer dependencies. + # - Make Composer packages available globally. + # - Builds WordPress. + # - Configures caching for PHPStan static analysis scans. + # - Runs PHPStan static analysis. + # - Reports the results as annotations. + # - Uploads the results as an artifact (pull requests only). + # - Checks for errors that cannot be reported as warnings, such as out-of-date baselines. + # - Saves the PHPStan result cache. + # - Ensures version-controlled files are not modified or deleted. + phpstan: + name: Run PHP static analysis (${{ matrix.label }}) + runs-on: ubuntu-26.04 + permissions: + contents: read + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + # The artifact of the analysis of the whole codebase keeps the name it had before there were two, which is + # the name the PHPStan Pull Request Comments workflow on trunk requires. That way the comment is kept up to + # date for a pull request whose branch does not have the second analysis yet. + # + # The analyses are named for their role rather than their rule level, which is read from the configuration + # when the results are reported, so that raising either level is an edit of its configuration alone. + - analysis: default + label: all paths + config: phpstan.neon.dist + baselines: tests/phpstan/baselines + script: phpstan:default + artifact: phpstan-results + - analysis: strict + label: strict paths + config: phpstan-strict.neon.dist + baselines: tests/phpstan/baselines-strict + script: phpstan:strict + artifact: phpstan-results-strict + + steps: + # For a pull request, the parents of the merge commit are fetched too, to find the files that the base branch + # has changed since the pull request branched from it. + - name: Checkout repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + show-progress: ${{ runner.debug == '1' && 'true' || 'false' }} + persist-credentials: false + fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 1 }} + + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # 2.37.2 + with: + php-version: ${{ inputs.php-version }} + coverage: none + + - name: General debug information + run: | + composer --version + + # Since Composer dependencies are installed using `composer update` and no lock file is in version control, + # passing a custom cache suffix ensures that the cache is flushed at least once per week. + - name: Install Composer dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 + with: + custom-cache-suffix: $(/bin/date -u --date='last Mon' "+%F") + + - name: Make Composer packages available globally + run: echo "${PWD}/vendor/bin" >> "$GITHUB_PATH" + + # The directory holds more than the analysis results. PHPStan also stores what it read out of + # each source file there, the docblocks and signatures it found, keyed by that file's contents + # and nothing else. The extensions in `tests/phpstan` change what reading a file yields without + # changing the file: a parser node visitor rewrites a docblock in the syntax tree, and the bytes + # on disk stay as they were. A cache written before one of them changed therefore answers with + # what the old code saw, and the analysis silently runs against types no longer derived. + # + # Keying on the configuration and the extensions keeps a run from restoring a cache that + # predates either. The baselines are left out of the key: they only decide which reported errors + # are ignored, PHPStan invalidates the results cache on a configuration change by itself, and + # including them would discard the whole cache every time one is regenerated. + # + # The cache is renamed rather than only prefixed, because the key this replaces restored on + # `phpstan-result-cache-`, which every key below still begins with. A branch that has not + # merged this commit yet runs the workflow it has, and that workflow would prefix-match the + # caches written here: it would analyse without the extensions against reflection derived with + # them. A name of its own leaves those runs restoring only their own caches. + # + # Each analysis caches separately. Its result cache records the rule level, and is discarded + # by a run at another level, so restoring the other analysis's cache would gain nothing. + - name: Cache PHP Static Analysis scan cache + uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + with: + path: .cache # This is defined in the base.neon file. + key: "phpstan-analysis-cache-${{ matrix.analysis }}-${{ hashFiles('phpstan.neon.dist', 'phpstan-strict.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}-${{ github.run_id }}" + restore-keys: | + phpstan-analysis-cache-${{ matrix.analysis }}-${{ hashFiles('phpstan.neon.dist', 'phpstan-strict.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}- + + - name: Run PHP static analysis tests + id: phpstan + env: + SCRIPT: ${{ matrix.script }} + run: | + # The report is written to a file for the steps below, which turn it into annotations, + # the pull request comment, and a check for errors that cannot be reported as warnings. + # Only the report goes to standard output; the debug output goes to standard error, so + # it stays in the log without corrupting the JSON. + # + # The step shell exits on the first failing command, which would also end the step on + # the status of 1 that PHPStan uses for reporting errors. Capture the status instead. + status=0 + composer run "${SCRIPT}" -- -vvv --error-format=json > "${RUNNER_TEMP}/phpstan-report.json" || status=$? + + # PHPStan exits 1 when it has errors to report, which is the expected case here and + # is what the annotations are for. Anything higher means it did not finish at all. + if [ "${status}" -gt 1 ]; then + echo "::error title=PHPStan did not complete::The analysis exited with status ${status}, so the code was not fully checked. This is a failure of the run itself rather than a problem found in the code." + exit "${status}" + fi + + # Errors are annotated as warnings, so that they are visible on the pull request without + # failing the run. The exception is an error that PHPStan does not allow to be ignored, + # such as an out-of-date baseline entry, or one that is not specific to a file. These are + # annotated as errors instead, and the run fails on them in the check further below. + # + # The results are also written out for the PHPStan Pull Request Comments workflow, which + # runs with the permissions needed to comment on the pull request. Only the facts are + # passed along: the comment is composed there, since a pull request can change anything + # that runs here. + - name: Report the analysis results + id: report + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + ANALYSIS: ${{ matrix.analysis }} + CONFIG: ${{ matrix.config }} + with: + script: | + const fs = require( 'fs' ); + + // The rule level the configuration analyzes at, as a number, or `max`. Only the line of the parameter is + // matched, rather than decoding the whole dump, because the JSON PHPStan prints can be invalid: it writes + // the `\<` in a message pattern as is, which is not a valid JSON escape. + let level = null; + try { + const parameters = require( 'child_process' ).execFileSync( + `${ process.env.GITHUB_WORKSPACE }/vendor/bin/phpstan`, + [ 'dump-parameters', `--configuration=${ process.env.CONFIG }`, '--json' ], + { encoding: 'utf8' } + ); + const match = parameters.match( /^\s*"level":\s*"?(max|\d+)"?,?$/m ); + if ( match ) { + level = match[ 1 ] === 'max' ? 'max' : Number( match[ 1 ] ); + } + } catch ( error ) { + core.warning( `The rule level of ${ process.env.CONFIG } could not be read: ${ error.message }` ); + } + + // Annotations from the stricter analysis say so, since the same code can pass the other one. + const analysis = process.env.ANALYSIS; + const titlePrefix = analysis === 'strict' ? `PHPStan (strict${ level === null ? '' : `, level ${ level }` })` : 'PHPStan'; + + const report = JSON.parse( fs.readFileSync( `${ process.env.RUNNER_TEMP }/phpstan-report.json`, { encoding: 'utf8' } ) ); + const workspace = `${ process.env.GITHUB_WORKSPACE }/`; + + const errors = []; + for ( const [ absolutePath, file ] of Object.entries( report.files ) ) { + const relativePath = absolutePath.startsWith( workspace ) ? absolutePath.slice( workspace.length ) : absolutePath; + for ( const message of file.messages ) { + errors.push( { + file: relativePath, + line: message.line ?? null, + message: message.message, + identifier: message.identifier ?? null, + tip: message.tip ?? null, + ignorable: message.ignorable, + fixable: message.fixable ?? false, + } ); + } + } + + // Errors that are not specific to a file, such as an `ignoreErrors` entry from a config + // file PHPStan cannot locate it in. These cannot be ignored either. + for ( const message of report.errors ) { + errors.push( { file: null, line: null, message, identifier: null, tip: null, ignorable: false, fixable: false } ); + } + + // PHPStan marks an error it can fix itself, such as a stale baseline entry, as fixable. + const fixHint = 'This can be fixed automatically by running `composer phpstan:fix` (or `npm run typecheck:php:fix`).'; + + for ( const error of errors ) { + const properties = { title: error.identifier ? `${ titlePrefix }: ${ error.identifier }` : titlePrefix }; + if ( error.file ) { + properties.file = error.file; + } + if ( error.line ) { + properties.startLine = error.line; + } + const message = [ error.message, error.tip, error.fixable ? fixHint : null ].filter( Boolean ).join( '\n' ); + if ( error.ignorable ) { + core.warning( message, properties ); + } else { + core.error( message, properties ); + } + } + + // Tips and whether an error is fixable are left out of the results, since they are only shown in the + // annotations, next to the code. + // + // The commit analyzed is the pull request merged into its base branch, whose second parent is the head + // commit. The files with errors that differ between the two are those the base branch has changed, in + // which the line numbers reported can be off in the head commit. + // + // Each analysis writes its own results. Those of the analysis of the whole codebase also list every + // analysis the run makes, so that the comment is not updated from only some of them: an error missing + // because its analysis did not upload results would otherwise be shown as resolved. + if ( context.eventName === 'pull_request' ) { + let changedInBase = []; + try { + const filesWithErrors = new Set( errors.map( ( error ) => error.file ) ); + changedInBase = require( 'child_process' ) + .execFileSync( 'git', [ 'diff', '--name-only', '--no-renames', 'HEAD^2', 'HEAD' ], { encoding: 'utf8' } ) + .split( '\n' ) + .filter( ( file ) => filesWithErrors.has( file ) ); + } catch ( error ) { + core.warning( `The files changed in the base branch could not be found: ${ error.message }` ); + } + fs.mkdirSync( `${ process.env.RUNNER_TEMP }/phpstan-results`, { recursive: true } ); + fs.writeFileSync( `${ process.env.RUNNER_TEMP }/phpstan-results/results.json`, JSON.stringify( { + pull_request: context.payload.pull_request.number, + analysis, + level, + // Keep this list in step with the `analysis` values of the job's matrix. + ...( analysis === 'default' ? { analyses: [ 'default', 'strict' ] } : {} ), + changed_in_base: changedInBase, + errors: errors.map( ( { tip, fixable, ...error } ) => error ), + } ) ); + } + + # Uploads the results for the PHPStan Pull Request Comments workflow, which keeps a comment on the + # pull request up to date with them. + - name: Upload the analysis results as an artifact + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + if: ${{ github.event_name == 'pull_request' && steps.report.outcome == 'success' }} + with: + name: ${{ matrix.artifact }} + path: ${{ runner.temp }}/phpstan-results/ + + # Some errors cannot be ignored, so they cannot be reported as warnings either. Most often + # this is an ignored error that no longer occurs, or occurs a different number of times, + # which is reported under an `ignore.*` identifier. That is not something to fix in the + # code: the usual cause is that the error *was* fixed, leaving a baseline describing a state + # that no longer exists. + # + # Such an error is reported without a line number, so its annotation is not shown alongside + # the changes in the pull request, and one that is not specific to a file has nowhere to be + # shown at all. A passing run would let it go unnoticed, so fail the run on it instead, and + # say what to do about it. + # + # Detection is on PHPStan's own `ignorable` flag rather than on the identifier or message. + - name: Check for errors that cannot be reported as warnings + if: ${{ !cancelled() }} + env: + BASELINES_URL: ${{ github.server_url }}/${{ github.repository }}/tree/${{ github.sha }}/${{ matrix.baselines }} + LABEL: ${{ matrix.label }} + README_URL: ${{ github.server_url }}/${{ github.repository }}/blob/${{ github.sha }}/tests/phpstan/README.md + run: | + # This step runs even when the analysis above it failed, in which case the report may + # never have been written. That failure is reported there, so there is nothing to add + # here beyond staying quiet about a file that was never going to exist. + report="${RUNNER_TEMP}/phpstan-report.json" + if [ ! -f "${report}" ]; then + exit 0 + fi + + # Errors that are not specific to a file are listed separately from the rest, and are + # never ignorable. + unignorable=$( jq '[ .files[].messages[] | select( .ignorable | not ) ] + .errors | length' "${report}" ) + if [ "${unignorable}" -eq 0 ]; then + exit 0 + fi + + # Whether the errors include ignore errors decides what to say about them, but not whether to + # fail: every error that reaches this point fails the run. Ignore errors concern an ignore + # configuration that no longer describes the code. They are `ignore.unmatched`, where a + # pattern matched nothing at all, and `ignore.count`, where it matched a different number of + # times than the entry records. The `ignore.` prefix is matched rather than those two names + # so that any later addition to the group is caught as well. Any other error that cannot be + # ignored is something regenerating the baselines would not help with, so it is reported + # plainly instead. + ignore_errors=$( jq '[ .files[].messages[] | select( .identifier // "" | startswith( "ignore." ) ) ] | length' "${report}" ) + + # The summary is Markdown, and its code spans and fences are written literally, so the + # heredoc is quoted to keep the backticks out of the shell's hands. The links are + # written in reference style for the same reason: the URLs are the only part needing + # a variable, so defining them afterwards keeps the whole of the prose in here. + # + # A newline renders as a line break rather than a space, so each paragraph is one + # line however long that makes it, and the rendered summary wraps to its own width. + # + # The heading names the analysis whose baselines are out of date, which is filled in for + # the LABEL placeholder when the summary is written, since the heredoc expands nothing. + baselines_summary=$( cat <<'SUMMARY' + ## PHPStan baselines are out of date (LABEL) + + An ignored error no longer occurs, or occurs a different number of times, so PHPStan reported it under an `ignore.unmatched` or `ignore.count` identifier. + + **If you fixed the error, this is expected.** Each baseline entry records an exact count for a specific file, so that a new occurrence of an already baselined error is reported rather than absorbed. That same exactness means fixing one leaves the baseline describing a state that no longer exists. There is nothing to fix in the code; the baselines just need to catch up. + + Remove the stale entries, and commit the result: + + ```bash + npm run typecheck:php:fix + ``` + + or, outside the Docker environment: + + ```bash + composer phpstan:fix + ``` + + That runs PHPStan with `--fix`, which lowers the counts in [the baselines][baselines], removes the entries that no longer match, and removes any `@phpstan-ignore` annotation in the code that no longer ignores anything. It then deletes any baseline left with no entries. + + Alternatively, regenerate the baselines with `npm run typecheck:php:baselines` or `composer phpstan:baselines`. That also deletes any baseline whose errors are now all fixed, but it does not clear an `@phpstan-ignore` annotation. + + See [`tests/phpstan/README.md`][readme] for details. + + SUMMARY + ) + + if [ "${ignore_errors}" -gt 0 ]; then + { + printf '%s\n\n' "${baselines_summary/LABEL/${LABEL}}" + echo "[baselines]: ${BASELINES_URL}" + echo "[readme]: ${README_URL}" + } >> "${GITHUB_STEP_SUMMARY}" + + echo "::error title=PHPStan baselines are out of date (${LABEL})::An ignored error no longer occurs, or occurs a different number of times. If you fixed it, that is expected: run \`npm run typecheck:php:fix\` or \`composer phpstan:fix\` and commit the updated baselines. See ${README_URL}" + else + echo "::error title=PHPStan reported errors that cannot be ignored (${LABEL})::PHPStan reported ${unignorable} error(s) that cannot be ignored or reported as warnings. See the error annotations for details, and ${README_URL} for how to run the analysis locally." + fi + + exit 1 + + - name: "Save result cache" + uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + if: ${{ !cancelled() }} + with: + path: .cache + key: "phpstan-analysis-cache-${{ matrix.analysis }}-${{ hashFiles('phpstan.neon.dist', 'phpstan-strict.neon.dist', 'tests/phpstan/*.neon', 'tests/phpstan/*.php') }}-${{ github.run_id }}" + + - name: Ensure version-controlled files are not modified or deleted + run: git diff --exit-code diff --git a/tests/phpstan/README.md b/tests/phpstan/README.md index 056c4acdfb077..520f8c76ebdb5 100644 --- a/tests/phpstan/README.md +++ b/tests/phpstan/README.md @@ -336,7 +336,7 @@ A cache written before one of them changed therefore answers with what the old c rm -rf .cache ``` -The results cache alone is not the problem. PHPStan invalidates that itself when the configuration changes, and also when a bootstrap file or the source of any extension the configuration registers is edited, which covers every file in this directory that runs during analysis. What survives either is the per-file reflection, which is keyed by the source file's own contents and has no way to know that reading it now yields something else. CI keys its cache on these files for the same reason; see [`.github/workflows/reusable-phpstan-static-analysis-v1.yml`](../../.github/workflows/reusable-phpstan-static-analysis-v1.yml). +The results cache alone is not the problem. PHPStan invalidates that itself when the configuration changes, and also when a bootstrap file or the source of any extension the configuration registers is edited, which covers every file in this directory that runs during analysis. What survives either is the per-file reflection, which is keyed by the source file's own contents and has no way to know that reading it now yields something else. CI keys its cache on these files for the same reason; see [`.github/workflows/reusable-phpstan-static-analysis-v2.yml`](../../.github/workflows/reusable-phpstan-static-analysis-v2.yml). Analyzing a subset of the tree used to call for the same treatment, the same silence arriving from the other direction. A file named on the command line is analyzed, but a file merely *read* on its behalf went to PHPStan's simple parser, where these visitors do not run, so the reflection stored for it carried no derived shape — wrong for that run, and there in the cache for the next full run to restore. [`base.neon`](base.neon) now has the simple parser wrap the rich one, so every parse rewrites the same docblocks and a run over a subset derives what a full run derives. It does so by redefining one of PHPStan's own parser services, which is not a documented extension point; if a hash notation type ever looks wrong after a PHPStan upgrade, check that definition first. From fa05da817a632f3e5c9a4f36c54e6c95e94b0803 Mon Sep 17 00:00:00 2001 From: Jonathan Desrosiers Date: Thu, 19 Nov 2026 19:17:47 +0000 Subject: [PATCH 30/85] External Libraries: Use the classic build of jQuery Form. As of version 4.4.0, `src/jquery.form.js` in the `jquery-form` package is an ES module. Because `jquery-form` is registered as a classic script, browsers reject the file with a syntax error and `ajaxForm()` and `ajaxSubmit()` are not defined. This updates the relevant build scripts to copy `dist/jquery.form.js` instead, which is the package's UMD build and matches the format shipped before 4.4.0. Follow-up to r65541. Reviewed by davidbaumwald. Props prosenjitbarman. Fixes #66711. git-svn-id: https://develop.svn.wordpress.org/trunk@65694 602fd350-edb4-49c9-b593-d223f7449a82 --- Gruntfile.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gruntfile.js b/Gruntfile.js index 0a9270f436847..05bdfda0a58c1 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -396,7 +396,7 @@ module.exports = function(grunt) { [ WORKING_DIR + 'wp-includes/js/jquery/jquery.min.js' ]: [ './node_modules/jquery/dist/jquery.min.js' ], [ WORKING_DIR + 'wp-includes/js/jquery/jquery-migrate.js' ]: [ './node_modules/jquery-migrate/dist/jquery-migrate.js' ], [ WORKING_DIR + 'wp-includes/js/jquery/jquery-migrate.min.js' ]: [ './node_modules/jquery-migrate/dist/jquery-migrate.min.js' ], - [ WORKING_DIR + 'wp-includes/js/jquery/jquery.form.js' ]: [ './node_modules/jquery-form/src/jquery.form.js' ], + [ WORKING_DIR + 'wp-includes/js/jquery/jquery.form.js' ]: [ './node_modules/jquery-form/dist/jquery.form.js' ], [ WORKING_DIR + 'wp-includes/js/jquery/jquery.color.min.js' ]: [ './node_modules/jquery-color/dist/jquery.color.min.js' ], [ WORKING_DIR + 'wp-includes/js/masonry.min.js' ]: [ './node_modules/masonry-layout/dist/masonry.pkgd.min.js' ], [ WORKING_DIR + 'wp-includes/js/underscore.js' ]: [ './node_modules/underscore/underscore.js' ], From accd2d45213a25dfd6ff4b83a14c18efc925ed0f Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Thu, 19 Nov 2026 21:25:47 +0000 Subject: [PATCH 31/85] Tests: Cover `rsd_link()`. Verify the expected output of `EditURI` RSD link element with the site XML-RPC endpoint URL. Developed in https://github.com/WordPress/wordpress-develop/pull/15356. Props devmuhib, huzaifaalmesbah, lancewillett. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65695 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/general/rsdLink.php | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 tests/phpunit/tests/general/rsdLink.php diff --git a/tests/phpunit/tests/general/rsdLink.php b/tests/phpunit/tests/general/rsdLink.php new file mode 100644 index 0000000000000..ea85f18c07b3c --- /dev/null +++ b/tests/phpunit/tests/general/rsdLink.php @@ -0,0 +1,29 @@ +'; + + ob_start(); + rsd_link(); + $actual = trim( ob_get_clean() ); + + $this->assertSame( $expected, $actual ); + } +} From 97f5bdf0e0a498fe2ce02b81b6c4cc464c9dbac6 Mon Sep 17 00:00:00 2001 From: Peter Wilson Date: Thu, 19 Nov 2026 23:15:56 +0000 Subject: [PATCH 32/85] Upgrade/Install: Update the `$_old_files` array for 7.2. Developed in: https://github.com/WordPress/wordpress-develop/pull/15830 Reviewed by jonsurrell. Props therssoftware, jonsurrell, nathanrice, courane01. Fixes #66456. git-svn-id: https://develop.svn.wordpress.org/trunk@65716 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/includes/update-core.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/wp-admin/includes/update-core.php b/src/wp-admin/includes/update-core.php index 22d9c3e2f463d..1aa79b39a8614 100644 --- a/src/wp-admin/includes/update-core.php +++ b/src/wp-admin/includes/update-core.php @@ -1171,6 +1171,18 @@ * 'wp-includes/images/icon-library/wordpress.svg', */ // 7.2 + 'wp-includes/css/dist/block-editor/default-editor-styles.css', + 'wp-includes/css/dist/block-editor/default-editor-styles.min.css', + 'wp-includes/css/dist/block-editor/default-editor-styles-rtl.css', + 'wp-includes/css/dist/block-editor/default-editor-styles-rtl.min.css', + 'wp-includes/js/dist/script-modules/block-library/form/view.js', + 'wp-includes/js/dist/script-modules/block-library/form/view.min.js', + 'wp-includes/js/dist/script-modules/block-library/form/view.min.asset.php', + 'wp-includes/js/dist/script-modules/block-library/form/', + 'wp-includes/js/dist/script-modules/content-types/index.js', + 'wp-includes/js/dist/script-modules/content-types/index.min.js', + 'wp-includes/js/dist/script-modules/content-types/index.min.asset.php', + 'wp-includes/js/dist/script-modules/content-types/', 'wp-includes/js/dist/sync.js', 'wp-includes/js/dist/sync.min.js', ); From 0f2e26abced97bb6b33f6d2ddd7aead8a72e7898 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 20 Nov 2026 14:41:45 +0000 Subject: [PATCH 33/85] Build/Test Tools: Share the release ZIP across test jobs. Wait for a verified release ZIP before starting the installation and upgrade jobs. Keep it available for failed-job reruns. Developed in: https://github.com/WordPress/wordpress-develop/pull/16106 Props adrianmoldovanwp. Fixes #66744. git-svn-id: https://develop.svn.wordpress.org/trunk@65722 602fd350-edb4-49c9-b593-d223f7449a82 --- .github/actionlint.yaml | 1 + .github/workflows/install-testing.yml | 31 +++++- .../reusable-download-wordpress-release.yml | 101 ++++++++++++++++++ .../workflows/reusable-upgrade-testing.yml | 28 ++++- .github/workflows/upgrade-testing.yml | 29 +++-- 5 files changed, 181 insertions(+), 9 deletions(-) create mode 100644 .github/workflows/reusable-download-wordpress-release.yml diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 9825166f0fb38..15d3c76f7da89 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -10,3 +10,4 @@ paths: .github/workflows/**/*.yml: ignore: - 'specifying action "\$/[^"]+" in invalid format because ref is missing' + - 'reusable workflow call "\$/[^"]+" at "uses" is not following the format' diff --git a/.github/workflows/install-testing.yml b/.github/workflows/install-testing.yml index 4e1af59a308fd..eb238338b3e87 100644 --- a/.github/workflows/install-testing.yml +++ b/.github/workflows/install-testing.yml @@ -18,6 +18,7 @@ on: - '.github/workflows/install-testing.yml' - '.version-support-*.json' - '.github/workflows/reusable-support-json-reader-v1.yml' + - '.github/workflows/reusable-download-wordpress-release.yml' pull_request: # Always test the workflow when changes are suggested. paths: @@ -27,6 +28,7 @@ on: - '.version-support-*.json' - '.github/workflows/install-testing.yml' - '.github/workflows/reusable-support-json-reader-v1.yml' + - '.github/workflows/reusable-download-wordpress-release.yml' schedule: - cron: '0 0 * * 1' @@ -59,6 +61,16 @@ jobs: with: wp-version: ${{ inputs.wp-version }} + # Downloads a release zip once for every matrix job, waiting until WordPress.org serves it. + download-wordpress: + name: Download WordPress + uses: $/.github/workflows/reusable-download-wordpress-release.yml + permissions: + contents: read + if: ${{ github.repository == 'WordPress/wordpress-develop' }} + with: + version: ${{ inputs.wp-version || 'nightly' }} + # Test the WordPress installation process through WP-CLI. # # Performs the following steps: @@ -74,7 +86,7 @@ jobs: runs-on: ${{ matrix.os }} if: ${{ github.repository == 'WordPress/wordpress-develop' }} timeout-minutes: 15 - needs: [ build-test-matrix ] + needs: [ build-test-matrix, download-wordpress ] env: WP_ADMIN_USER: admin @@ -147,9 +159,24 @@ jobs: with: version: ${{ contains( fromJSON('["5.4", "5.5"]'), matrix.php ) && '2.4.0' || contains( fromJSON('["5.6", "7.0", "7.1"]'), matrix.php ) && '2.12.0' || 'latest' }} + - name: Download the WordPress release artifact + if: ${{ needs.download-wordpress.outputs.artifact != '' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ needs.download-wordpress.outputs.artifact }} + path: ${{ runner.temp }} + + # WP-CLI 2.4.0 cannot install from a local zip, so unzip it. + - name: Extract WordPress + if: ${{ needs.download-wordpress.outputs.artifact != '' }} + run: | + unzip -q "${RUNNER_TEMP}/wordpress.zip" -d "${RUNNER_TEMP}" + mv "${RUNNER_TEMP}"/wordpress/* . + # WP-CLI 2.x extracts tarballs with PharData, which truncates paths longer than 100 characters. # Zip archives are not affected, so download the zip for every version. - name: Download WordPress + if: ${{ needs.download-wordpress.outputs.artifact == '' }} # WP-CLI requests WordPress from WordPress.org once, so a network error fails the job. # It extracts only after a complete download, so a retry starts from an empty directory. uses: $/.github/actions/run-with-retry @@ -187,7 +214,7 @@ jobs: permissions: actions: read contents: read - needs: [ install-tests-mysql ] + needs: [ download-wordpress, install-tests-mysql ] if: ${{ github.repository == 'WordPress/wordpress-develop' && github.event_name != 'pull_request' && always() }} with: calling_status: ${{ contains( needs.*.result, 'cancelled' ) && 'cancelled' || contains( needs.*.result, 'failure' ) && 'failure' || 'success' }} diff --git a/.github/workflows/reusable-download-wordpress-release.yml b/.github/workflows/reusable-download-wordpress-release.yml new file mode 100644 index 0000000000000..ec953abbfd58f --- /dev/null +++ b/.github/workflows/reusable-download-wordpress-release.yml @@ -0,0 +1,101 @@ +## +# A reusable workflow that downloads a WordPress release zip once and shares it as an artifact. +# +# For a while after a release is uploaded, some WordPress.org download servers do not have the new zip yet. +# This workflow waits until the zip downloads and passes its md5 check, so the jobs that use it do not each fail. +## +name: Download a WordPress release + +on: + workflow_call: + inputs: + version: + description: 'The WordPress version to download. "latest", "nightly", "trunk" and "develop" are not downloaded.' + type: string + required: true + outputs: + artifact: + description: 'The name of the artifact that holds wordpress.zip, or an empty string when nothing was downloaded.' + value: ${{ jobs.download.outputs.artifact }} + +# Disable permissions for all available scopes by default. +# Any needed permissions should be configured at the job level. +permissions: {} + +jobs: + # Downloads the release zip and uploads it as an artifact. + # + # Performs the following steps: + # - Sets up PHP and WP-CLI. + # - Downloads the release zip, retrying until it is available. + # - Uploads the zip as an artifact. + download: + name: Download WordPress ${{ inputs.version }} + permissions: + contents: read + runs-on: ubuntu-26.04 + timeout-minutes: 50 + outputs: + artifact: ${{ steps.upload.outcome == 'success' && 'wordpress-release' || '' }} + + steps: + - name: Check whether the version is a release + id: check + run: | + case "${WP_VERSION}" in + latest|nightly|trunk|develop) echo "release=false" >> "$GITHUB_OUTPUT" ;; + *) echo "release=true" >> "$GITHUB_OUTPUT" ;; + esac + env: + WP_VERSION: ${{ inputs.version }} + + - name: Set up PHP + if: ${{ steps.check.outputs.release == 'true' }} + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # 2.37.2 + with: + php-version: '8.4' + coverage: none + + # This job does not check out the repository: `$/` fetches the action from this workflow's commit. + - name: Set up WP-CLI + if: ${{ steps.check.outputs.release == 'true' }} + uses: $/.github/actions/setup-wp-cli + + # A missing md5 checksum is only a warning in WP-CLI, so a try passes only when the hash was verified. + # The URL form always saves a zip; `--version` can save a tar.gz. + - name: Download WordPress ${{ inputs.version }} + if: ${{ steps.check.outputs.release == 'true' }} + run: | + until output=$(wp core download "https://wordpress.org/wordpress-${WP_VERSION}.zip" --no-extract --path="$DOWNLOAD_DIR" 2>&1) \ + && grep -q 'md5 hash verified' <<< "$output"; do + echo "$output" + + if (( SECONDS + RETRY_DELAY_SECONDS > MAX_WAIT_SECONDS )); then + echo "::error::WordPress ${WP_VERSION} could not be downloaded after ${SECONDS} seconds." + exit 1 + fi + + echo "Trying again in ${RETRY_DELAY_SECONDS} seconds." + sleep "$RETRY_DELAY_SECONDS" + rm -rf "$DOWNLOAD_DIR" + done + + echo "$output" + echo "Downloaded WordPress ${WP_VERSION} after waiting ${SECONDS} seconds." + mv "$DOWNLOAD_DIR"/wp_*.zip "$DOWNLOAD_DIR/wordpress.zip" + env: + WP_VERSION: ${{ inputs.version }} + DOWNLOAD_DIR: ${{ runner.temp }}/wordpress-release + MAX_WAIT_SECONDS: 2700 # 45 minutes. + RETRY_DELAY_SECONDS: 60 + + - name: Upload the release zip + id: upload + if: ${{ steps.check.outputs.release == 'true' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: wordpress-release + path: ${{ runner.temp }}/wordpress-release/wordpress.zip + if-no-files-found: error + overwrite: true + retention-days: 30 diff --git a/.github/workflows/reusable-upgrade-testing.yml b/.github/workflows/reusable-upgrade-testing.yml index cc36c1a80587a..6510ba6818249 100644 --- a/.github/workflows/reusable-upgrade-testing.yml +++ b/.github/workflows/reusable-upgrade-testing.yml @@ -17,6 +17,11 @@ on: description: 'The version of WordPress to update to. Use "latest" to update to the latest version, "develop" to update to the current branch, or provide a specific version number to update to.' type: 'string' default: 'latest' + new-version-artifact: + description: 'Optional. The name of an artifact that holds the wordpress.zip of new-version. When set, the upgrade installs from it instead of downloading.' + required: false + type: 'string' + default: '' php: description: 'The version of PHP to use. Expected format: X.Y.' required: true @@ -137,8 +142,29 @@ jobs: run: | wp core update develop.zip + - name: Download the WordPress ${{ inputs.new-version }} artifact + if: ${{ inputs.new-version != 'develop' && inputs.new-version-artifact != '' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ inputs.new-version-artifact }} + + # With a zip, WP-CLI does not stop a downgrade, and the minor update can already be past the target. + # `sort -V` orders 7.2 before 7.2-RC2, so compare the way WordPress does. + - name: Upgrade to WordPress ${{ inputs.new-version }} from the artifact + if: ${{ inputs.new-version != 'develop' && inputs.new-version-artifact != '' }} + run: | + current=$(wp core version) + if ! CURRENT="$current" php -r 'exit( version_compare( getenv( "CURRENT" ), getenv( "WP_VERSION" ), "<" ) ? 0 : 1 );'; then + echo "WordPress ${current} is not older than ${WP_VERSION}, so there is nothing to upgrade." + exit 0 + fi + + wp core update wordpress.zip --version="$WP_VERSION" + env: + WP_VERSION: ${{ inputs.new-version }} + - name: Upgrade to WordPress ${{ inputs.new-version }} - if: ${{ inputs.new-version != 'develop' }} + if: ${{ inputs.new-version != 'develop' && inputs.new-version-artifact == '' }} run: | wp core update ${{ 'latest' != inputs.new-version && '--version="${WP_VERSION}"' || '' }} env: diff --git a/.github/workflows/upgrade-testing.yml b/.github/workflows/upgrade-testing.yml index d4817522585d9..3765692707b16 100644 --- a/.github/workflows/upgrade-testing.yml +++ b/.github/workflows/upgrade-testing.yml @@ -14,6 +14,7 @@ on: - '.github/actions/smoke-check/**' - '.github/workflows/upgrade-testing.yml' - '.github/workflows/reusable-upgrade-testing.yml' + - '.github/workflows/reusable-download-wordpress-release.yml' pull_request: # This workflow is only meant to run from trunk. Pull requests changing this file with different BASE branches should be ignored. branches: @@ -24,6 +25,7 @@ on: - '.github/actions/run-with-retry/**' - '.github/workflows/upgrade-testing.yml' - '.github/workflows/reusable-upgrade-testing.yml' + - '.github/workflows/reusable-download-wordpress-release.yml' workflow_dispatch: inputs: new-version: @@ -152,12 +154,22 @@ jobs: filter wp-5x-php-8x "$WP_5X_PHP_8X" filter oldest-wp "$OLDEST_WP" + # Downloads a release zip once for every matrix job, waiting until WordPress.org serves it. + download-wordpress: + name: Download WordPress + uses: $/.github/workflows/reusable-download-wordpress-release.yml + permissions: + contents: read + if: ${{ github.repository == 'WordPress/wordpress-develop' }} + with: + version: ${{ inputs.new-version && inputs.new-version || 'latest' }} + # Tests the full list of PHP/MySQL combinations for the two most recent versions of WordPress. upgrade-tests-recent-releases: name: ${{ matrix.wp }} to ${{ inputs.new-version && inputs.new-version || 'latest' }} uses: ./.github/workflows/reusable-upgrade-testing.yml if: ${{ github.repository == 'WordPress/wordpress-develop' && needs.build-test-matrix.outputs.recent-releases != '[]' }} - needs: [ build-test-matrix ] + needs: [ build-test-matrix, download-wordpress ] permissions: contents: read strategy: @@ -177,13 +189,14 @@ jobs: wp: ${{ matrix.wp }} new-version: ${{ inputs.new-version && inputs.new-version || 'latest' }} multisite: ${{ matrix.multisite }} + new-version-artifact: ${{ needs.download-wordpress.outputs.artifact }} # Tests 6.x releases where the WordPress database version changed on the oldest and newest supported versions of PHP 7 & 8. upgrade-tests-wp-6x-mysql: name: ${{ matrix.wp }} to ${{ inputs.new-version && inputs.new-version || 'latest' }} uses: ./.github/workflows/reusable-upgrade-testing.yml if: ${{ github.repository == 'WordPress/wordpress-develop' && needs.build-test-matrix.outputs.wp-6x != '[]' }} - needs: [ build-test-matrix ] + needs: [ build-test-matrix, download-wordpress ] permissions: contents: read strategy: @@ -203,13 +216,14 @@ jobs: wp: ${{ matrix.wp }} new-version: ${{ inputs.new-version && inputs.new-version || 'latest' }} multisite: ${{ matrix.multisite }} + new-version-artifact: ${{ needs.download-wordpress.outputs.artifact }} # Tests 5.x releases where the WordPress database version changed on the only supported version of PHP 7. upgrade-tests-wp-5x-php-7x-mysql: name: ${{ matrix.wp }} to ${{ inputs.new-version && inputs.new-version || 'latest' }} uses: ./.github/workflows/reusable-upgrade-testing.yml if: ${{ github.repository == 'WordPress/wordpress-develop' && needs.build-test-matrix.outputs.wp-5x-php-7x != '[]' }} - needs: [ build-test-matrix ] + needs: [ build-test-matrix, download-wordpress ] permissions: contents: read strategy: @@ -229,6 +243,7 @@ jobs: wp: ${{ matrix.wp }} new-version: ${{ inputs.new-version && inputs.new-version || 'latest' }} multisite: ${{ matrix.multisite }} + new-version-artifact: ${{ needs.download-wordpress.outputs.artifact }} # Tests 5.x releases where the WordPress database version changed on the oldest and newest supported versions of PHP 8. # @@ -239,7 +254,7 @@ jobs: name: ${{ matrix.wp }} to ${{ inputs.new-version && inputs.new-version || 'latest' }} uses: ./.github/workflows/reusable-upgrade-testing.yml if: ${{ github.repository == 'WordPress/wordpress-develop' && needs.build-test-matrix.outputs.wp-5x-php-8x != '[]' }} - needs: [ build-test-matrix ] + needs: [ build-test-matrix, download-wordpress ] permissions: contents: read strategy: @@ -259,6 +274,7 @@ jobs: wp: ${{ matrix.wp }} new-version: ${{ inputs.new-version && inputs.new-version || 'latest' }} multisite: ${{ matrix.multisite }} + new-version-artifact: ${{ needs.download-wordpress.outputs.artifact }} # The oldest version of WordPress receiving security updates should always be tested against # the widest possible list of PHP/MySQL combinations. @@ -270,7 +286,7 @@ jobs: name: ${{ matrix.wp }} to ${{ inputs.new-version && inputs.new-version || 'latest' }} uses: ./.github/workflows/reusable-upgrade-testing.yml if: ${{ github.repository == 'WordPress/wordpress-develop' && needs.build-test-matrix.outputs.oldest-wp != '[]' }} - needs: [ build-test-matrix ] + needs: [ build-test-matrix, download-wordpress ] permissions: contents: read strategy: @@ -290,6 +306,7 @@ jobs: wp: ${{ matrix.wp }} new-version: ${{ inputs.new-version && inputs.new-version || 'latest' }} multisite: ${{ matrix.multisite }} + new-version-artifact: ${{ needs.download-wordpress.outputs.artifact }} slack-notifications: name: Slack Notifications @@ -297,7 +314,7 @@ jobs: permissions: actions: read contents: read - needs: [ build-test-matrix, upgrade-tests-recent-releases, upgrade-tests-wp-6x-mysql, upgrade-tests-wp-5x-php-7x-mysql, upgrade-tests-wp-5x-php-8x-mysql, upgrade-tests-oldest-wp-mysql ] + needs: [ build-test-matrix, download-wordpress, upgrade-tests-recent-releases, upgrade-tests-wp-6x-mysql, upgrade-tests-wp-5x-php-7x-mysql, upgrade-tests-wp-5x-php-8x-mysql, upgrade-tests-oldest-wp-mysql ] if: ${{ github.repository == 'WordPress/wordpress-develop' && github.event_name != 'pull_request' && always() }} with: calling_status: ${{ contains( needs.*.result, 'cancelled' ) && 'cancelled' || contains( needs.*.result, 'failure' ) && 'failure' || 'success' }} From 3faf58619c87c89e80cb0c664020777e10b576b3 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 20 Nov 2026 14:42:52 +0000 Subject: [PATCH 34/85] Build/Test Tools: Run plugin management E2E tests in parallel. Use the `PLUGINS` lock so tests that share a plugin can run alongside other specs without changing the plugin at the same time. Developed in: https://github.com/WordPress/wordpress-develop/pull/16128 Props adrianmoldovanwp. See #66392. git-svn-id: https://develop.svn.wordpress.org/trunk@65723 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/e2e/README.md | 2 ++ tests/e2e/playwright.config.js | 1 - tests/e2e/specs/plugins.test.js | 7 ++++++- tests/e2e/utils/locks.js | 1 + 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 62601d8760797..def7aec52312d 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -80,6 +80,8 @@ test.describe( 'Settings -> General', { lock: GENERAL_SETTINGS }, () => {} ); A form save writes every field on the page, not only the field that the test changed. A spec that saves the General Settings form (`options-general.php`) must hold `GENERAL_SETTINGS`. A spec in `parallel` that changes a General Settings option in a different way, for example with `siteSettings` or `siteOptions`, must also hold it. +WordPress reads the full `active_plugins` list, changes it, and writes the full list back. If two tests turn plugins on or off at the same time, one change can be lost. A spec in `parallel` that installs, deletes, activates or deactivates a plugin must hold `PLUGINS`. + ## Logged-out pages Most specs run logged in as the admin user. There are two ways to run a test logged out: diff --git a/tests/e2e/playwright.config.js b/tests/e2e/playwright.config.js index 0db4d5c44e525..0f81e48df84cb 100644 --- a/tests/e2e/playwright.config.js +++ b/tests/e2e/playwright.config.js @@ -19,7 +19,6 @@ const SERIAL_SPECS = [ 'install.test.js', 'maintenance-mode.test.js', 'gutenberg-plugin.test.js', - 'plugins.test.js', 'themes.test.js', // This deletes all posts, including other workers' content. 'empty-trash.test.js', diff --git a/tests/e2e/specs/plugins.test.js b/tests/e2e/specs/plugins.test.js index a954315d77617..c32b0648055d2 100644 --- a/tests/e2e/specs/plugins.test.js +++ b/tests/e2e/specs/plugins.test.js @@ -3,6 +3,11 @@ */ import { test, expect } from '@wordpress/e2e-test-utils-playwright'; +/** + * Internal dependencies + */ +import { PLUGINS } from '../utils/locks'; + const plugin = 'e2e-test-plugin/e2e-test-plugin'; const pluginName = 'E2E Test Plugin'; @@ -49,7 +54,7 @@ async function deletePlugin( requestUtils ) { } ); } -test.describe( 'Plugin management', () => { +test.describe( 'Plugin management', { lock: PLUGINS }, () => { test.beforeEach( async ( { requestUtils } ) => { // The fixture slug requires an environment not shared with another test run. // An interrupted run can leave the fixture plugin installed. diff --git a/tests/e2e/utils/locks.js b/tests/e2e/utils/locks.js index b118484eb05ea..2cc6f1b1257fc 100644 --- a/tests/e2e/utils/locks.js +++ b/tests/e2e/utils/locks.js @@ -1,3 +1,4 @@ export const GENERAL_SETTINGS = 'general-settings'; export const NAV_MENU_LOCATIONS = 'nav-menu-locations'; +export const PLUGINS = 'plugins'; export const PRIVACY_POLICY_PAGE = 'privacy-policy-page'; From a5c41fa471dc061a39db3d5d47fd6dca0edae0fe Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 20 Nov 2026 14:43:26 +0000 Subject: [PATCH 35/85] Abilities API: Declare the `uri` format for the `link` output of `core/content-query`. The post permalink in the `link` output was a plain string, while the `link` output of `core/users-query` declares the `uri` format. Declare the same format for the post permalink, so clients that check formats treat both links the same. The value is unchanged. Developed in https://github.com/WordPress/wordpress-develop/pull/15987. Follow-up to [64388]. Props jorgefilipecosta, gziolo. Fixes #66268. git-svn-id: https://develop.svn.wordpress.org/trunk@65724 602fd350-edb4-49c9-b593-d223f7449a82 --- .../abilities/class-wp-abilities-content.php | 1 + .../wpRegisterCoreContentAbility.php | 78 +++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/src/wp-includes/abilities/class-wp-abilities-content.php b/src/wp-includes/abilities/class-wp-abilities-content.php index 17e1a81ac30df..a8d9954e30965 100644 --- a/src/wp-includes/abilities/class-wp-abilities-content.php +++ b/src/wp-includes/abilities/class-wp-abilities-content.php @@ -1024,6 +1024,7 @@ private function get_post_properties(): array { ), 'link' => array( 'type' => 'string', + 'format' => 'uri', 'description' => __( 'The permalink URL.' ), ), 'title' => array( diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php index 0a6b9fd447093..cf537f5cf0911 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php @@ -780,6 +780,7 @@ public function test_output_schema_describes_query_responses(): void { } $this->assertStringContainsString( "in ISO 8601 format using the site's timezone.", $post_schema['properties'][ $name ]['properties']['site']['description'], sprintf( 'The %s.site description should say the date uses the site timezone.', $name ) ); } + $this->assertSame( 'uri', $post_schema['properties']['link']['format'], 'The link should use the uri format.' ); $this->assertSame( 'object', $pagination['type'], 'The pagination should describe an object.' ); $this->assertFalse( $pagination['additionalProperties'], 'The pagination should not allow keys besides the totals.' ); @@ -822,6 +823,83 @@ private function find_schema_keywords( array $schema, array $keywords, string $p return $found; } + /** + * Returns posts whose permalinks take different forms. + * + * With pretty permalinks, a draft still links to its plain `?p=ID` form, while a + * published post and a private page the current user can read link to their pretty + * permalinks. + * + * @return array Post test cases. + */ + public static function data_posts_with_different_permalink_forms(): array { + return array( + 'published post' => array( + 'post_type' => 'post', + 'post_status' => 'publish', + 'plain_permalink' => false, + ), + 'draft post' => array( + 'post_type' => 'post', + 'post_status' => 'draft', + 'plain_permalink' => true, + ), + 'private page' => array( + 'post_type' => 'page', + 'post_status' => 'private', + 'plain_permalink' => false, + ), + ); + } + + /** + * Results validate against the output schema, which declares the `uri` format for the + * link, whatever form the permalink takes. + * + * @ticket 66268 + * @since 7.2.0 + * + * @dataProvider data_posts_with_different_permalink_forms + * + * @param string $post_type The post type to create. + * @param string $post_status The post status to create. + * @param bool $plain_permalink Whether the post links to its plain `?p=ID` permalink. + */ + public function test_results_validate_against_the_output_schema_for_each_permalink_form( string $post_type, string $post_status, bool $plain_permalink ): void { + $post_id = self::factory()->post->create( + array( + 'post_type' => $post_type, + 'post_status' => $post_status, + ) + ); + + $this->login_as( 'administrator' ); + $this->register_ability(); + + $ability = wp_get_ability( 'core/content-query' ); + $result = $ability->execute( + array( + 'where' => array( + 'type' => $post_type, + 'ids' => array( $post_id ), + ), + 'fields' => array( 'id', 'type', 'status', 'date', 'modified', 'slug', 'link', 'title', 'excerpt', 'content', 'author', 'parent' ), + ) + ); + + $this->assertIsArray( $result, 'The query should succeed.' ); + $this->assertCount( 1, $result['items'], 'The query should return the post.' ); + + $link = $result['items'][0]['link']; + if ( $plain_permalink ) { + $this->assertSame( home_url( '?p=' . $post_id ), $link, 'Precondition: the post should link to its plain permalink.' ); + } else { + $this->assertStringNotContainsString( '?', $link, 'Precondition: the post should link to its pretty permalink.' ); + } + $this->assertSame( get_permalink( $post_id ), $link, 'The link should be the permalink.' ); + $this->assertTrue( rest_validate_value_from_schema( $result, $ability->get_output_schema(), 'result' ), 'The result should validate against the output schema.' ); + } + /** * A post type registered by another active plugin and flagged `show_in_abilities` * is exposed by the ability, both in the input enum and in query results. From 5e0ad66bb840bc015033c4602b84f02c319dd85c Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 20 Nov 2026 14:52:17 +0000 Subject: [PATCH 36/85] Editor: Validate the entity in the entity fields reads and REST route. The entity fields API lacked two input checks that the entity actions API has: - `WP_Entity_Fields_Registry::get_registered()` and `::get_registered_field_modules()` did not validate the entity kind and name, so an array caused a fatal `TypeError`. They now return an empty list with a `_doing_it_wrong()` notice. - The `kind` and `name` arguments of `/wp/v2/entity-fields` had no `minLength`, so empty values returned a 200 response. They now return a 400 error, like `/wp/v2/entity-actions`. The entity actions endpoint no longer skips registering its route when a post type or taxonomy uses `entity-actions` as its REST base. No other core endpoint with a fixed base, such as `/wp/v2/settings` or `/wp/v2/search`, has this check. Developed in https://github.com/WordPress/wordpress-develop/pull/16067. Follow-up to [64517], [64528]. Props mukesh27, oandregal, jorgefilipecosta. Fixes #66229. git-svn-id: https://develop.svn.wordpress.org/trunk@65725 602fd350-edb4-49c9-b593-d223f7449a82 --- .../class-wp-entity-fields-registry.php | 10 ++++- ...lass-wp-rest-entity-actions-controller.php | 42 ------------------- ...class-wp-rest-entity-fields-controller.php | 2 + .../entity-fields/wpEntityFieldsRegistry.php | 33 +++++++++++++++ .../rest-entity-actions-controller.php | 30 ------------- .../rest-entity-fields-controller.php | 6 +++ tests/qunit/fixtures/wp-api-generated.js | 2 + 7 files changed, 52 insertions(+), 73 deletions(-) diff --git a/src/wp-includes/class-wp-entity-fields-registry.php b/src/wp-includes/class-wp-entity-fields-registry.php index 864828ca1c243..1cc9b629e086e 100644 --- a/src/wp-includes/class-wp-entity-fields-registry.php +++ b/src/wp-includes/class-wp-entity-fields-registry.php @@ -445,8 +445,12 @@ public function get_collection_fields( $directory ) { * @param string $kind The entity kind (e.g. `postType`). * @param string $name The entity name (e.g. `page`). * @return array[] The list of field definitions, in registration order. + * Empty when the entity is invalid. */ public function get_registered( $kind, $name ) { + if ( ! $this->validate_entity( __METHOD__, $kind, $name ) ) { + return array(); + } $this->initialize(); return array_values( $this->fields[ $kind ][ $name ] ?? array() ); } @@ -478,7 +482,8 @@ static function ( $entities ) { * @param string $kind The entity kind (e.g. `postType`). * @param string $name The entity name (e.g. `page`). * @return array[] { - * The script modules, in registration order. + * The script modules, in registration order. Empty when the entity + * is invalid. * * @type array ...$0 { * @type string $id The id of the script module. @@ -488,6 +493,9 @@ static function ( $entities ) { * } */ public function get_registered_field_modules( $kind, $name ) { + if ( ! $this->validate_entity( __METHOD__, $kind, $name ) ) { + return array(); + } $this->initialize(); $modules = array(); foreach ( $this->field_modules[ $kind ][ $name ] ?? array() as $module => $field_ids ) { diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-entity-actions-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-entity-actions-controller.php index bf9ebcf895a16..121421fc00576 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-entity-actions-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-entity-actions-controller.php @@ -39,10 +39,6 @@ public function __construct() { * @since 7.2.0 */ public function register_routes() { - if ( $this->is_route_of_entity_items() ) { - return; - } - register_rest_route( $this->namespace, '/' . $this->rest_base, @@ -71,44 +67,6 @@ public function register_routes() { ); } - /** - * Checks whether a post type or taxonomy has its items on the route of - * the controller, reporting it with _doing_it_wrong(). - * - * The route is then left to the post type or taxonomy: registering it - * as well would not serve the actions, as the route of the items comes - * first, and would replace the schema of that route. - * - * @since 7.2.0 - * - * @return bool Whether a post type or taxonomy has its items on the route. - */ - protected function is_route_of_entity_items() { - $objects = array_merge( - array_values( get_post_types( array( 'show_in_rest' => true ), 'objects' ) ), - array_values( get_taxonomies( array( 'show_in_rest' => true ), 'objects' ) ) - ); - foreach ( $objects as $object ) { - $namespace = $object->rest_namespace ? $object->rest_namespace : 'wp/v2'; - $base = $object->rest_base ? $object->rest_base : $object->name; - if ( $this->namespace === $namespace && $this->rest_base === $base ) { - _doing_it_wrong( - __METHOD__, - sprintf( - /* translators: 1: REST route, e.g. /wp/v2/entity-actions. 2: Post type or taxonomy name. */ - __( 'The %1$s route serves the items of the "%2$s" post type or taxonomy, so the actions of entities are not available.' ), - '/' . $this->namespace . '/' . $this->rest_base, - $object->name - ), - '7.2.0' - ); - return true; - } - } - - return false; - } - /** * Checks if a given request has access to read the actions of an entity. * diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-entity-fields-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-entity-fields-controller.php index c9738f2a7bb6e..cbc16bee7c01b 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-entity-fields-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-entity-fields-controller.php @@ -51,11 +51,13 @@ public function register_routes() { 'kind' => array( 'description' => __( 'Entity kind.' ), 'type' => 'string', + 'minLength' => 1, 'required' => true, ), 'name' => array( 'description' => __( 'Entity name.' ), 'type' => 'string', + 'minLength' => 1, 'required' => true, ), ), diff --git a/tests/phpunit/tests/entity-fields/wpEntityFieldsRegistry.php b/tests/phpunit/tests/entity-fields/wpEntityFieldsRegistry.php index 6a035503d1f1f..f12d6731bc365 100644 --- a/tests/phpunit/tests/entity-fields/wpEntityFieldsRegistry.php +++ b/tests/phpunit/tests/entity-fields/wpEntityFieldsRegistry.php @@ -548,6 +548,39 @@ static function () use ( &$results ) { $this->assertContains( 'author', array_column( wp_get_registered_entity_fields( 'postType', 'page' ), 'id' ), 'The default field is kept.' ); } + /** + * Reading with an entity kind or name that is not a non-empty string + * returns empty lists with a notice rather than a fatal error. + * + * @ticket 66229 + * + * @dataProvider data_invalid_entities + * + * @param mixed $kind The entity kind. + * @param mixed $name The entity name. + */ + public function test_reading_with_an_invalid_entity_returns_empty_lists( $kind, $name ) { + $this->setExpectedIncorrectUsage( 'WP_Entity_Fields_Registry::get_registered' ); + $this->setExpectedIncorrectUsage( 'WP_Entity_Fields_Registry::get_registered_field_modules' ); + + $this->assertSame( array(), wp_get_registered_entity_fields( $kind, $name ), 'No fields should be returned.' ); + $this->assertSame( array(), wp_get_registered_entity_field_modules( $kind, $name ), 'No script modules should be returned.' ); + } + + /** + * Data provider. + * + * @return array The entity kind and name. + */ + public static function data_invalid_entities() { + return array( + 'an array kind' => array( array(), 'page' ), + 'an array name' => array( 'postType', array() ), + 'an empty kind' => array( '', 'page' ), + 'an integer name' => array( 'postType', 1 ), + ); + } + /** * An id that is not a non-empty string is reported and skipped: the * other ids of the call are unregistered. diff --git a/tests/phpunit/tests/rest-api/rest-entity-actions-controller.php b/tests/phpunit/tests/rest-api/rest-entity-actions-controller.php index c67107147493a..15f58d7a47cc7 100644 --- a/tests/phpunit/tests/rest-api/rest-entity-actions-controller.php +++ b/tests/phpunit/tests/rest-api/rest-entity-actions-controller.php @@ -144,36 +144,6 @@ public function test_register_routes() { $this->assertInstanceOf( 'WP_REST_Entity_Actions_Controller', $routes[ self::ROUTE ][0]['callback'][0] ); } - /** - * A taxonomy whose items are on the route keeps it: the route of the - * actions is not registered, and that is reported. - * - * @covers ::register_routes - * @covers ::is_route_of_entity_items - * - * @ticket 66343 - */ - public function test_the_route_of_a_taxonomy_with_the_same_base_is_kept() { - global $wp_rest_server; - $this->setExpectedIncorrectUsage( 'WP_REST_Entity_Actions_Controller::is_route_of_entity_items' ); - register_taxonomy( 'entity-actions', 'post', array( 'show_in_rest' => true ) ); - - try { - $wp_rest_server = null; - $handlers = rest_get_server()->get_routes()[ self::ROUTE ]; - $response = rest_get_server()->dispatch( new WP_REST_Request( 'GET', self::ROUTE ) ); - } finally { - unregister_taxonomy( 'entity-actions' ); - $wp_rest_server = null; - } - - $this->assertCount( 2, $handlers, 'Only the route of the terms is registered.' ); - $this->assertInstanceOf( WP_REST_Terms_Controller::class, $handlers[0]['callback'][0] ); - $this->assertArrayHasKey( 'POST', $handlers[1]['methods'], 'Terms can still be created.' ); - $this->assertSame( 200, $response->get_status(), 'The terms are listed.' ); - $this->assertSame( array(), $response->get_data() ); - } - /** * Editors (with `edit_posts`) can read the actions. * diff --git a/tests/phpunit/tests/rest-api/rest-entity-fields-controller.php b/tests/phpunit/tests/rest-api/rest-entity-fields-controller.php index f5ac37779f8b3..5e3d5561ce435 100644 --- a/tests/phpunit/tests/rest-api/rest-entity-fields-controller.php +++ b/tests/phpunit/tests/rest-api/rest-entity-fields-controller.php @@ -405,6 +405,12 @@ public function test_get_items_requires_kind_and_name() { $missing_kind = $this->dispatch_request( null, 'page' ); $this->assertErrorResponse( 'rest_missing_callback_param', $missing_kind, 400 ); + + $empty_kind = $this->dispatch_request( '', 'page' ); + $this->assertErrorResponse( 'rest_invalid_param', $empty_kind, 400 ); + + $empty_name = $this->dispatch_request( 'postType', '' ); + $this->assertErrorResponse( 'rest_invalid_param', $empty_name, 400 ); } /** diff --git a/tests/qunit/fixtures/wp-api-generated.js b/tests/qunit/fixtures/wp-api-generated.js index 807eda9d2cf92..bb83cd91b8728 100644 --- a/tests/qunit/fixtures/wp-api-generated.js +++ b/tests/qunit/fixtures/wp-api-generated.js @@ -13134,11 +13134,13 @@ mockedApiResponse.Schema = { "kind": { "description": "Entity kind.", "type": "string", + "minLength": 1, "required": true }, "name": { "description": "Entity name.", "type": "string", + "minLength": 1, "required": true } } From 93d10b077b3d991f463ef19e05ddc28b2e957e2c Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 20 Nov 2026 15:46:43 +0000 Subject: [PATCH 37/85] Abilities API: Reject empty slugs and usernames in `core/users-query`. The items of the `slugs` and `usernames` filters now require at least one character, like the `slugs` filter of `core/content-query`, so a list holding an empty string fails schema validation instead of returning an empty list. A slug or username made only of whitespace names no user, so it is dropped before the query, and a list holding only such a value fails with `users_invalid_filter`. Developed in https://github.com/WordPress/wordpress-develop/pull/15986. Follow-up to [64346]. Props jorgefilipecosta, gziolo. Fixes #64657. git-svn-id: https://develop.svn.wordpress.org/trunk@65726 602fd350-edb4-49c9-b593-d223f7449a82 --- .../abilities/class-wp-abilities-users.php | 19 +++- .../wpRegisterCoreUsersAbility.php | 99 +++++++++++++++++++ 2 files changed, 113 insertions(+), 5 deletions(-) diff --git a/src/wp-includes/abilities/class-wp-abilities-users.php b/src/wp-includes/abilities/class-wp-abilities-users.php index a0f21de801e95..51df002dfe762 100644 --- a/src/wp-includes/abilities/class-wp-abilities-users.php +++ b/src/wp-includes/abilities/class-wp-abilities-users.php @@ -612,8 +612,10 @@ private function normalize_id_list( $value ): array { * Accepts arrays and CSV strings, which it parses with wp_parse_list(), as schema * validation does. Schema validation accepts a CSV string for an array, and only the * REST run controller converts input to the schema types, so callers that bypass it, - * such as a direct WP_Ability::execute() call, can pass one. Empty and duplicate - * items need no handling here, because validation has already rejected them. + * such as a direct WP_Ability::execute() call, can pass one. Empty and whitespace-only + * strings name nothing, so they are dropped, and a list that holds only such strings + * comes back empty. Duplicate items need no handling here, because validation has + * already rejected them. * * @since 7.2.0 * @@ -625,7 +627,12 @@ private function normalize_string_list( $value ): array { return array(); } - return array_values( array_filter( wp_parse_list( $value ), 'is_string' ) ); + return array_values( + array_filter( + wp_parse_list( $value ), + static fn( $item ) => is_string( $item ) && '' !== trim( $item ) + ) + ); } /** @@ -703,7 +710,8 @@ private function get_users_query_input_schema(): array { 'minItems' => 1, 'maxItems' => self::MAX_PER_PAGE, 'items' => array( - 'type' => 'string', + 'type' => 'string', + 'minLength' => 1, ), 'description' => __( 'Limit results to users with these slugs. If `pagination.per_page` is omitted, every matching user is returned on the first page.' ), ), @@ -713,7 +721,8 @@ private function get_users_query_input_schema(): array { 'minItems' => 1, 'maxItems' => self::MAX_PER_PAGE, 'items' => array( - 'type' => 'string', + 'type' => 'string', + 'minLength' => 1, ), 'description' => __( 'Limit results to users with these usernames. Requires permission to list users. If `pagination.per_page` is omitted, every matching user is returned on the first page.' ), ), diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreUsersAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreUsersAbility.php index 671db3381ec3b..9dedc9c7196e5 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreUsersAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreUsersAbility.php @@ -292,6 +292,8 @@ public function test_core_users_input_schema_exposes_strict_filters(): void { } $this->assertSame( 1, $where['properties']['ids']['items']['minimum'], 'The ids option should contain positive user IDs.' ); + $this->assertSame( 1, $where['properties']['slugs']['items']['minLength'], 'The slugs option should not contain an empty slug.' ); + $this->assertSame( 1, $where['properties']['usernames']['items']['minLength'], 'The usernames option should not contain an empty username.' ); $roles = $where['properties']['roles']; @@ -1606,6 +1608,103 @@ public static function data_unsupported_where_keys(): array { ); } + /** + * A slug or username list that holds an empty string fails schema validation, even next + * to a value that names a user. + * + * @ticket 64657 + * + * @dataProvider data_identifier_lists_with_an_empty_string + * + * @param string $filter The `where` filter. + * @param string[] $values The values given for the filter. + */ + public function test_identifier_list_with_an_empty_string_fails_schema_validation( string $filter, array $values ): void { + wp_set_current_user( self::$fixture_ids['administrator'] ); + $this->register_ability(); + + $result = wp_get_ability( 'core/users-query' )->execute( array( 'where' => array( $filter => $values ) ) ); + + $this->assertWPError( $result, sprintf( 'An empty string in the %s filter should fail the request.', $filter ) ); + $this->assertSame( 'ability_invalid_input', $result->get_error_code(), sprintf( 'An empty string in the %s filter should fail schema validation.', $filter ) ); + } + + /** + * Data provider for slug and username lists that hold an empty string. + * + * @return array + */ + public static function data_identifier_lists_with_an_empty_string(): array { + return array( + 'empty slug' => array( 'slugs', array( '' ) ), + 'empty and valid slug' => array( 'slugs', array( '', 'core-users-ability-admin' ) ), + 'empty username' => array( 'usernames', array( '' ) ), + 'empty and valid username' => array( 'usernames', array( '', 'core_users_ability_admin' ) ), + ); + } + + /** + * A slug or username made only of whitespace passes schema validation but names no user, + * so it is dropped: a list that holds only such a value fails as an invalid filter, and + * one next to a value that names a user still returns that user. + * + * @ticket 64657 + * + * @dataProvider data_slug_and_username_filters + * + * @param string $filter The `where` filter. + * @param string $value A value of the filter that names the administrator. + */ + public function test_whitespace_only_identifier_is_dropped( string $filter, string $value ): void { + wp_set_current_user( self::$fixture_ids['administrator'] ); + $this->register_ability(); + + $ability = wp_get_ability( 'core/users-query' ); + + $result = $ability->execute( array( 'where' => array( $filter => array( ' ' ) ) ) ); + + $this->assertWPError( $result, sprintf( 'A list of %s holding only a whitespace-only string should fail the request.', $filter ) ); + $this->assertSame( 'users_invalid_filter', $result->get_error_code(), sprintf( 'A list of %s holding only a whitespace-only string should fail closed as an invalid filter.', $filter ) ); + $this->assertSame( + array( 'where[' . $filter . ']' => $result->get_error_message() ), + $result->get_error_data()['params'], + sprintf( 'The error data should map the list of %s holding only a whitespace-only string to the error message.', $filter ) + ); + + $result = $ability->execute( + array( + 'where' => array( $filter => array( ' ', $value ) ), + 'fields' => array( 'id' ), + ) + ); + + $this->assertSame( + array( + 'items' => array( + array( 'id' => self::$fixture_ids['administrator'] ), + ), + 'pagination' => array( + 'total' => 1, + 'total_pages' => 1, + ), + ), + $result, + sprintf( 'A valid identifier alongside a whitespace-only string in the list of %s should still return the matching user.', $filter ) + ); + } + + /** + * Data provider for the slug and username filters, each with a value that names the administrator. + * + * @return array + */ + public static function data_slug_and_username_filters(): array { + return array( + 'slugs' => array( 'slugs', 'core-users-ability-admin' ), + 'usernames' => array( 'usernames', 'core_users_ability_admin' ), + ); + } + /** * Filters and pagination values at the root fail schema validation. * From 860be52c6739c0e280640c50aa0db58f5508b6af Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 20 Nov 2026 16:44:52 +0000 Subject: [PATCH 38/85] Tests: Isolate rewrite state in term link and redirect tests. Skip the rewrite flushes in the term link tests and unregister the `random` post type before teardown replaces the request. Developed in: https://github.com/WordPress/wordpress-develop/pull/16111, https://github.com/WordPress/wordpress-develop/pull/16112 Props faisalahammad. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65727 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/query/randomContentRedirect.php | 7 +++++++ tests/phpunit/tests/term/getTermLink.php | 4 ---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/phpunit/tests/query/randomContentRedirect.php b/tests/phpunit/tests/query/randomContentRedirect.php index 55e0cd025bc3b..9f867a0d48a92 100644 --- a/tests/phpunit/tests/query/randomContentRedirect.php +++ b/tests/phpunit/tests/query/randomContentRedirect.php @@ -254,6 +254,13 @@ public function tear_down(): void { unregister_post_type( 'wptests_unsearchable' ); unregister_taxonomy( 'wptests_genre' ); + /* + * The `random` post type shares the `random` query variable with core. Unregister it + * before the request is reset, as the reset at the start of the next test would remove + * the query variable from that test's request. + */ + unregister_post_type( 'random' ); + parent::tear_down(); } diff --git a/tests/phpunit/tests/term/getTermLink.php b/tests/phpunit/tests/term/getTermLink.php index 1e33a90cdaf62..d8a14bc3cab63 100644 --- a/tests/phpunit/tests/term/getTermLink.php +++ b/tests/phpunit/tests/term/getTermLink.php @@ -194,8 +194,6 @@ public function test_taxonomy_permastruct_with_hierarchical_rewrite_should_put_t ) ); - flush_rewrite_rules(); - $t1 = self::factory()->term->create( array( 'taxonomy' => 'wptests_tax2', @@ -229,8 +227,6 @@ public function test_taxonomy_permastruct_with_nonhierarchical_rewrite_should_no ) ); - flush_rewrite_rules(); - $t1 = self::factory()->term->create( array( 'taxonomy' => 'wptests_tax2', From d20a2fb918f84585bed47fc1e82cce8e64f19869 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 20 Nov 2026 16:46:31 +0000 Subject: [PATCH 39/85] Tests: Load the menu quick search helper in test setup. Load `nav-menu.php` before each test so the searches can run independently. Developed in: https://github.com/WordPress/wordpress-develop/pull/16130 Props ekamran. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65728 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/menu/wpAjaxMenuQuickSearch.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/phpunit/tests/menu/wpAjaxMenuQuickSearch.php b/tests/phpunit/tests/menu/wpAjaxMenuQuickSearch.php index 8cdcb2e04aefa..61f4307317618 100644 --- a/tests/phpunit/tests/menu/wpAjaxMenuQuickSearch.php +++ b/tests/phpunit/tests/menu/wpAjaxMenuQuickSearch.php @@ -5,14 +5,18 @@ */ class Tests_Menu_WpAjaxMenuQuickSearch extends WP_UnitTestCase { + public function set_up() { + parent::set_up(); + + require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; + } + /** * Test search returns results for pages. * * @ticket 27042 */ public function test_search_returns_results_for_pages() { - require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; - self::factory()->post->create_many( 3, array( @@ -48,8 +52,6 @@ public function test_search_returns_results_for_pages() { * @ticket 48655 */ public function test_search_only_returns_results_for_posts_with_term_in_title() { - require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; - // This will make sure that WP_Query sets is_admin to true. set_current_screen( 'nav-menu.php' ); @@ -87,8 +89,6 @@ public function test_search_only_returns_results_for_posts_with_term_in_title() * @ticket 33742 */ public function test_search_returns_results_for_published_posts() { - require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; - // This will make sure that WP_Query sets is_admin to true. set_current_screen( 'nav-menu.php' ); From a4a0272705d574cf21a2e8c4b874fe8b86a2fcd4 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 20 Nov 2026 16:51:04 +0000 Subject: [PATCH 40/85] Tests: Isolate theme, script module, and post password fixtures. Restore the registered theme features, allow the saved script modules instance to be `null`, and clear the post password cookie after the header tests. Developed in: https://github.com/WordPress/wordpress-develop/pull/16131, https://github.com/WordPress/wordpress-develop/pull/16132, https://github.com/WordPress/wordpress-develop/pull/16134 Props ekamran. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65729 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/script-modules/wpScriptModules.php | 2 +- tests/phpunit/tests/theme.php | 12 +++++++++++- tests/phpunit/tests/wp/sendHeaders.php | 6 ++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/tests/phpunit/tests/script-modules/wpScriptModules.php b/tests/phpunit/tests/script-modules/wpScriptModules.php index 47a79efb66a12..6cf280509b2af 100644 --- a/tests/phpunit/tests/script-modules/wpScriptModules.php +++ b/tests/phpunit/tests/script-modules/wpScriptModules.php @@ -11,7 +11,7 @@ */ class Tests_Script_Modules_WpScriptModules extends WP_UnitTestCase { - protected WP_Script_Modules $original_script_modules; + protected ?WP_Script_Modules $original_script_modules; protected string $original_wp_version; diff --git a/tests/phpunit/tests/theme.php b/tests/phpunit/tests/theme.php index 3fbb9dd2ae2f5..2edc022fae584 100644 --- a/tests/phpunit/tests/theme.php +++ b/tests/phpunit/tests/theme.php @@ -41,6 +41,13 @@ class Tests_Theme extends WP_UnitTestCase { */ private $orig_theme_features; + /** + * Theme features registered with register_theme_feature() before the test ran. + * + * @var array + */ + private $orig_registered_theme_features; + public function set_up() { global $wp_theme_directories; @@ -51,6 +58,8 @@ public function set_up() { $wp_theme_directories = array( WP_CONTENT_DIR . '/themes', realpath( DIR_TESTDATA . '/themedir1' ) ); $this->orig_theme_features = $GLOBALS['_wp_theme_features']; + $this->orig_registered_theme_features = $GLOBALS['_wp_registered_theme_features']; + add_filter( 'extra_theme_headers', array( $this, 'theme_data_extra_headers' ) ); wp_clean_themes_cache(); unset( $GLOBALS['wp_themes'] ); @@ -69,7 +78,8 @@ public function tear_down() { parent::tear_down(); } finally { // Restore after the parent removes HTML5 theme support. - $GLOBALS['_wp_theme_features'] = $this->orig_theme_features; + $GLOBALS['_wp_theme_features'] = $this->orig_theme_features; + $GLOBALS['_wp_registered_theme_features'] = $this->orig_registered_theme_features; } } diff --git a/tests/phpunit/tests/wp/sendHeaders.php b/tests/phpunit/tests/wp/sendHeaders.php index 4974d74caf8fc..ac502adf45d40 100644 --- a/tests/phpunit/tests/wp/sendHeaders.php +++ b/tests/phpunit/tests/wp/sendHeaders.php @@ -8,6 +8,12 @@ class Tests_WP_SendHeaders extends WP_UnitTestCase { protected $headers_sent = array(); + public function tear_down() { + unset( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ); + + parent::tear_down(); + } + /** * @ticket 56068 */ From f7c912eae498be622ef8fc5933e6653a36dba3af Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 20 Nov 2026 16:53:05 +0000 Subject: [PATCH 41/85] Tests: Reconnect the database helper after disconnect tests. Reconnect the shared test helper alongside `$wpdb` so later field-processing tests have a working connection. Developed in: https://github.com/WordPress/wordpress-develop/pull/16133 Props ekamran. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65730 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/db.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/phpunit/tests/db.php b/tests/phpunit/tests/db.php index 50ab02b260d1d..9d438504a3c99 100644 --- a/tests/phpunit/tests/db.php +++ b/tests/phpunit/tests/db.php @@ -1485,6 +1485,7 @@ public function test_close() { $this->assertTrue( $wpdb->close() ); $wpdb->check_connection(); + self::$_wpdb->db_connect(); } /** @@ -1503,6 +1504,7 @@ public function test_charset_not_determined_when_disconnected() { $this->assertSame( compact( 'charset', 'collate' ), $result ); $wpdb->check_connection(); + self::$_wpdb->db_connect(); } /** From 809c0133f1d37cec27698ffbe0dac03194ab99da Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 20 Nov 2026 16:54:06 +0000 Subject: [PATCH 42/85] Build/Test Tools: Type-check three more JavaScript files. Add `xfn.js`, `language-chooser.js`, and `sanitize.js` to the TypeScript compiler inputs. Developed in: https://github.com/WordPress/wordpress-develop/pull/16117 Props faisalahammad. See #66751. git-svn-id: https://develop.svn.wordpress.org/trunk@65731 602fd350-edb4-49c9-b593-d223f7449a82 --- tsconfig.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tsconfig.json b/tsconfig.json index b206bc162f72b..2a72ff4c550c2 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -35,12 +35,15 @@ "src/js/_enqueues/admin/media-frame-upload.js", "src/js/_enqueues/admin/media-new-upload.js", "src/js/_enqueues/admin/media-upload-pipeline.js", + "src/js/_enqueues/admin/xfn.js", "src/js/_enqueues/lib/accordion.js", "src/js/_enqueues/lib/codemirror/htmlhint-kses.js", "src/js/_enqueues/lib/codemirror/javascript-lint.js", "src/js/_enqueues/lib/emoji-loader.js", + "src/js/_enqueues/lib/language-chooser.js", "src/js/_enqueues/wp/code-editor.js", "src/js/_enqueues/wp/emoji.js", + "src/js/_enqueues/wp/sanitize.js", "src/js/_enqueues/wp/wp-tooltip.js", "tools/gutenberg/copy.js", "tools/gutenberg/download.js", From 1f84b51ab56ddd3bcab0be9be94ee477708642d6 Mon Sep 17 00:00:00 2001 From: Peter Wilson Date: Fri, 20 Nov 2026 21:17:39 +0000 Subject: [PATCH 43/85] Administration: Revert the On This Day section of the Activity widget. The On This Day section of the Activity widget has been removed from the WordPress 7.2 release. This restores the Recent Comments section to the Activity widget and removes the dedicated Recent Comments dashboard widget. This reverts r64593. Reviewed by audrasjb. Props annezazu. See #65116. git-svn-id: https://develop.svn.wordpress.org/trunk@65732 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/_index.php | 6 +- src/wp-admin/css/dashboard.css | 48 +- src/wp-admin/includes/dashboard.php | 254 +---------- .../tests/admin/wpDashboardSiteActivity.php | 413 ------------------ 4 files changed, 34 insertions(+), 687 deletions(-) delete mode 100644 tests/phpunit/tests/admin/wpDashboardSiteActivity.php diff --git a/src/wp-admin/_index.php b/src/wp-admin/_index.php index 4af8d0d66485b..de5cc21b8ff4f 100644 --- a/src/wp-admin/_index.php +++ b/src/wp-admin/_index.php @@ -86,11 +86,7 @@ $help .= '

' . __( 'At a Glance — Displays a summary of the content on your site and identifies which theme and version of WordPress you are using.' ) . '

'; } -$help .= '

' . __( 'Activity — Shows upcoming scheduled posts, recently published posts, and posts published on this day in previous years.' ) . '

'; - -if ( _wp_dashboard_has_received_comments() ) { - $help .= '

' . __( 'Recent Comments — Shows the most recent comments on your posts and allows you to moderate them.' ) . '

'; -} +$help .= '

' . __( 'Activity — Shows the upcoming scheduled posts, recently published posts, and the most recent comments on your posts and allows you to moderate them.' ) . '

'; if ( is_blog_admin() && current_user_can( 'edit_posts' ) ) { $help .= '

' . __( "Quick Draft — Allows you to create a new post and save it as a draft. Also displays links to the 3 most recent draft posts you've started." ) . '

'; diff --git a/src/wp-admin/css/dashboard.css b/src/wp-admin/css/dashboard.css index 100c4df0a9633..c75eca12ee7be 100644 --- a/src/wp-admin/css/dashboard.css +++ b/src/wp-admin/css/dashboard.css @@ -879,7 +879,7 @@ body #dashboard-widgets .postbox form .submit { /* Dashboard activity widget */ -#dashboard_recent_comments .comment-meta span.approve::before { +#dashboard_activity .comment-meta span.approve::before { content: "\f227"; content: "\f227" / ""; font: 20px/0.5 dashicons; @@ -890,8 +890,7 @@ body #dashboard-widgets .postbox form .submit { margin-right: 2px; } -#dashboard_activity .inside, -#dashboard_recent_comments .inside { +#dashboard_activity .inside { margin: 0; padding: 0 12px; } @@ -907,27 +906,25 @@ body #dashboard-widgets .postbox form .submit { font-size: 16px; } -#dashboard_recent_comments .subsubsub { +#dashboard_activity .subsubsub { float: none; border-top: 1px solid #f0f0f1; margin: 0 -12px; padding: 8px 12px 4px; } -#dashboard_recent_comments .subsubsub a .count, -#dashboard_recent_comments .subsubsub a.current .count { +#dashboard_activity .subsubsub a .count, +#dashboard_activity .subsubsub a.current .count { color: #646970; /* white background on the dashboard but #f0f0f1 on list tables */ } #future-posts ul, -#published-posts ul, -#on-this-day-posts ul { +#published-posts ul { margin: 8px -12px 0 -12px; } #future-posts li, -#published-posts li, -#on-this-day-posts li { +#published-posts li { display: grid; grid-template-columns: clamp(160px, calc(2vw + 140px), 200px) auto; column-gap: 10px; @@ -936,15 +933,10 @@ body #dashboard-widgets .postbox form .submit { } #future-posts li:nth-child(odd), -#published-posts li:nth-child(odd), -#on-this-day-posts li:nth-child(odd) { +#published-posts li:nth-child(odd) { background-color: #f6f7f7; } -#on-this-day-posts .wp-on-this-day-post-author { - color: #646970; -} - .activity-block { border-bottom: 1px solid #f0f0f1; margin: 0 -12px 6px -12px; @@ -963,45 +955,45 @@ body #dashboard-widgets .postbox form .submit { /* Dashboard activity widget - Comments */ /* @todo: needs serious de-duplication */ -#dashboard_recent_comments #the-comment-list tr.undo, -#dashboard_recent_comments #the-comment-list div.undo { +#activity-widget #the-comment-list tr.undo, +#activity-widget #the-comment-list div.undo { background: none; padding: 6px 0; margin-left: 12px; } -#dashboard_recent_comments #the-comment-list .comment-item { +#activity-widget #the-comment-list .comment-item { background: #f6f7f7; padding: 12px; position: relative; } -#dashboard_recent_comments #the-comment-list .avatar { +#activity-widget #the-comment-list .avatar { position: absolute; top: 12px; } -#dashboard_recent_comments #the-comment-list .dashboard-comment-wrap.has-avatar { +#activity-widget #the-comment-list .dashboard-comment-wrap.has-avatar { padding-left: 63px; } -#dashboard_recent_comments #the-comment-list .dashboard-comment-wrap blockquote { +#activity-widget #the-comment-list .dashboard-comment-wrap blockquote { margin: 1em 0; } -#dashboard_recent_comments #the-comment-list .comment-item p.row-actions { +#activity-widget #the-comment-list .comment-item p.row-actions { margin: 4px 0 0; } -#dashboard_recent_comments #the-comment-list .comment-item:first-child { +#activity-widget #the-comment-list .comment-item:first-child { border-top: 1px solid #f0f0f1; } -#dashboard_recent_comments #the-comment-list .unapproved { +#activity-widget #the-comment-list .unapproved { background-color: #fcf9e8; } -#dashboard_recent_comments #the-comment-list .unapproved::before { +#activity-widget #the-comment-list .unapproved::before { content: ""; display: block; position: absolute; @@ -1012,8 +1004,8 @@ body #dashboard-widgets .postbox form .submit { width: 4px; } -#dashboard_recent_comments #the-comment-list .spam-undo-inside .avatar, -#dashboard_recent_comments #the-comment-list .trash-undo-inside .avatar { +#activity-widget #the-comment-list .spam-undo-inside .avatar, +#activity-widget #the-comment-list .trash-undo-inside .avatar { position: relative; top: 0; } diff --git a/src/wp-admin/includes/dashboard.php b/src/wp-admin/includes/dashboard.php index 9ba75b74bc4c2..05e6e24f6b0c6 100644 --- a/src/wp-admin/includes/dashboard.php +++ b/src/wp-admin/includes/dashboard.php @@ -6,33 +6,6 @@ * @subpackage Administration */ -/** - * Determines whether the site has ever received a comment. - * - * The result is persisted so the Recent Comments widget remains registered if - * all comments are later deleted, preserving its Screen Options and position. - * - * @since 7.2.0 - * @access private - * - * @return bool Whether the site has received a comment. - */ -function _wp_dashboard_has_received_comments() { - if ( get_option( 'dashboard_recent_comments_widget_registered' ) ) { - return true; - } - - $comment_count = wp_count_comments(); - - if ( empty( $comment_count->all ) ) { - return false; - } - - update_option( 'dashboard_recent_comments_widget_registered', 1, false ); - - return true; -} - /** * Registers dashboard widgets. * @@ -109,11 +82,6 @@ function wp_dashboard_setup() { wp_add_dashboard_widget( 'dashboard_activity', __( 'Activity' ), 'wp_dashboard_site_activity' ); } - // Recent Comments Widget. - if ( is_blog_admin() && _wp_dashboard_has_received_comments() ) { - wp_add_dashboard_widget( 'dashboard_recent_comments', __( 'Recent Comments' ), 'wp_dashboard_recent_comments_widget' ); - } - // QuickPress Widget. if ( is_blog_admin() && current_user_can( get_post_type_object( 'post' )->cap->create_posts ) ) { $quick_draft_title = sprintf( '%1$s %2$s', __( 'Quick Draft' ), __( 'Your Recent Drafts' ) ); @@ -975,14 +943,12 @@ function _wp_dashboard_recent_comments_row( &$comment, $show_date = true ) { * Callback function for {@see 'dashboard_activity'}. * * @since 3.8.0 - * @since 7.2.0 Added the On This Day section and moved Recent Comments to a dedicated widget. */ function wp_dashboard_site_activity() { echo '
'; - $on_this_day_posts = wp_dashboard_on_this_day_get_posts(); - $future_posts = wp_dashboard_recent_posts( + $future_posts = wp_dashboard_recent_posts( array( 'max' => 5, 'status' => 'future', @@ -991,20 +957,19 @@ function wp_dashboard_site_activity() { 'id' => 'future-posts', ) ); - $recent_posts = wp_dashboard_recent_posts( + $recent_posts = wp_dashboard_recent_posts( array( - 'max' => 5, - 'status' => 'publish', - 'order' => 'DESC', - 'title' => __( 'Recently Published' ), - 'id' => 'published-posts', - 'exclude' => wp_list_pluck( $on_this_day_posts, 'ID' ), + 'max' => 5, + 'status' => 'publish', + 'order' => 'DESC', + 'title' => __( 'Recently Published' ), + 'id' => 'published-posts', ) ); - $on_this_day_rendered = wp_dashboard_on_this_day( $on_this_day_posts ); + $recent_comments = wp_dashboard_recent_comments(); - if ( ! $future_posts && ! $recent_posts && ! $on_this_day_rendered ) { + if ( ! $future_posts && ! $recent_posts && ! $recent_comments ) { echo '
'; echo '

' . __( 'No activity yet!' ) . '

'; echo '
'; @@ -1013,176 +978,6 @@ function wp_dashboard_site_activity() { echo '
'; } -/** - * Outputs the On This Day section of the Activity widget. - * - * @since 7.2.0 - * - * @param WP_Post[]|null $posts Optional. Posts to render. Defaults to querying for posts. - * @return bool False if no posts were found. True otherwise. - */ -function wp_dashboard_on_this_day( $posts = null ) { - if ( null === $posts ) { - $posts = wp_dashboard_on_this_day_get_posts(); - } - - if ( empty( $posts ) ) { - return false; - } - - echo '
'; - echo '

' . esc_html__( 'Published On This Day' ) . '

'; - echo '
    '; - - foreach ( $posts as $post ) { - /* translators: Date format for posts published in a previous year. */ - $date = get_the_date( __( 'M jS, Y' ), $post ); - - $title = get_the_title( $post ); - - if ( '' === trim( $title ) ) { - $title = __( '(no title)' ); - - if ( current_user_can( 'read_post', $post->ID ) && ! post_password_required( $post ) ) { - $excerpt = get_the_excerpt( $post ); - - if ( is_string( $excerpt ) && '' !== $excerpt ) { - $title .= ' ' . wp_trim_words( $excerpt, 15 ); - } - } - } - - $can_edit = current_user_can( 'edit_post', $post->ID ); - $link = $can_edit ? get_edit_post_link( $post->ID ) : get_permalink( $post ); - - if ( $can_edit ) { - /* translators: %s: Post title. */ - $aria_label = sprintf( __( 'Edit “%s”' ), $title ); - } else { - /* translators: %s: Post title. */ - $aria_label = sprintf( __( 'View “%s”' ), $title ); - } - - $author_id = (int) $post->post_author; - $author_name = $author_id > 0 ? (string) get_the_author_meta( 'display_name', $author_id ) : ''; - - printf( - '
  • %1$s%4$s', - esc_html( $date ), - esc_url( $link ), - esc_attr( $aria_label ), - esc_html( $title ) - ); - - if ( '' !== trim( $author_name ) && get_current_user_id() !== $author_id ) { - printf( - ' ', - esc_html( - sprintf( - /* translators: %s: Post author's display name. */ - __( 'by %s' ), - $author_name - ) - ) - ); - } - - echo '
  • '; - } - - echo '
'; - echo '
'; - - return true; -} - -/** - * Retrieves posts published on this calendar day in previous years. - * - * Up to ten posts are returned by default. Use the - * {@see 'wp_dashboard_on_this_day_query_args'} filter to change the limit. - * Results are cached by WP_Query's native query caching. - * - * @since 7.2.0 - * - * @return WP_Post[] Array of posts ordered by newest first. - */ -function wp_dashboard_on_this_day_get_posts() { - $today = current_datetime(); - $year = (int) $today->format( 'Y' ); - - $args = array( - 'post_type' => 'post', - 'post_status' => array( 'publish' ), - 'posts_per_page' => 10, - 'ignore_sticky_posts' => true, - 'orderby' => 'date', - 'order' => 'DESC', - 'no_found_rows' => true, - 'update_post_term_cache' => false, - 'update_post_meta_cache' => false, - 'date_query' => array( - 'relation' => 'AND', - array( - 'before' => array( 'year' => $year ), - ), - _wp_dashboard_on_this_day_date_query_clause( $today ), - ), - ); - - /** - * Filters the arguments used to query posts for the On This Day section. - * - * @since 7.2.0 - * - * @param array $args WP_Query arguments. - */ - $args = apply_filters( 'wp_dashboard_on_this_day_query_args', $args ); - - $query = new WP_Query( $args ); - - return $query->posts; -} - -/** - * Builds the date query clause for today's anniversary date. - * - * On February 28 in a non-leap year, February 29 posts are included so - * leap-day anniversaries still appear. - * - * @since 7.2.0 - * @access private - * - * @param DateTimeInterface $date Date to build the clause for. - * @return array Date query clause. - */ -function _wp_dashboard_on_this_day_date_query_clause( $date ) { - $month = (int) $date->format( 'm' ); - $day = (int) $date->format( 'd' ); - $clause = array( - 'month' => $month, - 'day' => $day, - ); - - // Display leap day posts on February 28 in non-leap years. - if ( - 28 === $day - && 2 === $month - && false === (bool) $date->format( 'L' ) - ) { - $clause = array( - 'relation' => 'OR', - $clause, - array( - 'month' => 2, - 'day' => 29, - ), - ); - } - - return $clause; -} - /** * Generates Publishing Soon and Recently Published sections. * @@ -1196,7 +991,6 @@ function _wp_dashboard_on_this_day_date_query_clause( $date ) { * @type string $order Designates ascending ('ASC') or descending ('DESC') order. * @type string $title Section title. * @type string $id The container id. - * @type int[] $exclude Optional. Post IDs to exclude. * } * @return bool False if no posts were found. True otherwise. */ @@ -1212,10 +1006,6 @@ function wp_dashboard_recent_posts( $args ) { 'perm' => ( 'future' === $args['status'] ) ? 'editable' : 'readable', ); - if ( ! empty( $args['exclude'] ) ) { - $query_args['post__not_in'] = array_map( 'intval', $args['exclude'] ); - } - /** * Filters the query arguments used for the Recent Posts widget. * @@ -1287,29 +1077,14 @@ function wp_dashboard_recent_posts( $args ) { } /** - * Outputs the Recent Comments dashboard widget. - * - * Callback function for {@see 'dashboard_recent_comments'}. - * - * @since 7.2.0 - */ -function wp_dashboard_recent_comments_widget() { - if ( ! wp_dashboard_recent_comments( 5, false ) ) { - echo '

' . esc_html__( 'No comments to show.' ) . '

'; - } -} - -/** - * Outputs recent comments. + * Show Comments section. * * @since 3.8.0 - * @since 7.2.0 Moved from the Activity widget to a dedicated dashboard widget. * - * @param int $total_items Optional. Number of comments to query. Default 5. - * @param bool $show_title Optional. Whether to display the section title. Default true. + * @param int $total_items Optional. Number of comments to query. Default 5. * @return bool False if no comments were found. True otherwise. */ -function wp_dashboard_recent_comments( $total_items = 5, $show_title = true ) { +function wp_dashboard_recent_comments( $total_items = 5 ) { // Select all comment types and filter out spam later for better query performance. $comments = array(); @@ -1353,10 +1128,7 @@ function wp_dashboard_recent_comments( $total_items = 5, $show_title = true ) { if ( $comments ) { echo '
'; - - if ( $show_title ) { - echo '

' . esc_html__( 'Recent Comments' ) . '

'; - } + echo '

' . __( 'Recent Comments' ) . '

'; echo '
    '; foreach ( $comments as $comment ) { diff --git a/tests/phpunit/tests/admin/wpDashboardSiteActivity.php b/tests/phpunit/tests/admin/wpDashboardSiteActivity.php deleted file mode 100644 index 9d5f673afc7d6..0000000000000 --- a/tests/phpunit/tests/admin/wpDashboardSiteActivity.php +++ /dev/null @@ -1,413 +0,0 @@ -user->create( - array( - 'display_name' => 'Current Writer', - 'role' => 'author', - ) - ); - self::$other_user_id = $factory->user->create( - array( - 'display_name' => 'Guest Writer', - 'role' => 'author', - ) - ); - } - - public static function wpTearDownAfterClass() { - self::delete_user( self::$user_id ); - self::delete_user( self::$other_user_id ); - } - - public function set_up() { - parent::set_up(); - - set_current_screen( 'dashboard' ); - wp_set_current_user( self::$user_id ); - $_SERVER['REQUEST_METHOD'] = 'GET'; - } - - public function tear_down() { - delete_option( 'dashboard_recent_comments_widget_registered' ); - unset( $GLOBALS['wp_meta_boxes']['dashboard'] ); - - parent::tear_down(); - } - - /** - * Creates a published post on today's calendar day in a previous year. - * - * @param int $author_id Author ID. - * @param string $title Post title. - * @param int $years_ago Number of years before today. - * @param array $post_args Additional post arguments. - * @return int Post ID. - */ - private function create_matching_post( $author_id, $title = 'A memory from last year', $years_ago = 1, $post_args = array() ) { - $today = current_datetime(); - - if ( '02-29' === $today->format( 'm-d' ) ) { - $years_ago *= 4; - } - - $post_date = ( (int) $today->format( 'Y' ) - $years_ago ) . '-' . $today->format( 'm-d' ) . ' 12:00:00'; - - return self::factory()->post->create( - array_merge( - array( - 'post_author' => $author_id, - 'post_date' => $post_date, - 'post_date_gmt' => get_gmt_from_date( $post_date ), - 'post_status' => 'publish', - 'post_title' => $title, - ), - $post_args - ) - ); - } - - /** - * @ticket 65116 - * - * @covers ::_wp_dashboard_on_this_day_date_query_clause - */ - public function test_date_query_includes_february_29_on_february_28_in_non_leap_year() { - $date = new DateTimeImmutable( '2023-02-28 12:00:00', wp_timezone() ); - - $this->assertSame( - array( - 'relation' => 'OR', - array( - 'month' => 2, - 'day' => 28, - ), - array( - 'month' => 2, - 'day' => 29, - ), - ), - _wp_dashboard_on_this_day_date_query_clause( $date ) - ); - } - - /** - * @ticket 65116 - * - * @covers ::wp_dashboard_on_this_day_get_posts - */ - public function test_query_returns_only_published_posts_from_this_day_in_previous_years() { - $matching_id = $this->create_matching_post( self::$user_id ); - $this->create_matching_post( self::$user_id, 'A draft memory', 2, array( 'post_status' => 'draft' ) ); - - $today = current_datetime(); - $current_day = $today->format( 'Y-m-d' ) . ' 12:00:00'; - self::factory()->post->create( - array( - 'post_author' => self::$user_id, - 'post_date' => $current_day, - 'post_status' => 'publish', - 'post_title' => 'A memory from this year', - ) - ); - - $nearby_date = $today->modify( '-1 year +1 day' )->format( 'Y-m-d' ) . ' 12:00:00'; - self::factory()->post->create( - array( - 'post_author' => self::$user_id, - 'post_date' => $nearby_date, - 'post_status' => 'publish', - 'post_title' => 'A nearby memory', - ) - ); - - $posts = wp_dashboard_on_this_day_get_posts(); - - $this->assertSame( array( $matching_id ), wp_list_pluck( $posts, 'ID' ) ); - } - - /** - * @ticket 65116 - * - * @covers ::wp_dashboard_on_this_day_get_posts - */ - public function test_query_defaults_to_ten_posts_and_limit_is_filterable() { - for ( $years_ago = 1; $years_ago <= 11; $years_ago++ ) { - $this->create_matching_post( self::$user_id, 'Anniversary post ' . $years_ago, $years_ago ); - } - - $this->assertCount( 10, wp_dashboard_on_this_day_get_posts() ); - - add_filter( 'wp_dashboard_on_this_day_query_args', array( $this, 'filter_on_this_day_query_limit' ) ); - try { - $this->assertCount( 3, wp_dashboard_on_this_day_get_posts() ); - } finally { - remove_filter( 'wp_dashboard_on_this_day_query_args', array( $this, 'filter_on_this_day_query_limit' ) ); - } - } - - /** - * @ticket 65116 - * - * @covers ::wp_dashboard_on_this_day - */ - public function test_section_renders_posts_from_all_authors_and_untitled_excerpts() { - $this->create_matching_post( self::$user_id, 'A note from me' ); - $this->create_matching_post( self::$other_user_id, 'A note from someone else', 2 ); - $this->create_matching_post( - self::$user_id, - '', - 3, - array( 'post_excerpt' => 'word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12 word13 word14 word15 word16' ) - ); - - ob_start(); - $result = wp_dashboard_on_this_day(); - $output = ob_get_clean(); - - $this->assertTrue( $result ); - $this->assertStringContainsString( 'Published On This Day', $output ); - $this->assertStringContainsString( 'A note from me', $output ); - $this->assertStringNotContainsString( 'by Current Writer', $output ); - $this->assertStringContainsString( 'A note from someone else', $output ); - $this->assertStringContainsString( 'by Guest Writer', $output ); - $this->assertStringContainsString( '(no title)', $output ); - $this->assertStringContainsString( 'word15', $output ); - $this->assertStringNotContainsString( 'word16', $output ); - } - - /** - * @ticket 65116 - * - * @covers ::wp_dashboard_on_this_day - */ - public function test_section_hides_untitled_excerpt_for_unreadable_posts() { - $this->create_matching_post( - self::$other_user_id, - '', - 1, - array( - 'post_excerpt' => 'Unreadable private anniversary memory.', - 'post_status' => 'private', - ) - ); - - add_filter( 'wp_dashboard_on_this_day_query_args', array( $this, 'filter_on_this_day_query_private_posts' ) ); - try { - ob_start(); - wp_dashboard_on_this_day(); - $output = ob_get_clean(); - } finally { - remove_filter( 'wp_dashboard_on_this_day_query_args', array( $this, 'filter_on_this_day_query_private_posts' ) ); - } - - $this->assertStringContainsString( '(no title)', $output ); - $this->assertStringNotContainsString( 'Unreadable private anniversary memory.', $output ); - } - - /** - * @ticket 65116 - * - * @covers ::wp_dashboard_on_this_day - */ - public function test_section_hides_untitled_excerpt_for_password_protected_posts() { - $this->create_matching_post( - self::$user_id, - '', - 1, - array( - 'post_excerpt' => 'Password-protected anniversary memory.', - 'post_password' => 'secret', - ) - ); - - ob_start(); - wp_dashboard_on_this_day(); - $output = ob_get_clean(); - - $this->assertStringContainsString( '(no title)', $output ); - $this->assertStringNotContainsString( 'Password-protected anniversary memory.', $output ); - } - - /** - * @ticket 65116 - * - * @covers ::wp_dashboard_site_activity - */ - public function test_activity_renders_no_activity_message_without_posts() { - ob_start(); - wp_dashboard_site_activity(); - $output = ob_get_clean(); - - $this->assertStringContainsString( 'No activity yet!', $output ); - $this->assertStringNotContainsString( 'Published On This Day', $output ); - } - - /** - * @ticket 65116 - * - * @covers ::wp_dashboard_site_activity - * @covers ::wp_dashboard_recent_posts - */ - public function test_activity_does_not_repeat_on_this_day_posts_in_recently_published() { - $this->create_matching_post( self::$user_id, 'One anniversary mention' ); - self::factory()->post->create( - array( - 'post_author' => self::$user_id, - 'post_status' => 'publish', - 'post_title' => 'A recent post', - ) - ); - - ob_start(); - wp_dashboard_site_activity(); - $output = ob_get_clean(); - - $this->assertStringContainsString( 'Published On This Day', $output ); - $this->assertSame( 1, preg_match( '/
    /s', $output, $recent_posts ) ); - $this->assertStringNotContainsString( 'One anniversary mention', $recent_posts[0] ); - } - - /** - * @ticket 65116 - * - * @covers ::wp_dashboard_site_activity - * @covers ::wp_dashboard_recent_comments_widget - * @covers ::wp_dashboard_recent_comments - */ - public function test_recent_comments_are_rendered_only_in_their_dedicated_widget() { - $post_id = self::factory()->post->create( - array( - 'post_author' => self::$user_id, - 'post_status' => 'draft', - ) - ); - self::factory()->comment->create( - array( - 'comment_post_ID' => $post_id, - 'comment_content' => 'A comment in its own widget.', - ) - ); - - ob_start(); - wp_dashboard_site_activity(); - $activity_output = ob_get_clean(); - - ob_start(); - wp_dashboard_recent_comments_widget(); - $comments_output = ob_get_clean(); - - ob_start(); - wp_dashboard_recent_comments(); - $direct_output = ob_get_clean(); - - $this->assertStringNotContainsString( 'A comment in its own widget.', $activity_output ); - $this->assertStringContainsString( 'No activity yet!', $activity_output ); - $this->assertStringContainsString( 'A comment in its own widget.', $comments_output ); - $this->assertStringNotContainsString( '

    Recent Comments

    ', $comments_output ); - $this->assertStringContainsString( '

    Recent Comments

    ', $direct_output ); - } - - /** - * @ticket 65116 - * - * @covers ::wp_dashboard_recent_comments_widget - */ - public function test_recent_comments_widget_renders_empty_state_when_user_has_no_visible_comments() { - $post_id = self::factory()->post->create( array( 'post_status' => 'publish' ) ); - self::factory()->comment->create( - array( - 'comment_post_ID' => $post_id, - 'comment_approved' => '0', - ) - ); - wp_set_current_user( self::factory()->user->create( array( 'role' => 'subscriber' ) ) ); - - ob_start(); - wp_dashboard_recent_comments_widget(); - $output = ob_get_clean(); - - $this->assertStringContainsString( 'No comments to show.', $output ); - } - - /** - * @ticket 65116 - * - * @covers ::_wp_dashboard_has_received_comments - * @covers ::wp_dashboard_setup - */ - public function test_recent_comments_widget_remains_registered_after_comments_are_deleted() { - add_filter( 'pre_http_request', array( $this, 'mock_http_request_failure' ) ); - - try { - wp_dashboard_setup(); - $this->assertArrayNotHasKey( 'dashboard_recent_comments', $GLOBALS['wp_meta_boxes']['dashboard']['normal']['core'] ); - - unset( $GLOBALS['wp_meta_boxes']['dashboard'] ); - - $post_id = self::factory()->post->create(); - $comment_id = self::factory()->comment->create( array( 'comment_post_ID' => $post_id ) ); - - wp_dashboard_setup(); - $this->assertArrayHasKey( 'dashboard_recent_comments', $GLOBALS['wp_meta_boxes']['dashboard']['normal']['core'] ); - $this->assertSame( - 'wp_dashboard_recent_comments_widget', - $GLOBALS['wp_meta_boxes']['dashboard']['normal']['core']['dashboard_recent_comments']['callback'] - ); - $this->assertSame( 1, get_option( 'dashboard_recent_comments_widget_registered' ) ); - - wp_delete_comment( $comment_id, true ); - unset( $GLOBALS['wp_meta_boxes']['dashboard'] ); - - wp_dashboard_setup(); - $this->assertArrayHasKey( 'dashboard_recent_comments', $GLOBALS['wp_meta_boxes']['dashboard']['normal']['core'] ); - } finally { - remove_filter( 'pre_http_request', array( $this, 'mock_http_request_failure' ) ); - } - } - - /** - * Mocks an HTTP request failure during dashboard setup. - * - * @return WP_Error Mock request error. - */ - public function mock_http_request_failure() { - return new WP_Error( 'http_request_failed' ); - } - - /** - * Sets the On This Day query limit to three. - * - * @param array $args Query arguments. - * @return array Filtered query arguments. - */ - public function filter_on_this_day_query_limit( $args ) { - $args['posts_per_page'] = 3; - - return $args; - } - - /** - * Filters the On This Day query to include private posts. - * - * @param array $args Query arguments. - * @return array Filtered query arguments. - */ - public function filter_on_this_day_query_private_posts( $args ) { - $args['post_status'] = array( 'private' ); - - return $args; - } -} From 2b8adf7286ea02579a18cca6942e6ad415990289 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Fri, 20 Nov 2026 23:02:41 +0000 Subject: [PATCH 44/85] Tests: Cover `esc_url_raw()`. Verify that ampersands are not entity-encoded in database context and custom protocols are accepted. Developed in https://github.com/WordPress/wordpress-develop/pull/15360. Props devmuhib, huzaifaalmesbah, lancewillett. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65733 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/formatting/escUrl.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/phpunit/tests/formatting/escUrl.php b/tests/phpunit/tests/formatting/escUrl.php index e994ecdebd30b..6140a23eaca70 100644 --- a/tests/phpunit/tests/formatting/escUrl.php +++ b/tests/phpunit/tests/formatting/escUrl.php @@ -4,6 +4,7 @@ * @group formatting * * @covers ::esc_url + * @covers ::esc_url_raw */ class Tests_Formatting_EscUrl extends WP_UnitTestCase { @@ -311,4 +312,15 @@ public function test_ipv6_hosts() { $this->assertSame( '//[::FFFF::127.0.0.1]/?foo%5Bbar%5D=baz', esc_url( '//[::FFFF::127.0.0.1]/?foo[bar]=baz' ) ); $this->assertSame( 'http://[::FFFF::127.0.0.1]/?foo%5Bbar%5D=baz', esc_url( 'http://[::FFFF::127.0.0.1]/?foo[bar]=baz' ) ); } + + /** + * Tests that esc_url_raw() preserves raw ampersands and accepts custom protocols. + * + * @ticket 65819 + */ + public function test_esc_url_raw() { + $url = 'custom://example.com/?one=1&two=2'; + + $this->assertSame( $url, esc_url_raw( $url, array( 'custom' ) ) ); + } } From cb7c390e06c58be30c35802bf975c064e3ec8833 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Sat, 21 Nov 2026 23:38:43 +0000 Subject: [PATCH 45/85] Tests: Cover `format_for_editor()`. Verify that HTML entities are encoded but quotes are preserved, and the `format_for_editor` filter receives arguments and modifies the returned text. Developed in https://github.com/WordPress/wordpress-develop/pull/15361. Props devmuhib, huzaifaalmesbah, lancewillett. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65734 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/formatting/formatForEditor.php | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 tests/phpunit/tests/formatting/formatForEditor.php diff --git a/tests/phpunit/tests/formatting/formatForEditor.php b/tests/phpunit/tests/formatting/formatForEditor.php new file mode 100644 index 0000000000000..375409ca47c10 --- /dev/null +++ b/tests/phpunit/tests/formatting/formatForEditor.php @@ -0,0 +1,39 @@ +"Hello" & \'World\'

    '; + $expected = '<p>"Hello" & \'World\'</p>'; + + $this->assertSame( $expected, format_for_editor( $input ) ); + } + + /** + * Tests that the `format_for_editor` filter receives arguments and modifies the returned text. + * + * @ticket 65819 + */ + public function test_format_for_editor_filter() { + $filter = new MockAction(); + add_filter( 'format_for_editor', array( $filter, 'filter_append' ), 10, 2 ); + + $actual = format_for_editor( 'Hello World', 'tinymce' ); + + $this->assertSame( 1, $filter->get_call_count() ); + $this->assertSame( array( 'Hello World', 'tinymce' ), $filter->get_args()[0] ); + $this->assertSame( 'Hello World_append', $actual ); + } +} From 4038eb0470ec624e445b61ba40ce77ec0460a143 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 22 Nov 2026 13:00:55 +0000 Subject: [PATCH 46/85] Tests: Delete the network created by the network option cache tests. Remove the network and its metadata after the class finishes so later multisite tests see only their own networks. Developed in: https://github.com/WordPress/wordpress-develop/pull/16145 Props ekamran. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65735 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/option/wpPrimeNetworkOptionCaches.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/phpunit/tests/option/wpPrimeNetworkOptionCaches.php b/tests/phpunit/tests/option/wpPrimeNetworkOptionCaches.php index 90daf6aff2eb7..57720b97373b9 100644 --- a/tests/phpunit/tests/option/wpPrimeNetworkOptionCaches.php +++ b/tests/phpunit/tests/option/wpPrimeNetworkOptionCaches.php @@ -24,6 +24,15 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { } } + public static function wpTearDownAfterClass() { + global $wpdb; + + if ( is_multisite() ) { + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->sitemeta} WHERE site_id = %d", self::$different_network_id ) ); + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->site} WHERE id = %d", self::$different_network_id ) ); + } + } + /** * Tests that wp_prime_network_option_caches() primes multiple options. * From 78d8b11e7bb8cee08e3bee8012d8e476553e0666 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 22 Nov 2026 13:03:05 +0000 Subject: [PATCH 47/85] Tests: Isolate script module registration in the entity action tests. Register the default modules for the assertion and restore the previous script module and Interactivity API instances afterward. Developed in: https://github.com/WordPress/wordpress-develop/pull/16146 Props ekamran. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65736 602fd350-edb4-49c9-b593-d223f7449a82 --- .../registerCoreEntityActions.php | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/tests/phpunit/tests/entity-actions/registerCoreEntityActions.php b/tests/phpunit/tests/entity-actions/registerCoreEntityActions.php index b52fe5eab5abf..664e6ea73af2f 100644 --- a/tests/phpunit/tests/entity-actions/registerCoreEntityActions.php +++ b/tests/phpunit/tests/entity-actions/registerCoreEntityActions.php @@ -483,12 +483,31 @@ public function test_the_rest_route_serves_the_core_actions() { * @ticket 66343 */ public function test_the_script_modules_of_the_core_actions_are_registered() { + global $wp_script_modules, $wp_interactivity; + wp_set_current_user( self::$admin_id ); - foreach ( wp_get_all_registered_entity_action_modules()['postType'] as $post_type => $modules ) { - foreach ( $modules as $module ) { - $this->assertNotNull( wp_script_modules()->get_registered( $module ), "The $module module of $post_type is registered." ); + /* + * Register the default script modules in fresh instances, so the test neither + * depends on nor changes the shared ones. Registering them also marks the + * block library modules in the Interactivity API. + */ + $original_script_modules = $wp_script_modules; + $original_interactivity = $wp_interactivity; + $wp_script_modules = null; + $wp_interactivity = null; + + try { + wp_default_script_modules(); + + foreach ( wp_get_all_registered_entity_action_modules()['postType'] as $post_type => $modules ) { + foreach ( $modules as $module ) { + $this->assertNotNull( wp_script_modules()->get_registered( $module ), "The $module module of $post_type is registered." ); + } } + } finally { + $wp_script_modules = $original_script_modules; + $wp_interactivity = $original_interactivity; } } From 2fcad860670a74bdb50e4dce1d4d1ba6ad72cfd6 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 22 Nov 2026 13:04:47 +0000 Subject: [PATCH 48/85] Tests: Isolate stylesheet assertions in embed and Customizer tests. Reset `$wp_styles` after the embed tests so later tests can print emoji styles. Check the `customize-preview` stylesheet in the Customizer manager test that enqueues it. Developed in: https://github.com/WordPress/wordpress-develop/pull/16147, https://github.com/WordPress/wordpress-develop/pull/16148 Props ekamran. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65737 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/customize/manager.php | 1 + tests/phpunit/tests/customize/widgets.php | 1 - tests/phpunit/tests/oembed/template.php | 3 ++- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/phpunit/tests/customize/manager.php b/tests/phpunit/tests/customize/manager.php index 91d0157b2719a..9dbc3e685d589 100644 --- a/tests/phpunit/tests/customize/manager.php +++ b/tests/phpunit/tests/customize/manager.php @@ -925,6 +925,7 @@ public function test_customize_preview_init() { $this->assertSame( 10, has_filter( 'wp_headers', array( $wp_customize, 'filter_iframe_security_headers' ) ) ); $this->assertSame( 10, has_filter( 'wp_redirect', array( $wp_customize, 'add_state_query_params' ) ) ); $this->assertTrue( wp_script_is( 'customize-preview', 'enqueued' ) ); + $this->assertTrue( wp_style_is( 'customize-preview', 'enqueued' ) ); $this->assertSame( 10, has_action( 'wp_head', array( $wp_customize, 'customize_preview_loading_style' ) ) ); $this->assertSame( 20, has_action( 'wp_footer', array( $wp_customize, 'customize_preview_settings' ) ) ); diff --git a/tests/phpunit/tests/customize/widgets.php b/tests/phpunit/tests/customize/widgets.php index ff90ece0ba945..70695f6bd7da0 100644 --- a/tests/phpunit/tests/customize/widgets.php +++ b/tests/phpunit/tests/customize/widgets.php @@ -782,7 +782,6 @@ public function test_selective_refresh_init_without_theme_support() { public function test_customize_preview_enqueue() { $this->manager->widgets->customize_preview_enqueue(); $this->assertTrue( wp_script_is( 'customize-preview-widgets', 'enqueued' ) ); - $this->assertTrue( wp_style_is( 'customize-preview', 'enqueued' ) ); $script = wp_scripts()->registered['customize-preview-widgets']; $this->assertContains( 'customize-selective-refresh', $script->deps ); } diff --git a/tests/phpunit/tests/oembed/template.php b/tests/phpunit/tests/oembed/template.php index 3675191ddd020..9eb43213854e7 100644 --- a/tests/phpunit/tests/oembed/template.php +++ b/tests/phpunit/tests/oembed/template.php @@ -23,8 +23,9 @@ public function set_up() { public function tear_down() { parent::tear_down(); - global $wp_scripts; + global $wp_scripts, $wp_styles; $wp_scripts = null; + $wp_styles = null; } /** From 9fb84f4217713ce9fda3d2f02c652b0a9a1eac18 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Sun, 22 Nov 2026 15:51:49 +0000 Subject: [PATCH 49/85] Tests: Cover `user_can_richedit()`. Verify that the function returns `true` when the browser supports the visual editor and the user option is enabled, `false` otherwise. Developed in https://github.com/WordPress/wordpress-develop/pull/15359. Props devmuhib, huzaifaalmesbah, lancewillett. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65738 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/general/userCanRichedit.php | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 tests/phpunit/tests/general/userCanRichedit.php diff --git a/tests/phpunit/tests/general/userCanRichedit.php b/tests/phpunit/tests/general/userCanRichedit.php new file mode 100644 index 0000000000000..15403744c35fd --- /dev/null +++ b/tests/phpunit/tests/general/userCanRichedit.php @@ -0,0 +1,80 @@ +orig_is_chrome = isset( $is_chrome ) ? $is_chrome : null; + } + + /** + * Cleans up global rich edit cache and restores the browser flag. + */ + public function tear_down() { + global $wp_rich_edit, $is_chrome; + + $wp_rich_edit = null; + + if ( null !== $this->orig_is_chrome ) { + $is_chrome = $this->orig_is_chrome; + } else { + unset( $GLOBALS['is_chrome'] ); + } + + parent::tear_down(); + } + + /** + * Tests that user_can_richedit() returns true when the browser supports it and user option is enabled. + * + * @ticket 65819 + */ + public function test_user_can_richedit_enabled() { + global $wp_rich_edit, $is_chrome; + + $wp_rich_edit = null; + $is_chrome = true; + + $user_id = self::factory()->user->create(); + wp_set_current_user( $user_id ); + update_user_option( $user_id, 'rich_editing', 'true' ); + + $this->assertTrue( user_can_richedit() ); + } + + /** + * Tests that user_can_richedit() returns false when user option is disabled. + * + * @ticket 65819 + */ + public function test_user_can_richedit_disabled_by_user_option() { + global $wp_rich_edit, $is_chrome; + + $wp_rich_edit = null; + $is_chrome = true; + + $user_id = self::factory()->user->create(); + wp_set_current_user( $user_id ); + update_user_option( $user_id, 'rich_editing', 'false' ); + + $this->assertFalse( user_can_richedit() ); + } +} From 9d7b7c2e3aef21b32cea66cc842a0c10337d6908 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Greg=20Zi=C3=B3=C5=82kowski?= Date: Mon, 23 Nov 2026 09:38:01 +0000 Subject: [PATCH 50/85] Abilities API: Reject input that sanitization makes invalid `WP_Ability::prepare_input()` validated input before sanitizing it, but did not validate the sanitized value. Sanitization can turn accepted input into a value that breaks the schema. For example, whitespace or markup can become an empty string below `minLength`, and an infinite number can become `0` when cast to an integer with `minimum: 1`. Callbacks could then receive input that does not match the schema. When sanitization changes the value, `prepare_input()` now validates it again with `validate_input()`, including the `wp_ability_validate_input` filter. Unchanged input is validated only once. Validation errors are returned before the permission and execute callbacks run. Developed in https://github.com/WordPress/wordpress-develop/pull/15911. Follow-up to r65044, r65370. Reviewed by jorgefilipecosta. Props aryanjasala, avinashzala01, gziolo, jorgefilipecosta. Fixes #66665. git-svn-id: https://develop.svn.wordpress.org/trunk@65739 602fd350-edb4-49c9-b593-d223f7449a82 --- .../abilities-api/class-wp-ability.php | 27 ++++++- .../phpunit/tests/abilities-api/wpAbility.php | 80 ++++++++++++++++--- .../wpRestAbilitiesV1RunController.php | 12 +-- 3 files changed, 98 insertions(+), 21 deletions(-) diff --git a/src/wp-includes/abilities-api/class-wp-ability.php b/src/wp-includes/abilities-api/class-wp-ability.php index 6903f66d66a48..3e9dc2c18fdac 100644 --- a/src/wp-includes/abilities-api/class-wp-ability.php +++ b/src/wp-includes/abilities-api/class-wp-ability.php @@ -682,7 +682,11 @@ public function validate_input( $input = null ) { * override it. If default validation passed, the filter can add additional * validation checks and return a WP_Error if those checks fail. * + * During input preparation, this filter runs again with sanitized input if + * sanitization changes the value and completes without an error. + * * @since 7.1.0 + * @since 7.2.0 Also runs with sanitized input when sanitization changes the value. * * @param true|WP_Error $is_valid The validation result from default validation. * @param mixed $input The input data being validated. @@ -704,7 +708,8 @@ public function validate_input( $input = null ) { * Normalizes the input, validates it against the input schema, and then sanitizes * it. `execute()` passes the result to the permission and execute callbacks. * Validation runs before sanitization, so sanitization cannot make invalid input - * valid. + * valid. Changed input is validated again after sanitization, including the + * `wp_ability_validate_input` filter, before it reaches the callbacks. * * @since 7.2.0 * @@ -726,7 +731,25 @@ public function prepare_input( $input = null ) { return $is_valid; } - return $this->sanitize_input( $input ); + $sanitized = $this->sanitize_input( $input ); + if ( is_wp_error( $sanitized ) ) { + return $sanitized; + } + + /* + * Sanitization can make valid input invalid, for example by trimming a string + * below its `minLength` or casting an out-of-range number to a different integer. + * Validate changed input again so validation filters also evaluate the value + * callbacks will receive. + */ + if ( $sanitized !== $input ) { + $is_valid = $this->validate_input( $sanitized ); + if ( is_wp_error( $is_valid ) ) { + return $is_valid; + } + } + + return $sanitized; } /** diff --git a/tests/phpunit/tests/abilities-api/wpAbility.php b/tests/phpunit/tests/abilities-api/wpAbility.php index 181c68d54ae15..d779de4cc37b7 100644 --- a/tests/phpunit/tests/abilities-api/wpAbility.php +++ b/tests/phpunit/tests/abilities-api/wpAbility.php @@ -2362,7 +2362,7 @@ public function test_prepare_input( array $schema, $input, $expected ): void { public static function data_input_coercion(): array { return array_intersect_key( self::data_input_is_coerced(), - array_flip( array( 'integer number', 'stdClass object input', 'default', 'text-field format' ) ) + array_flip( array( 'integer number', 'stdClass object input', 'default', 'text-field format', 'top-level string unchanged' ) ) ); } @@ -2420,14 +2420,18 @@ static function ( $name, $value ) use ( &$seen ) { $this->assertSame( 0, $ability->execute( $input ) ); $this->assertSame( $input, $seen['invoked'] ); - $this->assertSame( empty( $schema ) ? array() : array( $normalized ), $seen['validation'], 'Validate the normalized input exactly once.' ); + $expected_validation = array( $normalized ); + if ( $expected !== $normalized ) { + $expected_validation[] = $expected; + } + $this->assertSame( $expected_validation, $seen['validation'], 'Validate normalized input, then sanitized input only when it changes.' ); $this->assertSame( $expected, $seen['permission'] ); $this->assertSame( $expected, $seen['before'] ); $this->assertSame( $expected, $seen['execute'] ); } /** - * Provides top-level and nested collisions introduced by sanitization. + * Provides input that sanitization rejects or makes invalid. * * @return array */ @@ -2449,16 +2453,43 @@ public static function data_input_sanitization_errors(): array { 'ids' => '1,01', ); + $text = array( + 'type' => 'object', + 'properties' => array( + 'title' => array( + 'type' => 'string', + 'format' => 'text-field', + 'minLength' => 1, + ), + ), + ); + return array( - 'top-level array' => array( $unique, array( '1', '01' ), 'input' ), - 'nested object' => array( $object, $input, 'input[ids]' ), - 'object in list' => array( + 'top-level array' => array( $unique, array( '1', '01' ), 'input has duplicate items.' ), + 'nested object' => array( $object, $input, 'input[ids] has duplicate items.' ), + 'object in list' => array( array( 'type' => 'array', 'items' => $object, ), array( $input ), - 'input[0][ids]', + 'input[0][ids] has duplicate items.', + ), + 'whitespace below minLength' => array( $text, array( 'title' => ' ' ), 'input[title] must be at least 1 character long.' ), + 'markup below minLength' => array( $text, array( 'title' => '' ), 'input[title] must be at least 1 character long.' ), + // An out-of-range numeric string is cast to `PHP_INT_MAX`, which is not a multiple of 10. + 'integer cast breaks multipleOf' => array( + array( + 'type' => 'object', + 'properties' => array( + 'count' => array( + 'type' => 'integer', + 'multipleOf' => 10, + ), + ), + ), + array( 'count' => '1e19' ), + 'input[count] must be a multiple of 10.', ), ); } @@ -2469,11 +2500,11 @@ public static function data_input_sanitization_errors(): array { * @ticket 66383 * @dataProvider data_input_sanitization_errors * - * @param array $schema Input schema. - * @param mixed $input Input accepted by validation but rejected by sanitization. - * @param string $path Path of the duplicate items in the error message. + * @param array $schema Input schema. + * @param mixed $input Input accepted by validation but rejected by sanitization. + * @param string $message Expected error message fragment. */ - public function test_input_sanitization_errors( array $schema, $input, string $path ): void { + public function test_input_sanitization_errors( array $schema, $input, string $message ): void { $args = self::$test_ability_properties; $args['input_schema'] = $schema; $unexpected_callback = function () { @@ -2491,8 +2522,7 @@ public function test_input_sanitization_errors( array $schema, $input, string $p $error = $ability->prepare_input( $input ); $this->assertWPError( $error ); $this->assertSame( 'ability_invalid_input', $error->get_error_code() ); - $this->assertStringContainsString( $path . ' has duplicate items.', $error->get_error_message() ); - // Keep assertEquals() because the objects are intentionally compared by value. + $this->assertStringContainsString( $message, $error->get_error_message() ); $this->assertEquals( $error, $ability->execute( $input ), 'Execution should propagate the sanitization error.' ); } @@ -2551,6 +2581,30 @@ public function test_sanitization_respects_input_validation(): void { $this->assertSame( array( array( 'count' => 10 ) ), $seen ); } + /** + * Validation filters can reject the sanitized value before callbacks receive it. + * + * @ticket 66665 + */ + public function test_validation_filter_can_reject_sanitized_input(): void { + $args = self::$test_ability_properties; + $args['input_schema'] = array( 'type' => 'integer' ); + $ability = new WP_Ability( self::$test_ability_name, $args ); + $error = new WP_Error( 'sanitized_input_rejected' ); + $seen = array(); + $validate = static function ( $valid, $input ) use ( &$seen, $error ) { + $seen[] = $input; + return is_int( $input ) ? $error : $valid; + }; + + add_filter( 'wp_ability_validate_input', $validate, 10, 2 ); + $result = $ability->execute( '2' ); + remove_filter( 'wp_ability_validate_input', $validate ); + + $this->assertSame( array( '2', 2 ), $seen, 'The filter should receive both raw and sanitized input.' ); + $this->assertSame( $error, $result, 'Execution should propagate the filter rejection unchanged.' ); + } + /** * Returns the test ability properties with required capabilities and no permission callback. * diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesV1RunController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesV1RunController.php index 9eb1b4910edcb..0d3f14c01423c 100644 --- a/tests/phpunit/tests/rest-api/wpRestAbilitiesV1RunController.php +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesV1RunController.php @@ -2193,12 +2193,12 @@ public static function data_input_prepared_once(): array { public function test_input_is_prepared_once_before_permission_check( ?array $input ): void { $calls = new stdClass(); - $calls->validate = 0; + $calls->normalize = 0; add_filter( - 'wp_ability_validate_input', - static function ( $is_valid ) use ( $calls ) { - ++$calls->validate; - return $is_valid; + 'wp_ability_normalize_input', + static function ( $value ) use ( $calls ) { + ++$calls->normalize; + return $value; } ); @@ -2216,7 +2216,7 @@ static function ( $is_valid ) use ( $calls ) { ), ), 'permission_callback' => static function ( $value ) use ( $calls ) { - $calls->permission ??= array( $value, $calls->validate ); + $calls->permission ??= array( $value, $calls->normalize ); return true; }, 'execute_callback' => static function ( $value ) { From d09b3156f3b8d110e5da4a1ed3e1893fcbf20bb8 Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Mon, 23 Nov 2026 10:51:26 +0000 Subject: [PATCH 51/85] Application Passwords: Send the created notification in the user's locale. This ensures the receipient sees the notification in their chosen language when a password is added by a user that uses a different language. Developed in https://github.com/WordPress/wordpress-develop/pull/16065 Props mukesh27, peterwilsoncc. Fixes #63927 git-svn-id: https://develop.svn.wordpress.org/trunk@65740 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/functions.php | 6 +++++ ...ApplicationPasswordCreatedNotification.php | 23 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index d9927baffbcd5..59d91815d122e 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -9641,6 +9641,8 @@ function wp_application_password_created_notification( $user_id, $new_item ) { return; } + $switched_locale = switch_to_user_locale( $user->ID ); + /* translators: Do not translate USERNAME, APPLICATION_PASSWORD_NAME, ADMIN_EMAIL, SITENAME, SITEURL, EMAIL: those are placeholders. */ $application_password_create_text = __( 'Hi ###USERNAME###, @@ -9724,4 +9726,8 @@ function wp_application_password_created_notification( $user_id, $new_item ) { $email['message'], $email['headers'] ); + + if ( $switched_locale ) { + restore_previous_locale(); + } } diff --git a/tests/phpunit/tests/functions/wpApplicationPasswordCreatedNotification.php b/tests/phpunit/tests/functions/wpApplicationPasswordCreatedNotification.php index fceb10bd97c62..83888d9c74a1e 100644 --- a/tests/phpunit/tests/functions/wpApplicationPasswordCreatedNotification.php +++ b/tests/phpunit/tests/functions/wpApplicationPasswordCreatedNotification.php @@ -202,4 +202,27 @@ public function test_does_not_send_email_when_user_email_is_invalid() { $this->assertEmpty( tests_retrieve_phpmailer_instance()->mock_sent ); } + + /** + * Tests that the email is built in the recipient's locale, and the locale is restored after. + * + * @ticket 63927 + */ + public function test_email_uses_the_user_locale() { + update_user_meta( self::$user->ID, 'locale', 'de_DE' ); + + $email_locale = null; + add_filter( + 'wp_application_password_created_email', + static function ( $email ) use ( &$email_locale ) { + $email_locale = get_locale(); + return $email; + } + ); + + WP_Application_Passwords::create_new_application_password( self::$user->ID, array( 'name' => 'My App' ) ); + + $this->assertSame( 'de_DE', $email_locale, 'The email should be built in the user locale.' ); + $this->assertFalse( is_locale_switched(), 'The previous locale should be restored after the email is sent.' ); + } } From 89cc20982d5e2b431fd0e9b3e8382735008b1eee Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 23 Nov 2026 13:54:03 +0000 Subject: [PATCH 52/85] Tests: Reset the script queue after Customizer manager tests. The preview initialization test enqueues `customize-selective-refresh`. Clear `$wp_scripts` in `tear_down()` so the selective refresh test starts with its script unenqueued. Developed in: https://github.com/WordPress/wordpress-develop/pull/16158 Props ekamran. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65741 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/customize/manager.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/phpunit/tests/customize/manager.php b/tests/phpunit/tests/customize/manager.php index 9dbc3e685d589..0e153b13da24d 100644 --- a/tests/phpunit/tests/customize/manager.php +++ b/tests/phpunit/tests/customize/manager.php @@ -86,6 +86,7 @@ public function tear_down() { $this->manager = null; unset( $GLOBALS['wp_customize'] ); + unset( $GLOBALS['wp_scripts'] ); $_REQUEST = array(); $GLOBALS['_wp_theme_features'] = self::$theme_features; From 13c220976d01ad0c807ba17555fc41de337e14d1 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 23 Nov 2026 15:10:09 +0000 Subject: [PATCH 53/85] Build/Test Tools: Run theme management E2E tests in parallel. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep theme activation in the serial project. Use a shared `UPGRADER` lock so plugin and theme uploads cannot delete each other’s unpacked files. Developed in: https://github.com/WordPress/wordpress-develop/pull/16127 Follow-up to r65723. Props adrianmoldovanwp. See #66392. git-svn-id: https://develop.svn.wordpress.org/trunk@65742 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/e2e/README.md | 2 + tests/e2e/playwright.config.js | 2 +- tests/e2e/specs/plugins.test.js | 4 +- tests/e2e/specs/theme-activation.test.js | 91 ++++++++++++++++++++++++ tests/e2e/specs/themes.test.js | 90 +++-------------------- tests/e2e/utils/locks.js | 1 + tests/e2e/utils/themes.js | 44 ++++++++++++ 7 files changed, 152 insertions(+), 82 deletions(-) create mode 100644 tests/e2e/specs/theme-activation.test.js create mode 100644 tests/e2e/utils/themes.js diff --git a/tests/e2e/README.md b/tests/e2e/README.md index def7aec52312d..b0bf60e2ebafa 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -82,6 +82,8 @@ A form save writes every field on the page, not only the field that the test cha WordPress reads the full `active_plugins` list, changes it, and writes the full list back. If two tests turn plugins on or off at the same time, one change can be lost. A spec in `parallel` that installs, deletes, activates or deactivates a plugin must hold `PLUGINS`. +Before WordPress unzips an uploaded plugin or theme, it deletes everything in `wp-content/upgrade/`. This can delete the files of an upload in another test. A spec in `parallel` that uploads a plugin or theme zip must hold `UPGRADER`. + ## Logged-out pages Most specs run logged in as the admin user. There are two ways to run a test logged out: diff --git a/tests/e2e/playwright.config.js b/tests/e2e/playwright.config.js index 0f81e48df84cb..5c39af72c3fc5 100644 --- a/tests/e2e/playwright.config.js +++ b/tests/e2e/playwright.config.js @@ -19,7 +19,7 @@ const SERIAL_SPECS = [ 'install.test.js', 'maintenance-mode.test.js', 'gutenberg-plugin.test.js', - 'themes.test.js', + 'theme-activation.test.js', // This deletes all posts, including other workers' content. 'empty-trash.test.js', ]; diff --git a/tests/e2e/specs/plugins.test.js b/tests/e2e/specs/plugins.test.js index c32b0648055d2..51f91d5b3c194 100644 --- a/tests/e2e/specs/plugins.test.js +++ b/tests/e2e/specs/plugins.test.js @@ -6,7 +6,7 @@ import { test, expect } from '@wordpress/e2e-test-utils-playwright'; /** * Internal dependencies */ -import { PLUGINS } from '../utils/locks'; +import { PLUGINS, UPGRADER } from '../utils/locks'; const plugin = 'e2e-test-plugin/e2e-test-plugin'; const pluginName = 'E2E Test Plugin'; @@ -54,7 +54,7 @@ async function deletePlugin( requestUtils ) { } ); } -test.describe( 'Plugin management', { lock: PLUGINS }, () => { +test.describe( 'Plugin management', { lock: [ PLUGINS, UPGRADER ] }, () => { test.beforeEach( async ( { requestUtils } ) => { // The fixture slug requires an environment not shared with another test run. // An interrupted run can leave the fixture plugin installed. diff --git a/tests/e2e/specs/theme-activation.test.js b/tests/e2e/specs/theme-activation.test.js new file mode 100644 index 0000000000000..d63d7f30ee9d0 --- /dev/null +++ b/tests/e2e/specs/theme-activation.test.js @@ -0,0 +1,91 @@ +/** + * WordPress dependencies + */ +import { test, expect } from '@wordpress/e2e-test-utils-playwright'; + +/** + * Internal dependencies + */ +import { + deleteTheme, + themeName, + themeSlug, + uploadTheme, +} from '../utils/themes'; + +test.describe( 'Theme activation', () => { + let previousTheme; + + test.beforeEach( async ( { admin, page, requestUtils } ) => { + previousTheme = undefined; + // The fixture slug requires an environment not shared with another test run. + // An interrupted run can leave the fixture theme installed. + await deleteTheme( requestUtils ); + const themes = await requestUtils.rest( { path: '/wp/v2/themes' } ); + expect( themes.map( ( theme ) => theme.stylesheet ) ).not.toContain( + themeSlug + ); + previousTheme = themes.find( + ( theme ) => theme.status === 'active' + ).stylesheet; + await uploadTheme( admin, page, 'e2e-test-theme.zip' ); + await expect( + page.getByText( 'Theme installed successfully.', { exact: true } ) + ).toBeVisible(); + } ); + + test.afterEach( async ( { requestUtils } ) => { + if ( ! previousTheme ) { + return; + } + await requestUtils.activateTheme( previousTheme ); + await deleteTheme( requestUtils ); + const remainingThemes = await requestUtils.rest( { + path: '/wp/v2/themes', + } ); + expect( + remainingThemes.map( ( theme ) => theme.stylesheet ) + ).not.toContain( themeSlug ); + expect( + remainingThemes.find( ( theme ) => theme.status === 'active' ) + .stylesheet + ).toBe( previousTheme ); + } ); + + test( 'activates an installed theme from its card', async ( { + admin, + page, + requestUtils, + } ) => { + await admin.visitAdminPage( 'themes.php' ); + await page + .getByRole( 'button', { + name: `View Theme Details for ${ themeName }`, + exact: true, + } ) + .hover(); + await page + .getByRole( 'link', { + name: `Activate ${ themeName }`, + exact: true, + } ) + .click(); + await expect( + page.getByRole( 'heading', { + name: `Active: ${ themeName }`, + exact: true, + } ) + ).toBeVisible(); + await page.reload(); + await expect( + page.getByRole( 'heading', { + name: `Active: ${ themeName }`, + exact: true, + } ) + ).toBeVisible(); + const themes = await requestUtils.rest( { path: '/wp/v2/themes' } ); + expect( + themes.find( ( theme ) => theme.status === 'active' ).stylesheet + ).toBe( themeSlug ); + } ); +} ); diff --git a/tests/e2e/specs/themes.test.js b/tests/e2e/specs/themes.test.js index ffd2744a9c44a..9ec52f1bc8d9b 100644 --- a/tests/e2e/specs/themes.test.js +++ b/tests/e2e/specs/themes.test.js @@ -8,48 +8,21 @@ import { randomUUID } from 'node:crypto'; */ import { test, expect } from '@wordpress/e2e-test-utils-playwright'; -const themeSlug = 'e2e-test-theme'; -const themeName = 'E2E Test Theme'; - -async function uploadTheme( admin, page, fixture ) { - await admin.visitAdminPage( 'theme-install.php' ); - await page - .getByRole( 'button', { name: 'Upload Theme', exact: true } ) - .click(); - await page - .locator( '#themezip' ) - .setInputFiles( `tests/e2e/assets/${ fixture }` ); - await page - .getByRole( 'button', { name: 'Install Now', exact: true } ) - .click(); -} - -async function deleteTheme( requestUtils ) { - const themes = await requestUtils.rest( { path: '/wp/v2/themes' } ); - if ( ! themes.some( ( theme ) => theme.stylesheet === themeSlug ) ) { - return; - } - const themesResponse = await requestUtils.request.get( - 'wp-admin/themes.php' - ); - const html = await themesResponse.text(); - await themesResponse.dispose(); - const deleteQuery = html.match( - `action=delete&stylesheet=${ themeSlug }&_wpnonce=[a-z0-9]+` - ); - expect( deleteQuery ).not.toBeNull(); - const response = await requestUtils.request.get( - `wp-admin/themes.php?${ deleteQuery[ 0 ].replace( /&/g, '&' ) }` - ); - expect( response.ok() ).toBe( true ); - await response.dispose(); -} +/** + * Internal dependencies + */ +import { UPGRADER } from '../utils/locks'; +import { + deleteTheme, + themeName, + themeSlug, + uploadTheme, +} from '../utils/themes'; -test.describe( 'Theme management', () => { +test.describe( 'Theme management', { lock: UPGRADER }, () => { let previousTheme; test.beforeEach( async ( { admin, page, requestUtils } ) => { - previousTheme = undefined; // The fixture slug requires an environment not shared with another test run. // An interrupted run can leave the fixture theme installed. await deleteTheme( requestUtils ); @@ -67,10 +40,6 @@ test.describe( 'Theme management', () => { } ); test.afterEach( async ( { requestUtils } ) => { - if ( ! previousTheme ) { - return; - } - await requestUtils.activateTheme( previousTheme ); await deleteTheme( requestUtils ); const remainingThemes = await requestUtils.rest( { path: '/wp/v2/themes', @@ -84,43 +53,6 @@ test.describe( 'Theme management', () => { ).toBe( previousTheme ); } ); - test( 'activates an installed theme from its card', async ( { - admin, - page, - requestUtils, - } ) => { - await admin.visitAdminPage( 'themes.php' ); - await page - .getByRole( 'button', { - name: `View Theme Details for ${ themeName }`, - exact: true, - } ) - .hover(); - await page - .getByRole( 'link', { - name: `Activate ${ themeName }`, - exact: true, - } ) - .click(); - await expect( - page.getByRole( 'heading', { - name: `Active: ${ themeName }`, - exact: true, - } ) - ).toBeVisible(); - await page.reload(); - await expect( - page.getByRole( 'heading', { - name: `Active: ${ themeName }`, - exact: true, - } ) - ).toBeVisible(); - const themes = await requestUtils.rest( { path: '/wp/v2/themes' } ); - expect( - themes.find( ( theme ) => theme.status === 'active' ).stylesheet - ).toBe( themeSlug ); - } ); - test( 'deletes an inactive theme from its details', async ( { admin, page, diff --git a/tests/e2e/utils/locks.js b/tests/e2e/utils/locks.js index 2cc6f1b1257fc..039141eda4ee9 100644 --- a/tests/e2e/utils/locks.js +++ b/tests/e2e/utils/locks.js @@ -2,3 +2,4 @@ export const GENERAL_SETTINGS = 'general-settings'; export const NAV_MENU_LOCATIONS = 'nav-menu-locations'; export const PLUGINS = 'plugins'; export const PRIVACY_POLICY_PAGE = 'privacy-policy-page'; +export const UPGRADER = 'upgrader'; diff --git a/tests/e2e/utils/themes.js b/tests/e2e/utils/themes.js new file mode 100644 index 0000000000000..c908e66ca2b72 --- /dev/null +++ b/tests/e2e/utils/themes.js @@ -0,0 +1,44 @@ +/** + * WordPress dependencies + */ +import { expect } from '@wordpress/e2e-test-utils-playwright'; + +/** + * The fixture theme in `tests/e2e/assets/e2e-test-theme*.zip`. + */ +export const themeSlug = 'e2e-test-theme'; +export const themeName = 'E2E Test Theme'; + +export async function uploadTheme( admin, page, fixture ) { + await admin.visitAdminPage( 'theme-install.php' ); + await page + .getByRole( 'button', { name: 'Upload Theme', exact: true } ) + .click(); + await page + .locator( '#themezip' ) + .setInputFiles( `tests/e2e/assets/${ fixture }` ); + await page + .getByRole( 'button', { name: 'Install Now', exact: true } ) + .click(); +} + +export async function deleteTheme( requestUtils ) { + const themes = await requestUtils.rest( { path: '/wp/v2/themes' } ); + if ( ! themes.some( ( theme ) => theme.stylesheet === themeSlug ) ) { + return; + } + const themesResponse = await requestUtils.request.get( + 'wp-admin/themes.php' + ); + const html = await themesResponse.text(); + await themesResponse.dispose(); + const deleteQuery = html.match( + `action=delete&stylesheet=${ themeSlug }&_wpnonce=[a-z0-9]+` + ); + expect( deleteQuery ).not.toBeNull(); + const response = await requestUtils.request.get( + `wp-admin/themes.php?${ deleteQuery[ 0 ].replace( /&/g, '&' ) }` + ); + expect( response.ok() ).toBe( true ); + await response.dispose(); +} From 3d4146d265bf87cd33a780724c5e0c0e451eb1ba Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 23 Nov 2026 16:56:07 +0000 Subject: [PATCH 54/85] Build/Test Tools: Run the trash end-to-end tests in parallel. Give the Empty Trash test its own post type and restore only the post created by the current test. Developed in: https://github.com/WordPress/wordpress-develop/pull/16175 Props adrianmoldovanwp. See #66392. git-svn-id: https://develop.svn.wordpress.org/trunk@65743 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/e2e/playwright.config.js | 2 - .../empty-trash-restore-trashed-posts.test.js | 37 ++++++ tests/e2e/specs/empty-trash.test.js | 116 +++++++++++------- 3 files changed, 110 insertions(+), 45 deletions(-) diff --git a/tests/e2e/playwright.config.js b/tests/e2e/playwright.config.js index 5c39af72c3fc5..76c4c7c236c7a 100644 --- a/tests/e2e/playwright.config.js +++ b/tests/e2e/playwright.config.js @@ -20,8 +20,6 @@ const SERIAL_SPECS = [ 'maintenance-mode.test.js', 'gutenberg-plugin.test.js', 'theme-activation.test.js', - // This deletes all posts, including other workers' content. - 'empty-trash.test.js', ]; const config = defineConfig( { diff --git a/tests/e2e/specs/empty-trash-restore-trashed-posts.test.js b/tests/e2e/specs/empty-trash-restore-trashed-posts.test.js index 621f3a76fd62d..8c74bcf694c61 100644 --- a/tests/e2e/specs/empty-trash-restore-trashed-posts.test.js +++ b/tests/e2e/specs/empty-trash-restore-trashed-posts.test.js @@ -108,3 +108,40 @@ test( 'bulk trashes only the selected posts', async ( { } ); expect( control.status ).toBe( 'publish' ); } ); + +test( 'Restore trash post', async ( { + page, + admin, + postFactory, + requestUtils, +} ) => { + const title = postFactory.uniqueTitle( 'Restore trash' ); + const post = await postFactory.create( { title, status: 'publish' } ); + await requestUtils.rest( { + method: 'DELETE', + path: `/wp/v2/posts/${ post.id }`, + } ); + + await admin.visitAdminPage( + 'edit.php', + new URLSearchParams( { post_status: 'trash', s: title } ).toString() + ); + const row = postRow( page, post.id ); + await row.getByRole( 'cell' ).filter( { hasText: title } ).hover(); + await row + .getByRole( 'link', { + name: `Restore “${ title }” from the Trash`, + exact: true, + } ) + .click(); + + await expect( adminNotice( page ) ).toContainText( + '1 post restored from the Trash.' + ); + await expect( row ).toHaveCount( 0 ); + const restoredPost = await requestUtils.rest( { + path: `/wp/v2/posts/${ post.id }`, + params: { context: 'edit' }, + } ); + expect( restoredPost.status ).toBe( 'draft' ); +} ); diff --git a/tests/e2e/specs/empty-trash.test.js b/tests/e2e/specs/empty-trash.test.js index 7454ed082a4eb..d23d249495910 100644 --- a/tests/e2e/specs/empty-trash.test.js +++ b/tests/e2e/specs/empty-trash.test.js @@ -1,56 +1,86 @@ +/** + * External dependencies + */ +import { randomUUID } from 'node:crypto'; + /** * Internal dependencies */ import { test, expect } from '../fixtures'; import { adminNotice } from '../utils/admin'; -const POST_TITLE = 'Test Title'; - test.describe( 'Empty Trash', () => { - test.beforeEach( async ( { requestUtils } ) => { - await requestUtils.deleteAllPosts(); - }); - - test('Empty Trash', async ({ admin, editor, page }) => { - await admin.createNewPost( { title: POST_TITLE } ); - await editor.publishPost(); - - await admin.visitAdminPage( '/edit.php' ); - - const listTable = page.getByRole( 'table', { name: 'Table ordered by' } ); - await expect( listTable ).toBeVisible(); - - // Move post to trash - await listTable.getByRole( 'link', { name: POST_TITLE, exact: true } ).hover(); - await listTable.getByRole( 'link', { name: `Move “${POST_TITLE}” to the Trash` } ).click(); - - // Empty trash - await page.getByRole( 'link', { name: 'Trash' } ).click(); - await page.getByRole( 'button', { name: 'Empty Trash' } ).first().click(); - - await expect( adminNotice( page ) ).toContainText( '1 post permanently deleted.' ); - } ); - - test('Restore trash post', async ( { admin, editor, page }) => { - await admin.createNewPost( { title: POST_TITLE } ); - await editor.publishPost(); - - await admin.visitAdminPage( '/edit.php' ); - - const listTable = page.getByRole( 'table', { name: 'Table ordered by' } ); - await expect( listTable ).toBeVisible(); + test( 'Empty Trash', async ( { + admin, + muPlugin, + page, + requestUtils, + } ) => { + // Empty Trash deletes every trashed post of one post type, so this test owns its type. + // Post type names have at most 20 characters. + const postType = `e2e_${ randomUUID().replaceAll( '-', '' ).slice( 0, 16 ) }`; + // Other workers share the site, so only requests that name this type register it. + await muPlugin.write( + 'empty-trash-post-type.php', + ` 'Empty Trash test', + 'show_ui' => true, + 'show_in_menu' => false, + 'show_in_rest' => true, + 'rewrite' => false, + ) + ); + } + ); + }` + ); - // Move post to trash - await listTable.getByRole( 'link', { name: POST_TITLE, exact: true } ).hover(); - await listTable.getByRole( 'link', { name: `Move “${POST_TITLE}” to the Trash` } ).click(); + const post = await requestUtils.rest( { + method: 'POST', + path: `/wp/v2/${ postType }`, + data: { title: 'Empty Trash test', status: 'publish' }, + } ); - await page.getByRole( 'link', { name: 'Trash' } ).click(); + try { + await requestUtils.rest( { + method: 'DELETE', + path: `/wp/v2/${ postType }/${ post.id }`, + } ); - // Remove post from trash. - await listTable.getByRole( 'cell' ).filter( { hasText: POST_TITLE } ).hover(); - await listTable.getByRole( 'link', { name: `Restore “${POST_TITLE}” from the Trash` } ).click(); + await admin.visitAdminPage( + 'edit.php', + new URLSearchParams( { + post_type: postType, + post_status: 'trash', + } ).toString() + ); + await page + .getByRole( 'button', { name: 'Empty Trash' } ) + .first() + .click(); - // Expect for success message for restored post. - await expect( adminNotice( page ) ).toContainText( '1 post restored from the Trash.' ); + await expect( adminNotice( page ) ).toContainText( + '1 post permanently deleted.' + ); + } finally { + await requestUtils + .rest( { + method: 'DELETE', + path: `/wp/v2/${ postType }/${ post.id }`, + params: { force: true }, + } ) + .catch( ( error ) => { + if ( error.data?.status !== 404 ) { + throw error; + } + } ); + } } ); } ); From 8d1741e0e00a8b78c2c16925571f6b20bef2e599 Mon Sep 17 00:00:00 2001 From: Dennis Snell Date: Mon, 23 Nov 2026 18:49:28 +0000 Subject: [PATCH 55/85] Mail: Guard against line feeds in untrusted header sources. Email-sending functions should ensure that header fields are guarded against untrusted inputs, and that they should not bleed into new headers or into the email body. This patch adds these guards by removing line feeds in the inputs to these header values. This will result in some minor corruption of already-corrupt data, but will prevent unwanted structural injetions into the outbound emails. Developed in: https://github.com/WordPress/wordpress-develop/pull/16113 Discussed in: https://core.trac.wordpress.org/ticket/66769 Props dmsnell, sirlouen, westonruter. Fixes #66769. git-svn-id: https://develop.svn.wordpress.org/trunk@65744 602fd350-edb4-49c9-b593-d223f7449a82 --- phpcs.xml.dist | 2 + src/wp-includes/pluggable.php | 70 ++++-- tests/phpunit/tests/comment.php | 381 ++++++++++++++++++++++++++++++++ 3 files changed, 431 insertions(+), 22 deletions(-) diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 9f15c0c3670d6..469f013a3a23a 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -194,6 +194,8 @@ + + diff --git a/src/wp-includes/pluggable.php b/src/wp-includes/pluggable.php index 0aaeabbb3b9c0..94aab93a98455 100644 --- a/src/wp-includes/pluggable.php +++ b/src/wp-includes/pluggable.php @@ -1841,17 +1841,30 @@ function wp_notify_postauthor( $comment_id, $deprecated = null ) { $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); $comment_content = wp_specialchars_decode( $comment->comment_content ); + /* + * Line breaks in the comment author fields would end the header or line they + * are placed in, letting the comment author add email headers or lines of their own. + */ + $isolate_header_value = static function ( $value ): string { + $is_stringy = is_string( $value ) || ( is_object( $value ) && method_exists( $value, '__toString' ) ); + $value = $is_stringy ? (string) $value : ''; + return trim( (string) preg_replace( '/[\r\n]+/', ' ', $value ) ); + }; + $comment_author = $isolate_header_value( $comment->comment_author ); + $comment_author_email = $isolate_header_value( $comment->comment_author_email ); + $comment_author_url = $isolate_header_value( $comment->comment_author_url ); + $wp_email = 'wordpress@' . preg_replace( '#^www\.#', '', wp_parse_url( network_home_url(), PHP_URL_HOST ) ); - if ( '' === $comment->comment_author ) { + if ( '' === $comment_author ) { $from = "From: \"$blogname\" <$wp_email>"; - if ( '' !== $comment->comment_author_email ) { - $reply_to = "Reply-To: $comment->comment_author_email"; + if ( is_email( $comment_author_email ) ) { + $reply_to = "Reply-To: $comment_author_email"; } } else { - $from = "From: \"$comment->comment_author\" <$wp_email>"; - if ( '' !== $comment->comment_author_email ) { - $reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>"; + $from = "From: \"$comment_author\" <$wp_email>"; + if ( is_email( $comment_author_email ) ) { + $reply_to = "Reply-To: \"$comment_author_email\" <$comment_author_email>"; } } @@ -1886,9 +1899,9 @@ function wp_notify_postauthor( $comment_id, $deprecated = null ) { /* translators: %s: Post title. */ $notify_message = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n"; /* translators: 1: Trackback/pingback website name, 2: Website IP address, 3: Website hostname. */ - $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; + $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; /* translators: %s: Trackback/pingback/comment author URL. */ - $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n"; + $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; /* translators: %s: Comment text. */ $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n"; $notify_message .= __( 'You can see all trackbacks on this post here:' ) . "\r\n"; @@ -1900,9 +1913,9 @@ function wp_notify_postauthor( $comment_id, $deprecated = null ) { /* translators: %s: Post title. */ $notify_message = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n"; /* translators: 1: Trackback/pingback website name, 2: Website IP address, 3: Website hostname. */ - $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; + $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; /* translators: %s: Trackback/pingback/comment author URL. */ - $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n"; + $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; /* translators: %s: Comment text. */ $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n"; $notify_message .= __( 'You can see all pingbacks on this post here:' ) . "\r\n"; @@ -1914,9 +1927,9 @@ function wp_notify_postauthor( $comment_id, $deprecated = null ) { /* translators: %s: Post title. */ $notify_message = sprintf( __( 'New note on your post "%s"' ), $post->post_title ) . "\r\n"; /* translators: 1: Note author's name, 2: Note author's IP address, 3: Note author's hostname. */ - $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; + $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; /* translators: %s: Note author email. */ - $notify_message .= sprintf( __( 'Email: %s' ), $comment->comment_author_email ) . "\r\n"; + $notify_message .= sprintf( __( 'Email: %s' ), $comment_author_email ) . "\r\n"; /* translators: %s: Note text. */ $notify_message .= sprintf( __( 'Note: %s' ), "\r\n" . ( empty( $comment_content ) ? __( 'resolved/reopened' ) : $comment_content ) ) . "\r\n\r\n"; $notify_message .= __( 'You can see all notes on this post here:' ) . "\r\n"; @@ -1928,11 +1941,11 @@ function wp_notify_postauthor( $comment_id, $deprecated = null ) { /* translators: %s: Post title. */ $notify_message = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n"; /* translators: 1: Comment author's name, 2: Comment author's IP address, 3: Comment author's hostname. */ - $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; + $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; /* translators: %s: Comment author email. */ - $notify_message .= sprintf( __( 'Email: %s' ), $comment->comment_author_email ) . "\r\n"; + $notify_message .= sprintf( __( 'Email: %s' ), $comment_author_email ) . "\r\n"; /* translators: %s: Trackback/pingback/comment author URL. */ - $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n"; + $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; if ( $comment->comment_parent && user_can( $post->post_author, 'edit_comment', $comment->comment_parent ) ) { /* translators: Comment moderation. %s: Parent comment edit URL. */ @@ -2056,6 +2069,19 @@ function wp_notify_moderator( $comment_id ) { $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); $comment_content = wp_specialchars_decode( $comment->comment_content ); + /* + * Line breaks in the comment author fields would end the header or line they + * are placed in, letting the comment author add email headers or lines of their own. + */ + $isolate_header_value = static function ( $value ): string { + $is_stringy = is_string( $value ) || ( is_object( $value ) && method_exists( $value, '__toString' ) ); + $value = $is_stringy ? (string) $value : ''; + return trim( (string) preg_replace( '/[\r\n]+/', ' ', $value ) ); + }; + $comment_author = $isolate_header_value( $comment->comment_author ); + $comment_author_email = $isolate_header_value( $comment->comment_author_email ); + $comment_author_url = $isolate_header_value( $comment->comment_author_url ); + $message_headers = ''; /** @@ -2093,9 +2119,9 @@ function wp_notify_moderator( $comment_id ) { $notify_message = sprintf( __( 'A new trackback on the post "%s" is waiting for your approval' ), $post->post_title ) . "\r\n"; $notify_message .= get_permalink( $comment->comment_post_ID ) . "\r\n\r\n"; /* translators: 1: Trackback/pingback website name, 2: Website IP address, 3: Website hostname. */ - $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; + $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; /* translators: %s: Trackback/pingback/comment author URL. */ - $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n"; + $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; /* translators: %s: Trackback excerpt text. */ $notify_message .= sprintf( __( 'Trackback excerpt: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n"; break; @@ -2105,9 +2131,9 @@ function wp_notify_moderator( $comment_id ) { $notify_message = sprintf( __( 'A new pingback on the post "%s" is waiting for your approval' ), $post->post_title ) . "\r\n"; $notify_message .= get_permalink( $comment->comment_post_ID ) . "\r\n\r\n"; /* translators: 1: Trackback/pingback website name, 2: Website IP address, 3: Website hostname. */ - $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; + $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; /* translators: %s: Trackback/pingback/comment author URL. */ - $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n"; + $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; /* translators: %s: Pingback excerpt text. */ $notify_message .= sprintf( __( 'Pingback excerpt: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n"; break; @@ -2117,11 +2143,11 @@ function wp_notify_moderator( $comment_id ) { $notify_message = sprintf( __( 'A new comment on the post "%s" is waiting for your approval' ), $post->post_title ) . "\r\n"; $notify_message .= get_permalink( $comment->comment_post_ID ) . "\r\n\r\n"; /* translators: 1: Comment author's name, 2: Comment author's IP address, 3: Comment author's hostname. */ - $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; + $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; /* translators: %s: Comment author email. */ - $notify_message .= sprintf( __( 'Email: %s' ), $comment->comment_author_email ) . "\r\n"; + $notify_message .= sprintf( __( 'Email: %s' ), $comment_author_email ) . "\r\n"; /* translators: %s: Trackback/pingback/comment author URL. */ - $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n"; + $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; if ( $comment->comment_parent ) { /* translators: Comment moderation. %s: Parent comment edit URL. */ diff --git a/tests/phpunit/tests/comment.php b/tests/phpunit/tests/comment.php index c5c40b9b34da6..52d9e5698cf6d 100644 --- a/tests/phpunit/tests/comment.php +++ b/tests/phpunit/tests/comment.php @@ -1247,6 +1247,387 @@ public function test_wp_new_comment_notify_postauthor_content_should_include_lin $this->assertStringContainsString( admin_url( "comment.php?action=editcomment&c={$c1}" ), self::$notify_message ); } + /** + * Ensures that a pingback cannot add lines to the comment notifications. + * + * The comment author of a pingback is the title of the linking page. + * + * @covers ::wp_notify_postauthor + * @covers ::wp_notify_moderator + * + * @dataProvider data_line_break_injections + * + * @param string $author Linking page title containing some form of line feed. + * @param string $email Unused, since pingbacks have no author email address. + * @param string $url Linking page URL containing some form of line feed. + */ + public function test_pingback_cannot_inject_into_comment_notifications( string $author, string $email, string $url ) { + /** + * @see wp_xmlrpc_server::pingback_ping(). + */ + $comment_id = wp_new_comment( + wp_slash( + array( + 'comment_post_ID' => self::$post_id, + 'comment_type' => 'pingback', + 'comment_author' => $author, + 'comment_author_email' => '', + 'comment_author_url' => $url, + 'comment_content' => 'Pingback content.', + ) + ) + ); + + $this->assert_comment_notifications_not_injected( $comment_id ); + } + + /** + * Ensures that a trackback cannot add lines to the comment notifications. + * + * The comment author of a trackback is the name of the linking blog. + * + * @covers ::wp_notify_postauthor + * @covers ::wp_notify_moderator + * + * @dataProvider data_line_break_injections + * + * @param string $author Linking blog name containing some form of line feed. + * @param string $email Unused, since trackbacks have no author email address. + * @param string $url Linking page URL containing some form of line feed. + */ + public function test_trackback_cannot_inject_into_comment_notifications( string $author, string $email, string $url ) { + /** + * @see wp-trackback.php + */ + $comment_id = wp_new_comment( + wp_slash( + array( + 'comment_post_ID' => self::$post_id, + 'comment_type' => 'trackback', + 'comment_author' => sanitize_text_field( $author ), + 'comment_author_email' => '', + 'comment_author_url' => sanitize_url( $url ), + 'comment_content' => 'Trackback content.', + ) + ) + ); + + $this->assert_comment_notifications_not_injected( $comment_id ); + } + + /** + * Ensures that an anonymous XML-RPC comment cannot add lines to the comment notifications. + * + * @covers ::wp_notify_postauthor + * @covers ::wp_notify_moderator + * + * @dataProvider data_line_break_injections_with_valid_email + * + * @param string $author Author name containing some form of line feed. + * @param string $email Author email address containing some form of line feed. + * @param string $url Author URL containing some form of line feed. + */ + public function test_xmlrpc_comment_cannot_inject_into_comment_notifications( string $author, string $email, string $url ) { + require_once ABSPATH . 'wp-admin/includes/admin.php'; + require_once ABSPATH . WPINC . '/class-IXR.php'; + require_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php'; + + add_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' ); + + $server = new wp_xmlrpc_server(); + $comment_id = $server->wp_newComment( + array( + 1, + '', + '', + self::$post_id, + array( + 'author' => $author, + 'author_email' => $email, + 'author_url' => $url, + 'content' => 'XML-RPC content.', + ), + ) + ); + + $this->assert_comment_notifications_not_injected( $comment_id ); + } + + /** + * Ensures that an anonymous comment form submission cannot add lines to the comment notifications. + * + * @covers ::wp_notify_postauthor + * @covers ::wp_notify_moderator + * + * @dataProvider data_line_break_injections_with_valid_email + * + * @param string $author Author name containing some form of line feed. + * @param string $email Author email address containing some form of line feed. + * @param string $url Author URL containing some form of line feed. + */ + public function test_comment_form_cannot_inject_into_comment_notifications( string $author, string $email, string $url ) { + $comment = wp_handle_comment_submission( + array( + 'comment_post_ID' => self::$post_id, + 'author' => $author, + 'email' => $email, + 'url' => $url, + 'comment' => 'Comment form content.', + ) + ); + + $this->assertInstanceOf( 'WP_Comment', $comment ); + $this->assert_comment_notifications_not_injected( (int) $comment->comment_ID ); + } + + /** + * Ensures that the profile of a logged-in commenter cannot add lines to the comment notifications. + * + * @covers ::wp_notify_postauthor + * @covers ::wp_notify_moderator + * + * @dataProvider data_line_break_injections + * + * @param string $author Display name containing some form of line feed. + * @param string $email User email address containing some form of line feed. + * @param string $url User URL containing some form of line feed. + */ + public function test_logged_in_comment_form_cannot_inject_into_comment_notifications( string $author, string $email, string $url ) { + wp_set_current_user( + self::factory()->user->create( + array( + 'display_name' => $author, + 'user_email' => $email, + 'user_url' => $url, + ) + ) + ); + + $comment = wp_handle_comment_submission( + array( + 'comment_post_ID' => self::$post_id, + 'comment' => 'Logged-in comment form content.', + ) + ); + + $this->assertInstanceOf( 'WP_Comment', $comment ); + $this->assert_comment_notifications_not_injected( (int) $comment->comment_ID ); + } + + /** + * Ensures that author fields in a REST API request cannot add lines to the comment notifications. + * + * @covers ::wp_notify_postauthor + * @covers ::wp_notify_moderator + * + * @dataProvider data_line_break_injections_with_valid_email + * + * @param string $author Author name containing some form of line feed. + * @param string $email Author email address containing some form of line feed. + * @param string $url Author URL containing some form of line feed. + */ + public function test_rest_api_comment_cannot_inject_into_comment_notifications( string $author, string $email, string $url ) { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + $request = new WP_REST_Request( 'POST', '/wp/v2/comments' ); + $request->set_body_params( + array( + 'post' => self::$post_id, + 'author_name' => $author, + 'author_email' => $email, + 'author_url' => $url, + 'content' => 'REST API content.', + ) + ); + + $response = rest_do_request( $request ); + + $this->assertSame( 201, $response->get_status() ); + $this->assert_comment_notifications_not_injected( $response->get_data()['id'] ); + } + + /** + * Ensures that the profile of a logged-in REST API commenter cannot add lines to the comment notifications. + * + * @covers ::wp_notify_postauthor + * @covers ::wp_notify_moderator + * + * @dataProvider data_line_break_injections + * + * @param string $author Display name containing some form of line feed. + * @param string $email User email address containing some form of line feed. + * @param string $url User URL containing some form of line feed. + */ + public function test_logged_in_rest_api_comment_cannot_inject_into_comment_notifications( string $author, string $email, string $url ) { + wp_set_current_user( + self::factory()->user->create( + array( + 'display_name' => $author, + 'user_email' => $email, + 'user_url' => $url, + ) + ) + ); + + $request = new WP_REST_Request( 'POST', '/wp/v2/comments' ); + $request->set_body_params( + array( + 'post' => self::$post_id, + 'content' => 'Logged-in REST API content.', + ) + ); + + $response = rest_do_request( $request ); + + $this->assertSame( 201, $response->get_status() ); + $this->assert_comment_notifications_not_injected( $response->get_data()['id'] ); + } + + /** + * Ensures that editing a comment cannot add lines to the comment notifications. + * + * @covers ::wp_notify_postauthor + * @covers ::wp_notify_moderator + * + * @dataProvider data_line_break_injections + * + * @param string $author Author name containing some form of line feed. + * @param string $email Author email address containing some form of line feed. + * @param string $url Author URL containing some form of line feed. + */ + public function test_comment_edit_cannot_inject_into_comment_notifications( string $author, string $email, string $url ) { + $comment_id = self::factory()->comment->create( array( 'comment_post_ID' => self::$post_id ) ); + + wp_update_comment( + wp_slash( + array( + 'comment_ID' => $comment_id, + 'comment_author' => $author, + 'comment_author_email' => $email, + 'comment_author_url' => $url, + ) + ) + ); + + $this->assert_comment_notifications_not_injected( $comment_id ); + } + + /** + * Ensures that values already stored in a comment cannot add lines to the comment notifications. + * + * Values may reach the database through plugins, imports, or direct queries + * which skip the save filters, so the notifications must not rely on them. + * + * @covers ::wp_notify_postauthor + * @covers ::wp_notify_moderator + * + * @dataProvider data_line_break_injections + * + * @param string $author Stored comment author. + * @param string $email Stored comment author email address. + * @param string $url Stored comment author URL. + */ + public function test_stored_comment_cannot_inject_into_comment_notifications( string $author, string $email, string $url ) { + $comment_id = self::factory()->comment->create( + array( + 'comment_post_ID' => self::$post_id, + 'comment_author' => $author, + 'comment_author_email' => $email, + 'comment_author_url' => $url, + ) + ); + + $this->assert_comment_notifications_not_injected( $comment_id ); + } + + /** + * Data provider. + * + * Each value tries to end the line it is placed in, then add lines which + * replace the sender and add a recipient when read as email headers, or + * which look like part of the notification when read in the email body. + * + * @return array + */ + public static function data_line_break_injections(): array { + $author = static function ( $line_break ) { + return "Name{$line_break}From: spoof@example.net{$line_break}Bcc: attacker@example.net{$line_break}X:"; + }; + + $email = static function ( $line_break, $colon, $at ) { + return "name{$line_break}Bcc{$colon}attacker{$at}example.net{$line_break}x@example.com"; + }; + + $url = static function ( $line_break ) { + return "https://example.net/{$line_break}Bcc:attacker@example.net"; + }; + + return array( + 'Line feed' => array( $author( "\n" ), $email( "\n", ':', '@' ), $url( "\n" ) ), + 'Carriage return' => array( $author( "\r" ), $email( "\r", ':', '@' ), $url( "\r" ) ), + 'Carriage return and line feed' => array( $author( "\r\n" ), $email( "\r\n", ':', '@' ), $url( "\r\n" ) ), + 'Escaped line feed' => array( $author( ' ' ), $email( ' ', ':', '@' ), $url( ' ' ) ), + 'Escaped line feed without semicolon' => array( $author( ' ' ), $email( ' ', ':', '@' ), $url( ' ' ) ), + 'Escaped line feed in hexadecimal' => array( $author( ' ' ), $email( ' ', ':', '@' ), $url( ' ' ) ), + 'Escaped line feed with leading zeros' => array( $author( ' ' ), $email( ' ', ':', '@' ), $url( ' ' ) ), + 'Escaped line feed by name' => array( $author( ' ' ), $email( ' ', ':', '@' ), $url( ' ' ) ), + 'Escaped carriage return' => array( $author( ' ' ), $email( ' ', ':', '@' ), $url( ' ' ) ), + 'Escaped carriage return and line feed' => array( $author( ' ' ), $email( ' ', ':', '@' ), $url( ' ' ) ), + 'Carriage return and escaped line feed' => array( $author( "\r " ), $email( "\r ", ':', '@' ), $url( "\r " ) ), + 'Double-escaped line feed' => array( $author( '&#10;' ), $email( '&#10', ':', '@' ), $url( '&#10;' ) ), + ); + } + + /** + * Data provider for sources which reject email addresses that fail is_email(). + * + * These sources refuse such submissions before saving them, so a valid + * address replaces those emails to still test the other fields. + * + * @return array + */ + public static function data_line_break_injections_with_valid_email(): array { + $data = self::data_line_break_injections(); + + foreach ( $data as $name => $values ) { + if ( ! is_email( $values[1] ) ) { + $data[ $name ][1] = 'commenter@example.com'; + } + } + + return $data; + } + + /** + * Asserts that the notifications for a comment contain no lines added through its author fields. + * + * Sends the post author and moderator notifications, then checks the + * headers and body of every email sent. + * + * @param mixed $comment_id Comment ID, or an error value from attempting to create a comment. + */ + private function assert_comment_notifications_not_injected( $comment_id ) { + $this->assertIsInt( $comment_id, 'The comment should have been created.' ); + + reset_phpmailer_instance(); + + $this->assertTrue( wp_notify_postauthor( $comment_id ), 'The post author notification should have been sent.' ); + $this->assertTrue( wp_notify_moderator( $comment_id ), 'The moderator notification should have been sent.' ); + + $mailer = tests_retrieve_phpmailer_instance(); + + $this->assertGreaterThanOrEqual( 2, count( $mailer->mock_sent ), 'Both notifications should have been sent.' ); + + foreach ( $mailer->mock_sent as $sent ) { + $this->assertSame( array(), $sent['cc'], 'The notification should not have Cc recipients.' ); + $this->assertSame( array(), $sent['bcc'], 'The notification should not have Bcc recipients.' ); + $this->assertSame( 1, preg_match_all( '/^From:/mi', $sent['header'] ), 'The notification should have one From header.' ); + $this->assertStringNotContainsString( '', $sent['header'], 'The notification should be sent from the site address.' ); + $this->assertLessThanOrEqual( 1, preg_match_all( '/^Reply-To:/mi', $sent['header'] ), 'The notification should have at most one Reply-To header.' ); + $this->assertDoesNotMatchRegularExpression( '/^(From|Bcc|X):/m', $sent['body'], 'The notification body should not contain lines added through the author fields.' ); + } + } + /** * @ticket 43805 * From 9669668ad3e491534a8441f022e7b7297ea1ee85 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 23 Nov 2026 22:05:19 +0000 Subject: [PATCH 56/85] Tests: Restore theme features after image header tests. Keep custom header dimensions set by these tests from affecting later REST theme responses. Developed in: https://github.com/WordPress/wordpress-develop/pull/16182 Props mayankmajeji. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65745 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/image/header.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/phpunit/tests/image/header.php b/tests/phpunit/tests/image/header.php index fce617fd7df4f..ffe864e3d55a5 100644 --- a/tests/phpunit/tests/image/header.php +++ b/tests/phpunit/tests/image/header.php @@ -8,11 +8,25 @@ class Tests_Image_Header extends WP_UnitTestCase { public $custom_image_header; + /** + * Original value of the `$_wp_theme_features` global. + * + * @var array + */ + private $orig_theme_features; + public function set_up() { parent::set_up(); + $this->orig_theme_features = $GLOBALS['_wp_theme_features']; $this->custom_image_header = new Custom_Image_Header( '__return_null' ); } + public function tear_down() { + $GLOBALS['_wp_theme_features'] = $this->orig_theme_features; + + parent::tear_down(); + } + public function test_header_image_has_correct_dimensions_with_max_width() { global $_wp_theme_features; From f6689590e0ec3ddfcd33470cdb95902c25519e40 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 23 Nov 2026 22:14:54 +0000 Subject: [PATCH 57/85] Tests: Log out after creating privileged class fixtures. Restore the logged-out user before the test harness saves the sanitization filters for subsequent tests. Developed in: https://github.com/WordPress/wordpress-develop/pull/16185 Props mayankmajeji. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65746 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/ajax/wpAjaxHeartbeat.php | 1 + tests/phpunit/tests/post/wpGetAutoSave.php | 1 + tests/phpunit/tests/rest-api/rest-autosaves-controller.php | 1 + .../phpunit/tests/rest-api/wpRestTemplateAutosavesController.php | 1 + .../phpunit/tests/rest-api/wpRestTemplateRevisionsController.php | 1 + 5 files changed, 5 insertions(+) diff --git a/tests/phpunit/tests/ajax/wpAjaxHeartbeat.php b/tests/phpunit/tests/ajax/wpAjaxHeartbeat.php index 87d49987b5752..01e5e63c6de60 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHeartbeat.php +++ b/tests/phpunit/tests/ajax/wpAjaxHeartbeat.php @@ -39,6 +39,7 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { self::$post_id = $factory->post->create( array( 'post_status' => 'draft' ) ); self::$post = get_post( self::$post_id ); + wp_set_current_user( 0 ); } /** diff --git a/tests/phpunit/tests/post/wpGetAutoSave.php b/tests/phpunit/tests/post/wpGetAutoSave.php index db27d25fad58d..a3449820fc4e7 100644 --- a/tests/phpunit/tests/post/wpGetAutoSave.php +++ b/tests/phpunit/tests/post/wpGetAutoSave.php @@ -37,6 +37,7 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { wp_set_current_user( self::$admin_id ); self::$post_id = $factory->post->create( array( 'post_status' => 'publish' ) ); + wp_set_current_user( 0 ); } /** diff --git a/tests/phpunit/tests/rest-api/rest-autosaves-controller.php b/tests/phpunit/tests/rest-api/rest-autosaves-controller.php index be6a1996ee98a..42f76b931de02 100644 --- a/tests/phpunit/tests/rest-api/rest-autosaves-controller.php +++ b/tests/phpunit/tests/rest-api/rest-autosaves-controller.php @@ -108,6 +108,7 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { 'post_author' => self::$editor_id, ) ); + wp_set_current_user( 0 ); } public static function wpTearDownAfterClass() { diff --git a/tests/phpunit/tests/rest-api/wpRestTemplateAutosavesController.php b/tests/phpunit/tests/rest-api/wpRestTemplateAutosavesController.php index 972cdccdb034d..246c7562a6be6 100644 --- a/tests/phpunit/tests/rest-api/wpRestTemplateAutosavesController.php +++ b/tests/phpunit/tests/rest-api/wpRestTemplateAutosavesController.php @@ -131,6 +131,7 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { ); wp_set_post_terms( self::$template_part_post->ID, self::TEST_THEME, 'wp_theme' ); wp_set_post_terms( self::$template_part_post->ID, WP_TEMPLATE_PART_AREA_HEADER, 'wp_template_part_area' ); + wp_set_current_user( 0 ); } /** diff --git a/tests/phpunit/tests/rest-api/wpRestTemplateRevisionsController.php b/tests/phpunit/tests/rest-api/wpRestTemplateRevisionsController.php index 3475c87d68750..88a4b548bfa9f 100644 --- a/tests/phpunit/tests/rest-api/wpRestTemplateRevisionsController.php +++ b/tests/phpunit/tests/rest-api/wpRestTemplateRevisionsController.php @@ -222,6 +222,7 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { ); wp_set_post_terms( self::$template_part_post_2->ID, self::TEST_THEME, 'wp_theme' ); wp_set_post_terms( self::$template_part_post_2->ID, WP_TEMPLATE_PART_AREA_HEADER, 'wp_template_part_area' ); + wp_set_current_user( 0 ); } /** From 1ccce2133e92fad7cea0837fb5da432ea6ba980f Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Mon, 23 Nov 2026 23:23:12 +0000 Subject: [PATCH 58/85] Tests: Cover `wp_default_editor()`. Verify that the function returns `tinymce` by default or user editor setting when set. Developed in https://github.com/WordPress/wordpress-develop/pull/15358. Props devmuhib, huzaifaalmesbah, lancewillett. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65747 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/general/wpDefaultEditor.php | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 tests/phpunit/tests/general/wpDefaultEditor.php diff --git a/tests/phpunit/tests/general/wpDefaultEditor.php b/tests/phpunit/tests/general/wpDefaultEditor.php new file mode 100644 index 0000000000000..6235a8b613f72 --- /dev/null +++ b/tests/phpunit/tests/general/wpDefaultEditor.php @@ -0,0 +1,64 @@ +assertSame( 'tinymce', wp_default_editor() ); + } + + /** + * Tests that wp_default_editor() returns user editor setting when set. + * + * @ticket 65819 + */ + public function test_wp_default_editor_respects_user_setting() { + $user_id = self::factory()->user->create(); + wp_set_current_user( $user_id ); + + $orig_updated_user_settings = $GLOBALS['_updated_user_settings'] ?? null; + unset( $GLOBALS['_updated_user_settings'] ); + + $_COOKIE[ 'wp-settings-' . $user_id ] = 'editor=html'; + + try { + $this->assertSame( 'html', wp_default_editor() ); + } finally { + unset( $_COOKIE[ 'wp-settings-' . $user_id ] ); + + if ( null !== $orig_updated_user_settings ) { + $GLOBALS['_updated_user_settings'] = $orig_updated_user_settings; + } else { + unset( $GLOBALS['_updated_user_settings'] ); + } + } + } + + /** + * Tests that the `wp_default_editor` filter modifies the default editor. + * + * @ticket 65819 + */ + public function test_wp_default_editor_filter() { + add_filter( + 'wp_default_editor', + static function () { + return 'html'; + } + ); + + $this->assertSame( 'html', wp_default_editor() ); + } +} From 5ae0af920fddb8aa009f379491ba234d584b9842 Mon Sep 17 00:00:00 2001 From: Adam Silverstein Date: Mon, 23 Nov 2026 23:28:40 +0000 Subject: [PATCH 59/85] Media: Create image sizes that share dimensions on upload. When client-side media processing is active and two or more registered image sizes have the same dimensions, the Media Library upload pipeline sideloads one file for all of them and sends their names as an array in `image_size`. `flattenFormData()` in `media-upload-pipeline.js` only recursed into plain objects, so the array was sent as a comma-separated string. The sideload endpoint rejected it with a 400 and none of those sizes were created, while the upload itself appeared to succeed. Recurse into arrays as well as plain objects, matching `flattenFormData()` in the media-utils package since https://github.com/WordPress/gutenberg/pull/82353. This affects only Media > Add New and the Media Library grid. The block editor already handled arrays correctly. Follow-up to [64588]. Reviewed by westonruter. Props aryanjasala, ozgursar, dhrupo, jyria, kirasong, westonruter. Fixes #66412. git-svn-id: https://develop.svn.wordpress.org/trunk@65748 602fd350-edb4-49c9-b593-d223f7449a82 --- .../_enqueues/admin/media-upload-pipeline.js | 9 +-- .../media-new-client-side-upload.test.js | 69 +++++++++++++++++++ 2 files changed, 74 insertions(+), 4 deletions(-) diff --git a/src/js/_enqueues/admin/media-upload-pipeline.js b/src/js/_enqueues/admin/media-upload-pipeline.js index bd25774d48491..4b0fd4f47bae0 100644 --- a/src/js/_enqueues/admin/media-upload-pipeline.js +++ b/src/js/_enqueues/admin/media-upload-pipeline.js @@ -46,7 +46,7 @@ window.wp = window.wp || {}; const IMAGE_SUBTYPES = [ 'jpeg', 'png', 'gif', 'webp', 'avif', 'heic', 'heif' ]; /** - * Recursively appends data to a FormData object, supporting nested objects. + * Recursively appends data to a FormData object, supporting nested objects and arrays. * * Mirrors flattenFormData() in the media-utils package. * @@ -56,9 +56,10 @@ window.wp = window.wp || {}; */ function flattenFormData( formData, key, data ) { if ( - data !== null && - typeof data === 'object' && - Object.getPrototypeOf( data ) === Object.prototype + Array.isArray( data ) || + ( data !== null && + typeof data === 'object' && + Object.getPrototypeOf( data ) === Object.prototype ) ) { Object.keys( data ).forEach( function ( name ) { flattenFormData( formData, key + '[' + name + ']', data[ name ] ); diff --git a/tests/e2e/specs/media-new-client-side-upload.test.js b/tests/e2e/specs/media-new-client-side-upload.test.js index 65e731654a1c9..39b943fb554a0 100644 --- a/tests/e2e/specs/media-new-client-side-upload.test.js +++ b/tests/e2e/specs/media-new-client-side-upload.test.js @@ -1,3 +1,8 @@ +/** + * External dependencies + */ +import { randomUUID } from 'node:crypto'; + /** * Internal dependencies */ @@ -166,6 +171,70 @@ test.describe( 'Add New Media File client-side uploads', () => { expect( thumbnailResponse.status() ).toBe( 200 ); } ); + test( 'creates every image size when two sizes share dimensions', async ( { + page, + admin, + attachments, + requestUtils, + muPlugin, + baseURL, + } ) => { + // Sizes with the same dimensions are sideloaded as one file, with + // their names sent as an array in `image_size`. Other workers share + // the site, so only this test's requests see the extra sizes. + const trigger = `e2e_${ randomUUID().replaceAll( '-', '' ) }`; + await muPlugin.write( + 'shared-image-sizes.php', + ` { + if ( + /\/wp\/v2\/media\/\d+\/sideload/.test( + decodeURIComponent( response.url() ) + ) + ) { + sideloadStatuses.push( response.status() ); + } + } ); + + const ids = trackUploads( page, attachments ); + const fileInput = page.locator( FILE_INPUT_SELECTOR ).first(); + await expect( fileInput ).toBeAttached( { timeout: 30_000 } ); + await fileInput.setInputFiles( TEST_IMAGE_PATH ); + + await expect( editLinks( page ) ).toBeVisible( { timeout: 60_000 } ); + + expect( sideloadStatuses.length ).toBeGreaterThanOrEqual( 1 ); + expect( + sideloadStatuses.filter( ( status ) => status !== 200 ) + ).toEqual( [] ); + + const attachment = await requestUtils.rest( { + path: `/wp/v2/media/${ ids.at( -1 ) }`, + } ); + expect( Object.keys( attachment.media_details.sizes || {} ) ).toEqual( + expect.arrayContaining( [ 'e2e-shared-a', 'e2e-shared-b' ] ) + ); + } ); + test( 'warns before leaving while a pipeline upload is in flight', async ( { page, admin, From 9f134f61ea67854377a1aaf795f38bd1198196ba Mon Sep 17 00:00:00 2001 From: Peter Wilson Date: Tue, 24 Nov 2026 01:12:19 +0000 Subject: [PATCH 60/85] Editor: Restore the default block editor styles. Moves the default block editor styles into `get_default_block_editor_settings()` rather than attempting to read them from `wp-includes/css/dist/block-editor/default-editor-styles.css`. The file's source was removed from the block editor package in https://github.com/WordPress/gutenberg/commit/aee1d484423d020fd6b4857abdae29b01c079530, so the `defaultEditorStyles` setting was empty and the styles were missing in these places: * The block editor, when a user turns off the theme styles preference. * The Customizer's widgets editor. The file's post title rule is not restored. The `.editor-post-title__block` class it targets was removed in WordPress 5.9. The tests are updated to ensure the default editor styles are populated. Developed in: https://github.com/WordPress/wordpress-develop/pull/16118 Follow-up to r63535. Reviewed by wildworks. Props mukesh27, wildworks. Fixes #66762. git-svn-id: https://develop.svn.wordpress.org/trunk@65749 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/block-editor.php | 27 ++++++++++++--------------- tests/phpunit/tests/blocks/editor.php | 3 +++ 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/wp-includes/block-editor.php b/src/wp-includes/block-editor.php index 24bdd2f6db5db..8aa19ffe35224 100644 --- a/src/wp-includes/block-editor.php +++ b/src/wp-includes/block-editor.php @@ -194,21 +194,18 @@ function get_default_block_editor_settings() { } } - // These styles are used if the "no theme styles" options is triggered or on - // themes without their own editor styles. - $default_editor_styles_file = ABSPATH . WPINC . '/css/dist/block-editor/default-editor-styles.css'; - - static $default_editor_styles_file_contents = false; - if ( ! $default_editor_styles_file_contents && file_exists( $default_editor_styles_file ) ) { - $default_editor_styles_file_contents = file_get_contents( $default_editor_styles_file ); - } - - $default_editor_styles = array(); - if ( $default_editor_styles_file_contents ) { - $default_editor_styles = array( - array( 'css' => $default_editor_styles_file_contents ), - ); - } + /* + * These styles are used when the "Use theme styles" preference is turned off + * and in the Customizer widgets editor. + * + * They were previously read from `css/dist/block-editor/default-editor-styles.css`, + * which the block editor package no longer ships. + */ + $default_editor_styles = array( + array( + 'css' => 'body{font-family:-apple-system,system-ui,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;font-size:18px;line-height:1.5;--wp--style--block-gap:2em}p{line-height:1.8}', + ), + ); $editor_settings = array( 'alignWide' => get_theme_support( 'align-wide' ), diff --git a/tests/phpunit/tests/blocks/editor.php b/tests/phpunit/tests/blocks/editor.php index 5055aab4d999e..d152e8b8577f6 100644 --- a/tests/phpunit/tests/blocks/editor.php +++ b/tests/phpunit/tests/blocks/editor.php @@ -247,6 +247,7 @@ public function test_get_allowed_block_types_deprecated_filter_post_editor() { /** * @ticket 52920 + * @ticket 66762 */ public function test_get_default_block_editor_settings() { $settings = get_default_block_editor_settings(); @@ -300,6 +301,8 @@ public function test_get_default_block_editor_settings() { $this->assertFalse( $settings['disableCustomFontSizes'] ); $this->assertFalse( $settings['disableCustomGradients'] ); $this->assertFalse( $settings['disableLayoutStyles'] ); + $this->assertCount( 1, $settings['defaultEditorStyles'] ); + $this->assertStringContainsString( 'font-size:18px', $settings['defaultEditorStyles'][0]['css'] ); $this->assertFalse( $settings['enableCustomLineHeight'] ); $this->assertFalse( $settings['enableCustomSpacing'] ); $this->assertFalse( $settings['enableCustomUnits'] ); From 14f13cb7e9d05ed75fe1b124008859c9a21c65c2 Mon Sep 17 00:00:00 2001 From: Adam Silverstein Date: Tue, 24 Nov 2026 06:18:49 +0000 Subject: [PATCH 61/85] Comments: Tighten note and reaction rules in all handlers. Ensure all routes enforce that a reaction belongs to its author, carries one of the curated emoji keys and sits under a note on the same post, including Ajax and XML-RPC update routes. Also, a note reply must have a note on the same post as its parent, and `reaction_summary` only counts reactions that are on their note's post and use a curated key. Follow-up to [64488], [64999], [65222]. Reviewed by westonruter. Props westonruter, wildworks, mamaduka. Fixes #66635. git-svn-id: https://develop.svn.wordpress.org/trunk@65750 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/includes/ajax-actions.php | 21 + src/wp-admin/includes/comment.php | 34 +- src/wp-includes/class-wp-xmlrpc-server.php | 9 +- .../class-wp-rest-comments-controller.php | 124 ++++- .../phpunit/tests/ajax/wpAjaxEditComment.php | 517 ++++++++++++++++++ .../tests/ajax/wpAjaxReplytoComment.php | 99 ++++ tests/phpunit/tests/comment.php | 40 ++ .../rest-api/rest-comments-controller.php | 341 ++++++++++++ tests/phpunit/tests/xmlrpc/wp/editComment.php | 56 ++ tests/qunit/fixtures/wp-api-generated.js | 7 +- 10 files changed, 1227 insertions(+), 21 deletions(-) diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index 076549b218b82..ba3b9bc2851a1 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -1310,12 +1310,33 @@ function wp_ajax_replyto_comment( $action ) { $comment_type = isset( $_POST['comment_type'] ) ? trim( $_POST['comment_type'] ) : 'comment'; + /* + * Notes and reactions are only created through the REST API. The lowercase + * ASCII limit also catches spellings the case- and accent-insensitive + * collation would match. + */ + if ( + ! preg_match( '/^[a-z0-9_-]+\z/', $comment_type ) || + in_array( $comment_type, array( 'note', 'reaction' ), true ) + ) { + wp_die( -1 ); + } + $comment_parent = 0; if ( isset( $_POST['comment_ID'] ) ) { $comment_parent = absint( $_POST['comment_ID'] ); } + // A comment on another post cannot be the parent. + if ( $comment_parent ) { + $parent = get_comment( $comment_parent ); + + if ( $parent && (int) $parent->comment_post_ID !== $comment_post_id ) { + $comment_parent = 0; + } + } + $comment_auto_approved = false; $commentdata = array( diff --git a/src/wp-admin/includes/comment.php b/src/wp-admin/includes/comment.php index 5f46be6a5cdfa..49c2b3d32c421 100644 --- a/src/wp-admin/includes/comment.php +++ b/src/wp-admin/includes/comment.php @@ -80,6 +80,11 @@ function edit_comment() { $comment_id = (int) $_POST['comment_ID']; $comment = get_comment( $comment_id ); + // Reactions are only validated on creation. Removing one is a delete. + if ( $comment && 'reaction' === $comment->comment_type ) { + wp_die( __( 'Reactions cannot be edited. Remove the reaction and add a new one instead.' ), 403 ); + } + /* * The comment type is not editable from the Edit Comment screen. Changing it * would turn a private note into a public comment or vice versa, and would @@ -135,7 +140,7 @@ function edit_comment() { $comment_status = $_POST['comment_approved'] ?? $comment->comment_approved; $comment_is_approved = in_array( $comment_status, array( 1, '1', 'approve' ), true ); - // The parent must be a comment of the same type, on the same post, and publicly visible if the comment is approved. + // The parent must be a comment of the same type, on the post the comment will be on, and publicly visible if the comment is approved. if ( ! $parent || (int) $parent->comment_post_ID !== $comment_post_id @@ -196,6 +201,19 @@ function edit_comment() { } } + // The checks above only run when the parent changes. A kept parent must be on the destination post too. + if ( $comment && $comment_post_id !== (int) $comment->comment_post_ID ) { + $kept_parent = (int) ( isset( $_POST['comment_parent'] ) && is_numeric( $_POST['comment_parent'] ) ? $_POST['comment_parent'] : $comment->comment_parent ); + + if ( $kept_parent ) { + $parent = get_comment( $kept_parent ); + + if ( ! $parent || (int) $parent->comment_post_ID !== $comment_post_id ) { + return new WP_Error( 'comment_parent_invalid', __( 'Invalid parent comment.' ) ); + } + } + } + foreach ( array( 'aa', 'mm', 'jj', 'hh', 'mn' ) as $timeunit ) { if ( ! empty( $_POST[ 'hidden_' . $timeunit ] ) && $_POST[ 'hidden_' . $timeunit ] !== $_POST[ $timeunit ] ) { $_POST['edit_date'] = '1'; @@ -283,6 +301,20 @@ static function ( $item ) { return new WP_Error( 'comment_post_invalid', __( 'Sorry, you are not allowed to move this comment to that post.' ) ); } + // Replies and reactions stay on the note's post, so a move would separate them. + $children = get_comments( + array( + 'parent' => $comment->comment_ID, + 'type' => array( 'note', 'reaction' ), + 'status' => 'any', + 'count' => true, + ) + ); + + if ( $children ) { + return new WP_Error( 'comment_post_invalid', __( 'A note with replies or reactions cannot be moved to another post.' ) ); + } + return true; } diff --git a/src/wp-includes/class-wp-xmlrpc-server.php b/src/wp-includes/class-wp-xmlrpc-server.php index 515a2458f9e38..56448aa6e2520 100644 --- a/src/wp-includes/class-wp-xmlrpc-server.php +++ b/src/wp-includes/class-wp-xmlrpc-server.php @@ -3971,7 +3971,9 @@ public function wp_editComment( $args ) { return $this->error; } - if ( ! get_comment( $comment_id ) ) { + $existing_comment = get_comment( $comment_id ); + + if ( ! $existing_comment ) { return new IXR_Error( 404, __( 'Invalid comment ID.' ) ); } @@ -3979,6 +3981,11 @@ public function wp_editComment( $args ) { return new IXR_Error( 403, __( 'Sorry, you are not allowed to moderate or edit this comment.' ) ); } + // Reactions are only validated on creation. Removing one is a delete. + if ( 'reaction' === $existing_comment->comment_type ) { + return new IXR_Error( 403, __( 'Reactions cannot be edited. Remove the reaction and add a new one instead.' ) ); + } + /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */ do_action( 'xmlrpc_call', 'wp.editComment', $args, $this ); $comment = array( diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php index 490bd7659ea59..3bb44059052eb 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php @@ -731,6 +731,14 @@ public function create_item( $request ) { ); } + if ( 'note' === $request['type'] && $request['parent'] ) { + $parent_check = $this->check_note_parent( absint( $request['parent'] ), absint( $request['post'] ) ); + + if ( is_wp_error( $parent_check ) ) { + return $parent_check; + } + } + /* * The canonical reaction key, populated once validated below so the * stored content matches what was validated (not the raw input). @@ -841,10 +849,12 @@ public function create_item( $request ) { * * Scope to active (approved) reactions only — trashed reactions * are invisible to the user and must not block re-adding the - * same emoji. + * same emoji. The same goes for a reaction stored on another + * post, which the reaction summary leaves out. */ $existing = get_comments( array( + 'post_id' => absint( $request['post'] ), 'parent' => $request['parent'], 'user_id' => get_current_user_id(), 'type' => 'reaction', @@ -1035,6 +1045,7 @@ public function create_item( $request ) { if ( null !== $reaction_key ) { $matching = get_comments( array( + 'post_id' => absint( $request['post'] ), 'parent' => $request['parent'], 'user_id' => get_current_user_id(), 'type' => 'reaction', @@ -1233,6 +1244,40 @@ public function update_item( $request ) { ); } + if ( 'note' === $comment->comment_type ) { + $post_id = isset( $request['post'] ) ? absint( $request['post'] ) : (int) $comment->comment_post_ID; + $parent_id = isset( $request['parent'] ) ? absint( $request['parent'] ) : (int) $comment->comment_parent; + $is_moving = $post_id !== (int) $comment->comment_post_ID; + + if ( $parent_id && ( $is_moving || $parent_id !== (int) $comment->comment_parent ) ) { + $parent_check = $this->check_note_parent( $parent_id, $post_id ); + + if ( is_wp_error( $parent_check ) ) { + return $parent_check; + } + } + + // Replies and reactions stay on the note's post, so a move would separate them. + if ( $is_moving ) { + $children = get_comments( + array( + 'parent' => $id, + 'type' => array( 'note', 'reaction' ), + 'status' => 'any', + 'count' => true, + ) + ); + + if ( $children ) { + return new WP_Error( + 'rest_comment_has_children', + __( 'A note with replies or reactions cannot be moved to another post.' ), + array( 'status' => 400 ) + ); + } + } + } + /* * Re-sending the current author is a no-op. Otherwise the author's details * would be refreshed from their user account, exposing any change to their @@ -2010,12 +2055,14 @@ public function get_item_schema() { 'parent' => array( 'description' => __( 'The ID for the parent of the comment.' ), 'type' => 'integer', + 'minimum' => 0, 'context' => array( 'view', 'edit', 'embed' ), 'default' => 0, ), 'post' => array( 'description' => __( 'The ID of the associated post object.' ), 'type' => 'integer', + 'minimum' => 0, 'context' => array( 'view', 'edit' ), 'default' => 0, ), @@ -2189,7 +2236,8 @@ public function get_collection_params() { 'description' => __( 'Limit result set to comments of specific parent IDs.' ), 'type' => 'array', 'items' => array( - 'type' => 'integer', + 'type' => 'integer', + 'minimum' => 0, ), ); @@ -2374,26 +2422,27 @@ protected function prefetch_reaction_summaries( $note_ids ) { $current_user_id = get_current_user_id(); - $parent_in = $wpdb->prepare( - 'comment_parent IN (' . implode( ',', array_fill( 0, count( $note_ids ), '%d' ) ) . ')', + // Only reactions stored on their note's post count, which is what create_item() writes. + $from = "FROM $wpdb->comments AS r INNER JOIN $wpdb->comments AS n"; + $from .= " ON n.comment_ID = r.comment_parent AND n.comment_post_ID = r.comment_post_ID AND n.comment_type = 'note'"; + $where = "WHERE r.comment_type = 'reaction' AND r.comment_approved = '1' AND "; + $where .= $wpdb->prepare( + 'r.comment_parent IN (' . implode( ',', array_fill( 0, count( $note_ids ), '%d' ) ) . ')', ...$note_ids ); // Query 1: Get aggregated counts per emoji per note. - $query = "SELECT comment_parent, comment_content, COUNT(*) AS reaction_count FROM $wpdb->comments WHERE comment_type = 'reaction' AND comment_approved = '1' AND "; - $query .= $parent_in; - $query .= ' GROUP BY comment_parent, comment_content'; - // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared - $counts = $wpdb->get_results( $query ); + $query = "SELECT r.comment_parent, r.comment_content, COUNT(*) AS reaction_count $from $where GROUP BY r.comment_parent, r.comment_content"; + /** @var list|null $counts */ + $counts = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- It is prepared above. // Query 2: Get the current user's own reaction IDs (if logged in). $my_reactions = array(); if ( $current_user_id ) { - $query = "SELECT comment_ID, comment_parent, comment_content FROM $wpdb->comments WHERE comment_type = 'reaction' AND comment_approved = '1' AND "; - $query .= $parent_in; - $query .= $wpdb->prepare( ' AND user_id = %d', $current_user_id ); - // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared - $user_rows = $wpdb->get_results( $query ); + $query = "SELECT r.comment_ID, r.comment_parent, r.comment_content $from $where"; + $query .= $wpdb->prepare( ' AND r.user_id = %d', $current_user_id ); + /** @var list|null $user_rows */ + $user_rows = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- It is prepared above. if ( $user_rows ) { foreach ( $user_rows as $row ) { @@ -2412,15 +2461,27 @@ protected function prefetch_reaction_summaries( $note_ids ) { return; } + $allowed_keys = self::get_note_reaction_keys(); + foreach ( $counts as $row ) { $note_id = (int) $row->comment_parent; $emoji_key = wp_strip_all_tags( $row->comment_content ); $key = $note_id . ':' . $emoji_key; - $this->reaction_summaries[ $note_id ][ $emoji_key ] = array( - 'count' => (int) $row->reaction_count, - 'current_user_reaction' => $my_reactions[ $key ] ?? 0, - ); + // Only curated emoji keys are summarized. + if ( ! in_array( $emoji_key, $allowed_keys, true ) ) { + continue; + } + + // Rows are grouped on the raw content, so several groups can strip to one key. + if ( ! isset( $this->reaction_summaries[ $note_id ][ $emoji_key ] ) ) { + $this->reaction_summaries[ $note_id ][ $emoji_key ] = array( + 'count' => 0, + 'current_user_reaction' => $my_reactions[ $key ] ?? 0, + ); + } + + $this->reaction_summaries[ $note_id ][ $emoji_key ]['count'] += (int) $row->reaction_count; } } @@ -2699,6 +2760,33 @@ protected function check_target_post_permission( int $post_id, WP_REST_Request $ return true; } + /** + * Checks that a note's parent is a note on the same post. + * + * @since 7.2.0 + * + * @param int $parent_id ID of the parent comment. + * @param int $post_id ID of the post the note is, or will be, on. + * @return true|WP_Error True if the parent is valid, error object otherwise. + */ + private function check_note_parent( int $parent_id, int $post_id ) { + $parent = get_comment( $parent_id ); + + if ( + ! $parent || + 'note' !== $parent->comment_type || + ( $post_id && $post_id !== (int) $parent->comment_post_ID ) + ) { + return new WP_Error( + 'rest_comment_invalid_parent', + __( 'A note reply must be attached to a note on the same post.' ), + array( 'status' => 400 ) + ); + } + + return true; + } + /** * Checks whether a note belongs to a resolved thread. * diff --git a/tests/phpunit/tests/ajax/wpAjaxEditComment.php b/tests/phpunit/tests/ajax/wpAjaxEditComment.php index fb39bd4dae41b..155a7ccc278db 100644 --- a/tests/phpunit/tests/ajax/wpAjaxEditComment.php +++ b/tests/phpunit/tests/ajax/wpAjaxEditComment.php @@ -242,4 +242,521 @@ public function test_wp_update_comment_data_is_wp_error() { public function _wp_update_comment_data_filter( $data, $comment, $commentarr ) { return new WP_Error( 'comment_wrong', 'wp_update_comment_data filter fails for this comment.', 500 ); } + + /** + * The curated reaction key for the heart emoji, as stored in a reaction's content. + */ + private const HEART_REACTION_KEY = '2764'; + + /** + * Creates an administrator's open note and approved reaction on a post. + * + * @param int $post_id Post to attach the note to. + * @param int $admin_id User who owns the note and reaction. + * @return positive-int The reaction ID. + */ + private function create_admin_reaction( int $post_id, int $admin_id ): int { + $note_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => 'note', + 'comment_approved' => 0, + 'user_id' => $admin_id, + 'comment_content' => 'Editorial note', + ) + ); + + return self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => 'reaction', + 'comment_parent' => $note_id, + 'comment_approved' => 1, + 'user_id' => $admin_id, + 'comment_content' => self::HEART_REACTION_KEY, + ) + ); + } + + /** + * Reactions are immutable. The REST API refuses to update them, and the + * admin-ajax writer has to refuse too, or anyone who can edit the post + * rewrites and reattributes other users' reactions. + * + * @ticket 66635 + */ + public function test_cannot_edit_reaction(): void { + $this->_setRole( 'contributor' ); + + $admin_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); + $draft_id = self::factory()->post->create( + array( + 'post_author' => get_current_user_id(), + 'post_status' => 'draft', + ) + ); + $reaction_id = $this->create_admin_reaction( $draft_id, $admin_id ); + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $reaction_id, + 'content' => 'rewritten', + 'newcomment_author' => 'Forged', + 'newcomment_author_email' => 'forged@example.org', + 'user_id' => (string) get_current_user_id(), + ) + ); + + try { + $this->_handleAjax( 'edit-comment' ); + $this->fail( 'The handler should have refused to edit a reaction.' ); + } catch ( WPAjaxDieStopException $e ) { + unset( $e ); + } + + $reaction = get_comment( $reaction_id ); + $this->assertInstanceOf( WP_Comment::class, $reaction ); + $this->assertSame( self::HEART_REACTION_KEY, $reaction->comment_content ); + $this->assertSame( (string) $admin_id, $reaction->user_id ); + $this->assertSame( '', $reaction->comment_author_email ); + } + + /** + * Moving a comment requires edit access to the destination post, not only + * to the post it is on. + * + * @ticket 66635 + */ + public function test_cannot_move_comment_to_post_user_cannot_edit(): void { + $this->_setRole( 'contributor' ); + + $admin_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); + $draft_id = self::factory()->post->create( + array( + 'post_author' => get_current_user_id(), + 'post_status' => 'draft', + ) + ); + $admin_post_id = self::factory()->post->create( array( 'post_author' => $admin_id ) ); + $comment_id = self::factory()->comment->create( array( 'comment_post_ID' => $draft_id ) ); + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $comment_id, + 'content' => 'Moved', + 'comment_post_ID' => (string) $admin_post_id, + ) + ); + + try { + $this->_handleAjax( 'edit-comment' ); + $this->fail( 'The handler should have refused to move the comment.' ); + } catch ( WPAjaxDieStopException $e ) { + unset( $e ); + } + + $comment = get_comment( $comment_id ); + $this->assertInstanceOf( WP_Comment::class, $comment ); + $this->assertSame( (string) $draft_id, $comment->comment_post_ID ); + } + + /** + * A user who can edit both posts can still move a comment between them. + * + * @ticket 66635 + */ + public function test_can_move_comment_to_post_user_can_edit(): void { + $this->_setRole( 'editor' ); + + $source_post_id = self::factory()->post->create(); + $target_post_id = self::factory()->post->create(); + $comment_id = self::factory()->comment->create( array( 'comment_post_ID' => $source_post_id ) ); + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $comment_id, + 'content' => 'Moved', + 'comment_post_ID' => (string) $target_post_id, + ) + ); + + try { + $this->_handleAjax( 'edit-comment' ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } + + $comment = get_comment( $comment_id ); + $this->assertInstanceOf( WP_Comment::class, $comment ); + $this->assertSame( (string) $target_post_id, $comment->comment_post_ID ); + } + + /** + * An author who can reply beneath a note on their own post must not be + * able to turn that reply into a reaction attributed to someone else. + * + * @ticket 66635 + */ + public function test_cannot_convert_comment_into_reaction(): void { + $this->_setRole( 'author' ); + + $admin_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); + $post_id = self::factory()->post->create( array( 'post_author' => get_current_user_id() ) ); + $note_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => 'note', + 'comment_approved' => 0, + 'user_id' => $admin_id, + 'comment_content' => 'Editorial note', + ) + ); + + // Step 1: reply beneath the note with an ordinary comment. + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_post_ID' => (string) $post_id, + 'comment_ID' => (string) $note_id, + 'content' => 'Ordinary reply', + ) + ); + + try { + $this->_handleAjax( 'replyto-comment' ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } + + $replies = get_comments( + array( + 'post_id' => $post_id, + 'parent' => $note_id, + 'type' => 'comment', + 'status' => 'all', + 'fields' => 'ids', + ) + ); + $this->assertCount( 1, $replies ); + $reply_id = (int) $replies[0]; + + // Step 2: edit the reply into a reaction owned by the administrator. + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $reply_id, + 'content' => self::HEART_REACTION_KEY, + 'comment_type' => 'reaction', + 'user_id' => (string) $admin_id, + ) + ); + + try { + $this->_handleAjax( 'edit-comment' ); + } catch ( WPDieException $e ) { + unset( $e ); + } + + $reply = get_comment( $reply_id ); + $this->assertInstanceOf( WP_Comment::class, $reply ); + $this->assertSame( 'comment', $reply->comment_type ); + $this->assertSame( 'Ordinary reply', $reply->comment_content ); + $this->assertSame( (string) get_current_user_id(), $reply->user_id ); + } + + /** + * A post ID of zero skips the destination check and would orphan the + * comment, which drops its capability mapping to the post. + * + * @ticket 66635 + */ + public function test_cannot_detach_comment_from_its_post(): void { + $this->_setRole( 'contributor' ); + + $admin_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); + $draft_id = self::factory()->post->create( + array( + 'post_author' => get_current_user_id(), + 'post_status' => 'draft', + ) + ); + $note_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $draft_id, + 'comment_type' => 'note', + 'comment_approved' => 0, + 'user_id' => $admin_id, + 'comment_content' => 'Editorial note', + ) + ); + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $note_id, + 'content' => 'Editorial note', + 'comment_post_ID' => '0', + ) + ); + + try { + $this->_handleAjax( 'edit-comment' ); + } catch ( WPDieException $e ) { + unset( $e ); + } + + $note = get_comment( $note_id ); + $this->assertInstanceOf( WP_Comment::class, $note ); + $this->assertSame( (string) $draft_id, $note->comment_post_ID ); + } + + /** + * The new parent has to be on the post the comment is moving to, not the + * one it is leaving. + * + * @ticket 66635 + */ + public function test_cannot_move_comment_under_parent_on_the_post_it_leaves(): void { + $this->_setRole( 'editor' ); + update_option( 'thread_comments', 1 ); + + $post_a_id = self::factory()->post->create(); + $post_b_id = self::factory()->post->create(); + $parent_id = self::factory()->comment->create( array( 'comment_post_ID' => $post_a_id ) ); + $comment_id = self::factory()->comment->create( array( 'comment_post_ID' => $post_a_id ) ); + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $comment_id, + 'content' => 'Moved', + 'comment_post_ID' => (string) $post_b_id, + 'comment_parent' => (string) $parent_id, + ) + ); + + try { + $this->_handleAjax( 'edit-comment' ); + } catch ( WPDieException $e ) { + unset( $e ); + } + + $comment = get_comment( $comment_id ); + $this->assertInstanceOf( WP_Comment::class, $comment ); + $this->assertSame( (string) $post_a_id, $comment->comment_post_ID ); + $this->assertSame( '0', $comment->comment_parent ); + } + + /** + * A reply cannot move to another post while still threaded under a + * comment on the post it leaves. + * + * @ticket 66635 + */ + public function test_cannot_move_reply_away_from_its_parent(): void { + $this->_setRole( 'editor' ); + update_option( 'thread_comments', 1 ); + + $post_a_id = self::factory()->post->create(); + $post_b_id = self::factory()->post->create(); + $parent_id = self::factory()->comment->create( array( 'comment_post_ID' => $post_a_id ) ); + $reply_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $post_a_id, + 'comment_parent' => $parent_id, + ) + ); + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $reply_id, + 'content' => 'Moved', + 'comment_post_ID' => (string) $post_b_id, + ) + ); + + try { + $this->_handleAjax( 'edit-comment' ); + } catch ( WPDieException $e ) { + unset( $e ); + } + + $reply = get_comment( $reply_id ); + $this->assertInstanceOf( WP_Comment::class, $reply ); + $this->assertSame( (string) $post_a_id, $reply->comment_post_ID ); + } + + /** + * A reply can move to another post when the same request detaches it from + * its parent, since the submitted parent is the one that will be kept. + * + * @ticket 66635 + */ + public function test_can_move_reply_to_another_post_when_detached_from_its_parent(): void { + $this->_setRole( 'editor' ); + update_option( 'thread_comments', 1 ); + + $post_a_id = self::factory()->post->create(); + $post_b_id = self::factory()->post->create(); + $parent_id = self::factory()->comment->create( array( 'comment_post_ID' => $post_a_id ) ); + $reply_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $post_a_id, + 'comment_parent' => $parent_id, + ) + ); + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $reply_id, + 'content' => 'Moved', + 'comment_post_ID' => (string) $post_b_id, + 'comment_parent' => '0', + ) + ); + + try { + $this->_handleAjax( 'edit-comment' ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } + + $reply = get_comment( $reply_id ); + $this->assertInstanceOf( WP_Comment::class, $reply ); + $this->assertSame( (string) $post_b_id, $reply->comment_post_ID ); + $this->assertSame( '0', $reply->comment_parent ); + } + + /** + * A note's reactions stay on its post, so moving the note would separate + * them and empty its reaction summary. + * + * @ticket 66635 + */ + public function test_cannot_move_note_that_has_reactions(): void { + $this->_setRole( 'editor' ); + + $post_a_id = self::factory()->post->create(); + $post_b_id = self::factory()->post->create(); + $reaction_id = $this->create_admin_reaction( $post_a_id, get_current_user_id() ); + $reaction = get_comment( $reaction_id ); + $this->assertInstanceOf( WP_Comment::class, $reaction ); + $note_id = (int) $reaction->comment_parent; + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $note_id, + 'content' => 'Moved', + 'comment_post_ID' => (string) $post_b_id, + ) + ); + + try { + $this->_handleAjax( 'edit-comment' ); + } catch ( WPDieException $e ) { + unset( $e ); + } + + $note = get_comment( $note_id ); + $this->assertInstanceOf( WP_Comment::class, $note ); + $this->assertSame( (string) $post_a_id, $note->comment_post_ID ); + } + + /** + * A note with no replies or reactions can still move. + * + * @ticket 66635 + */ + public function test_can_move_note_without_children(): void { + $this->_setRole( 'editor' ); + + $post_a_id = self::factory()->post->create(); + $post_b_id = self::factory()->post->create(); + $note_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $post_a_id, + 'comment_type' => 'note', + 'comment_approved' => 0, + ) + ); + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $note_id, + 'content' => 'Moved', + 'comment_post_ID' => (string) $post_b_id, + ) + ); + + try { + $this->_handleAjax( 'edit-comment' ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } + + $note = get_comment( $note_id ); + $this->assertInstanceOf( WP_Comment::class, $note ); + $this->assertSame( (string) $post_b_id, $note->comment_post_ID ); + } + + /** + * A note cannot stop being one, including by a change of case. + * + * @ticket 66635 + * + * @dataProvider data_types_a_note_cannot_become + * + * @param non-falsy-string $type The requested comment type. + */ + public function test_cannot_convert_note_into_another_type( string $type ): void { + $this->_setRole( 'editor' ); + + $post_id = self::factory()->post->create(); + $note_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => 'note', + 'comment_approved' => 0, + ) + ); + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $note_id, + 'content' => 'Converted', + 'comment_type' => $type, + ) + ); + + try { + $this->_handleAjax( 'edit-comment' ); + $this->fail( 'The handler should have refused to change the note type.' ); + } catch ( WPAjaxDieStopException $e ) { + unset( $e ); + } + + $note = get_comment( $note_id ); + $this->assertInstanceOf( WP_Comment::class, $note ); + $this->assertSame( 'note', $note->comment_type ); + } + + /** + * Data provider. + * + * @return array + */ + public function data_types_a_note_cannot_become(): array { + return array( + 'comment' => array( 'comment' ), + 'uppercase note' => array( 'NOTE' ), + ); + } } diff --git a/tests/phpunit/tests/ajax/wpAjaxReplytoComment.php b/tests/phpunit/tests/ajax/wpAjaxReplytoComment.php index b67a7ba828439..5c6d335aa7e68 100644 --- a/tests/phpunit/tests/ajax/wpAjaxReplytoComment.php +++ b/tests/phpunit/tests/ajax/wpAjaxReplytoComment.php @@ -270,4 +270,103 @@ public function test_pre_comments_approved() { public function _pre_comment_approved_filter( $approved, $commentdata ) { return new WP_Error( 'comment_wrong', 'pre_comment_approved filter fails for new comment.', 403 ); } + + /** + * Notes and reactions are created through the REST API, which enforces + * their invariants. The reply handler must not mint them. + * + * @ticket 66635 + * + * @dataProvider data_restricted_comment_types + * + * @param non-falsy-string $type The comment type to request. + */ + public function test_cannot_reply_with_restricted_comment_type( string $type ): void { + $this->_setRole( 'administrator' ); + + $post_id = self::factory()->post->create(); + $parent_id = self::factory()->comment->create( array( 'comment_post_ID' => $post_id ) ); + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $parent_id, + 'content' => '2764', + 'comment_post_ID' => (string) $post_id, + 'comment_type' => $type, + ) + ); + + try { + $this->_handleAjax( 'replyto-comment' ); + $this->fail( 'The handler should have refused the comment type.' ); + } catch ( WPAjaxDieStopException $e ) { + $this->assertSame( '-1', $e->getMessage() ); + } + + $this->assertSame( + array(), + get_comments( + array( + 'type' => $type, + 'status' => 'any', + 'fields' => 'ids', + ) + ), + 'No comment of the restricted type should have been created.' + ); + } + + /** + * Data provider. + * + * @return array + */ + public function data_restricted_comment_types(): array { + return array( + 'reaction' => array( 'reaction' ), + 'reaction, capitalized' => array( 'Reaction' ), + 'note' => array( 'note' ), + 'note, capitalized' => array( 'Note' ), + 'reaction, accented' => array( 'reactión' ), + 'uppercase custom type' => array( 'Custom' ), + ); + } + + /** + * A reply whose parent is on a different post is stored unthreaded. + * + * @ticket 66635 + */ + public function test_reply_to_comment_on_another_post_is_not_threaded(): void { + $this->_setRole( 'administrator' ); + + $post_id = self::factory()->post->create(); + $other_post = self::factory()->post->create(); + $other_comment = self::factory()->comment->create( array( 'comment_post_ID' => $other_post ) ); + + $_POST = wp_slash( + array( + '_ajax_nonce-replyto-comment' => wp_create_nonce( 'replyto-comment' ), + 'comment_ID' => (string) $other_comment, + 'content' => 'Reply across posts', + 'comment_post_ID' => (string) $post_id, + ) + ); + + try { + $this->_handleAjax( 'replyto-comment' ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } + + $xml = simplexml_load_string( $this->_last_response, 'SimpleXMLElement', LIBXML_NOCDATA ); + $this->assertInstanceOf( SimpleXMLElement::class, $xml ); + + $comment = get_comment( (int) $xml->response[0]->comment['id'] ); + $this->assertInstanceOf( WP_Comment::class, $comment ); + + $this->assertSame( (string) $post_id, $comment->comment_post_ID ); + $this->assertSame( '0', $comment->comment_parent, 'A parent on another post should be dropped.' ); + } } diff --git a/tests/phpunit/tests/comment.php b/tests/phpunit/tests/comment.php index 52d9e5698cf6d..fd403088b5ce3 100644 --- a/tests/phpunit/tests/comment.php +++ b/tests/phpunit/tests/comment.php @@ -3035,4 +3035,44 @@ public function test_meta_query_invalidation_preserves_absent_callback() { add_action( 'added_comment_meta', 'wp_cache_set_comments_last_changed' ); } } + + /** + * The rules for notes and reactions belong to the request handlers. + * wp_update_comment() stays unrestricted, like other low-level writers. + * + * @ticket 66635 + */ + public function test_wp_update_comment_does_not_restrict_reactions(): void { + $post_id = self::factory()->post->create(); + $note_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => 'note', + 'comment_approved' => 0, + ) + ); + $reaction_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => 'reaction', + 'comment_parent' => $note_id, + 'comment_approved' => 1, + 'comment_content' => '2764', + ) + ); + + $result = wp_update_comment( + array( + 'comment_ID' => $reaction_id, + 'comment_content' => '1f680', + ), + true + ); + + $this->assertSame( 1, $result ); + + $reaction = get_comment( $reaction_id ); + $this->assertInstanceOf( WP_Comment::class, $reaction ); + $this->assertSame( '1f680', $reaction->comment_content ); + } } diff --git a/tests/phpunit/tests/rest-api/rest-comments-controller.php b/tests/phpunit/tests/rest-api/rest-comments-controller.php index 7cb9f647063d9..513bdbfd51220 100644 --- a/tests/phpunit/tests/rest-api/rest-comments-controller.php +++ b/tests/phpunit/tests/rest-api/rest-comments-controller.php @@ -6635,4 +6635,345 @@ public function test_reaction_summary_excludes_trashed_reactions() { $this->assertSame( array(), $response->get_data()['reaction_summary'] ); } + + /** + * The curated reaction key for the heart emoji, as stored in a reaction's content. + */ + private const HEART_REACTION_KEY = '2764'; + + /** + * Creates an open note by the editor on a new post. + * + * @return array{int, int} The post ID and the note ID. + */ + private function create_editor_note(): array { + $post_id = self::factory()->post->create(); + $note_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => 'note', + 'comment_approved' => 0, + 'user_id' => self::$editor_id, + 'comment_content' => 'Test note', + ) + ); + + return array( $post_id, $note_id ); + } + + /** + * Reads a note's reaction summary as the editor. + * + * @param int $note_id The note ID. + * @return array + */ + private function get_reaction_summary( int $note_id ): array { + wp_set_current_user( self::$editor_id ); + + $request = new WP_REST_Request( 'GET', '/wp/v2/comments/' . $note_id ); + $request->set_param( 'context', 'edit' ); + + $data = rest_get_server()->dispatch( $request )->get_data(); + $this->assertIsArray( $data ); + $this->assertArrayHasKey( 'reaction_summary', $data ); + $this->assertIsArray( $data['reaction_summary'] ); + + /** @var array $summary */ + $summary = $data['reaction_summary']; + + return $summary; + } + + /** + * A reaction stored against another post is not a reaction to this note, + * whatever its parent says. + * + * @ticket 66635 + */ + public function test_reaction_summary_ignores_reactions_stored_on_another_post(): void { + list( , $note_id ) = $this->create_editor_note(); + $other_post_id = self::factory()->post->create(); + + self::factory()->comment->create( + array( + 'comment_post_ID' => $other_post_id, + 'comment_type' => 'reaction', + 'comment_parent' => $note_id, + 'comment_approved' => 1, + 'user_id' => self::$subscriber_id, + 'comment_content' => self::HEART_REACTION_KEY, + ) + ); + + $this->assertSame( array(), $this->get_reaction_summary( $note_id ) ); + } + + /** + * Only the curated emoji keys are summarized. + * + * @ticket 66635 + */ + public function test_reaction_summary_ignores_uncurated_keys(): void { + list( $post_id, $note_id ) = $this->create_editor_note(); + + self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => 'reaction', + 'comment_parent' => $note_id, + 'comment_approved' => 1, + 'user_id' => self::$subscriber_id, + 'comment_content' => 'not-an-emoji-key', + ) + ); + + $this->assertSame( array(), $this->get_reaction_summary( $note_id ) ); + } + + /** + * Rows that strip to the same key are counted together rather than the + * last one overwriting the others. + * + * @ticket 66635 + */ + public function test_reaction_summary_accumulates_rows_that_strip_to_the_same_key(): void { + list( $post_id, $note_id ) = $this->create_editor_note(); + + $heart_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => 'reaction', + 'comment_parent' => $note_id, + 'comment_approved' => 1, + 'user_id' => self::$editor_id, + 'comment_content' => self::HEART_REACTION_KEY, + ) + ); + + self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => 'reaction', + 'comment_parent' => $note_id, + 'comment_approved' => 1, + 'user_id' => self::$subscriber_id, + 'comment_content' => '' . self::HEART_REACTION_KEY . '', + ) + ); + + $summary = $this->get_reaction_summary( $note_id ); + + $this->assertCount( 1, $summary ); + $this->assertArrayHasKey( self::HEART_REACTION_KEY, $summary ); + $this->assertSame( 2, $summary[ self::HEART_REACTION_KEY ]['count'] ); + $this->assertSame( $heart_id, $summary[ self::HEART_REACTION_KEY ]['current_user_reaction'] ); + } + + /** + * A note reply has to sit on the same post as the note it answers, or a + * user could thread their own note under one on a post they cannot read. + * + * @ticket 66635 + */ + public function test_cannot_create_note_reply_under_note_on_another_post(): void { + list( , $note_id ) = $this->create_editor_note(); + $post_b_id = self::factory()->post->create(); + + wp_set_current_user( self::$editor_id ); + + $request = new WP_REST_Request( 'POST', '/wp/v2/comments' ); + $request->set_param( 'type', 'note' ); + $request->set_param( 'post', $post_b_id ); + $request->set_param( 'parent', $note_id ); + $request->set_param( 'content', 'Reply from another post' ); + + $response = rest_get_server()->dispatch( $request ); + + $this->assertErrorResponse( 'rest_comment_invalid_parent', $response, 400 ); + } + + /** + * The same-post rule for note replies holds on update too. + * + * @ticket 66635 + */ + public function test_cannot_update_note_parent_to_note_on_another_post(): void { + list( , $note_a_id ) = $this->create_editor_note(); + list( , $note_b_id ) = $this->create_editor_note(); + + wp_set_current_user( self::$editor_id ); + + $request = new WP_REST_Request( 'PUT', '/wp/v2/comments/' . $note_b_id ); + $request->set_param( 'parent', $note_a_id ); + + $response = rest_get_server()->dispatch( $request ); + + $this->assertErrorResponse( 'rest_comment_invalid_parent', $response, 400 ); + + $note_b = get_comment( $note_b_id ); + $this->assertInstanceOf( WP_Comment::class, $note_b ); + $this->assertSame( '0', $note_b->comment_parent ); + } + + /** + * A note cannot be threaded under a regular comment by an update. + * + * @ticket 66635 + */ + public function test_cannot_update_note_parent_to_a_comment(): void { + list( $post_id, $note_id ) = $this->create_editor_note(); + $comment_id = self::factory()->comment->create( array( 'comment_post_ID' => $post_id ) ); + + wp_set_current_user( self::$editor_id ); + + $request = new WP_REST_Request( 'PUT', '/wp/v2/comments/' . $note_id ); + $request->set_param( 'parent', $comment_id ); + + $response = rest_get_server()->dispatch( $request ); + + $this->assertErrorResponse( 'rest_comment_invalid_parent', $response, 400 ); + } + + /** + * Moving a note reply to another post would leave it under a note on the + * post it left. + * + * @ticket 66635 + */ + public function test_cannot_move_note_reply_away_from_its_parent(): void { + list( $post_id, $note_id ) = $this->create_editor_note(); + $other_post_id = self::factory()->post->create(); + $reply_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => 'note', + 'comment_parent' => $note_id, + 'comment_approved' => 0, + 'user_id' => self::$editor_id, + ) + ); + + wp_set_current_user( self::$editor_id ); + + $request = new WP_REST_Request( 'PUT', '/wp/v2/comments/' . $reply_id ); + $request->set_param( 'post', $other_post_id ); + + $response = rest_get_server()->dispatch( $request ); + + $this->assertErrorResponse( 'rest_comment_invalid_parent', $response, 400 ); + + $reply = get_comment( $reply_id ); + $this->assertInstanceOf( WP_Comment::class, $reply ); + $this->assertSame( (string) $post_id, $reply->comment_post_ID ); + } + + /** + * A note's replies and reactions stay on its post, so moving the note + * would separate them and empty its reaction summary. + * + * @ticket 66635 + * + * @dataProvider data_note_child_types + * + * @param string $child_type Comment type of the note's child. + */ + public function test_cannot_move_note_that_has_children( string $child_type ): void { + list( $post_id, $note_id ) = $this->create_editor_note(); + $other_post_id = self::factory()->post->create(); + + self::factory()->comment->create( + array( + 'comment_post_ID' => $post_id, + 'comment_type' => $child_type, + 'comment_parent' => $note_id, + 'comment_approved' => 'reaction' === $child_type ? 1 : 0, + 'user_id' => self::$subscriber_id, + 'comment_content' => 'reaction' === $child_type ? self::HEART_REACTION_KEY : 'Reply', + ) + ); + + wp_set_current_user( self::$editor_id ); + + $request = new WP_REST_Request( 'PUT', '/wp/v2/comments/' . $note_id ); + $request->set_param( 'post', $other_post_id ); + + $response = rest_get_server()->dispatch( $request ); + + $this->assertErrorResponse( 'rest_comment_has_children', $response, 400 ); + + $note = get_comment( $note_id ); + $this->assertInstanceOf( WP_Comment::class, $note ); + $this->assertSame( (string) $post_id, $note->comment_post_ID ); + } + + /** + * Data provider. + * + * @return array + */ + public function data_note_child_types(): array { + return array( + 'a reaction' => array( 'reaction' ), + 'a reply' => array( 'note' ), + ); + } + + /** + * A note with no replies or reactions can still move. + * + * @ticket 66635 + */ + public function test_can_move_note_without_children(): void { + list( , $note_id ) = $this->create_editor_note(); + $other_post_id = self::factory()->post->create(); + + wp_set_current_user( self::$editor_id ); + + $request = new WP_REST_Request( 'PUT', '/wp/v2/comments/' . $note_id ); + $request->set_param( 'post', $other_post_id ); + + $response = rest_get_server()->dispatch( $request ); + + $this->assertSame( 200, $response->get_status() ); + + $note = get_comment( $note_id ); + $this->assertInstanceOf( WP_Comment::class, $note ); + $this->assertSame( (string) $other_post_id, $note->comment_post_ID ); + } + + /** + * The reaction summary ignores a reaction stored on another post, so the + * uniqueness check has to as well, or the user is refused a reaction they + * cannot see. + * + * @ticket 66635 + */ + public function test_reaction_stored_on_another_post_does_not_block_a_new_reaction(): void { + list( $post_id, $note_id ) = $this->create_editor_note(); + $other_post_id = self::factory()->post->create(); + + self::factory()->comment->create( + array( + 'comment_post_ID' => $other_post_id, + 'comment_type' => 'reaction', + 'comment_parent' => $note_id, + 'comment_approved' => 1, + 'user_id' => self::$editor_id, + 'comment_content' => self::HEART_REACTION_KEY, + ) + ); + + wp_set_current_user( self::$editor_id ); + + $request = new WP_REST_Request( 'POST', '/wp/v2/comments' ); + $request->set_param( 'type', 'reaction' ); + $request->set_param( 'post', $post_id ); + $request->set_param( 'parent', $note_id ); + $request->set_param( 'content', self::HEART_REACTION_KEY ); + + $response = rest_get_server()->dispatch( $request ); + + $this->assertSame( 201, $response->get_status() ); + $this->assertArrayHasKey( self::HEART_REACTION_KEY, $this->get_reaction_summary( $note_id ) ); + } } diff --git a/tests/phpunit/tests/xmlrpc/wp/editComment.php b/tests/phpunit/tests/xmlrpc/wp/editComment.php index 0f998df96707a..860591eab1f85 100644 --- a/tests/phpunit/tests/xmlrpc/wp/editComment.php +++ b/tests/phpunit/tests/xmlrpc/wp/editComment.php @@ -93,4 +93,60 @@ public function test_trash_comment() { $this->assertSame( 'trash', get_comment( $comment_id )->comment_approved ); } + + /** + * Reactions are immutable, whoever asks: XML-RPC needs no nonce, so it + * must not be the one writer that lets a reaction be rewritten. + * + * @ticket 66635 + */ + public function test_cannot_edit_reaction(): void { + $contributor_id = $this->make_user_by_role( 'contributor' ); + $admin_id = $this->make_user_by_role( 'administrator' ); + $draft_id = self::factory()->post->create( + array( + 'post_author' => $contributor_id, + 'post_status' => 'draft', + ) + ); + $note_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $draft_id, + 'comment_type' => 'note', + 'comment_approved' => 0, + 'user_id' => $admin_id, + 'comment_content' => 'Editorial note', + ) + ); + $reaction_id = self::factory()->comment->create( + array( + 'comment_post_ID' => $draft_id, + 'comment_type' => 'reaction', + 'comment_parent' => $note_id, + 'comment_approved' => 1, + 'user_id' => $admin_id, + 'comment_content' => '2764', + ) + ); + + $result = $this->myxmlrpcserver->wp_editComment( + array( + 1, + 'contributor', + 'contributor', + $reaction_id, + array( + 'content' => 'rewritten', + 'author' => 'Forged', + ), + ) + ); + + $this->assertIXRError( $result ); + + $reaction = get_comment( $reaction_id ); + $this->assertInstanceOf( WP_Comment::class, $reaction ); + $this->assertSame( '2764', $reaction->comment_content ); + $this->assertSame( $admin_id, (int) $reaction->user_id ); + } } diff --git a/tests/qunit/fixtures/wp-api-generated.js b/tests/qunit/fixtures/wp-api-generated.js index bb83cd91b8728..ba63e6425b7fd 100644 --- a/tests/qunit/fixtures/wp-api-generated.js +++ b/tests/qunit/fixtures/wp-api-generated.js @@ -10598,7 +10598,8 @@ mockedApiResponse.Schema = { "description": "Limit result set to comments of specific parent IDs.", "type": "array", "items": { - "type": "integer" + "type": "integer", + "minimum": 0 }, "required": false }, @@ -10722,12 +10723,14 @@ mockedApiResponse.Schema = { "default": 0, "description": "The ID for the parent of the comment.", "type": "integer", + "minimum": 0, "required": false }, "post": { "default": 0, "description": "The ID of the associated post object.", "type": "integer", + "minimum": 0, "required": false }, "status": { @@ -10870,11 +10873,13 @@ mockedApiResponse.Schema = { "parent": { "description": "The ID for the parent of the comment.", "type": "integer", + "minimum": 0, "required": false }, "post": { "description": "The ID of the associated post object.", "type": "integer", + "minimum": 0, "required": false }, "status": { From 91b5036f4ec5c60465a796358b56e274334ff8f5 Mon Sep 17 00:00:00 2001 From: George Mamadashvili Date: Tue, 24 Nov 2026 09:17:17 +0000 Subject: [PATCH 62/85] General: Bump the pinned hash for Gutenberg to `c5bdc7f`. This updates the pinned commit hash of the Gutenberg repository from `efd7722f89ebb8abfc3607fffdd86f5e34afbd9c` to `c5bdc7f4898ec98114cdccbe1cacec7a979b85cc` (head of the `wp/7.2` branch). A full list of changes included in this commit can be found on GitHub: https://github.com/WordPress/gutenberg/compare/efd7722f89ebb8abfc3607fffdd86f5e34afbd9c...c5bdc7f4898ec98114cdccbe1cacec7a979b85cc. - Interactivity API: Align unsupported `data-wp-html` bindings with PHP (https://github.com/WordPress/gutenberg/pull/86968) (https://github.com/WordPress/gutenberg/pull/87015) - E2E: Select the link preview by URL in the keyboard test (https://github.com/WordPress/gutenberg/pull/87053) (https://github.com/WordPress/gutenberg/pull/87102) - Update the Update icon. (https://github.com/WordPress/gutenberg/pull/87088) (https://github.com/WordPress/gutenberg/pull/87139) - Editor: Hide parent controls for non-hierarchical post types (https://github.com/WordPress/gutenberg/pull/85679) (https://github.com/WordPress/gutenberg/pull/87150) - SearchableChipSelect: Use a single string for the chips toolbar label (https://github.com/WordPress/gutenberg/pull/87219) (https://github.com/WordPress/gutenberg/pull/87275) - E2E Tests: Switch the theme before the other setup resets (https://github.com/WordPress/gutenberg/pull/86278) - Abilities: Accept a date-time without an offset in the `date-time` schema format (https://github.com/WordPress/gutenberg/pull/86845) (https://github.com/WordPress/gutenberg/pull/87311) - Fix iOS tap into a quote jumping to the caret's block when it's off screen (https://github.com/WordPress/gutenberg/pull/86923) - Place the caret on a tap after the keyboard is swiped away (https://github.com/WordPress/gutenberg/pull/87182) - Writing flow: Keep the browser from deleting into a neighbouring block (https://github.com/WordPress/gutenberg/pull/87188) - Writing flow: Bring back the header iOS slides off screen, once the canvas stops scrolling (https://github.com/WordPress/gutenberg/pull/87316) - List: Drag a list item by its bullet again (https://github.com/WordPress/gutenberg/pull/85801) - MediaEdit: Show the image preview when the MIME type is empty (https://github.com/WordPress/gutenberg/pull/87207) (https://github.com/WordPress/gutenberg/pull/87326) - Block Editor: Fix block hover outline flicker when moving between elements of a block (https://github.com/WordPress/gutenberg/pull/86852) (https://github.com/WordPress/gutenberg/pull/87328) Developed in: https://github.com/WordPress/wordpress-develop/pull/16187 Props peterwilsoncc, mamaduka, linewebdigital, abhishekfdd, oandregal, jorgefilipecosta. See #66340. Fixes #66428. git-svn-id: https://develop.svn.wordpress.org/trunk@65751 602fd350-edb4-49c9-b593-d223f7449a82 --- package.json | 2 +- .../assets/script-loader-packages.php | 8 ++-- .../assets/script-modules-packages.php | 8 ++-- .../build/scripts/core-fields/index.php | 4 +- .../post_type_supports/parent/field.php | 6 +-- .../images/icon-library/update.svg | 3 +- .../wpRegisterCoreFieldCollections.php | 46 ++++++++++++++++++- 7 files changed, 61 insertions(+), 16 deletions(-) diff --git a/package.json b/package.json index 12a90c83b077b..4b51f22f896b2 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "url": "https://develop.svn.wordpress.org/trunk" }, "gutenberg": { - "sha": "efd7722f89ebb8abfc3607fffdd86f5e34afbd9c", + "sha": "c5bdc7f4898ec98114cdccbe1cacec7a979b85cc", "ghcrRepo": "WordPress/gutenberg/gutenberg-wp-develop-build" }, "engines": { diff --git a/src/wp-includes/assets/script-loader-packages.php b/src/wp-includes/assets/script-loader-packages.php index e33f77b5f7755..dca8010311142 100644 --- a/src/wp-includes/assets/script-loader-packages.php +++ b/src/wp-includes/assets/script-loader-packages.php @@ -105,7 +105,7 @@ 'wp-url', 'wp-warning' ), - 'version' => 'f9a3114894c529a215ac' + 'version' => 'e21efcc5c30f26ee0aba' ), 'block-library.js' => array( 'dependencies' => array( @@ -151,7 +151,7 @@ 'import' => 'dynamic' ) ), - 'version' => '58156d96a4c9fdf86645' + 'version' => '9ad7f7e62e9fbecbab34' ), 'block-serialization-default-parser.js' => array( 'dependencies' => array( @@ -549,7 +549,7 @@ 'import' => 'static' ) ), - 'version' => '33deefc6545abe93022a' + 'version' => 'c1e50b340a6f2a32176c' ), 'element.js' => array( 'dependencies' => array( @@ -670,7 +670,7 @@ 'wp-url', 'wp-warning' ), - 'version' => 'd91937a9b82062da49eb' + 'version' => '5ef0448131de57454ed0' ), 'notices.js' => array( 'dependencies' => array( diff --git a/src/wp-includes/assets/script-modules-packages.php b/src/wp-includes/assets/script-modules-packages.php index a0560e1063778..9fcc01076e986 100644 --- a/src/wp-includes/assets/script-modules-packages.php +++ b/src/wp-includes/assets/script-modules-packages.php @@ -10,7 +10,7 @@ 'wp-data', 'wp-i18n' ), - 'version' => '9448bb3053516a39086d' + 'version' => '2dfc1cc1ffd6007eaacd' ), 'block-editor/utils/fit-text-frontend.js' => array( 'dependencies' => array( @@ -349,7 +349,7 @@ 'import' => 'static' ) ), - 'version' => '2aa2fe44937a04cb98c7' + 'version' => '5a1005804ad8a5083c79' ), 'core-fields/root_site.js' => array( 'dependencies' => array( @@ -466,7 +466,7 @@ 'dependencies' => array( ), - 'version' => 'b2185b9b3c06dcd1869d' + 'version' => '0c838873c424e941c437' ), 'interactivity-router/full-page.js' => array( 'dependencies' => array( @@ -494,7 +494,7 @@ 'import' => 'static' ) ), - 'version' => 'c0110eac0afb41d3f204' + 'version' => '4555574d1243e79178f5' ), 'latex-to-mathml/index.js' => array( 'dependencies' => array( diff --git a/src/wp-includes/build/scripts/core-fields/index.php b/src/wp-includes/build/scripts/core-fields/index.php index 8b4b10f88233e..8d9fdc42b6dd9 100644 --- a/src/wp-includes/build/scripts/core-fields/index.php +++ b/src/wp-includes/build/scripts/core-fields/index.php @@ -32,7 +32,7 @@ * - `last_edited_date`, for every post type. * - `notesCount`, for the post types whose `editor` support has the `notes` * argument. - * - `parent`, for the post types supporting `page-attributes`. + * - `parent`, for hierarchical post types supporting `page-attributes`. * - `password`, for every post type but the design ones. * - `ping_status`, for the post types supporting `trackbacks`. * - `post-content-info`, for the post types supporting `editor`. @@ -71,7 +71,7 @@ function wp_register_core_post_type_supports_fields() { 'format' => post_type_supports( $post_type, 'post-formats' ) && current_theme_supports( 'post-formats' ), 'last_edited_date' => true, 'notesCount' => is_array( $editor ) && (bool) array_filter( array_column( $editor, 'notes' ) ), - 'parent' => post_type_supports( $post_type, 'page-attributes' ), + 'parent' => is_post_type_hierarchical( $post_type ) && post_type_supports( $post_type, 'page-attributes' ), 'password' => true, 'ping_status' => post_type_supports( $post_type, 'trackbacks' ), 'post-content-info' => post_type_supports( $post_type, 'editor' ), diff --git a/src/wp-includes/build/scripts/core-fields/post_type_supports/parent/field.php b/src/wp-includes/build/scripts/core-fields/post_type_supports/parent/field.php index d26460c976ad8..f3a04ab52ce2f 100644 --- a/src/wp-includes/build/scripts/core-fields/post_type_supports/parent/field.php +++ b/src/wp-includes/build/scripts/core-fields/post_type_supports/parent/field.php @@ -1,8 +1,8 @@ - + + diff --git a/tests/phpunit/tests/entity-fields/wpRegisterCoreFieldCollections.php b/tests/phpunit/tests/entity-fields/wpRegisterCoreFieldCollections.php index 6f9f4ab660089..6150def80e2ee 100644 --- a/tests/phpunit/tests/entity-fields/wpRegisterCoreFieldCollections.php +++ b/tests/phpunit/tests/entity-fields/wpRegisterCoreFieldCollections.php @@ -286,7 +286,6 @@ public static function data_default_fields_and_their_supports() { return array( 'discussion' => array( 'discussion', array( 'comments', 'trackbacks' ) ), 'excerpt' => array( 'excerpt', array( 'excerpt' ) ), - 'parent' => array( 'parent', array( 'page-attributes' ) ), 'ping_status' => array( 'ping_status', array( 'trackbacks' ) ), 'title' => array( 'title', array( 'title' ) ), 'post-content-info' => array( 'post-content-info', array( 'editor' ) ), @@ -318,6 +317,51 @@ public function test_a_default_field_follows_its_supports( $field_id, $supports $this->assertNotContains( $field_id, self::get_field_ids( 'test_without' ), 'A post type without the supports does not get the field.' ); } + /** + * Data provider. + * + * @return array[] Post type settings and expected parent field registration. + */ + public static function data_parent_field_requirements() { + return array( + 'hierarchical with attributes' => array( true, true, true ), + 'hierarchical without attributes' => array( true, false, false ), + 'non-hierarchical with attributes' => array( false, true, false ), + 'non-hierarchical without attributes' => array( false, false, false ), + ); + } + + /** + * The parent field requires both hierarchy and page attributes support. + * + * @ticket 66428 + * + * @dataProvider data_parent_field_requirements + * + * @param bool $hierarchical Whether the post type is hierarchical. + * @param bool $has_attributes Whether the post type supports page attributes. + * @param bool $has_parent Whether the parent field should be registered. + */ + public function test_the_parent_field_requires_hierarchy_and_page_attributes( $hierarchical, $has_attributes, $has_parent ) { + register_post_type( + 'test_parent', + array( + 'show_in_rest' => true, + 'hierarchical' => $hierarchical, + 'supports' => $has_attributes ? array( 'page-attributes' ) : array(), + ) + ); + + try { + self::reset_registry(); + $ids = self::get_field_ids( 'test_parent' ); + } finally { + unregister_post_type( 'test_parent' ); + } + + $this->assertSame( $has_parent, in_array( 'parent', $ids, true ) ); + } + /** * The default fields come from the `field.php` files of the * `post_type_supports` folder. From 649b316869c43f1ef688e6086746d0aa749101eb Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Tue, 24 Nov 2026 09:42:25 +0000 Subject: [PATCH 63/85] Abilities API: Read the schema default in `core/settings-get`. Uses the default declared in a setting's `show_in_abilities` or `show_in_rest` schema when reading a setting that was never saved, rather than only the registered `default` argument. The registered default is still used when the schema declares none. The tests are updated to ensure schema defaults are returned for settings that were never saved. Developed in: https://github.com/WordPress/wordpress-develop/pull/16062 Follow-up to r64311. Reviewed by peterwilsoncc. Props mukesh27, peterwilsoncc. Fixes #64605. git-svn-id: https://develop.svn.wordpress.org/trunk@65752 602fd350-edb4-49c9-b593-d223f7449a82 --- .../abilities/class-wp-abilities-settings.php | 9 ++- .../wpRegisterCoreSettingsGetAbility.php | 64 +++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/abilities/class-wp-abilities-settings.php b/src/wp-includes/abilities/class-wp-abilities-settings.php index 3beb82570ccfe..5729103846917 100644 --- a/src/wp-includes/abilities/class-wp-abilities-settings.php +++ b/src/wp-includes/abilities/class-wp-abilities-settings.php @@ -220,7 +220,8 @@ private function get_settings_get_output_schema(): array { * Reads {@see get_registered_settings()} and keeps only settings flagged with a truthy * `show_in_abilities` argument, of a type the settings endpoint supports. Each entry is * keyed by its exposed name and carries the underlying option name, the settings group, - * the registered default (null when there is none), and a JSON Schema describing the value. + * the default (the exposure schema's default when it declares one, otherwise the registered + * default, or null when there is none), and a JSON Schema describing the value. * * Two settings exposed under the same name trigger a notice, and the later one is exposed. * @@ -260,10 +261,14 @@ private function get_exposed_settings(): array { ); } + /* + * As the settings endpoint does, a default declared in the exposure schema + * overrides the registered default. + */ $settings[ $exposed_name ] = array( 'option' => $option_name, 'group' => $args['group'] ?? '', - 'default' => $args['default'] ?? null, + 'default' => array_key_exists( 'default', $schema ) ? $schema['default'] : ( $args['default'] ?? null ), 'schema' => $schema, ); } diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php index cfdc6677fff8f..016bca1b7a756 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php @@ -625,7 +625,71 @@ public static function data_never_saved_settings(): array { ), 'false', ), + 'a default in the REST API schema' => array( + array( + 'type' => 'string', + 'show_in_rest' => array( + 'schema' => array( 'default' => 'from-rest-schema' ), + ), + ), + '"from-rest-schema"', + ), + 'a REST API schema default overriding the registered default' => array( + array( + 'type' => 'string', + 'default' => 'registered', + 'show_in_rest' => array( + 'schema' => array( 'default' => 'from-rest-schema' ), + ), + ), + '"from-rest-schema"', + ), + 'a default in the abilities schema' => array( + array( + 'type' => 'string', + 'show_in_abilities' => array( + 'schema' => array( 'default' => 'from-abilities-schema' ), + ), + ), + '"from-abilities-schema"', + ), + ); + } + + /** + * A setting that was never saved reads the same default through the ability as through + * the settings endpoint, including a default declared only in the REST API schema. + * + * @ticket 64605 + */ + public function test_core_settings_get_matches_the_settings_endpoint_for_a_schema_default(): void { + $option = 'core_settings_get_ability_schema_default_test_option'; + + register_setting( + 'general', + $option, + array( + 'type' => 'string', + 'show_in_rest' => array( + 'schema' => array( 'default' => 'from-rest-schema' ), + ), + 'show_in_abilities' => true, + ) ); + + try { + $this->register_ability(); + $this->become_admin(); + + $ability_result = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( $option ) ) ); + $rest_result = rest_get_server()->dispatch( new WP_REST_Request( 'GET', '/wp/v2/settings' ) )->get_data(); + } finally { + unregister_setting( 'general', $option ); + $this->register_ability(); + } + + $this->assertSame( 'from-rest-schema', $rest_result[ $option ] ?? null, 'The settings endpoint should read the REST API schema default.' ); + $this->assertSame( $rest_result[ $option ] ?? null, $ability_result[ $option ] ?? null, 'The ability should read the same default as the settings endpoint.' ); } /** From 9f62d9339fc05ac3e22d56aa3e7fadd0948976bf Mon Sep 17 00:00:00 2001 From: Aki Hamano Date: Tue, 24 Nov 2026 10:59:19 +0000 Subject: [PATCH 64/85] Help/About: Update the About page for 7.2. Introduces the new content for the 7.2 About page. Developed in: https://github.com/WordPress/wordpress-develop/pull/16078 Props adamsilverstein, fcoveram, huzaifaalmesbah, mamaduka, markoserb, mosescursor, nazmul111, obenland, peterwilsoncc, sfougnier, trascaandrei, tusharaddweb, wildworks. Fixes #66202. git-svn-id: https://develop.svn.wordpress.org/trunk@65753 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/about.php | 44 +++++++++---------- src/wp-admin/css/about.css | 40 +++++++++++------ .../images/about-header-credits-rtl.svg | 2 +- src/wp-admin/images/about-header-credits.svg | 2 +- .../images/about-header-default-rtl.svg | 2 +- src/wp-admin/images/about-header-default.svg | 2 +- .../images/about-header-freedoms-rtl.svg | 2 +- src/wp-admin/images/about-header-freedoms.svg | 2 +- .../images/about-header-get-involved-rtl.svg | 2 +- .../images/about-header-get-involved.svg | 2 +- .../images/about-header-privacy-rtl.svg | 2 +- src/wp-admin/images/about-header-privacy.svg | 2 +- src/wp-admin/images/about-release-badge.svg | 7 ++- 13 files changed, 65 insertions(+), 46 deletions(-) diff --git a/src/wp-admin/about.php b/src/wp-admin/about.php index 1bfc3018e0556..a3c27bca791fb 100644 --- a/src/wp-admin/about.php +++ b/src/wp-admin/about.php @@ -14,7 +14,7 @@ $title = _x( 'About', 'page title' ); list( $display_version ) = explode( '-', wp_get_wp_version() ); -$display_major_version = '7.1'; +$display_major_version = '7.2'; $release_notes_url = sprintf( /* translators: %s: WordPress version number. */ @@ -69,21 +69,21 @@ ); ?> -

    +

-

+

-
- +
+

- +
@@ -91,29 +91,29 @@
- +
-

+

-
- +
+

-

+

-
- +
+

- +
@@ -121,14 +121,14 @@
- +
-

+

-
- +
+

@@ -143,8 +143,8 @@ -

-

+

+

@@ -153,7 +153,7 @@

-

+

@@ -183,7 +183,7 @@
- <?php echo esc_attr( $version_text ); ?> + <?php echo esc_attr( $version_text ); ?>

diff --git a/src/wp-admin/css/about.css b/src/wp-admin/css/about.css index f0c81acac8ec8..bc3c1353b1da8 100644 --- a/src/wp-admin/css/about.css +++ b/src/wp-admin/css/about.css @@ -20,9 +20,14 @@ */ .about__container { - /* Section backgrounds */ - --background: #3858e9; - --subtle-background: #f4f4f4; + /* + * Section backgrounds + * + * Section header backgrounds are set to the dominant color of the + * image to avoid display issues if the image fails to load. + */ + --background: #eeece5; + --subtle-background: #f3f2ee; /* Main text color */ --text: #1e1e1e; @@ -617,7 +622,7 @@ padding-right: 26rem; /* Space for the background image. */ min-height: clamp(10rem, 25vw, 18.75rem); border-radius: var(--border-radius); - background-image: url(../images/about-header-default.svg?ver=7.1); + background-image: url(../images/about-header-default.svg?ver=7.2); background-repeat: no-repeat; background-position: right center; background-size: cover; @@ -627,39 +632,42 @@ } .credits-php .about__header { - background-image: url(../images/about-header-credits.svg?ver=7.1); + background-image: url(../images/about-header-credits.svg?ver=7.2); + --background: #3858e9; } .freedoms-php .about__header { - background-image: url(../images/about-header-freedoms.svg?ver=7.1); + background-image: url(../images/about-header-freedoms.svg?ver=7.2); + --background: #757575; } .privacy-php .about__header { - background-image: url(../images/about-header-privacy.svg?ver=7.1); + background-image: url(../images/about-header-privacy.svg?ver=7.2); + --background: #323232; } .contribute-php .about__header { - background-image: url(../images/about-header-get-involved.svg?ver=7.1); + background-image: url(../images/about-header-get-involved.svg?ver=7.2); } [dir="rtl"] .about__header { - background-image: url(../images/about-header-default-rtl.svg?ver=7.1); + background-image: url(../images/about-header-default-rtl.svg?ver=7.2); } [dir="rtl"] .credits-php .about__header { - background-image: url(../images/about-header-credits-rtl.svg?ver=7.1); + background-image: url(../images/about-header-credits-rtl.svg?ver=7.2); } [dir="rtl"] .freedoms-php .about__header { - background-image: url(../images/about-header-freedoms-rtl.svg?ver=7.1); + background-image: url(../images/about-header-freedoms-rtl.svg?ver=7.2); } [dir="rtl"] .privacy-php .about__header { - background-image: url(../images/about-header-privacy-rtl.svg?ver=7.1); + background-image: url(../images/about-header-privacy-rtl.svg?ver=7.2); } [dir="rtl"] .contribute-php .about__header { - background-image: url(../images/about-header-get-involved-rtl.svg?ver=7.1); + background-image: url(../images/about-header-get-involved-rtl.svg?ver=7.2); } .about__header-image { @@ -691,6 +699,12 @@ font-size: clamp(2rem, 20vw - 9rem, 4rem); } +.about-php .about__header-title h1, +.contribute-php .about__header-title h1, +.contribute-php .about__header-text { + color: var(--text); +} + .about__header-text { box-sizing: border-box; max-width: 26em; diff --git a/src/wp-admin/images/about-header-credits-rtl.svg b/src/wp-admin/images/about-header-credits-rtl.svg index 001e47d6949f8..2d25e88c3141a 100644 --- a/src/wp-admin/images/about-header-credits-rtl.svg +++ b/src/wp-admin/images/about-header-credits-rtl.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/wp-admin/images/about-header-credits.svg b/src/wp-admin/images/about-header-credits.svg index ac6dfef6883ea..ef03c86055079 100644 --- a/src/wp-admin/images/about-header-credits.svg +++ b/src/wp-admin/images/about-header-credits.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/wp-admin/images/about-header-default-rtl.svg b/src/wp-admin/images/about-header-default-rtl.svg index d8574fc4c3b75..108ab85d28d0b 100644 --- a/src/wp-admin/images/about-header-default-rtl.svg +++ b/src/wp-admin/images/about-header-default-rtl.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/wp-admin/images/about-header-default.svg b/src/wp-admin/images/about-header-default.svg index ca71da7d8a2be..108ab85d28d0b 100644 --- a/src/wp-admin/images/about-header-default.svg +++ b/src/wp-admin/images/about-header-default.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/wp-admin/images/about-header-freedoms-rtl.svg b/src/wp-admin/images/about-header-freedoms-rtl.svg index 5eb445f4b8a4a..fdea9bac9ab1c 100644 --- a/src/wp-admin/images/about-header-freedoms-rtl.svg +++ b/src/wp-admin/images/about-header-freedoms-rtl.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/wp-admin/images/about-header-freedoms.svg b/src/wp-admin/images/about-header-freedoms.svg index e996bcc373802..fdea9bac9ab1c 100644 --- a/src/wp-admin/images/about-header-freedoms.svg +++ b/src/wp-admin/images/about-header-freedoms.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/wp-admin/images/about-header-get-involved-rtl.svg b/src/wp-admin/images/about-header-get-involved-rtl.svg index 3db4448e465af..12f58506d380f 100644 --- a/src/wp-admin/images/about-header-get-involved-rtl.svg +++ b/src/wp-admin/images/about-header-get-involved-rtl.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/wp-admin/images/about-header-get-involved.svg b/src/wp-admin/images/about-header-get-involved.svg index 17b2717ddf63b..4aad0f8dc4136 100644 --- a/src/wp-admin/images/about-header-get-involved.svg +++ b/src/wp-admin/images/about-header-get-involved.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/wp-admin/images/about-header-privacy-rtl.svg b/src/wp-admin/images/about-header-privacy-rtl.svg index e2b3084e14b55..932c1b21a986d 100644 --- a/src/wp-admin/images/about-header-privacy-rtl.svg +++ b/src/wp-admin/images/about-header-privacy-rtl.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/wp-admin/images/about-header-privacy.svg b/src/wp-admin/images/about-header-privacy.svg index ed37fb636362b..ca291d1d61894 100644 --- a/src/wp-admin/images/about-header-privacy.svg +++ b/src/wp-admin/images/about-header-privacy.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/wp-admin/images/about-release-badge.svg b/src/wp-admin/images/about-release-badge.svg index 845f4817a441f..bd595eda8d392 100644 --- a/src/wp-admin/images/about-release-badge.svg +++ b/src/wp-admin/images/about-release-badge.svg @@ -1 +1,6 @@ - \ No newline at end of file + + + + + + From d0ba8805d18e81318ce0086b11956271ca18d434 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Tue, 24 Nov 2026 14:19:18 +0000 Subject: [PATCH 65/85] Tests: Keep the oEmbed suite running without SimpleXML. Require `SimpleXML` for the XML-only tests so an unavailable extension cannot end the PHPUnit run early with a successful exit code. Check the requirement before starting the isolated headers test. Keep checking JSON discovery links and filters on every build. Expect the XML discovery link only when `SimpleXMLElement` is available. Developed in: https://github.com/WordPress/wordpress-develop/pull/16171 Props shanerounce. Fixes #66788. git-svn-id: https://develop.svn.wordpress.org/trunk@65754 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/oembed/controller.php | 6 +++++ tests/phpunit/tests/oembed/discovery.php | 30 +++++++++++++++-------- tests/phpunit/tests/oembed/headers.php | 1 + 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/tests/phpunit/tests/oembed/controller.php b/tests/phpunit/tests/oembed/controller.php index 6077b088d924a..aef68f068d6b0 100644 --- a/tests/phpunit/tests/oembed/controller.php +++ b/tests/phpunit/tests/oembed/controller.php @@ -185,6 +185,9 @@ public function test_wp_oembed_ensure_format() { $this->assertSame( 'json', wp_oembed_ensure_format( array() ) ); } + /** + * @requires extension simplexml + */ public function test_oembed_create_xml() { $actual = _oembed_create_xml( array( @@ -454,6 +457,9 @@ public function test_request_ms_child_in_root_blog() { restore_current_blog(); } + /** + * @requires extension simplexml + */ public function test_rest_pre_serve_request() { $user = get_user_by( 'id', self::$subscriber ); $post = self::factory()->post->create_and_get( diff --git a/tests/phpunit/tests/oembed/discovery.php b/tests/phpunit/tests/oembed/discovery.php index e478786ce49e9..20bfcbb9372db 100644 --- a/tests/phpunit/tests/oembed/discovery.php +++ b/tests/phpunit/tests/oembed/discovery.php @@ -32,8 +32,10 @@ public function test_add_oembed_discovery_links_static_front_page() { $this->go_to( home_url() ); $this->assertQueryTrue( 'is_front_page', 'is_singular', 'is_page' ); - $expected = '' . "\n"; - $expected .= '' . "\n"; + $expected = '' . "\n"; + if ( class_exists( 'SimpleXMLElement' ) ) { + $expected .= '' . "\n"; + } $this->assertSame( $expected, get_echo( 'wp_oembed_add_discovery_links' ) ); @@ -45,8 +47,10 @@ public function test_add_oembed_discovery_links_to_post() { $this->go_to( get_permalink( $post_id ) ); $this->assertQueryTrue( 'is_single', 'is_singular' ); - $expected = '' . "\n"; - $expected .= '' . "\n"; + $expected = '' . "\n"; + if ( class_exists( 'SimpleXMLElement' ) ) { + $expected .= '' . "\n"; + } $this->assertSame( $expected, get_echo( 'wp_oembed_add_discovery_links' ) ); @@ -63,8 +67,10 @@ public function test_add_oembed_discovery_links_to_page() { $this->go_to( get_permalink( $post_id ) ); $this->assertQueryTrue( 'is_page', 'is_singular' ); - $expected = '' . "\n"; - $expected .= '' . "\n"; + $expected = '' . "\n"; + if ( class_exists( 'SimpleXMLElement' ) ) { + $expected .= '' . "\n"; + } $this->assertSame( $expected, get_echo( 'wp_oembed_add_discovery_links' ) ); } @@ -83,8 +89,10 @@ public function test_add_oembed_discovery_links_to_attachment() { $this->go_to( get_permalink( $attachment_id ) ); $this->assertQueryTrue( 'is_attachment', 'is_singular', 'is_single' ); - $expected = '' . "\n"; - $expected .= '' . "\n"; + $expected = '' . "\n"; + if ( class_exists( 'SimpleXMLElement' ) ) { + $expected .= '' . "\n"; + } $this->assertSame( $expected, get_echo( 'wp_oembed_add_discovery_links' ) ); } @@ -132,8 +140,10 @@ public function test_wp_oembed_add_discovery_links_back_compat() { $wp_head_output = get_echo( 'wp_head' ); $this->assertSame( 1, $mock_action->get_call_count() ); - $expected = '' . "\n"; - $expected .= '' . "\n"; + $expected = '' . "\n"; + if ( class_exists( 'SimpleXMLElement' ) ) { + $expected .= '' . "\n"; + } $this->assertSame( $expected, $wp_head_output, 'Expected wp_head output to be the same as the wp_oembed_add_discovery_links() output.' ); $this->assertSame( $expected, get_echo( $callback ), 'Expected wp_oembed_add_discovery_links() output to be the same as the wp_head output when called outside of wp_head.' ); diff --git a/tests/phpunit/tests/oembed/headers.php b/tests/phpunit/tests/oembed/headers.php index 8f9c4e4c8d50a..5f5799447f7b5 100644 --- a/tests/phpunit/tests/oembed/headers.php +++ b/tests/phpunit/tests/oembed/headers.php @@ -6,6 +6,7 @@ * @group oembed * @group oembed-headers * @group xdebug + * @requires extension simplexml */ class Tests_oEmbed_HTTP_Headers extends WP_UnitTestCase { From 2d7fd1e9565beb7ce520692fc3780d682dbe4fe0 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Tue, 24 Nov 2026 14:21:03 +0000 Subject: [PATCH 66/85] Tests: Allow hosts to opt out of HTTP loopback fixtures. Honor `WP_TESTS_SKIP_HTTP_LOOPBACK=1` when PHP cannot reserve a local TCP port. Continue running transport tests that do not need the fixture. If PHP reserves a port but the server fails to start, report the failure. Developed in: https://github.com/WordPress/wordpress-develop/pull/16183 Props verygoode, tessory, amykamala, lucatume, adrianmoldovanwp. See #66794. git-svn-id: https://develop.svn.wordpress.org/trunk@65755 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/README.md | 4 ++++ tests/phpunit/tests/http/base.php | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index 679ed831112d2..6308e75c3d3da 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -6,6 +6,10 @@ For more information, please review the relevant Core Handbook pages: - [PHP: PHPUnit](https://make.wordpress.org/core/handbook/testing/automated-testing/phpunit/) - [Writing PHP Tests](https://make.wordpress.org/core/handbook/testing/automated-testing/writing-phpunit-tests/) +## Run on a host that prohibits loopback listening + +Set `WP_TESTS_SKIP_HTTP_LOOPBACK=1` in the PHPUnit process environment if the host prohibits listening on a local TCP port. When PHP cannot reserve a port, PHPUnit skips only the HTTP transport tests that need the local fixture server. If PHP reserves a port, the tests run normally and server startup errors still fail. + ## Run the full matrix on a pull request Add the `Full PHPUnit Matrix` label to a pull request in `WordPress/wordpress-develop` to run the same PHP and database combinations as the weekly scheduled run. The label-triggered workflow uses the same path filters as normal PHPUnit runs. diff --git a/tests/phpunit/tests/http/base.php b/tests/phpunit/tests/http/base.php index a279a8386024a..3b6456b5e9d53 100644 --- a/tests/phpunit/tests/http/base.php +++ b/tests/phpunit/tests/http/base.php @@ -151,6 +151,11 @@ static function () { if ( ! $socket ) { self::remove_file_stream_fixture_dir( $fixture_dir ); + if ( '1' === getenv( 'WP_TESTS_SKIP_HTTP_LOOPBACK' ) ) { + self::$file_stream_fixture_skip_reason = 'Loopback listening is restricted on this test host.'; + return; + } + self::$file_stream_fixture_fail_reason = sprintf( 'Could not reserve a local TCP port for the HTTP stream fixture server (%d: %s).', (int) $errno, From bc37c9436b921acad9d3ea79c6e8bdb26c85e095 Mon Sep 17 00:00:00 2001 From: Jb Audras Date: Tue, 24 Nov 2026 15:17:58 +0000 Subject: [PATCH 67/85] WordPress 7.2 RC 3. git-svn-id: https://develop.svn.wordpress.org/trunk@65756 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/version.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/version.php b/src/wp-includes/version.php index 6bc5d15fb0437..5aa16a02da065 100644 --- a/src/wp-includes/version.php +++ b/src/wp-includes/version.php @@ -16,7 +16,7 @@ * * @global string $wp_version */ -$wp_version = '7.2-RC2-65605-src'; +$wp_version = '7.2-RC3-src'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. From 119ed74b83bcd8b191eb1123bb66a0c0d5c4c23f Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Tue, 24 Nov 2026 15:31:32 +0000 Subject: [PATCH 68/85] Tests: Simplify post type cleanup. Remove duplicate cleanup for ordinary post types. Use `unregister_post_type()` where the test needs a type to disappear before an assertion. Developed in: https://github.com/WordPress/wordpress-develop/pull/15489, https://github.com/WordPress/wordpress-develop/pull/15491, https://github.com/WordPress/wordpress-develop/pull/15492, https://github.com/WordPress/wordpress-develop/pull/15493, https://github.com/WordPress/wordpress-develop/pull/15495, https://github.com/WordPress/wordpress-develop/pull/15496 Props devmuhib, peterwilsoncc. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65757 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/customize/nav-menu-item-setting.php | 2 +- tests/phpunit/tests/link/getDeletePostLink.php | 2 -- tests/phpunit/tests/rest-api/rest-posts-controller.php | 1 - tests/phpunit/tests/rewrite.php | 4 ---- tests/phpunit/tests/user/capabilities.php | 9 ++------- tests/phpunit/tests/view-config.php | 2 -- 6 files changed, 3 insertions(+), 17 deletions(-) diff --git a/tests/phpunit/tests/customize/nav-menu-item-setting.php b/tests/phpunit/tests/customize/nav-menu-item-setting.php index a094ff8674c29..42cbe0e8f7bf8 100644 --- a/tests/phpunit/tests/customize/nav-menu-item-setting.php +++ b/tests/phpunit/tests/customize/nav-menu-item-setting.php @@ -897,7 +897,7 @@ public function test_invalid_nav_menu_item() { $value_object = $setting->value_as_wp_post_nav_menu_item(); $this->assertFalse( $value_object->_invalid ); - _unregister_post_type( 'poem' ); + unregister_post_type( 'poem' ); $setting = new WP_Customize_Nav_Menu_Item_Setting( $this->wp_customize, $setting_id ); $value = $setting->value(); $this->assertTrue( $value['_invalid'] ); diff --git a/tests/phpunit/tests/link/getDeletePostLink.php b/tests/phpunit/tests/link/getDeletePostLink.php index 59ce75f6bceb7..de5b8215fcb9b 100644 --- a/tests/phpunit/tests/link/getDeletePostLink.php +++ b/tests/phpunit/tests/link/getDeletePostLink.php @@ -265,8 +265,6 @@ public function test_get_delete_post_link_custom_post_type() { $actual = get_delete_post_link( $cpt_post_id ); - unregister_post_type( 'cpt_delete_test' ); - $this->assertSame( $expected, $actual ); } diff --git a/tests/phpunit/tests/rest-api/rest-posts-controller.php b/tests/phpunit/tests/rest-api/rest-posts-controller.php index 7f4f09d78b308..910bc953dbcd4 100644 --- a/tests/phpunit/tests/rest-api/rest-posts-controller.php +++ b/tests/phpunit/tests/rest-api/rest-posts-controller.php @@ -4880,7 +4880,6 @@ public function test_register_post_type_invalid_controller() { create_initial_rest_routes(); $routes = rest_get_server()->get_routes(); $this->assertArrayNotHasKey( '/wp/v2/invalid-controller', $routes ); - _unregister_post_type( 'invalid-controller' ); } public function test_get_item_schema() { diff --git a/tests/phpunit/tests/rewrite.php b/tests/phpunit/tests/rewrite.php index 1adfe0243e9c3..e42ccc42c7cdf 100644 --- a/tests/phpunit/tests/rewrite.php +++ b/tests/phpunit/tests/rewrite.php @@ -188,8 +188,6 @@ public function test_url_to_postid_custom_post_type() { $id = self::factory()->post->create( array( 'post_type' => $post_type ) ); $this->assertSame( $id, url_to_postid( get_permalink( $id ) ) ); - - _unregister_post_type( $post_type ); } public function test_url_to_postid_hierarchical() { @@ -396,8 +394,6 @@ public function test_parse_request_home_path_non_public_type() { $this->go_to( $url ); - _unregister_post_type( 'foo' ); - $this->assertSame( array(), $GLOBALS['wp']->query_vars ); } diff --git a/tests/phpunit/tests/user/capabilities.php b/tests/phpunit/tests/user/capabilities.php index f47a841219bbe..ba788a4227118 100644 --- a/tests/phpunit/tests/user/capabilities.php +++ b/tests/phpunit/tests/user/capabilities.php @@ -1298,7 +1298,6 @@ public function test_post_meta_caps() { $something = get_post_type_object( 'something' ); $this->assertSame( 'draw_somethings', $something->cap->edit_posts ); $this->assertSame( 'create_somethings', $something->cap->create_posts ); - _unregister_post_type( 'something' ); // Test meta authorization callbacks. if ( function_exists( 'register_meta' ) ) { @@ -1389,7 +1388,7 @@ public function test_create_posts_caps() { $this->assertTrue( $contributor->has_cap( $cap->create_posts ) ); $this->assertFalse( $subscriber->has_cap( $cap->create_posts ) ); - _unregister_post_type( 'foobar' ); + unregister_post_type( 'foobar' ); // Primitive capability 'edit_foobars' is not assigned to any users. register_post_type( 'foobar', array( 'capability_type' => array( 'foobar', 'foobars' ) ) ); @@ -1415,8 +1414,6 @@ public function test_create_posts_caps() { $admin->remove_cap( 'edit_foobars' ); - _unregister_post_type( 'foobar' ); - $cap = get_post_type_object( 'attachment' )->cap; $this->assertSame( 'upload_files', $cap->create_posts ); $this->assertSame( 'edit_posts', $cap->edit_posts ); @@ -1994,7 +1991,7 @@ public function test_multisite_administrator_with_manage_network_users_can_not_e public function test_require_edit_others_posts_if_post_type_doesnt_exist() { register_post_type( 'existed' ); $post_id = self::factory()->post->create( array( 'post_type' => 'existed' ) ); - _unregister_post_type( 'existed' ); + unregister_post_type( 'existed' ); $subscriber_id = self::$users['subscriber']->ID; $editor_id = self::$users['editor']->ID; @@ -2080,8 +2077,6 @@ public function test_cpt_with_page_capability_type() { $this->assertTrue( user_can( $editor->ID, 'edit_post', $author_post->ID ) ); $this->assertFalse( user_can( $author->ID, 'edit_post', $author_post->ID ) ); $this->assertFalse( user_can( $contributor->ID, 'edit_post', $author_post->ID ) ); - - _unregister_post_type( 'page_capability' ); } public function test_non_logged_in_users_have_no_capabilities() { diff --git a/tests/phpunit/tests/view-config.php b/tests/phpunit/tests/view-config.php index 1d84c7e676113..a3a008f8725ea 100644 --- a/tests/phpunit/tests/view-config.php +++ b/tests/phpunit/tests/view-config.php @@ -425,8 +425,6 @@ public function test_view_list_uses_post_type_all_items_label() { $config = wp_get_entity_view_config( 'postType', 'view_config_cpt' ); $this->assertSame( 'All Custom Things', $config['view_list'][0]['title'] ); - - unregister_post_type( 'view_config_cpt' ); } /** From ef06eef64ecc79bd95209ffd51494928f748e40f Mon Sep 17 00:00:00 2001 From: Jb Audras Date: Tue, 24 Nov 2026 15:45:44 +0000 Subject: [PATCH 69/85] Post WordPress 7.2 RC 3 version bump. git-svn-id: https://develop.svn.wordpress.org/trunk@65758 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/version.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/version.php b/src/wp-includes/version.php index 5aa16a02da065..c45442b7a5341 100644 --- a/src/wp-includes/version.php +++ b/src/wp-includes/version.php @@ -16,7 +16,7 @@ * * @global string $wp_version */ -$wp_version = '7.2-RC3-src'; +$wp_version = '7.2-RC3-65559-src'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. From 546a35a0db18245de7c9696d75cac660e543af1e Mon Sep 17 00:00:00 2001 From: Jb Audras Date: Tue, 24 Nov 2026 15:49:22 +0000 Subject: [PATCH 70/85] Revert [65758]. git-svn-id: https://develop.svn.wordpress.org/trunk@65759 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/version.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/version.php b/src/wp-includes/version.php index c45442b7a5341..5aa16a02da065 100644 --- a/src/wp-includes/version.php +++ b/src/wp-includes/version.php @@ -16,7 +16,7 @@ * * @global string $wp_version */ -$wp_version = '7.2-RC3-65559-src'; +$wp_version = '7.2-RC3-src'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. From 084145c2f36c99fbba349d17ddcbb316b1a43a8f Mon Sep 17 00:00:00 2001 From: Jb Audras Date: Tue, 24 Nov 2026 15:50:09 +0000 Subject: [PATCH 71/85] Post WordPress 7.2 RC 3 version bump. git-svn-id: https://develop.svn.wordpress.org/trunk@65760 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/version.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/version.php b/src/wp-includes/version.php index 5aa16a02da065..b52c24fb59cd1 100644 --- a/src/wp-includes/version.php +++ b/src/wp-includes/version.php @@ -16,7 +16,7 @@ * * @global string $wp_version */ -$wp_version = '7.2-RC3-src'; +$wp_version = '7.2-RC3-65760-src'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. From 0f60cedecccfeb3bb574851765d8375553782ed5 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Tue, 24 Nov 2026 16:29:30 +0000 Subject: [PATCH 72/85] Tests: Remove redundant taxonomy cleanup. The test harness resets the private block-binding and category test taxonomies before the next test. Developed in: https://github.com/WordPress/wordpress-develop/pull/15502, https://github.com/WordPress/wordpress-develop/pull/15503 Props devmuhib, peterwilsoncc. See #66755. git-svn-id: https://develop.svn.wordpress.org/trunk@65761 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/block-bindings/termDataSource.php | 4 ---- tests/phpunit/tests/category/getAllCategoryIds.php | 2 -- 2 files changed, 6 deletions(-) diff --git a/tests/phpunit/tests/block-bindings/termDataSource.php b/tests/phpunit/tests/block-bindings/termDataSource.php index c8b95cedfc783..050c2eb8ac3b4 100644 --- a/tests/phpunit/tests/block-bindings/termDataSource.php +++ b/tests/phpunit/tests/block-bindings/termDataSource.php @@ -449,8 +449,6 @@ public function test_get_value_non_publicly_queryable_taxonomy_unauthenticated() wp_set_current_user( 0 ); $this->assertNull( _block_bindings_term_data_get_value( array( 'field' => 'name' ), $block ) ); - - _unregister_taxonomy( 'wptests_private_tax' ); } /** @@ -482,8 +480,6 @@ public function test_get_value_non_publicly_queryable_taxonomy_with_read_capabil wp_set_current_user( $subscriber_id ); $this->assertSame( 'Secret Term', _block_bindings_term_data_get_value( array( 'field' => 'name' ), $block ) ); - - _unregister_taxonomy( 'wptests_private_tax' ); } /** diff --git a/tests/phpunit/tests/category/getAllCategoryIds.php b/tests/phpunit/tests/category/getAllCategoryIds.php index 3fb8223afa060..58720ce8995d9 100644 --- a/tests/phpunit/tests/category/getAllCategoryIds.php +++ b/tests/phpunit/tests/category/getAllCategoryIds.php @@ -22,8 +22,6 @@ public function test_get_all_category_ids() { wp_insert_term( 'test1', 'test_tax_cat' ); $cat_ids = get_all_category_ids(); - _unregister_taxonomy( 'test_tax_cat' ); - // Validate length is 1 + created due to uncategorized. $this->assertCount( 3, $cat_ids ); } From e9b0cd348124e67df019e2e9d6e7a0aacdd85fd4 Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Tue, 24 Nov 2026 21:27:42 +0000 Subject: [PATCH 73/85] Build/Test Tools: Post-branching updates for trunk. Developed in https://github.com/WordPress/wordpress-develop/pull/16215 Props johnbillion, sergeybiryukov, audrasjb See #66738 git-svn-id: https://develop.svn.wordpress.org/trunk@65764 602fd350-edb4-49c9-b593-d223f7449a82 --- .github/workflows/test-old-branches.yml | 12 ++++++++---- .github/workflows/upgrade-develop-testing.yml | 4 ++-- .github/workflows/upgrade-testing.yml | 2 +- .version-support-mysql.json | 10 ++++++++++ .version-support-php.json | 10 ++++++++++ SECURITY.md | 1 + composer.json | 2 +- package-lock.json | 4 ++-- package.json | 2 +- src/wp-includes/version.php | 2 +- 10 files changed, 37 insertions(+), 12 deletions(-) diff --git a/.github/workflows/test-old-branches.yml b/.github/workflows/test-old-branches.yml index a7d2ddcb01836..c858088879b95 100644 --- a/.github/workflows/test-old-branches.yml +++ b/.github/workflows/test-old-branches.yml @@ -25,7 +25,7 @@ on: permissions: {} env: - CURRENTLY_SUPPORTED_BRANCH: '7.1' + CURRENTLY_SUPPORTED_BRANCH: '7.2' jobs: dispatch-workflows-for-old-branches: @@ -45,13 +45,15 @@ jobs: 'test-build-processes.yml' ] branch: [ - '7.1', '7.0', + '7.2', '7.1', '7.0', '6.9', '6.8', '6.7', '6.6', '6.5', '6.4', '6.3', '6.2', '6.1','6.0', '5.9', '5.8', '5.7', '5.6', '5.5', '5.4', '5.3', '5.2', '5.1', '5.0', '4.9', '4.8', '4.7' ] include: # PHP Compatibility testing was introduced in 5.5. + - branch: '7.2' + workflow: 'php-compatibility.yml' - branch: '7.1' workflow: 'php-compatibility.yml' - branch: '7.0' @@ -90,6 +92,8 @@ jobs: # End-to-end testing was introduced in 5.3 but was later removed as there were no meaningful assertions. # Starting in 5.8 with #52905, some additional tests with real assertions were introduced. # Branches 5.8 and newer should be tested to confirm no regressions are introduced. + - branch: '7.2' + workflow: 'end-to-end-tests.yml' - branch: '7.1' workflow: 'end-to-end-tests.yml' - branch: '7.0' @@ -122,9 +126,9 @@ jobs: # Performance testing was introduced in 6.2 using Puppeteer but was overhauled to use Playwright instead in 6.4. # Since the workflow frequently failed for 6.2 and 6.3 due to the flaky nature of the Puppeteer tests, # the workflow was removed from those two branches. - - branch: '7.1' + - branch: '7.2' workflow: 'performance.yml' - - branch: '7.0' + - branch: '7.1' workflow: 'performance.yml' # Run all branches monthly, but only the currently supported one twice per month. diff --git a/.github/workflows/upgrade-develop-testing.yml b/.github/workflows/upgrade-develop-testing.yml index dcd921c2e6c7e..1073c46786c0b 100644 --- a/.github/workflows/upgrade-develop-testing.yml +++ b/.github/workflows/upgrade-develop-testing.yml @@ -92,7 +92,7 @@ jobs: db-type: [ 'mysql' ] db-version: [ '5.7', '8.4' ] # WordPress 5.3 is the oldest version that supports PHP 7.4. - wp: [ '5.3', '7.0', '7.1' ] + wp: [ '5.3', '7.0', '7.1', '7.2-RC3' ] multisite: [ false, true ] with: os: ${{ matrix.os }} @@ -126,7 +126,7 @@ jobs: php: [ '7.4', '8.4' ] db-type: [ 'mysql' ] db-version: [ '8.4' ] - wp: [ '7.0', '7.1' ] + wp: [ '7.0', '7.1', '7.2-RC3' ] multisite: [ false, true ] with: os: ${{ matrix.os }} diff --git a/.github/workflows/upgrade-testing.yml b/.github/workflows/upgrade-testing.yml index 3765692707b16..59eec3837613a 100644 --- a/.github/workflows/upgrade-testing.yml +++ b/.github/workflows/upgrade-testing.yml @@ -94,7 +94,7 @@ jobs: env: NEW_VERSION: ${{ inputs.new-version && inputs.new-version || 'latest' }} # The versions each job below starts from. See the comment on the job for why those versions are tested. - RECENT_RELEASES: '7.0 7.1' # upgrade-tests-recent-releases + RECENT_RELEASES: '7.0 7.1 7.2-RC3' # upgrade-tests-recent-releases WP_6X: '6.0 6.3 6.4 6.5' # upgrade-tests-wp-6x-mysql WP_5X_PHP_7X: '5.0 5.1 5.3 5.4 5.5 5.6 5.9' # upgrade-tests-wp-5x-php-7x-mysql WP_5X_PHP_8X: '5.3 5.4 5.5 5.6 5.9' # upgrade-tests-wp-5x-php-8x-mysql diff --git a/.version-support-mysql.json b/.version-support-mysql.json index 68c6d2ac77407..bcd6946aa9eb7 100644 --- a/.version-support-mysql.json +++ b/.version-support-mysql.json @@ -1,4 +1,14 @@ { + "7-3": [ + "26.10", + "26.7", + "9.7", + "8.4", + "8.0", + "5.7", + "5.6", + "5.5" + ], "7-2": [ "26.10", "26.7", diff --git a/.version-support-php.json b/.version-support-php.json index 31d8169338822..057204cd67f65 100644 --- a/.version-support-php.json +++ b/.version-support-php.json @@ -1,4 +1,14 @@ { + "7-3": [ + "7.4", + "8.0", + "8.1", + "8.2", + "8.3", + "8.4", + "8.5", + "8.6" + ], "7-2": [ "7.4", "8.0", diff --git a/SECURITY.md b/SECURITY.md index 13e8007009af8..b73d6ab5c0b6d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -10,6 +10,7 @@ Full details of the WordPress Security Policy and the list of covered projects a | Version | Supported | |---------| --------- | +| 7.2.x | Yes | | 7.1.x | Yes | | 7.0.x | Yes | | 6.9.x | Yes | diff --git a/composer.json b/composer.json index f17e0922e00d1..eb8e9cabfc9a4 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "wordpress/wordpress", - "version": "7.2.0", + "version": "7.3.0", "license": "GPL-2.0-or-later", "description": "WordPress is open source software you can use to create a beautiful website, blog, or app.", "homepage": "https://wordpress.org", diff --git a/package-lock.json b/package-lock.json index bb9ee39445a7d..77cb8b4e307b5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "WordPress", - "version": "7.2.0", + "version": "7.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "WordPress", - "version": "7.2.0", + "version": "7.3.0", "license": "GPL-2.0-or-later", "dependencies": { "backbone": "1.6.1", diff --git a/package.json b/package.json index 4b51f22f896b2..30e853bd255bd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "WordPress", - "version": "7.2.0", + "version": "7.3.0", "description": "WordPress is open source software you can use to create a beautiful website, blog, or app.", "repository": { "type": "svn", diff --git a/src/wp-includes/version.php b/src/wp-includes/version.php index b52c24fb59cd1..0f269f989c991 100644 --- a/src/wp-includes/version.php +++ b/src/wp-includes/version.php @@ -16,7 +16,7 @@ * * @global string $wp_version */ -$wp_version = '7.2-RC3-65760-src'; +$wp_version = '7.3-alpha-65762-src'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. From 7824ab0d697047d31858abc9ea75a879dd4e93ab Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Tue, 24 Nov 2026 23:15:29 +0000 Subject: [PATCH 74/85] Build/Test Tools: Show individual end-to-end test names in CI. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Enable Playwright’s `list` reporter alongside the `github` reporter in CI so the job log names each test and retains GitHub annotations. Developed in: https://github.com/WordPress/wordpress-develop/pull/16212 Props adrianmoldovanwp. See #66455. git-svn-id: https://develop.svn.wordpress.org/trunk@65767 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/e2e/playwright.config.js | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/e2e/playwright.config.js b/tests/e2e/playwright.config.js index 76c4c7c236c7a..c4c8e4a1441bc 100644 --- a/tests/e2e/playwright.config.js +++ b/tests/e2e/playwright.config.js @@ -27,6 +27,7 @@ const config = defineConfig( { globalSetup: require.resolve( './config/global-setup.js' ), workers: '50%', retries: process.env.CI ? 1 : 0, + reporter: process.env.CI ? [ [ 'github' ], [ 'list' ] ] : [ [ 'list' ] ], webServer: { ...baseConfig.webServer, command: 'npm run env:start', From b412a3ad1c74bb842ca617375117679d3c886a13 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Tue, 24 Nov 2026 23:34:57 +0000 Subject: [PATCH 75/85] Tests: Cover `wp_heartbeat_settings()`. Verify: - Injecting the relative `ajaxurl` for frontend requests while leaving `nonce` unset when logged out. - Injecting both `ajaxurl` and a valid `heartbeat-nonce` when a user is logged in. - Preserving any custom settings keys passed into the function. Developed in https://github.com/WordPress/wordpress-develop/pull/15791. Props devmuhib, huzaifaalmesbah. See #66757. git-svn-id: https://develop.svn.wordpress.org/trunk@65768 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/general/wpHeartbeatSettings.php | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 tests/phpunit/tests/general/wpHeartbeatSettings.php diff --git a/tests/phpunit/tests/general/wpHeartbeatSettings.php b/tests/phpunit/tests/general/wpHeartbeatSettings.php new file mode 100644 index 0000000000000..94169da433499 --- /dev/null +++ b/tests/phpunit/tests/general/wpHeartbeatSettings.php @@ -0,0 +1,61 @@ + 60 ); + $settings = wp_heartbeat_settings( $initial ); + + $this->assertSame( 60, $settings['interval'] ); + $this->assertSame( admin_url( 'admin-ajax.php', 'relative' ), $settings['ajaxurl'] ); + $this->assertArrayNotHasKey( 'nonce', $settings ); + } + + /** + * Tests frontend logged-in settings behavior with valid nonce. + * + * @ticket 66614 + */ + public function test_wp_heartbeat_settings_frontend_logged_in() { + $user_id = self::factory()->user->create(); + wp_set_current_user( $user_id ); + + $settings = wp_heartbeat_settings( array() ); + + $this->assertArrayHasKey( 'nonce', $settings ); + $this->assertNotFalse( wp_verify_nonce( $settings['nonce'], 'heartbeat-nonce' ) ); + $this->assertSame( admin_url( 'admin-ajax.php', 'relative' ), $settings['ajaxurl'] ); + } + + /** + * Tests that existing settings are preserved. + * + * @ticket 66614 + */ + public function test_wp_heartbeat_settings_preserves_custom_settings() { + wp_set_current_user( 0 ); + + $custom = array( + 'interval' => 15, + 'customKey' => 'customValue', + ); + $settings = wp_heartbeat_settings( $custom ); + + $this->assertSame( 15, $settings['interval'] ); + $this->assertSame( 'customValue', $settings['customKey'] ); + } +} From 5cb65d8463280b80eff30919e84cf118c5855df0 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Wed, 25 Nov 2026 04:09:19 +0000 Subject: [PATCH 76/85] Build/Test Tools: Update PHPStan to 2.3.7. This also updates `phpstan/phpstan-strict-rules` to 2.1.2. Both are bugfix releases, and neither changes what PHPStan reports for core, so the baselines are unchanged. Developed in https://github.com/WordPress/wordpress-develop/pull/16186. Follow-up to r65265, r65537. See #66739. git-svn-id: https://develop.svn.wordpress.org/trunk@65769 602fd350-edb4-49c9-b593-d223f7449a82 --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index eb8e9cabfc9a4..77226897cee1c 100644 --- a/composer.json +++ b/composer.json @@ -52,9 +52,9 @@ "squizlabs/php_codesniffer": "3.13.5", "wp-coding-standards/wpcs": "~3.4.1", "phpcompatibility/phpcompatibility-wp": "~2.1.3", - "phpstan/phpstan": "2.3.6", + "phpstan/phpstan": "2.3.7", "phpstan/phpstan-phpunit": "2.1.2", - "phpstan/phpstan-strict-rules": "2.1.1", + "phpstan/phpstan-strict-rules": "2.1.2", "yoast/phpunit-polyfills": "^1.1.0" }, "config": { From 2da24adc29cbd4f14045fc34dd0fecf203042342 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Wed, 25 Nov 2026 07:08:03 +0000 Subject: [PATCH 77/85] Code Quality: Call `process_blocks_custom_css()` statically. The `WP_Theme_JSON::process_blocks_custom_css()` method is declared static, yet three of its call sites invoked it through `$this` while the others already used `static::`. Behavior is unchanged, since both forms resolve the method with late static binding. In Gutenberg the same change, made in https://github.com/WordPress/gutenberg/pull/87058, cleared the only errors of the `dynamicCallOnStaticMethod` rule from phpstan-strict-rules, so making it here keeps `WP_Theme_JSON` in sync with its Gutenberg counterpart. Developed in https://github.com/WordPress/wordpress-develop/pull/16093. Follow-up to r55192, r58421. Props noruzzaman, westonruter. See #66739. git-svn-id: https://develop.svn.wordpress.org/trunk@65770 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-theme-json.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/wp-includes/class-wp-theme-json.php b/src/wp-includes/class-wp-theme-json.php index 15d08fba457a9..f432b45ab45ee 100644 --- a/src/wp-includes/class-wp-theme-json.php +++ b/src/wp-includes/class-wp-theme-json.php @@ -2283,7 +2283,7 @@ public function get_custom_css() { $custom_block_css = $this->theme_json['styles']['blocks'][ $name ]['css'] ?? null; if ( $custom_block_css ) { $selector = static::$blocks_metadata[ $name ]['selector']; - $stylesheet .= $this->process_blocks_custom_css( $custom_block_css, $selector ); + $stylesheet .= static::process_blocks_custom_css( $custom_block_css, $selector ); } } } @@ -4202,7 +4202,7 @@ public function get_styles_for_block( $block_metadata ) { // 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'], $variation_css_selector ); + $style_variation_custom_css[ $style_variation['selector'] ] = static::process_blocks_custom_css( $style_variation_node['css'], $variation_css_selector ); } // Store variation metadata and node for layout styles generation. @@ -4534,7 +4534,7 @@ static function ( $pseudo_selector ) use ( $selector ) { // 7. Generate and append any custom CSS rules. if ( isset( $node['css'] ) && ! $is_root_selector ) { $css_selector = $css_feature_selector ?? $selector; - $block_rules .= $this->process_blocks_custom_css( $node['css'], $css_selector ); + $block_rules .= static::process_blocks_custom_css( $node['css'], $css_selector ); } // 8. Wrap the entire block output in a media query if this is a responsive node. From 635c42cfce0a2e125dbf8d89b904956dc24b4bf7 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Wed, 25 Nov 2026 07:18:50 +0000 Subject: [PATCH 78/85] Code Quality: Correct by-ref types in UTF-8 compat functions. In `_wp_scan_utf8()` the `$has_noncharacters` reference was accumulated with the bitwise `|=` operator, which turned the boolean into an integer as soon as a sequence able to encode a noncharacter was scanned, contrary to its documented type. It is now accumulated with a logical OR, so callers always receive a boolean. New `@param-out` tags document that `$has_noncharacters` and `$found_code_points` are never null on return, even though both accept null when passed in. This empties the `parameterByRef.unusedType` baseline, so it is removed. New tests cover how `_wp_scan_utf8()` counts code points across multibyte sequences and grapheme clusters, how it reports the maximal subparts of invalid byte sequences, and how it detects noncharacters. Developed in https://github.com/WordPress/wordpress-develop/pull/14025. Follow-up to r61000, r63022. Props huzaifaalmesbah, dmsnell, lancewillett, westonruter, rcwpdev. See #66739. git-svn-id: https://develop.svn.wordpress.org/trunk@65771 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/compat-utf8.php | 6 +- .../baselines/parameterByRef.type.neon | 5 - .../baselines/parameterByRef.unusedType.neon | 30 ---- tests/phpunit/tests/compat/wpScanUtf8.php | 154 ++++++++++++++++++ 4 files changed, 158 insertions(+), 37 deletions(-) delete mode 100644 tests/phpstan/baselines/parameterByRef.unusedType.neon create mode 100644 tests/phpunit/tests/compat/wpScanUtf8.php diff --git a/src/wp-includes/compat-utf8.php b/src/wp-includes/compat-utf8.php index 326786fe608f2..924ee4443c412 100644 --- a/src/wp-includes/compat-utf8.php +++ b/src/wp-includes/compat-utf8.php @@ -42,6 +42,7 @@ * @param int|null $max_bytes Stop scanning after this many bytes have been seen. * @param int|null $max_code_points Stop scanning after this many code points have been seen. * @param bool|null $has_noncharacters Set to indicate if scanned string contained noncharacters. + * @param-out bool $has_noncharacters * @return int How many code points were successfully scanned. */ function _wp_scan_utf8( string $bytes, int &$at, int &$invalid_length, ?int $max_bytes = null, ?int $max_code_points = null, ?bool &$has_noncharacters = null ): int { @@ -151,7 +152,7 @@ function _wp_scan_utf8( string $bytes, int &$at, int &$invalid_length, ?int $max // Covers the range U+FDD0–U+FDEF, U+FFFE, U+FFFF. if ( 0xEF === $b1 ) { - $has_noncharacters |= ( + $has_noncharacters = $has_noncharacters || ( ( 0xB7 === $b2 && $b3 >= 0x90 && $b3 <= 0xAF ) || ( 0xBF === $b2 && ( 0xBE === $b3 || 0xBF === $b3 ) ) ); @@ -176,7 +177,7 @@ function _wp_scan_utf8( string $bytes, int &$at, int &$invalid_length, ?int $max $i += 3; // Covers U+1FFFE, U+1FFFF, U+2FFFE, U+2FFFF, …, U+10FFFE, U+10FFFF. - $has_noncharacters |= ( + $has_noncharacters = $has_noncharacters || ( ( 0x0F === ( $b2 & 0x0F ) ) && 0xBF === $b3 && ( 0xBE === $b4 || 0xBF === $b4 ) @@ -376,6 +377,7 @@ function _wp_utf8_codepoint_count( string $text, ?int $byte_offset = 0, ?int $ma * @param ?int $found_code_points Optional. Will be set to number of found code points in * span, as this might be smaller than the maximum count if * the string is not long enough. + * @param-out int $found_code_points * @return int Number of bytes spanned by the code points. */ function _wp_utf8_codepoint_span( string $text, int $byte_offset, int $max_code_points, ?int &$found_code_points = 0 ): int { diff --git a/tests/phpstan/baselines/parameterByRef.type.neon b/tests/phpstan/baselines/parameterByRef.type.neon index 0a99ae46d6d27..0c1fffe95ebb9 100644 --- a/tests/phpstan/baselines/parameterByRef.type.neon +++ b/tests/phpstan/baselines/parameterByRef.type.neon @@ -38,11 +38,6 @@ parameters: identifier: parameterByRef.type count: 1 path: ../../../src/wp-includes/class-wp-token-map.php - - - message: '#^Parameter &\$has_noncharacters by\-ref type of function _wp_scan_utf8\(\) expects bool\|null, int given\.$#' - identifier: parameterByRef.type - count: 2 - path: ../../../src/wp-includes/compat-utf8.php - message: '#^Parameter &\$result by\-ref type of function _page_traverse_name\(\) expects array\, array given\.$#' identifier: parameterByRef.type diff --git a/tests/phpstan/baselines/parameterByRef.unusedType.neon b/tests/phpstan/baselines/parameterByRef.unusedType.neon deleted file mode 100644 index 4738b39636023..0000000000000 --- a/tests/phpstan/baselines/parameterByRef.unusedType.neon +++ /dev/null @@ -1,30 +0,0 @@ -# PHPStan baseline for the `parameterByRef.unusedType` errors in WordPress core. -# -# https://phpstan.org/error-identifiers/parameterByRef.unusedType -# -# Each entry is scoped to a single file and carries an exact occurrence count, -# so that a new instance is reported as a new error rather than being absorbed -# silently. Fixing an occurrence therefore means decrementing or removing its -# entry here as part of the same change. -# -# The goal is to empty this file and delete it. -# -# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: -# -# composer phpstan:baselines -- --identifier=parameterByRef.unusedType --config=phpstan.neon.dist -# -# This reruns the analysis with the baselines in this directory suppressed, so -# that their errors surface again, and rewrites only this file. - -parameters: - ignoreErrors: - - - message: '#^Function _wp_scan_utf8\(\) never assigns null to &\$has_noncharacters so it can be removed from the by\-ref type\.$#' - identifier: parameterByRef.unusedType - count: 1 - path: ../../../src/wp-includes/compat-utf8.php - - - message: '#^Function _wp_utf8_codepoint_span\(\) never assigns null to &\$found_code_points so it can be removed from the by\-ref type\.$#' - identifier: parameterByRef.unusedType - count: 1 - path: ../../../src/wp-includes/compat-utf8.php diff --git a/tests/phpunit/tests/compat/wpScanUtf8.php b/tests/phpunit/tests/compat/wpScanUtf8.php new file mode 100644 index 0000000000000..ec7608ed9278c --- /dev/null +++ b/tests/phpunit/tests/compat/wpScanUtf8.php @@ -0,0 +1,154 @@ +assertSame( mb_strlen( $text, 'UTF-8' ), $count, 'Should have counted every code point.' ); + $this->assertSame( strlen( $text ), $at, 'Should have scanned to the end of the text.' ); + $this->assertSame( 0, $invalid_length, 'Should not have found any invalid bytes.' ); + $this->assertFalse( $has_noncharacters, 'Should not have found any noncharacters.' ); + } + + /** + * Data provider for {@see self::test_counts_code_points_in_valid_utf8()}. + * + * @return array + */ + public static function data_valid_utf8(): array { + return array( + 'Empty string' => array( '' ), + 'US-ASCII' => array( 'Hello, World!' ), + 'Two-byte sequences' => array( "Pi\u{00F1}a \u{00E9}t\u{00E9}" ), + 'Three-byte sequences' => array( "\u{65E5}\u{672C}\u{8A9E}" ), + 'Four-byte sequences' => array( "\u{1F600}\u{1F170}\u{10348}" ), + 'Mixed sequence lengths' => array( "a\u{00F1}\u{65E5}\u{1F600}z" ), + 'Boundaries between lengths' => array( "\u{007F}\u{0080}\u{07FF}\u{0800}\u{FFFD}\u{10000}\u{10FFFD}" ), + 'Combining character' => array( "e\u{0301}" ), + 'Hangul syllable as conjoining jamo' => array( "\u{1112}\u{1161}\u{11AB}" ), + 'Devanagari grapheme clusters' => array( "\u{0928}\u{092E}\u{0938}\u{094D}\u{0924}\u{0947}" ), + 'Regional indicator pair (flag)' => array( "\u{1F1E7}\u{1F1E9}" ), + 'Emoji with skin tone modifier' => array( "\u{1F44D}\u{1F3FD}" ), + 'Keycap sequence' => array( "1\u{FE0F}\u{20E3}" ), + 'ZWJ sequence' => array( "\u{1F469}\u{200D}\u{1F4BB}" ), + 'ZWJ family sequence' => array( "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}" ), + 'ZWJ sequence with VS-16' => array( "\u{1F3F3}\u{FE0F}\u{200D}\u{1F308}" ), + ); + } + + /** + * Ensures that each maximal subpart of an invalid byte sequence is reported + * as its own invalid span, so that it can be replaced by a single U+FFFD. + * + * @ticket 65817 + * + * @dataProvider data_invalid_utf8 + * + * @param string $text Text containing invalid UTF-8 bytes. + * @param list $expected_spans Byte length of each invalid span, in order. + * @param positive-int $expected_code_points Code points when each invalid span counts as one. + */ + public function test_finds_maximal_subparts_of_invalid_bytes( string $text, array $expected_spans, int $expected_code_points ) { + $end = strlen( $text ); + $at = 0; + $invalid_length = 0; + $invalid_spans = array(); + $code_points = 0; + + while ( $at < $end ) { + $code_points += _wp_scan_utf8( $text, $at, $invalid_length ); + + if ( 0 === $invalid_length ) { + break; + } + + $invalid_spans[] = $invalid_length; + ++$code_points; + $at += $invalid_length; + } + + $this->assertSame( $expected_spans, $invalid_spans, 'Should have found the maximal subpart of each invalid span.' ); + $this->assertSame( $expected_code_points, $code_points, 'Should have counted one code point for each invalid span.' ); + $this->assertSame( $end, $at, 'Should have scanned to the end of the text.' ); + } + + /** + * Data provider for {@see self::test_finds_maximal_subparts_of_invalid_bytes()}. + * + * @return array, 2: positive-int }> + */ + public static function data_invalid_utf8(): array { + return array( + 'Lone continuation byte' => array( "a\x80b", array( 1 ), 3 ), + 'Run of continuation bytes' => array( "a\x80\xBF\x80b", array( 1, 1, 1 ), 5 ), + 'Truncated two-byte sequence' => array( "a\xC3b", array( 1 ), 3 ), + 'Truncated three-byte sequence' => array( "a\xE2\x82b", array( 2 ), 3 ), + 'Truncated four-byte sequence' => array( "a\xF0\x9F\x98b", array( 3 ), 3 ), + 'Truncated sequence at the end' => array( "abc\xF0\x9F\x98", array( 3 ), 4 ), + 'Overlong two-byte sequence' => array( "a\xC0\xAFb", array( 1, 1 ), 4 ), + 'Overlong three-byte sequence' => array( "a\xE0\x80\xAFb", array( 1, 1, 1 ), 5 ), + 'UTF-16 surrogate half' => array( "a\xED\xA0\x80b", array( 1, 1, 1 ), 5 ), + 'Code point above U+10FFFF' => array( "a\xF4\x90\x80\x80b", array( 1, 1, 1, 1 ), 6 ), + 'Byte that never appears in UTF-8' => array( "a\xFFb", array( 1 ), 3 ), + 'Windows-1252 encoded text' => array( "Pi\xF1a", array( 1 ), 4 ), + 'Truncated sequences back to back' => array( "\xE2\x82\xF0\x9F\x98", array( 2, 3 ), 2 ), + 'Invalid span between valid multibyte' => array( "\u{1F600}\xE2\x82\u{65E5}", array( 2 ), 3 ), + ); + } + + /** + * Tests scanning UTF-8 string containing noncharacters. + * + * @ticket 65817 + * + * @dataProvider data_strings_with_noncharacters + * + * @param string $text UTF-8 string containing a noncharacter. + */ + public function test_scan_string_with_noncharacters( string $text ) { + $at = 0; + $invalid_length = 0; + $has_noncharacters = null; + + _wp_scan_utf8( $text, $at, $invalid_length, null, null, $has_noncharacters ); + + $this->assertTrue( $has_noncharacters ); + } + + /** + * Data provider for {@see self::test_scan_string_with_noncharacters()}. + * + * @return array + */ + public static function data_strings_with_noncharacters(): array { + return array( + 'U+FFFF (3-byte noncharacter)' => array( "test \xEF\xBF\xBF end" ), + 'U+FFFE (3-byte noncharacter)' => array( "test \xEF\xBF\xBE end" ), + 'U+FDD0 (3-byte noncharacter)' => array( "test \xEF\xB7\x90 end" ), + 'U+1FFFF (4-byte noncharacter)' => array( "test \xF0\x9F\xBF\xBF end" ), + ); + } +} From 916de6f6b6df55ed2c9db292f36a1690a67c403c Mon Sep 17 00:00:00 2001 From: Nik Tsekouras Date: Wed, 25 Nov 2026 08:07:25 +0000 Subject: [PATCH 79/85] Editor: Update the post editor preload paths for the DataForm inspector. The DataForm-based inspector requests the form config of the post type on load, so preload `/wp/v2/view-config` with `_fields=form`. Remove the preload of the post author user, which was only requested by the previous author panel. See https://github.com/WordPress/gutenberg/pull/85081. Developed in https://github.com/WordPress/wordpress-develop/pull/14494. Props ntsekouras, oandregal, mamaduka. Fixes #66339. git-svn-id: https://develop.svn.wordpress.org/trunk@65772 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/edit-form-blocks.php | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/wp-admin/edit-form-blocks.php b/src/wp-admin/edit-form-blocks.php index 820424fb3c477..6585fbc2d63bc 100644 --- a/src/wp-admin/edit-form-blocks.php +++ b/src/wp-admin/edit-form-blocks.php @@ -121,15 +121,14 @@ static function ( $classes ) { '/wp/v2/templates/lookup?slug=front-page', '/wp/v2/taxonomies?context=edit', array( rest_get_route_for_post_type_items( $post_type ), 'OPTIONS' ), + /* + * The post summary of the inspector requests the form config of the post type + * through `useViewConfig` with `fields: [ 'form' ]`, so the path must match + * the resulting `_fields=form` request. + */ + '/wp/v2/view-config?kind=postType&name=' . $post_type . '&_fields=form', ); -if ( post_type_supports( $post_type, 'author' ) && $post->post_author > 0 ) { - $preload_paths[] = sprintf( - '/wp/v2/users/%d?context=view&_fields=id,name', - (int) $post->post_author - ); -} - block_editor_rest_api_preload( $preload_paths, $block_editor_context ); wp_add_inline_script( From fa31aaeb2011a1fabcb8f5418bdd60a34bc4c0ac Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Wed, 25 Nov 2026 08:09:51 +0000 Subject: [PATCH 80/85] Code Quality: Resolve the `deadCode.unreachable` PHPStan errors. Only one of the unreachable statements in the baseline could never run, the trailing `wp_send_json_error()` in `wp_ajax_set_attachment_thumbnail()`, which would only have appended a second response after one had already been sent, and it is removed. The others are kept on purpose: * Translatable strings after a `return`, so that they are added to the POT file. * An `exit` or `break` that keeps a `switch` case from reading as falling through. * The `wp_die()` fallback for a list table supplied by the `wp_list_table_class_name` filter whose `ajax_response()` returns. * The `die()` that stops a request with an invalid nonce even if a custom `wp_die()` handler returns. Since these should never be fixed, they are ignored inline with a reason rather than left in a baseline, which would invite contributors to remove them. Unlike the counted entries used for the HTML API in r64294, an inline ignore names the exact statement, so a genuine unreachable statement added to the same file is still reported. The Ajax handlers involved are also documented as never returning. Developed in https://github.com/WordPress/wordpress-develop/pull/16224. Follow-up to r29029, r63023, r64294. Props mukesh27, westonruter. See #66739. git-svn-id: https://develop.svn.wordpress.org/trunk@65773 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/about.php | 2 +- src/wp-admin/credits.php | 2 +- src/wp-admin/includes/ajax-actions.php | 12 +++-- src/wp-admin/post.php | 4 +- src/wp-includes/capabilities.php | 2 +- src/wp-includes/pluggable.php | 2 +- .../baselines/deadCode.unreachable.neon | 50 ------------------- 7 files changed, 14 insertions(+), 60 deletions(-) delete mode 100644 tests/phpstan/baselines/deadCode.unreachable.neon diff --git a/src/wp-admin/about.php b/src/wp-admin/about.php index a3c27bca791fb..a2cf8c5ca1ec4 100644 --- a/src/wp-admin/about.php +++ b/src/wp-admin/about.php @@ -294,7 +294,7 @@ // These are strings we may use to describe maintenance/security releases, where we aim for no new strings. return; -__( 'Maintenance Release' ); +__( 'Maintenance Release' ); // @phpstan-ignore deadCode.unreachable (Placed after the return so that the strings are added to the POT file without running.) __( 'Maintenance Releases' ); __( 'Security Release' ); diff --git a/src/wp-admin/credits.php b/src/wp-admin/credits.php index 75993cf6652a7..26f06b76a6010 100644 --- a/src/wp-admin/credits.php +++ b/src/wp-admin/credits.php @@ -122,7 +122,7 @@ return; // These are strings returned by the API that we want to be translatable. -__( 'Project Leaders' ); +__( 'Project Leaders' ); // @phpstan-ignore deadCode.unreachable (Placed after the return so that the strings are added to the POT file without running.) /* translators: %s: The current WordPress version number. */ __( 'Core Contributors to WordPress %s' ); __( 'Noteworthy Contributors' ); diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index ba3b9bc2851a1..ede68a275b64b 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -79,6 +79,8 @@ function wp_ajax_nopriv_heartbeat() { * Handles fetching a list table via AJAX. * * @since 3.1.0 + * + * @return never */ function wp_ajax_fetch_list() { $list_class = $_GET['list_args']['class']; @@ -95,7 +97,7 @@ function wp_ajax_fetch_list() { $wp_list_table->ajax_response(); - wp_die( 0 ); + wp_die( 0 ); // @phpstan-ignore deadCode.unreachable (The wp_list_table_class_name filter can supply a class whose ajax_response() returns.) } /** @@ -2684,6 +2686,8 @@ function wp_ajax_upload_attachment() { * Handles image editing via AJAX. * * @since 3.1.0 + * + * @return never */ function wp_ajax_image_editor() { $attachment_id = (int) $_POST['postid']; @@ -2705,7 +2709,7 @@ function wp_ajax_image_editor() { } wp_send_json_success( $message ); - break; + break; // @phpstan-ignore deadCode.unreachable (Ends the case so that it does not read as falling through, which PHPCS reports.) case 'scale': $message = wp_save_image( $attachment_id ); break; @@ -2804,6 +2808,8 @@ function wp_ajax_get_post_thumbnail_html() { * @since 4.0.0 * * @see set_post_thumbnail() + * + * @return never */ function wp_ajax_set_attachment_thumbnail() { if ( empty( $_POST['urls'] ) || ! is_array( $_POST['urls'] ) ) { @@ -2849,8 +2855,6 @@ function wp_ajax_set_attachment_thumbnail() { } else { wp_send_json_success(); } - - wp_send_json_error(); } /** diff --git a/src/wp-admin/post.php b/src/wp-admin/post.php index 3cb4a9048d536..7d685cffe30bf 100644 --- a/src/wp-admin/post.php +++ b/src/wp-admin/post.php @@ -125,7 +125,7 @@ check_admin_referer( 'add-' . $post_type ); $post_id = 'postajaxpost' === $action ? edit_post() : write_post(); redirect_post( $post_id ); - exit; + exit; // @phpstan-ignore deadCode.unreachable (Ends the case so that it does not read as falling through, which PHPCS reports.) case 'edit': $editing = true; @@ -245,7 +245,7 @@ redirect_post( $post_id ); // Send user on their way while we keep working. - exit; + exit; // @phpstan-ignore deadCode.unreachable (Ends the case so that it does not read as falling through into the trash case.) case 'trash': check_admin_referer( 'trash-post_' . $post_id ); diff --git a/src/wp-includes/capabilities.php b/src/wp-includes/capabilities.php index 0cf3341abaa5c..4262f6e4a093b 100644 --- a/src/wp-includes/capabilities.php +++ b/src/wp-includes/capabilities.php @@ -1365,7 +1365,7 @@ function wp_maybe_grant_site_health_caps( $allcaps, $caps, $args, $user ) { // Dummy gettext calls to get strings in the catalog. /* translators: User role for administrators. */ -_x( 'Administrator', 'User role' ); +_x( 'Administrator', 'User role' ); // @phpstan-ignore deadCode.unreachable (Placed after the return so that the strings are added to the POT file without running.) /* translators: User role for editors. */ _x( 'Editor', 'User role' ); /* translators: User role for authors. */ diff --git a/src/wp-includes/pluggable.php b/src/wp-includes/pluggable.php index 94aab93a98455..640ab86e06f2e 100644 --- a/src/wp-includes/pluggable.php +++ b/src/wp-includes/pluggable.php @@ -1399,7 +1399,7 @@ function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) { if ( ! $result && ! ( -1 === $action && str_starts_with( $referer, $adminurl ) ) ) { wp_nonce_ays( $action ); - die(); + die(); // @phpstan-ignore deadCode.unreachable (Stops a request with an invalid nonce even if a custom wp_die() handler returns.) } return $result; diff --git a/tests/phpstan/baselines/deadCode.unreachable.neon b/tests/phpstan/baselines/deadCode.unreachable.neon deleted file mode 100644 index 1a688f51c78a1..0000000000000 --- a/tests/phpstan/baselines/deadCode.unreachable.neon +++ /dev/null @@ -1,50 +0,0 @@ -# PHPStan baseline for the `deadCode.unreachable` errors in WordPress core. -# -# https://phpstan.org/error-identifiers/deadCode.unreachable -# -# Each entry is scoped to a single file and carries an exact occurrence count, -# so that a new instance is reported as a new error rather than being absorbed -# silently. Fixing an occurrence therefore means decrementing or removing its -# entry here as part of the same change. -# -# The goal is to empty this file and delete it. -# -# Generated by `composer phpstan:baselines`. Do not edit by hand. Regenerate with: -# -# composer phpstan:baselines -- --identifier=deadCode.unreachable --config=phpstan.neon.dist -# -# This reruns the analysis with the baselines in this directory suppressed, so -# that their errors surface again, and rewrites only this file. - -parameters: - ignoreErrors: - - - message: '#^Unreachable statement \- code above always terminates\.$#' - identifier: deadCode.unreachable - count: 1 - path: ../../../src/wp-admin/about.php - - - message: '#^Unreachable statement \- code above always terminates\.$#' - identifier: deadCode.unreachable - count: 1 - path: ../../../src/wp-admin/credits.php - - - message: '#^Unreachable statement \- code above always terminates\.$#' - identifier: deadCode.unreachable - count: 3 - path: ../../../src/wp-admin/includes/ajax-actions.php - - - message: '#^Unreachable statement \- code above always terminates\.$#' - identifier: deadCode.unreachable - count: 2 - path: ../../../src/wp-admin/post.php - - - message: '#^Unreachable statement \- code above always terminates\.$#' - identifier: deadCode.unreachable - count: 1 - path: ../../../src/wp-includes/capabilities.php - - - message: '#^Unreachable statement \- code above always terminates\.$#' - identifier: deadCode.unreachable - count: 1 - path: ../../../src/wp-includes/pluggable.php From 967cbe965e1c503dee9524b683d109b1a01b26a2 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 25 Nov 2026 10:53:33 +0000 Subject: [PATCH 81/85] I18N: Place translator comments directly before their strings. Some translator comments were placed in front of a ternary operator or shared a line with several translatable strings. String extraction tools either miss such comments or attach them to the wrong string. This moves each comment directly before the gettext call it describes. Developed in: https://github.com/WordPress/wordpress-develop/pull/16069 Props swissspidy, mukesh27. See #66747. git-svn-id: https://develop.svn.wordpress.org/trunk@65774 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/includes/deprecated.php | 9 ++++++-- src/wp-admin/includes/update.php | 7 ++++-- src/wp-includes/class-wp-object-cache.php | 13 ++++++++---- src/wp-includes/class-wp-taxonomy.php | 8 +++++-- src/wp-includes/class-wp-theme-json.php | 26 +++++++++++++++++++---- src/wp-includes/pluggable.php | 7 ++++-- 6 files changed, 54 insertions(+), 16 deletions(-) diff --git a/src/wp-admin/includes/deprecated.php b/src/wp-admin/includes/deprecated.php index b3aaad1ad9a2f..e39f332e7f0d5 100644 --- a/src/wp-admin/includes/deprecated.php +++ b/src/wp-admin/includes/deprecated.php @@ -1386,10 +1386,15 @@ function wp_dashboard_plugins_output( $rss, $args = array() ) { $raw_title = $item->get_title(); $ilink = wp_nonce_url('plugin-install.php?tab=plugin-information&plugin=' . $slug, 'install-plugin_' . $slug) . '&TB_iframe=true&width=600&height=800'; + $install_label = sprintf( + /* translators: %s: Plugin name. */ + _x( 'Install %s', 'plugin' ), + $raw_title + ); + echo '
  • ' . __( 'Popular Plugin' ) . ': ' . esc_html( $raw_title ) . ' (' . __( 'Install' ) . ')
  • '; + esc_attr( $install_label ) . '">(' . __( 'Install' ) . ')'; $feed->__destruct(); unset( $feed ); diff --git a/src/wp-admin/includes/update.php b/src/wp-admin/includes/update.php index e7b02a2a62c8a..60d84a54dac8f 100644 --- a/src/wp-admin/includes/update.php +++ b/src/wp-admin/includes/update.php @@ -385,8 +385,11 @@ function update_right_now_message() { $msg .= sprintf( '%s', network_admin_url( 'update-core.php' ), - /* translators: %s: WordPress version number, or 'Latest' string. */ - sprintf( __( 'Update to %s' ), $cur->current ? $cur->current : __( 'Latest' ) ) + sprintf( + /* translators: %s: WordPress version number, or 'Latest' string. */ + __( 'Update to %s' ), + $cur->current ? $cur->current : __( 'Latest' ) + ) ); } } diff --git a/src/wp-includes/class-wp-object-cache.php b/src/wp-includes/class-wp-object-cache.php index 443af49e3112d..0ac9e10dcde3c 100644 --- a/src/wp-includes/class-wp-object-cache.php +++ b/src/wp-includes/class-wp-object-cache.php @@ -154,10 +154,15 @@ protected function is_valid_key( $key ) { wp_load_translations_early(); } - $message = is_string( $key ) - ? __( 'Cache key must not be an empty string.' ) - /* translators: %s: The type of the given cache key. */ - : sprintf( __( 'Cache key must be an integer or a non-empty string, %s given.' ), $type ); + if ( is_string( $key ) ) { + $message = __( 'Cache key must not be an empty string.' ); + } else { + $message = sprintf( + /* translators: %s: The type of the given cache key. */ + __( 'Cache key must be an integer or a non-empty string, %s given.' ), + $type + ); + } _doing_it_wrong( sprintf( '%s::%s', __CLASS__, debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 )[1]['function'] ), diff --git a/src/wp-includes/class-wp-taxonomy.php b/src/wp-includes/class-wp-taxonomy.php index f44ce34a11def..d563a2c4386da 100644 --- a/src/wp-includes/class-wp-taxonomy.php +++ b/src/wp-includes/class-wp-taxonomy.php @@ -633,8 +633,12 @@ public static function get_default_labels() { 'filter_by_item' => array( null, __( 'Filter by category' ) ), 'items_list_navigation' => array( __( 'Tags list navigation' ), __( 'Categories list navigation' ) ), 'items_list' => array( __( 'Tags list' ), __( 'Categories list' ) ), - /* translators: Tab heading when selecting from the most used terms. */ - 'most_used' => array( _x( 'Most Used', 'tags' ), _x( 'Most Used', 'categories' ) ), + 'most_used' => array( + /* translators: Tab heading when selecting from the most used terms. */ + _x( 'Most Used', 'tags' ), + /* translators: Tab heading when selecting from the most used terms. */ + _x( 'Most Used', 'categories' ), + ), 'back_to_items' => array( __( '← Go to Tags' ), __( '← Go to Categories' ) ), 'item_link' => array( _x( 'Tag Link', 'navigation link block title' ), diff --git a/src/wp-includes/class-wp-theme-json.php b/src/wp-includes/class-wp-theme-json.php index f432b45ab45ee..85dc55bce5501 100644 --- a/src/wp-includes/class-wp-theme-json.php +++ b/src/wp-includes/class-wp-theme-json.php @@ -5860,9 +5860,18 @@ private static function compute_spacing_sizes( $spacing_scale ) { break; } + if ( $below_midpoint_count === $steps_mid_point - 1 ) { + $name = __( 'Small' ); + } else { + $name = sprintf( + /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Small. */ + __( '%sX-Small' ), + (string) $x_small_count + ); + } + $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 ), + 'name' => $name, 'slug' => (string) $slug, 'size' => round( $current_step, 2 ) . $unit, ); @@ -5897,9 +5906,18 @@ private static function compute_spacing_sizes( $spacing_scale ) { ? $current_step + $spacing_scale['increment'] : ( $spacing_scale['increment'] >= 1 ? $current_step * $spacing_scale['increment'] : $current_step / $spacing_scale['increment'] ); + if ( 0 === $above_midpoint_count ) { + $name = __( 'Large' ); + } else { + $name = sprintf( + /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Large. */ + __( '%sX-Large' ), + (string) $x_large_count + ); + } + $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 ), + 'name' => $name, 'slug' => (string) $slug, 'size' => round( $current_step, 2 ) . $unit, ); diff --git a/src/wp-includes/pluggable.php b/src/wp-includes/pluggable.php index 640ab86e06f2e..8e8f885f87d06 100644 --- a/src/wp-includes/pluggable.php +++ b/src/wp-includes/pluggable.php @@ -1930,8 +1930,11 @@ function wp_notify_postauthor( $comment_id, $deprecated = null ) { $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; /* translators: %s: Note author email. */ $notify_message .= sprintf( __( 'Email: %s' ), $comment_author_email ) . "\r\n"; - /* translators: %s: Note text. */ - $notify_message .= sprintf( __( 'Note: %s' ), "\r\n" . ( empty( $comment_content ) ? __( 'resolved/reopened' ) : $comment_content ) ) . "\r\n\r\n"; + $notify_message .= sprintf( + /* translators: %s: Note text. */ + __( 'Note: %s' ), + "\r\n" . ( empty( $comment_content ) ? __( 'resolved/reopened' ) : $comment_content ) + ) . "\r\n\r\n"; $notify_message .= __( 'You can see all notes on this post here:' ) . "\r\n"; /* translators: Note notification email subject. 1: Site title, 2: Post title. */ $subject = sprintf( __( '[%1$s] Note: "%2$s"' ), $blogname, $post->post_title ); From 9fedd3c36686e94619620f79780ada6bf60bdd92 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 25 Nov 2026 10:55:10 +0000 Subject: [PATCH 82/85] Bundled Themes: Place translator comments directly before their strings. Some translator comments were placed in front of a ternary operator or shared a line with several translatable strings. String extraction tools either miss such comments or attach them to the wrong string. This moves each comment directly before the gettext call it describes. This is the bundled themes counterpart of r65774, which fixes the same problem in core. Developed in: https://github.com/WordPress/wordpress-develop/pull/16071 Props swissspidy, mukesh27. See #66747. git-svn-id: https://develop.svn.wordpress.org/trunk@65775 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-content/themes/twentyeleven/archive.php | 14 ++++++++++---- .../themes/twentyfourteen/archive.php | 14 ++++++++++---- .../themes/twentyfourteen/inc/customizer.php | 9 +++++++-- .../themes/twentyseventeen/single.php | 18 ++++++++++++++---- src/wp-content/themes/twentyten/archive.php | 14 ++++++++++---- .../themes/twentythirteen/archive.php | 14 ++++++++++---- src/wp-content/themes/twentytwelve/archive.php | 14 ++++++++++---- 7 files changed, 71 insertions(+), 26 deletions(-) diff --git a/src/wp-content/themes/twentyeleven/archive.php b/src/wp-content/themes/twentyeleven/archive.php index a21e626b70108..6e43c967d9506 100644 --- a/src/wp-content/themes/twentyeleven/archive.php +++ b/src/wp-content/themes/twentyeleven/archive.php @@ -26,11 +26,17 @@ /* translators: %s: Date. */ printf( __( 'Daily Archives: %s', 'twentyeleven' ), '' . get_the_date() . '' ); } elseif ( is_month() ) { - /* translators: %s: Date. */ - printf( __( 'Monthly Archives: %s', 'twentyeleven' ), '' . get_the_date( _x( 'F Y', 'monthly archives date format', 'twentyeleven' ) ) . '' ); + printf( + /* translators: %s: Date. */ + __( 'Monthly Archives: %s', 'twentyeleven' ), + '' . get_the_date( _x( 'F Y', 'monthly archives date format', 'twentyeleven' ) ) . '' + ); } elseif ( is_year() ) { - /* translators: %s: Date. */ - printf( __( 'Yearly Archives: %s', 'twentyeleven' ), '' . get_the_date( _x( 'Y', 'yearly archives date format', 'twentyeleven' ) ) . '' ); + printf( + /* translators: %s: Date. */ + __( 'Yearly Archives: %s', 'twentyeleven' ), + '' . get_the_date( _x( 'Y', 'yearly archives date format', 'twentyeleven' ) ) . '' + ); } else { _e( 'Blog Archives', 'twentyeleven' ); } diff --git a/src/wp-content/themes/twentyfourteen/archive.php b/src/wp-content/themes/twentyfourteen/archive.php index f11a57ff1af01..0b43532e3375b 100644 --- a/src/wp-content/themes/twentyfourteen/archive.php +++ b/src/wp-content/themes/twentyfourteen/archive.php @@ -31,11 +31,17 @@ /* translators: %s: Date. */ printf( __( 'Daily Archives: %s', 'twentyfourteen' ), get_the_date() ); } elseif ( is_month() ) { - /* translators: %s: Date. */ - printf( __( 'Monthly Archives: %s', 'twentyfourteen' ), get_the_date( _x( 'F Y', 'monthly archives date format', 'twentyfourteen' ) ) ); + printf( + /* translators: %s: Date. */ + __( 'Monthly Archives: %s', 'twentyfourteen' ), + get_the_date( _x( 'F Y', 'monthly archives date format', 'twentyfourteen' ) ) + ); } elseif ( is_year() ) { - /* translators: %s: Date. */ - printf( __( 'Yearly Archives: %s', 'twentyfourteen' ), get_the_date( _x( 'Y', 'yearly archives date format', 'twentyfourteen' ) ) ); + printf( + /* translators: %s: Date. */ + __( 'Yearly Archives: %s', 'twentyfourteen' ), + get_the_date( _x( 'Y', 'yearly archives date format', 'twentyfourteen' ) ) + ); } else { _e( 'Archives', 'twentyfourteen' ); } diff --git a/src/wp-content/themes/twentyfourteen/inc/customizer.php b/src/wp-content/themes/twentyfourteen/inc/customizer.php index 624d4e6207602..8ba5759f38bb1 100644 --- a/src/wp-content/themes/twentyfourteen/inc/customizer.php +++ b/src/wp-content/themes/twentyfourteen/inc/customizer.php @@ -164,8 +164,13 @@ function twentyfourteen_contextual_help() { 'title' => __( 'Twenty Fourteen', 'twentyfourteen' ), 'content' => '
      ' . - /* translators: 1: Featured tag editor URL, 2: Post editor URL, 3: Customizer URL, 4: Post editor URL. */ - '
    • ' . sprintf( __( 'The home page features your choice of up to 6 posts prominently displayed in a grid or slider, controlled by a tag; you can change the tag and layout in Appearance → Customize. If no posts match the tag, sticky posts will be displayed instead.', 'twentyfourteen' ), esc_url( add_query_arg( 'tag', _x( 'featured', 'featured content default tag slug', 'twentyfourteen' ), admin_url( 'edit.php' ) ) ), admin_url( 'customize.php' ), admin_url( 'edit.php?show_sticky=1' ) ) . '
    • ' . + '
    • ' . sprintf( + /* translators: 1: Featured tag editor URL, 2: Post editor URL, 3: Customizer URL, 4: Post editor URL. */ + __( 'The home page features your choice of up to 6 posts prominently displayed in a grid or slider, controlled by a tag; you can change the tag and layout in Appearance → Customize. If no posts match the tag, sticky posts will be displayed instead.', 'twentyfourteen' ), + esc_url( add_query_arg( 'tag', _x( 'featured', 'featured content default tag slug', 'twentyfourteen' ), admin_url( 'edit.php' ) ) ), + admin_url( 'customize.php' ), + admin_url( 'edit.php?show_sticky=1' ) + ) . '
    • ' . /* translators: %s: Featured images documentation URL. */ '
    • ' . sprintf( __( 'Enhance your site design by using Featured Images for posts you’d like to stand out (also known as post thumbnails). This allows you to associate an image with your post without inserting it. Twenty Fourteen uses featured images for posts and pages—above the title—and in the Featured Content area on the home page.', 'twentyfourteen' ), 'https://codex.wordpress.org/Post_Thumbnails#Setting_a_Post_Thumbnail' ) . '
    • ' . /* translators: %s: Twenty Fourteen documentation URL. */ diff --git a/src/wp-content/themes/twentyseventeen/single.php b/src/wp-content/themes/twentyseventeen/single.php index 7fe1bc64891d5..406b4727b9131 100644 --- a/src/wp-content/themes/twentyseventeen/single.php +++ b/src/wp-content/themes/twentyseventeen/single.php @@ -30,10 +30,20 @@ the_post_navigation( array( - /* translators: Hidden accessibility text. */ - 'prev_text' => '' . __( 'Previous Post', 'twentyseventeen' ) . ' ' . twentyseventeen_get_svg( array( 'icon' => 'arrow-left' ) ) . '%title', - /* translators: Hidden accessibility text. */ - 'next_text' => '' . __( 'Next Post', 'twentyseventeen' ) . ' %title' . twentyseventeen_get_svg( array( 'icon' => 'arrow-right' ) ) . '', + 'prev_text' => '' . + /* translators: Hidden accessibility text. */ + __( 'Previous Post', 'twentyseventeen' ) . + ' ' . twentyseventeen_get_svg( array( 'icon' => 'arrow-left' ) ) . '%title', + 'next_text' => '' . + /* translators: Hidden accessibility text. */ + __( 'Next Post', 'twentyseventeen' ) . + ' %title' . twentyseventeen_get_svg( array( 'icon' => 'arrow-right' ) ) . '', ) ); diff --git a/src/wp-content/themes/twentyten/archive.php b/src/wp-content/themes/twentyten/archive.php index 36c5e0b3e2a39..056643232e04d 100644 --- a/src/wp-content/themes/twentyten/archive.php +++ b/src/wp-content/themes/twentyten/archive.php @@ -36,11 +36,17 @@ /* translators: %s: Date. */ printf( __( 'Daily Archives: %s', 'twentyten' ), get_the_date() ); } elseif ( is_month() ) { - /* translators: %s: Date. */ - printf( __( 'Monthly Archives: %s', 'twentyten' ), get_the_date( _x( 'F Y', 'monthly archives date format', 'twentyten' ) ) ); + printf( + /* translators: %s: Date. */ + __( 'Monthly Archives: %s', 'twentyten' ), + get_the_date( _x( 'F Y', 'monthly archives date format', 'twentyten' ) ) + ); } elseif ( is_year() ) { - /* translators: %s: Date. */ - printf( __( 'Yearly Archives: %s', 'twentyten' ), get_the_date( _x( 'Y', 'yearly archives date format', 'twentyten' ) ) ); + printf( + /* translators: %s: Date. */ + __( 'Yearly Archives: %s', 'twentyten' ), + get_the_date( _x( 'Y', 'yearly archives date format', 'twentyten' ) ) + ); } else { _e( 'Blog Archives', 'twentyten' ); } diff --git a/src/wp-content/themes/twentythirteen/archive.php b/src/wp-content/themes/twentythirteen/archive.php index b4dc2eaa0cd22..dddf548882547 100644 --- a/src/wp-content/themes/twentythirteen/archive.php +++ b/src/wp-content/themes/twentythirteen/archive.php @@ -30,11 +30,17 @@ /* translators: %s: Date. */ printf( __( 'Daily Archives: %s', 'twentythirteen' ), get_the_date() ); } elseif ( is_month() ) { - /* translators: %s: Date. */ - printf( __( 'Monthly Archives: %s', 'twentythirteen' ), get_the_date( _x( 'F Y', 'monthly archives date format', 'twentythirteen' ) ) ); + printf( + /* translators: %s: Date. */ + __( 'Monthly Archives: %s', 'twentythirteen' ), + get_the_date( _x( 'F Y', 'monthly archives date format', 'twentythirteen' ) ) + ); } elseif ( is_year() ) { - /* translators: %s: Date. */ - printf( __( 'Yearly Archives: %s', 'twentythirteen' ), get_the_date( _x( 'Y', 'yearly archives date format', 'twentythirteen' ) ) ); + printf( + /* translators: %s: Date. */ + __( 'Yearly Archives: %s', 'twentythirteen' ), + get_the_date( _x( 'Y', 'yearly archives date format', 'twentythirteen' ) ) + ); } else { _e( 'Archives', 'twentythirteen' ); } diff --git a/src/wp-content/themes/twentytwelve/archive.php b/src/wp-content/themes/twentytwelve/archive.php index b44a1c6c9f53c..084a15845f1ec 100644 --- a/src/wp-content/themes/twentytwelve/archive.php +++ b/src/wp-content/themes/twentytwelve/archive.php @@ -30,11 +30,17 @@ /* translators: %s: Date. */ printf( __( 'Daily Archives: %s', 'twentytwelve' ), '' . get_the_date() . '' ); } elseif ( is_month() ) { - /* translators: %s: Date. */ - printf( __( 'Monthly Archives: %s', 'twentytwelve' ), '' . get_the_date( _x( 'F Y', 'monthly archives date format', 'twentytwelve' ) ) . '' ); + printf( + /* translators: %s: Date. */ + __( 'Monthly Archives: %s', 'twentytwelve' ), + '' . get_the_date( _x( 'F Y', 'monthly archives date format', 'twentytwelve' ) ) . '' + ); } elseif ( is_year() ) { - /* translators: %s: Date. */ - printf( __( 'Yearly Archives: %s', 'twentytwelve' ), '' . get_the_date( _x( 'Y', 'yearly archives date format', 'twentytwelve' ) ) . '' ); + printf( + /* translators: %s: Date. */ + __( 'Yearly Archives: %s', 'twentytwelve' ), + '' . get_the_date( _x( 'Y', 'yearly archives date format', 'twentytwelve' ) ) . '' + ); } else { _e( 'Archives', 'twentytwelve' ); } From 00a656a91f43d05f7de9cede8d311e21953df25a Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 25 Nov 2026 10:59:46 +0000 Subject: [PATCH 83/85] Code Quality: Add PHPStan integer ranges and literal types. Narrow integer return and parameter types to ranges such as `non-negative-int` and `positive-int`, and string and integer types to the literal values a function can actually take or return, so that static analysis can catch more mistakes. Developed in: https://github.com/WordPress/wordpress-develop/pull/13893 Props swissspidy, westonruter, marian1. See #66739. git-svn-id: https://develop.svn.wordpress.org/trunk@65776 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/includes/bookmark.php | 14 ++++++-- .../includes/class-custom-image-header.php | 2 ++ src/wp-admin/includes/class-wp-importer.php | 4 +-- src/wp-admin/includes/taxonomy.php | 4 ++- src/wp-admin/includes/template.php | 2 ++ src/wp-includes/bookmark.php | 12 ++++--- src/wp-includes/class-wp-locale.php | 2 ++ src/wp-includes/class-wpdb.php | 3 ++ src/wp-includes/comment.php | 2 ++ src/wp-includes/formatting.php | 3 ++ src/wp-includes/functions.php | 15 ++++++++ src/wp-includes/load.php | 6 ++++ src/wp-includes/pluggable.php | 6 ++-- src/wp-includes/plugin.php | 36 ++++++++++--------- src/wp-includes/post-template.php | 2 ++ src/wp-includes/rest-api.php | 2 ++ src/wp-includes/script-loader.php | 3 ++ src/wp-includes/taxonomy.php | 8 +++-- tests/phpstan/baselines/argument.type.neon | 7 +++- tests/phpunit/includes/abstract-testcase.php | 16 ++++----- tests/phpunit/includes/utils.php | 2 +- tests/phpunit/tests/user.php | 20 +++++++++++ 22 files changed, 131 insertions(+), 40 deletions(-) diff --git a/src/wp-admin/includes/bookmark.php b/src/wp-admin/includes/bookmark.php index aae87b9abc60f..b7295237ddbde 100644 --- a/src/wp-admin/includes/bookmark.php +++ b/src/wp-admin/includes/bookmark.php @@ -12,6 +12,8 @@ * @since 2.0.0 * * @return int The link ID on success. The value 0 on failure. + * + * @phpstan-return non-negative-int */ function add_link() { return edit_link(); @@ -24,6 +26,8 @@ function add_link() { * * @param int $link_id Optional. ID of the link to edit. Default 0. * @return int The link ID on success. The value 0 on failure. + * + * @phpstan-return non-negative-int */ function edit_link( $link_id = 0 ) { if ( ! current_user_can( 'manage_links' ) ) { @@ -174,7 +178,7 @@ function get_link_to_edit( $link ) { * @param bool $wp_error Optional. Whether to return a WP_Error object on failure. Default false. * @return int|WP_Error The link ID on success. The value 0 or WP_Error on failure. * - * @phpstan-return ( $wp_error is false ? int : int|WP_Error ) + * @phpstan-return ( $wp_error is false ? non-negative-int : non-negative-int|WP_Error ) */ function wp_insert_link( $linkdata, $wp_error = false ) { global $wpdb; @@ -189,10 +193,14 @@ function wp_insert_link( $linkdata, $wp_error = false ) { $parsed_args = wp_parse_args( $linkdata, $defaults ); $parsed_args = wp_unslash( sanitize_bookmark( $parsed_args, 'db' ) ); - $link_id = $parsed_args['link_id']; + $link_id = (int) $parsed_args['link_id']; $link_name = $parsed_args['link_name']; $link_url = $parsed_args['link_url']; + if ( $link_id < 0 ) { + return 0; + } + $update = false; if ( ! empty( $link_id ) ) { $update = true; @@ -301,6 +309,8 @@ function wp_set_link_cats( $link_id = 0, $link_categories = array() ) { * * @param array $linkdata Link data to update. See wp_insert_link() for accepted arguments. * @return int The updated link ID on success. The value 0 on failure. + * + * @phpstan-return non-negative-int */ function wp_update_link( $linkdata ) { $link_id = (int) $linkdata['link_id']; diff --git a/src/wp-admin/includes/class-custom-image-header.php b/src/wp-admin/includes/class-custom-image-header.php index 147f44cc1057b..9166bca3cd1b4 100644 --- a/src/wp-admin/includes/class-custom-image-header.php +++ b/src/wp-admin/includes/class-custom-image-header.php @@ -318,6 +318,8 @@ public function process_default_headers() { * * @param string $type The header type. One of 'default' (for the Uploaded Images control) * or 'uploaded' (for the Uploaded Images control). + * + * @phpstan-param 'default'|'uploaded' $type */ public function show_header_selector( $type = 'default' ) { if ( 'default' === $type ) { diff --git a/src/wp-admin/includes/class-wp-importer.php b/src/wp-admin/includes/class-wp-importer.php index a1b76e388f04e..5205393458551 100644 --- a/src/wp-admin/includes/class-wp-importer.php +++ b/src/wp-admin/includes/class-wp-importer.php @@ -280,8 +280,8 @@ public function min_whitespace( $text ) { * * @since 3.0.0 * - * @global wpdb $wpdb WordPress database abstraction object. - * @global int[] $wp_actions Stores the number of times each action was triggered. + * @global wpdb $wpdb WordPress database abstraction object. + * @global array $wp_actions Stores the number of times each action was triggered. */ public function stop_the_insanity() { global $wpdb, $wp_actions; diff --git a/src/wp-admin/includes/taxonomy.php b/src/wp-admin/includes/taxonomy.php index dbdab1af4fab8..73677c9d7617d 100644 --- a/src/wp-admin/includes/taxonomy.php +++ b/src/wp-admin/includes/taxonomy.php @@ -119,7 +119,7 @@ function wp_create_categories( $categories, $post_id = 0 ) { * depending on param `$wp_error`. * * @phpstan-return ( - * $wp_error is false ? int : int|WP_Error + * $wp_error is false ? non-negative-int : non-negative-int|WP_Error * ) */ function wp_insert_category( $catarr, $wp_error = false ) { @@ -188,6 +188,8 @@ function wp_insert_category( $catarr, $wp_error = false ) { * * @param array $catarr The 'cat_ID' value is required. All other keys are optional. * @return int|false The ID number of the new or updated Category on success. Zero or FALSE on failure. + * + * @phpstan-return non-negative-int|false */ function wp_update_category( $catarr ) { $cat_id = (int) $catarr['cat_ID']; diff --git a/src/wp-admin/includes/template.php b/src/wp-admin/includes/template.php index c4496dea3d403..b9c2779c08187 100644 --- a/src/wp-admin/includes/template.php +++ b/src/wp-admin/includes/template.php @@ -1290,6 +1290,8 @@ function _get_plugin_from_callback( $callback ) { * Often this is the object that's the focus of the current screen, * for example a `WP_Post` or `WP_Comment` object. * @return int Number of meta_boxes. + * + * @phpstan-return non-negative-int */ function do_meta_boxes( $screen, $context, $data_object ) { global $wp_meta_boxes; diff --git a/src/wp-includes/bookmark.php b/src/wp-includes/bookmark.php index e1c8a6e522a00..f8314af645f49 100644 --- a/src/wp-includes/bookmark.php +++ b/src/wp-includes/bookmark.php @@ -80,16 +80,15 @@ function get_bookmark( $bookmark, $output = OBJECT, $filter = 'raw' ) { * @param string $field The name of the data field to return. * @param int $bookmark The bookmark ID to get field. * @param string $context Optional. The context of how the field will be used. Default 'display'. - * @return string|WP_Error + * @return mixed The sanitized field value, or an empty string if the bookmark or field does not exist. + * + * @phpstan-param 'link_id'|'link_url'|'link_name'|'link_image'|'link_target'|'link_description'|'link_visible'|'link_owner'|'link_rating'|'link_updated'|'link_rel'|'link_notes'|'link_rss'|'link_category' $field + * @phpstan-return ( $field is 'link_category' ? array|'' : ( $field is 'link_id'|'link_rating' ? int|'' : mixed ) ) */ function get_bookmark_field( $field, $bookmark, $context = 'display' ) { $bookmark = (int) $bookmark; $bookmark = get_bookmark( $bookmark ); - if ( is_wp_error( $bookmark ) ) { - return $bookmark; - } - if ( ! is_object( $bookmark ) ) { return ''; } @@ -403,6 +402,9 @@ function sanitize_bookmark( $bookmark, $context = 'display' ) { * @param string $context How to filter the field value. Accepts 'raw', 'edit', 'db', * 'display', 'attribute', or 'js'. Default 'display'. * @return mixed The filtered value. + * + * @phpstan-param 'link_id'|'link_url'|'link_name'|'link_image'|'link_target'|'link_description'|'link_visible'|'link_owner'|'link_rating'|'link_updated'|'link_rel'|'link_notes'|'link_rss'|'link_category' $field + * @phpstan-return ($field is 'link_category' ? array : ($field is 'link_id'|'link_rating' ? int : mixed)) */ function sanitize_bookmark_field( $field, $value, $bookmark_id, $context ) { $int_fields = array( 'link_id', 'link_rating' ); diff --git a/src/wp-includes/class-wp-locale.php b/src/wp-includes/class-wp-locale.php index cd022fdaf9c83..7de22f0d24ee7 100644 --- a/src/wp-includes/class-wp-locale.php +++ b/src/wp-includes/class-wp-locale.php @@ -119,6 +119,8 @@ class WP_Locale { * * @since 6.2.0 * @var string|null + * + * @phpstan-var 'characters_excluding_spaces'|'characters_including_spaces'|'words'|null */ public $word_count_type; diff --git a/src/wp-includes/class-wpdb.php b/src/wp-includes/class-wpdb.php index 5f5c05bd1553e..39958db99fe19 100644 --- a/src/wp-includes/class-wpdb.php +++ b/src/wp-includes/class-wpdb.php @@ -125,6 +125,7 @@ class wpdb { * @since 0.71 * * @var int + * @phpstan-var non-negative-int */ public $insert_id = 0; @@ -3121,6 +3122,8 @@ public function get_var( $query = null, $x = 0, $y = 0 ) { * ) * : null * ) + * + * @phpstan-param non-negative-int $y */ public function get_row( $query = null, $output = OBJECT, $y = 0 ) { $this->func_call = "\$db->get_row(\"$query\",$output,$y)"; diff --git a/src/wp-includes/comment.php b/src/wp-includes/comment.php index 6a1641cbae4d0..8a48108effa43 100644 --- a/src/wp-includes/comment.php +++ b/src/wp-includes/comment.php @@ -1993,6 +1993,8 @@ function wp_unspam_comment( $comment_id ) { * * @param int|WP_Comment $comment_id Comment ID or WP_Comment object * @return string|false Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure. + * + * @phpstan-return 'approved'|'spam'|'trash'|'unapproved'|false */ function wp_get_comment_status( $comment_id ) { $comment = get_comment( $comment_id ); diff --git a/src/wp-includes/formatting.php b/src/wp-includes/formatting.php index ad12579fdafa1..14836be11db76 100644 --- a/src/wp-includes/formatting.php +++ b/src/wp-includes/formatting.php @@ -2835,6 +2835,7 @@ function format_to_edit( $content, $rich_text = false ) { * @param int $threshold Digit places number needs to be to not have zeros added. * @return string Adds leading zeros to number if needed. * + * @phpstan-param non-negative-int $threshold * @phpstan-return ( * $threshold is 0 * ? lowercase-string&non-empty-string&numeric-string @@ -3006,6 +3007,8 @@ function urldecode_deep( $value ) { * @param string $email_address Email address. * @param int $hex_encoding Optional. Set to 1 to enable hex encoding. * @return string Converted email address. + * + * @phpstan-param 0|1 $hex_encoding */ function antispambot( $email_address, $hex_encoding = 0 ) { $obfuscated = ''; diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index 59d91815d122e..693ba8c38859e 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -1041,6 +1041,8 @@ function wp_get_http_headers( $url, $deprecated = false ) { * @global string $previousday The day of the previous post in the loop. * * @return int 1 when new day, 0 if not a new day. + * + * @phpstan-return 0|1 */ function is_new_day() { global $currentday, $previousday; @@ -4525,6 +4527,7 @@ function _wp_die_process_input( $message, $title = '', $args = array() ) { * greater than 0. Default 512. * @return string|false The JSON encoded string, or false if it cannot be encoded. * + * @phpstan-param positive-int $depth * @phpstan-return non-empty-string|false */ function wp_json_encode( $value, $flags = 0, $depth = 512 ) { @@ -6303,6 +6306,8 @@ function _doing_it_wrong( $function_name, $message, $version ) { * before passing to this function to avoid being stripped {@see wp_kses()}. * @param int $error_level Optional. The designated error type for this error. * Only works with E_USER family of constants. Default E_USER_NOTICE. + * + * @phpstan-param E_USER_ERROR|E_USER_WARNING|E_USER_NOTICE|E_USER_DEPRECATED $error_level */ function wp_trigger_error( $function_name, $message, $error_level = E_USER_NOTICE ) { /** @@ -6739,6 +6744,8 @@ function is_main_network( $network_id = null ) { * @since 4.3.0 * * @return int The ID of the main network. + * + * @phpstan-return non-negative-int */ function get_main_network_id() { if ( ! is_multisite() ) { @@ -6768,6 +6775,8 @@ function get_main_network_id() { * @since 4.3.0 * * @param int $main_network_id The ID of the main network. + * + * @phpstan-param non-negative-int $main_network_id */ return (int) apply_filters( 'get_main_network_id', $main_network_id ); } @@ -7250,6 +7259,8 @@ function __return_false() { // phpcs:ignore WordPress.NamingConventions.ValidFun * @since 3.0.0 * * @return int 0. + * + * @phpstan-return 0 */ function __return_zero() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore return 0; @@ -7263,6 +7274,8 @@ function __return_zero() { // phpcs:ignore WordPress.NamingConventions.ValidFunc * @since 3.0.0 * * @return array Empty array. + * + * @phpstan-return array{} */ function __return_empty_array() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore return array(); @@ -7291,6 +7304,8 @@ function __return_null() { // phpcs:ignore WordPress.NamingConventions.ValidFunc * @see __return_null() * * @return string Empty string. + * + * @phpstan-return '' */ function __return_empty_string() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore return ''; diff --git a/src/wp-includes/load.php b/src/wp-includes/load.php index 909a4ed98f66f..b9086e733c966 100644 --- a/src/wp-includes/load.php +++ b/src/wp-includes/load.php @@ -11,6 +11,8 @@ * @since 4.4.0 * * @return string The HTTP protocol. Default: HTTP/1.0. + * + * @phpstan-return 'HTTP/1.0'|'HTTP/1.1'|'HTTP/2'|'HTTP/2.0'|'HTTP/3' */ function wp_get_server_protocol() { $protocol = $_SERVER['SERVER_PROTOCOL'] ?? ''; @@ -1517,6 +1519,8 @@ function absint( $maybeint ): int { * @global int $blog_id * * @return int Site ID. + * + * @phpstan-return non-negative-int */ function get_current_blog_id() { global $blog_id; @@ -1530,6 +1534,8 @@ function get_current_blog_id() { * @since 4.6.0 * * @return int The ID of the current network. + * + * @phpstan-return non-negative-int */ function get_current_network_id() { if ( ! is_multisite() ) { diff --git a/src/wp-includes/pluggable.php b/src/wp-includes/pluggable.php index 8e8f885f87d06..30fa4b9814b58 100644 --- a/src/wp-includes/pluggable.php +++ b/src/wp-includes/pluggable.php @@ -1375,7 +1375,7 @@ function auth_redirect() { * 2 if the nonce is valid and generated between 12-24 hours ago. * False if the nonce is invalid. Only possible when `$action` is -1, * as the function otherwise exits rather than returning false. - * @phpstan-return ( $action is -1 ? int|false : int ) + * @phpstan-return ( $action is -1 ? 1|2|false : 1|2 ) */ function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) { if ( -1 === $action ) { @@ -1422,7 +1422,7 @@ function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) { * 2 if the nonce is valid and generated between 12-24 hours ago. * False if the nonce is invalid. Only possible when `$stop` is false, * as the function otherwise exits rather than returning false. - * @phpstan-return ( $stop is true ? int : int|false ) + * @phpstan-return ( $stop is true ? 1|2 : 1|2|false ) */ function check_ajax_referer( $action = -1, $query_arg = false, $stop = true ) { if ( -1 === $action ) { @@ -2506,6 +2506,8 @@ function wp_nonce_tick( $action = -1 ) { * @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. + * + * @phpstan-return 1|2|false */ function wp_verify_nonce( $nonce, $action = -1 ) { $nonce = (string) $nonce; diff --git a/src/wp-includes/plugin.php b/src/wp-includes/plugin.php index b35f7a994457d..9bef5f03e88e7 100644 --- a/src/wp-includes/plugin.php +++ b/src/wp-includes/plugin.php @@ -28,10 +28,10 @@ /** @var WP_Hook[] $wp_filter */ global $wp_filter; -/** @var int[] $wp_actions */ +/** @var array $wp_actions */ global $wp_actions; -/** @var int[] $wp_filters */ +/** @var array $wp_filters */ global $wp_filters; /** @var string[] $wp_current_filter */ @@ -156,9 +156,9 @@ function add_filter( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) * @since 6.0.0 Formalized the existing and already documented `...$args` parameter * by adding it to the function signature. * - * @global WP_Hook[] $wp_filter Stores all of the filters and actions. - * @global int[] $wp_filters Stores the number of times each filter was triggered. - * @global string[] $wp_current_filter Stores the list of current filters with the current one last. + * @global WP_Hook[] $wp_filter Stores all of the filters and actions. + * @global array $wp_filters Stores the number of times each filter was triggered. + * @global string[] $wp_current_filter Stores the list of current filters with the current one last. * * @param string $hook_name The name of the filter hook. * @param mixed $value The value to filter. @@ -213,9 +213,9 @@ function apply_filters( $hook_name, $value, ...$args ) { * @see apply_filters() This function is identical, but the arguments passed to the * functions hooked to `$hook_name` are supplied using an array. * - * @global WP_Hook[] $wp_filter Stores all of the filters and actions. - * @global int[] $wp_filters Stores the number of times each filter was triggered. - * @global string[] $wp_current_filter Stores the list of current filters with the current one last. + * @global WP_Hook[] $wp_filter Stores all of the filters and actions. + * @global array $wp_filters Stores the number of times each filter was triggered. + * @global string[] $wp_current_filter Stores the list of current filters with the current one last. * * @param string $hook_name The name of the filter hook. * @param non-empty-list $args The arguments supplied to the functions hooked to `$hook_name`. @@ -413,10 +413,12 @@ function doing_filter( $hook_name = null ) { * * @since 6.1.0 * - * @global int[] $wp_filters Stores the number of times each filter was triggered. + * @global array $wp_filters Stores the number of times each filter was triggered. * * @param string $hook_name The name of the filter hook. * @return int The number of times the filter hook has been applied. + * + * @phpstan-return non-negative-int */ function did_filter( $hook_name ) { global $wp_filters; @@ -481,9 +483,9 @@ function add_action( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) * @since 5.3.0 Formalized the existing and already documented `...$arg` parameter * by adding it to the function signature. * - * @global WP_Hook[] $wp_filter Stores all of the filters and actions. - * @global int[] $wp_actions Stores the number of times each action was triggered. - * @global string[] $wp_current_filter Stores the list of current filters with the current one last. + * @global WP_Hook[] $wp_filter Stores all of the filters and actions. + * @global array $wp_actions Stores the number of times each action was triggered. + * @global string[] $wp_current_filter Stores the list of current filters with the current one last. * * @param string $hook_name The name of the action to be executed. * @param mixed ...$arg Optional. Additional arguments which are passed on to the @@ -538,9 +540,9 @@ function do_action( $hook_name, ...$arg ) { * @see do_action() This function is identical, but the arguments passed to the * functions hooked to `$hook_name` are supplied using an array. * - * @global WP_Hook[] $wp_filter Stores all of the filters and actions. - * @global int[] $wp_actions Stores the number of times each action was triggered. - * @global string[] $wp_current_filter Stores the list of current filters with the current one last. + * @global WP_Hook[] $wp_filter Stores all of the filters and actions. + * @global array $wp_actions Stores the number of times each action was triggered. + * @global string[] $wp_current_filter Stores the list of current filters with the current one last. * * @param string $hook_name The name of the action to be executed. * @param list $args The arguments supplied to the functions hooked to `$hook_name`. @@ -692,10 +694,12 @@ function doing_action( $hook_name = null ) { * * @since 2.1.0 * - * @global int[] $wp_actions Stores the number of times each action was triggered. + * @global array $wp_actions Stores the number of times each action was triggered. * * @param string $hook_name The name of the action hook. * @return int The number of times the action hook has been fired. + * + * @phpstan-return non-negative-int */ function did_action( $hook_name ) { global $wp_actions; diff --git a/src/wp-includes/post-template.php b/src/wp-includes/post-template.php index 4aa7f83ce8716..b609ee725f954 100644 --- a/src/wp-includes/post-template.php +++ b/src/wp-includes/post-template.php @@ -2052,6 +2052,8 @@ function wp_post_revision_title_expanded( $revision, $link = true ) { * * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post. * @param string $type 'all' (default), 'revision' or 'autosave' + * + * @phpstan-param 'all'|'revision'|'autosave' $type */ function wp_list_post_revisions( $post = 0, $type = 'all' ) { $post = get_post( $post ); diff --git a/src/wp-includes/rest-api.php b/src/wp-includes/rest-api.php index d61bb4fe31ee5..4438594baeda3 100644 --- a/src/wp-includes/rest-api.php +++ b/src/wp-includes/rest-api.php @@ -1554,6 +1554,8 @@ function rest_get_date_with_gmt( $date, $is_utc = false ) { * @since 4.7.0 * * @return int 401 if the user is not logged in, 403 if the user is logged in. + * + * @phpstan-return 401|403 */ function rest_authorization_required_code() { return is_user_logged_in() ? 403 : 401; diff --git a/src/wp-includes/script-loader.php b/src/wp-includes/script-loader.php index ef81a42106e88..b37f2d5717e0e 100644 --- a/src/wp-includes/script-loader.php +++ b/src/wp-includes/script-loader.php @@ -678,8 +678,11 @@ function wp_default_packages( $scripts ) { * * @param string $type The type of suffix to retrieve. * @return string The script suffix. + * + * @phpstan-return ''|'.min' */ function wp_scripts_get_suffix( $type = '' ) { + /** @var array{ suffix: ''|'.min', dev_suffix: ''|'.min' }|null $suffixes */ static $suffixes; if ( null === $suffixes ) { diff --git a/src/wp-includes/taxonomy.php b/src/wp-includes/taxonomy.php index 8a64e726d2fcd..d888833ecf9f2 100644 --- a/src/wp-includes/taxonomy.php +++ b/src/wp-includes/taxonomy.php @@ -2580,7 +2580,7 @@ function wp_get_object_terms( $object_ids, $taxonomies, $args = array() ) { * ... * } $args * @phpstan-return array{ - * term_id: int, + * term_id: non-negative-int, * term_taxonomy_id: int|decimal-int-string, * }|WP_Error */ @@ -2807,6 +2807,8 @@ function wp_insert_term( $term, $taxonomy, $args = array() ) { * @param string $taxonomy Taxonomy name. * @param array $args Arguments passed to wp_insert_term(). * @param int $tt_id term_taxonomy_id for the newly created term. + * + * @phpstan-param object{ term_id: non-negative-int, term_taxonomy_id: int|numeric-string }|null $duplicate_term */ $duplicate_term = apply_filters( 'wp_insert_term_duplicate_term_check', $duplicate_term, $term, $taxonomy, $args, $tt_id ); @@ -2869,6 +2871,8 @@ function wp_insert_term( $term, $taxonomy, $args = array() ) { * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. * @param array $args Arguments passed to wp_insert_term(). + * + * @phpstan-param non-negative-int $term_id */ $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id, $args ); @@ -3392,7 +3396,7 @@ function wp_unique_term_slug( $slug, $term ) { * ... * } $args * @phpstan-return array{ - * term_id: int, + * term_id: non-negative-int, * term_taxonomy_id: int, * }|WP_Error */ diff --git a/tests/phpstan/baselines/argument.type.neon b/tests/phpstan/baselines/argument.type.neon index bd6828d096b11..7d4b6aa03dccb 100644 --- a/tests/phpstan/baselines/argument.type.neon +++ b/tests/phpstan/baselines/argument.type.neon @@ -1196,7 +1196,12 @@ parameters: - message: '#^Parameter \#2 \$fallback_title of function sanitize_title expects string, int given\.$#' identifier: argument.type - count: 2 + count: 1 + path: ../../../src/wp-includes/taxonomy.php + - + message: '#^Parameter \#2 \$fallback_title of function sanitize_title expects string, int\<0, max\> given\.$#' + identifier: argument.type + count: 1 path: ../../../src/wp-includes/taxonomy.php - message: '#^Parameter \#2 \$taxonomy of function wp_update_term_count expects string, null given\.$#' diff --git a/tests/phpunit/includes/abstract-testcase.php b/tests/phpunit/includes/abstract-testcase.php index edae9d14c2035..7dd0fddde9bb6 100644 --- a/tests/phpunit/includes/abstract-testcase.php +++ b/tests/phpunit/includes/abstract-testcase.php @@ -575,10 +575,10 @@ protected function reset__SERVER() { * Stores $wp_filter, $wp_actions, $wp_filters, and $wp_current_filter * on a class variable so they can be restored on tear_down() using _restore_hooks(). * - * @global array $wp_filter All of the filters and actions. - * @global array $wp_actions The number of times each action was triggered. - * @global array $wp_filters The number of times each filter was triggered. - * @global array $wp_current_filter The list of current filters with the current one last. + * @global array $wp_filter All of the filters and actions. + * @global array $wp_actions The number of times each action was triggered. + * @global array $wp_filters The number of times each filter was triggered. + * @global array $wp_current_filter The list of current filters with the current one last. */ protected function _backup_hooks() { self::$hooks_saved['wp_filter'] = array(); @@ -598,10 +598,10 @@ protected function _backup_hooks() { * Restores the hook-related globals to their state at set_up() * so that future tests aren't affected by hooks set during this last test. * - * @global array $wp_filter All of the filters and actions. - * @global array $wp_actions The number of times each action was triggered. - * @global array $wp_filters The number of times each filter was triggered. - * @global array $wp_current_filter The list of current filters with the current one last. + * @global array $wp_filter All of the filters and actions. + * @global array $wp_actions The number of times each action was triggered. + * @global array $wp_filters The number of times each filter was triggered. + * @global array $wp_current_filter The list of current filters with the current one last. */ protected function _restore_hooks() { if ( isset( self::$hooks_saved['wp_filter'] ) ) { diff --git a/tests/phpunit/includes/utils.php b/tests/phpunit/includes/utils.php index a99e640ced4b9..272a1e55050e3 100644 --- a/tests/phpunit/includes/utils.php +++ b/tests/phpunit/includes/utils.php @@ -101,7 +101,7 @@ public function reset(): void { /** * @since UT (3.7.0) * - * @global array $wp_actions + * @global array $wp_actions * @return string|false */ public function current_filter() { diff --git a/tests/phpunit/tests/user.php b/tests/phpunit/tests/user.php index c87e852012f1f..7d819969d7d13 100644 --- a/tests/phpunit/tests/user.php +++ b/tests/phpunit/tests/user.php @@ -386,6 +386,26 @@ public function test_construction() { $this->assertSame( $user->user_login, $user7->user_login ); } + /** + * Tests that {@see WP_User::init()} keeps the ID property and the ID in the data in agreement. + * + * @covers WP_User::init + */ + public function test_init_keeps_id_in_agreement_with_data(): void { + // Some plugins create virtual users with negative IDs, so these are preserved. + $negative = new WP_User( (object) array( 'ID' => -1 ) ); + $this->assertSame( -1, $negative->ID, 'Expected a negative ID to be preserved.' ); + $this->assertSame( -1, $negative->data->ID, 'Expected the data to agree with the ID property.' ); + + $missing = new WP_User( (object) array( 'user_login' => 'nobody' ) ); + $this->assertSame( 0, $missing->ID, 'Expected a missing ID to be 0.' ); + $this->assertSame( 0, $missing->data->ID, 'Expected the data to be given an ID of 0.' ); + + $user_id = self::factory()->user->create(); + $author = new WP_User( $user_id ); + $this->assertSame( (string) $user_id, $author->data->ID, 'Expected the numeric-string ID of a database row to be preserved.' ); + } + public function test_get() { $user = new WP_User( self::$author_id ); $this->assertSame( 'author_login', $user->get( 'user_login' ) ); From 31b09c206b1b16dd41e3cebce513d8d8f97dd183 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 25 Nov 2026 11:11:52 +0000 Subject: [PATCH 84/85] Code Quality: Add PHPStan array shapes. Document the known keys of arrays that functions accept or return as array shapes, such as the HTTP API response, which is defined once on `WP_Http` and reused by the remote request functions, and the widget, robots, and admin helper arrays. This lets static analysis check how the values are used. Developed in: https://github.com/WordPress/wordpress-develop/pull/13894 Props swissspidy, westonruter, marian1, johnbillion. See #66739. git-svn-id: https://develop.svn.wordpress.org/trunk@65777 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/includes/media.php | 4 ++ src/wp-admin/includes/ms.php | 2 + src/wp-admin/includes/nav-menu.php | 10 +++ src/wp-admin/includes/post.php | 2 + src/wp-includes/class-wp-dependencies.php | 4 +- src/wp-includes/class-wp-http.php | 17 +++++ src/wp-includes/class-wp-widget.php | 16 +++++ src/wp-includes/feed.php | 2 + src/wp-includes/formatting.php | 2 + src/wp-includes/functions.php | 1 + src/wp-includes/http.php | 72 +++++++++++++++++++ src/wp-includes/nav-menu.php | 2 +- src/wp-includes/robots-template.php | 28 ++++---- src/wp-includes/shortcodes.php | 2 + src/wp-includes/widgets.php | 30 ++++++++ .../baselines-strict/argument.type.neon | 5 -- 16 files changed, 180 insertions(+), 19 deletions(-) diff --git a/src/wp-admin/includes/media.php b/src/wp-admin/includes/media.php index 9f5b87ce85f93..543d2c7f89766 100644 --- a/src/wp-admin/includes/media.php +++ b/src/wp-admin/includes/media.php @@ -1237,6 +1237,8 @@ function image_align_input_fields( $post, $checked = '' ) { * @param WP_Post $post * @param bool|string $check * @return array An array of data for the image size input fields. + * + * @phpstan-return array{label: string, input: 'html', html: string} */ function image_size_input_fields( $post, $check = '' ) { /** @@ -1937,6 +1939,8 @@ function get_media_item( $attachment_id, $args = null ) { * @param int $attachment_id * @param array $args * @return array An array containing the media item and its metadata. + * + * @phpstan-return array{item: string, meta: string} */ function get_compat_media_markup( $attachment_id, $args = null ) { $post = get_post( $attachment_id ); diff --git a/src/wp-admin/includes/ms.php b/src/wp-admin/includes/ms.php index 8e3c141af2850..ff9fb830c4d2a 100644 --- a/src/wp-admin/includes/ms.php +++ b/src/wp-admin/includes/ms.php @@ -1187,6 +1187,8 @@ function network_edit_site_nav( $args = array() ) { * @since 4.9.0 * * @return array Help tab arguments. + * + * @phpstan-return array{id: non-falsy-string, title: string, content: non-falsy-string} */ function get_site_screen_help_tab_args() { return array( diff --git a/src/wp-admin/includes/nav-menu.php b/src/wp-admin/includes/nav-menu.php index dc90feb3b3309..68726f4062cde 100644 --- a/src/wp-admin/includes/nav-menu.php +++ b/src/wp-admin/includes/nav-menu.php @@ -1348,6 +1348,16 @@ function wp_get_nav_menu_to_edit( $menu_id = 0 ) { * @since 3.0.0 * * @return string[] Array of column titles keyed by their column name. + * + * @phpstan-return array{ + * _title: string, + * cb: non-falsy-string, + * link-target: string, + * title-attribute: string, + * css-classes: string, + * xfn: string, + * description: string, + * } */ function wp_nav_menu_manage_columns() { return array( diff --git a/src/wp-admin/includes/post.php b/src/wp-admin/includes/post.php index f08f81766df67..7d900970fd0cc 100644 --- a/src/wp-admin/includes/post.php +++ b/src/wp-admin/includes/post.php @@ -1220,6 +1220,8 @@ function _fix_attachment_links( $post ) { * * @param string $type The post_type you want the statuses for. Default 'post'. * @return string[] An array of all the statuses for the supplied post type. + * + * @phpstan-return list */ function get_available_post_statuses( $type = 'post' ) { $statuses = wp_count_posts( $type ); diff --git a/src/wp-includes/class-wp-dependencies.php b/src/wp-includes/class-wp-dependencies.php index f9aa688cca3af..204ade1d6f0f0 100644 --- a/src/wp-includes/class-wp-dependencies.php +++ b/src/wp-includes/class-wp-dependencies.php @@ -73,7 +73,9 @@ class WP_Dependencies { * * @since 2.8.0 * - * @var (int|false)[] + * @var array + * + * @phpstan-var array */ public $groups = array(); diff --git a/src/wp-includes/class-wp-http.php b/src/wp-includes/class-wp-http.php index 66cf907d0e00a..de53011d11983 100644 --- a/src/wp-includes/class-wp-http.php +++ b/src/wp-includes/class-wp-http.php @@ -29,6 +29,15 @@ * Debugging includes several actions, which pass different variables for debugging the HTTP API. * * @since 2.7.0 + * + * @phpstan-type HTTP_Response array{ + * headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array, + * body: string, + * response: array{code: int|false, message: string|false}, + * cookies: WP_Http_Cookie[], + * filename?: string|null, + * http_response?: WP_HTTP_Requests_Response|null, + * } */ #[AllowDynamicProperties] class WP_Http { @@ -166,6 +175,8 @@ class WP_Http { * @type string|null $filename Optional. Filename of the response. * @type WP_HTTP_Requests_Response|null $http_response Response object. * } + * + * @phpstan-return HTTP_Response|WP_Error */ public function request( $url, $args = array() ) { $defaults = array( @@ -647,6 +658,8 @@ private function _dispatch_request( $url, $args ) { * @param string|array $args Optional. Override the defaults. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. See WP_Http::response() for details. + * + * @phpstan-return HTTP_Response|WP_Error */ public function post( $url, $args = array() ) { $defaults = array( 'method' => 'POST' ); @@ -665,6 +678,8 @@ public function post( $url, $args = array() ) { * @param string|array $args Optional. Override the defaults. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. See WP_Http::response() for details. + * + * @phpstan-return HTTP_Response|WP_Error */ public function get( $url, $args = array() ) { $defaults = array( 'method' => 'GET' ); @@ -683,6 +698,8 @@ public function get( $url, $args = array() ) { * @param string|array $args Optional. Override the defaults. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. See WP_Http::response() for details. + * + * @phpstan-return HTTP_Response|WP_Error */ public function head( $url, $args = array() ) { $defaults = array( 'method' => 'HEAD' ); diff --git a/src/wp-includes/class-wp-widget.php b/src/wp-includes/class-wp-widget.php index f1d432c0d3fb5..9cc2d79a7ac20 100644 --- a/src/wp-includes/class-wp-widget.php +++ b/src/wp-includes/class-wp-widget.php @@ -109,6 +109,22 @@ class WP_Widget { * @param array $args Display arguments including 'before_title', 'after_title', * 'before_widget', and 'after_widget'. * @param array $instance The settings for the particular instance of the widget. + * + * @phpstan-param array{ + * name?: string, + * id?: string, + * description?: string, + * class?: string, + * before_widget: string, + * after_widget: string, + * before_title: string, + * after_title: string, + * before_sidebar?: string, + * after_sidebar?: string, + * show_in_rest?: bool, + * widget_id?: string, + * widget_name?: string, + * } $args */ public function widget( $args, $instance ) { die( 'function WP_Widget::widget() must be overridden in a subclass.' ); diff --git a/src/wp-includes/feed.php b/src/wp-includes/feed.php index 952194c1bce84..016d6a86b32f3 100644 --- a/src/wp-includes/feed.php +++ b/src/wp-includes/feed.php @@ -599,6 +599,8 @@ function atom_enclosure() { * * @param string $data Input string. * @return array array(type, value) + * + * @phpstan-return array{'html'|'text'|'xhtml', string} */ function prep_atom_text_construct( $data ) { if ( ! str_contains( $data, '<' ) && ! str_contains( $data, '&' ) ) { diff --git a/src/wp-includes/formatting.php b/src/wp-includes/formatting.php index 14836be11db76..6bfba5a873cb7 100644 --- a/src/wp-includes/formatting.php +++ b/src/wp-includes/formatting.php @@ -611,6 +611,8 @@ function wpautop( $text, $br = true ) { * * @param string $input The text which has to be formatted. * @return string[] Array of the formatted text. + * + * @phpstan-return non-empty-list */ function wp_html_split( $input ) { return preg_split( get_html_split_regex(), $input, -1, PREG_SPLIT_DELIM_CAPTURE ); diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index 693ba8c38859e..9f05a8c592a86 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -8394,6 +8394,7 @@ function wp_unique_prefixed_id( $prefix = '' ) { * @param string $prefix Optional. A prefix to prepend to the generated ID. Default empty string. * @return string The generated unique ID for the array. * + * @phpstan-param non-empty-array $data * @phpstan-return ( $prefix is lowercase-string ? lowercase-string&non-falsy-string : non-falsy-string ) */ function wp_unique_id_from_values( array $data, string $prefix = '' ): string { diff --git a/src/wp-includes/http.php b/src/wp-includes/http.php index 34e1f452a797f..ac589db1e91d3 100644 --- a/src/wp-includes/http.php +++ b/src/wp-includes/http.php @@ -48,6 +48,15 @@ function _wp_http_get_object() { * See WP_Http::request() for information on accepted arguments. * @return array|WP_Error The response or WP_Error on failure. * See WP_Http::request() for information on return value. + * + * @phpstan-return array{ + * headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array, + * body: string, + * response: array{code: int|false, message: string|false}, + * cookies: WP_Http_Cookie[], + * filename?: string|null, + * http_response?: WP_HTTP_Requests_Response|null, + * }|WP_Error */ function wp_safe_remote_request( $url, $args = array() ) { $args['reject_unsafe_urls'] = true; @@ -77,6 +86,15 @@ function wp_safe_remote_request( $url, $args = array() ) { * See WP_Http::request() for information on accepted arguments. * @return array|WP_Error The response or WP_Error on failure. * See WP_Http::request() for information on return value. + * + * @phpstan-return array{ + * headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array, + * body: string, + * response: array{code: int|false, message: string|false}, + * cookies: WP_Http_Cookie[], + * filename?: string|null, + * http_response?: WP_HTTP_Requests_Response|null, + * }|WP_Error */ function wp_safe_remote_get( $url, $args = array() ) { $args['reject_unsafe_urls'] = true; @@ -106,6 +124,15 @@ function wp_safe_remote_get( $url, $args = array() ) { * See WP_Http::request() for information on accepted arguments. * @return array|WP_Error The response or WP_Error on failure. * See WP_Http::request() for information on return value. + * + * @phpstan-return array{ + * headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array, + * body: string, + * response: array{code: int|false, message: string|false}, + * cookies: WP_Http_Cookie[], + * filename?: string|null, + * http_response?: WP_HTTP_Requests_Response|null, + * }|WP_Error */ function wp_safe_remote_post( $url, $args = array() ) { $args['reject_unsafe_urls'] = true; @@ -135,6 +162,15 @@ function wp_safe_remote_post( $url, $args = array() ) { * See WP_Http::request() for information on accepted arguments. * @return array|WP_Error The response or WP_Error on failure. * See WP_Http::request() for information on return value. + * + * @phpstan-return array{ + * headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array, + * body: string, + * response: array{code: int|false, message: string|false}, + * cookies: WP_Http_Cookie[], + * filename?: string|null, + * http_response?: WP_HTTP_Requests_Response|null, + * }|WP_Error */ function wp_safe_remote_head( $url, $args = array() ) { $args['reject_unsafe_urls'] = true; @@ -162,6 +198,15 @@ function wp_safe_remote_head( $url, $args = array() ) { * See WP_Http::request() for information on accepted arguments. * @return array|WP_Error The response array or a WP_Error on failure. * See WP_Http::request() for information on return value. + * + * @phpstan-return array{ + * headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array, + * body: string, + * response: array{code: int|false, message: string|false}, + * cookies: WP_Http_Cookie[], + * filename?: string|null, + * http_response?: WP_HTTP_Requests_Response|null, + * }|WP_Error */ function wp_remote_request( $url, $args = array() ) { $http = _wp_http_get_object(); @@ -183,6 +228,15 @@ function wp_remote_request( $url, $args = array() ) { * See WP_Http::request() for information on accepted arguments. * @return array|WP_Error The response or WP_Error on failure. * See WP_Http::request() for information on return value. + * + * @phpstan-return array{ + * headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array, + * body: string, + * response: array{code: int|false, message: string|false}, + * cookies: WP_Http_Cookie[], + * filename?: string|null, + * http_response?: WP_HTTP_Requests_Response|null, + * }|WP_Error */ function wp_remote_get( $url, $args = array() ) { $http = _wp_http_get_object(); @@ -204,6 +258,15 @@ function wp_remote_get( $url, $args = array() ) { * See WP_Http::request() for information on accepted arguments. * @return array|WP_Error The response or WP_Error on failure. * See WP_Http::request() for information on return value. + * + * @phpstan-return array{ + * headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array, + * body: string, + * response: array{code: int|false, message: string|false}, + * cookies: WP_Http_Cookie[], + * filename?: string|null, + * http_response?: WP_HTTP_Requests_Response|null, + * }|WP_Error */ function wp_remote_post( $url, $args = array() ) { $http = _wp_http_get_object(); @@ -225,6 +288,15 @@ function wp_remote_post( $url, $args = array() ) { * See WP_Http::request() for information on accepted arguments. * @return array|WP_Error The response or WP_Error on failure. * See WP_Http::request() for information on return value. + * + * @phpstan-return array{ + * headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array, + * body: string, + * response: array{code: int|false, message: string|false}, + * cookies: WP_Http_Cookie[], + * filename?: string|null, + * http_response?: WP_HTTP_Requests_Response|null, + * }|WP_Error */ function wp_remote_head( $url, $args = array() ) { $http = _wp_http_get_object(); diff --git a/src/wp-includes/nav-menu.php b/src/wp-includes/nav-menu.php index 191c8d06489c6..2420a2583c82d 100644 --- a/src/wp-includes/nav-menu.php +++ b/src/wp-includes/nav-menu.php @@ -85,7 +85,7 @@ function is_nav_menu( $menu ) { * * @global array $_wp_registered_nav_menus * - * @param string[] $locations Associative array of menu location identifiers (like a slug) and descriptive text. + * @param array $locations Associative array of menu location identifiers (like a slug) and descriptive text. */ function register_nav_menus( $locations = array() ) { global $_wp_registered_nav_menus; diff --git a/src/wp-includes/robots-template.php b/src/wp-includes/robots-template.php index e719e745d61e7..49216bfa7400e 100644 --- a/src/wp-includes/robots-template.php +++ b/src/wp-includes/robots-template.php @@ -64,8 +64,8 @@ function wp_robots() { * * @see wp_robots_no_robots() * - * @param array $robots Associative array of robots directives. - * @return array Filtered robots directives. + * @param array $robots Associative array of robots directives. + * @return array Filtered robots directives. */ function wp_robots_noindex( array $robots ) { if ( ! get_option( 'blog_public' ) ) { @@ -86,8 +86,8 @@ function wp_robots_noindex( array $robots ) { * * @see wp_robots_no_robots() * - * @param array $robots Associative array of robots directives. - * @return array Filtered robots directives. + * @param array $robots Associative array of robots directives. + * @return array Filtered robots directives. */ function wp_robots_noindex_embeds( array $robots ) { if ( is_embed() ) { @@ -112,8 +112,8 @@ function wp_robots_noindex_embeds( array $robots ) { * * @see wp_robots_no_robots() * - * @param array $robots Associative array of robots directives. - * @return array Filtered robots directives. + * @param array $robots Associative array of robots directives. + * @return array Filtered robots directives. */ function wp_robots_noindex_search( array $robots ) { if ( is_search() ) { @@ -134,8 +134,10 @@ function wp_robots_noindex_search( array $robots ) { * * @since 5.7.0 * - * @param array $robots Associative array of robots directives. - * @return array Filtered robots directives. + * @param array $robots Associative array of robots directives. + * @return array Filtered robots directives. + * + * @phpstan-return array{ noindex: true, ... } */ function wp_robots_no_robots( array $robots ) { $robots['noindex'] = true; @@ -161,8 +163,10 @@ function wp_robots_no_robots( array $robots ) { * * @since 5.7.0 * - * @param array $robots Associative array of robots directives. - * @return array Filtered robots directives. + * @param array $robots Associative array of robots directives. + * @return array Filtered robots directives. + * + * @phpstan-return array{ noindex: true, noarchive: true, ... } */ function wp_robots_sensitive_page( array $robots ) { $robots['noindex'] = true; @@ -182,8 +186,8 @@ function wp_robots_sensitive_page( array $robots ) { * * @since 5.7.0 * - * @param array $robots Associative array of robots directives. - * @return array Filtered robots directives. + * @param array $robots Associative array of robots directives. + * @return array Filtered robots directives. */ function wp_robots_max_image_preview_large( array $robots ) { if ( get_option( 'blog_public' ) ) { diff --git a/src/wp-includes/shortcodes.php b/src/wp-includes/shortcodes.php index bc946676bd81c..32429b871d668 100644 --- a/src/wp-includes/shortcodes.php +++ b/src/wp-includes/shortcodes.php @@ -188,6 +188,8 @@ function has_shortcode( $content, $tag ) { * * @param string $content The content to check. * @return string[] An array of registered shortcode names found in the content. + * + * @phpstan-return list */ function get_shortcode_tags_in_content( $content ) { if ( ! str_contains( $content, '[' ) ) { diff --git a/src/wp-includes/widgets.php b/src/wp-includes/widgets.php index 31fce41b65954..b6d9c018851f3 100644 --- a/src/wp-includes/widgets.php +++ b/src/wp-includes/widgets.php @@ -1717,6 +1717,25 @@ function wp_widget_rss_output( $rss, $args = array() ) { * * @param array|string $args Values for input fields. * @param array $inputs Override default display options. + * + * @phpstan-param array{ + * number: int|string, + * error?: string|false, + * title?: string, + * url?: string, + * items?: int, + * show_summary?: int, + * show_author?: int, + * show_date?: int, + * } $args + * @phpstan-param array{ + * title?: bool|'hidden', + * url?: bool|'hidden', + * items?: bool|'hidden', + * show_summary?: bool|'hidden', + * show_author?: bool|'hidden', + * show_date?: bool|'hidden', + * } $inputs */ function wp_widget_rss_form( $args, $inputs = null ) { $default_inputs = array( @@ -1802,6 +1821,17 @@ function wp_widget_rss_form( $args, $inputs = null ) { * @param array $widget_rss RSS widget feed data. Expects unescaped data. * @param bool $check_feed Optional. Whether to check feed for errors. Default true. * @return array + * + * @phpstan-return array{ + * title: string, + * url: string, + * link: string, + * items: int<1, 20>, + * error: string|false, + * show_summary: int, + * show_author: int, + * show_date: int, + * } */ function wp_widget_rss_process( $widget_rss, $check_feed = true ) { $items = (int) $widget_rss['items']; diff --git a/tests/phpstan/baselines-strict/argument.type.neon b/tests/phpstan/baselines-strict/argument.type.neon index dd83b950de430..967bf80d53e61 100644 --- a/tests/phpstan/baselines-strict/argument.type.neon +++ b/tests/phpstan/baselines-strict/argument.type.neon @@ -33,11 +33,6 @@ parameters: identifier: argument.type count: 1 path: ../../../src/wp-includes/ai-client/adapters/class-wp-ai-client-http-client.php - - - message: '#^Parameter \#1 \$wp_response of method WP_AI_Client_HTTP_Client\:\:create_psr_response\(\) expects array\, array given\.$#' - identifier: argument.type - count: 2 - path: ../../../src/wp-includes/ai-client/adapters/class-wp-ai-client-http-client.php - message: '#^Parameter \#2 \$value of method WordPress\\AiClientDependencies\\Psr\\Http\\Message\\MessageInterface\:\:withHeader\(\) expects array\\|string, mixed given\.$#' identifier: argument.type From d622142cd09b0e05749e551a9e1b5b22f3fb0c7d Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 25 Nov 2026 11:17:44 +0000 Subject: [PATCH 85/85] HTTP API: Do not resend batched requests when a batch fails. `WP_Http::request_multiple()` caught every exception thrown while sending a batch and then sent each request of the batch again, one by one. Such an exception can come from a callback on a hook that fires after the requests were sent, so non-idempotent requests could be sent twice, and exceptions unrelated to the Requests library were swallowed. Reject non-HTTP(S) URLs per request up front instead, with the same error that `Requests::request()` throws, and report a Requests exception thrown for the batch as the error of each of its requests without resending them. Also fire the `requests.before_request` hook for each batched request, as `Requests::request()` does for a single request but `Requests::request_multiple()` does not. See #37459. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pYrbbBoL1571AjtuT --- src/wp-includes/class-wp-http.php | 75 +++++++++++------- .../tests/http/wpRemoteRequestMultiple.php | 76 +++++++++++++++++++ 2 files changed, 123 insertions(+), 28 deletions(-) diff --git a/src/wp-includes/class-wp-http.php b/src/wp-includes/class-wp-http.php index 44b1e54a4f695..38db56efbc4e0 100644 --- a/src/wp-includes/class-wp-http.php +++ b/src/wp-includes/class-wp-http.php @@ -298,42 +298,61 @@ public function request_multiple( array $requests, array $options = array() ): a $concurrency = max( 1, $concurrency ); foreach ( array_chunk( $pending, $concurrency, true ) as $batch ) { + $results = array(); $batch_requests = array(); - foreach ( $batch as $id => $prepared ) { - $batch_requests[ $id ] = array( - 'url' => $prepared['url'], - 'headers' => $prepared['headers'], - 'data' => $prepared['data'], - 'type' => $prepared['type'], - 'options' => $prepared['options'], - ); - } - // Avoid issues where mbstring.func_overload is enabled. mbstring_binary_safe_encoding(); try { - /** @var array<\WpOrg\Requests\Response|\WpOrg\Requests\Exception> $results */ - $results = WpOrg\Requests\Requests::request_multiple( $batch_requests ); - } catch ( Exception $e ) { + foreach ( $batch as $id => $prepared ) { + $request_url = $prepared['url']; + $request_headers = $prepared['headers']; + $request_data = $prepared['data']; + $request_type = $prepared['type']; + $request_options = $prepared['options']; + + /* + * Requests::request() fires this hook for a single request, but + * Requests::request_multiple() does not, so fire it here to treat + * the requests of a batch like requests sent on their own. + */ + $request_options['hooks']->dispatch( + 'requests.before_request', + array( &$request_url, &$request_headers, &$request_data, &$request_type, &$request_options ) + ); + + /* + * Requests::request_multiple() throws for the whole batch if one of its URLs + * is not an HTTP(S) URL. Reject such a request on its own instead, with the + * same error that Requests::request() would throw for it. + */ + if ( ! preg_match( '/^http(s)?:\/\//i', $request_url ) ) { + $results[ $id ] = new WpOrg\Requests\Exception( 'Only HTTP(S) requests are handled.', 'nonhttp', $request_url ); + continue; + } + + $batch_requests[ $id ] = array( + 'url' => $request_url, + 'headers' => $request_headers, + 'data' => $request_data, + 'type' => $request_type, + 'options' => $request_options, + ); + } + + if ( ! empty( $batch_requests ) ) { + /** @var array<\WpOrg\Requests\Response|\WpOrg\Requests\Exception> $batch_results */ + $batch_results = WpOrg\Requests\Requests::request_multiple( $batch_requests ); + $results = $batch_results + $results; + } + } catch ( WpOrg\Requests\Exception $e ) { /* - * The batch could not be sent at all, for example because the Requests - * library rejected one of the URLs while building it. Send its requests - * one by one instead, so that each of them gets its own response or error. + * The batch failed as a whole. Its requests may already have been sent, + * so do not send them again: report the error for each of them instead. */ - $results = array(); - - foreach ( $batch_requests as $id => $request ) { - try { - $results[ $id ] = WpOrg\Requests\Requests::request( - $request['url'], - $request['headers'], - $request['data'], - $request['type'], - $request['options'] - ); - } catch ( WpOrg\Requests\Exception $e ) { + foreach ( $batch as $id => $prepared ) { + if ( ! isset( $results[ $id ] ) ) { $results[ $id ] = $e; } } diff --git a/tests/phpunit/tests/http/wpRemoteRequestMultiple.php b/tests/phpunit/tests/http/wpRemoteRequestMultiple.php index 29b48d26cb126..7e68683a0f7dc 100644 --- a/tests/phpunit/tests/http/wpRemoteRequestMultiple.php +++ b/tests/phpunit/tests/http/wpRemoteRequestMultiple.php @@ -319,6 +319,82 @@ static function ( $response, $context, $transport, $parsed_args, $url ) use ( &$ $this->assertSame( $urls, $debugged, "The 'http_api_debug' action should fire for each response." ); } + /** + * @ticket 37459 + * + * @covers WP_HTTP_Requests_Hooks::dispatch + */ + public function test_should_fire_the_requests_before_request_hook_for_each_batched_request() { + $this->allow_requests_rejected_before_sending(); + + $urls = array(); + + add_action( + 'requests-requests.before_request', + static function ( &$url ) use ( &$urls ) { + $urls[] = $url; + // Rewrite the URL so that the Requests library rejects it before anything is sent. + $url = str_replace( 'https://', 'ftp://', $url ); + } + ); + + $responses = wp_remote_request_multiple( + array( + 'first' => 'https://example.org/first', + 'second' => 'https://example.org/second', + ) + ); + + $this->assertSame( array( 'https://example.org/first', 'https://example.org/second' ), $urls, 'The hook should fire once for each request.' ); + + foreach ( $responses as $response ) { + $this->assertWPError( $response ); + $this->assertSame( 'Only HTTP(S) requests are handled.', $response->get_error_message() ); + } + } + + /** + * @ticket 37459 + */ + public function test_should_not_send_the_requests_again_when_the_batch_fails() { + $this->skip_without_curl(); + $this->allow_requests_rejected_before_sending(); + + $count = 0; + + add_action( + 'http_api_curl', + static function () use ( &$count ) { + ++$count; + } + ); + // Make the batch fail before the transfers start, so that nothing leaves the process. + add_action( + 'requests-curl.before_multi_exec', + static function () { + throw new WpOrg\Requests\Exception( 'Batch failed.', 'test' ); + } + ); + + $responses = wp_remote_request_multiple( + array( + 'first' => 'https://example.org/first', + 'second' => array( + 'url' => 'https://example.org/second', + 'args' => array( 'method' => 'POST' ), + ), + ) + ); + + $this->assertSame( 2, $count, 'Each request should only be prepared for sending once.' ); + + foreach ( $responses as $response ) { + $this->assertWPError( $response ); + $this->assertSame( 'http_request_failed', $response->get_error_code() ); + $this->assertSame( 'Batch failed.', $response->get_error_message() ); + } + } + /** * @ticket 37459 * @group external-http