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/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}`, + } + }); 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/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..386a71cece831 100644 --- a/.github/workflows/phpstan-static-analysis.yml +++ b/.github/workflows/phpstan-static-analysis.yml @@ -17,11 +17,13 @@ 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' + - '.github/workflows/reusable-phpstan-static-analysis-v2.yml' workflow_dispatch: # Cancels all previous workflow runs for pull requests that have not completed. @@ -39,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-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-phpstan-static-analysis-v1.yml b/.github/workflows/reusable-phpstan-static-analysis-v1.yml index 9a80af539ae13..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 @@ -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/.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/.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/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 d4817522585d9..59eec3837613a 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: @@ -92,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 @@ -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' }} 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/.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/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' ], 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 dd7f57d5b6313..77226897cee1c 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", @@ -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": { @@ -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/package-lock.json b/package-lock.json index 89c91e4f79522..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", @@ -43,24 +43,24 @@ "devDependencies": { "@343dev/gifsicle": "1.2.0", "@lodder/grunt-postcss": "^3.1.1", - "@napi-rs/image": "1.14.0", - "@playwright/test": "1.64.1", - "@pmmmwh/react-refresh-webpack-plugin": "0.6.2", + "@napi-rs/image": "1.16.0", + "@playwright/test": "1.65.1", + "@pmmmwh/react-refresh-webpack-plugin": "0.6.3", "@types/backbone": "1.4.23", - "@types/codemirror": "5.60.17", + "@types/codemirror": "5.60.18", "@types/espree": "10.1.0", "@types/htmlhint": "1.1.5", "@types/jquery": "3.5.34", - "@types/node": "20.19.43", + "@types/node": "24.19.2", "@types/underscore": "1.13.0", "@wordpress/e2e-test-utils-playwright": "1.51.0", "@wordpress/prettier-config": "4.51.0", "@wordpress/scripts": "33.0.0", - "autoprefixer": "10.5.3", + "autoprefixer": "10.6.2", "chokidar": "4.0.3", "dotenv": "17.4.2", "dotenv-expand": "13.0.0", - "grunt": "1.6.2", + "grunt": "1.6.3", "grunt-banner": "^0.6.0", "grunt-contrib-clean": "~2.0.1", "grunt-contrib-concat": "2.1.0", @@ -75,23 +75,23 @@ "grunt-replace-lts": "~1.1.0", "grunt-rtlcss": "~2.0.2", "grunt-sass": "~4.1.0", - "grunt-webpack": "7.0.1", + "grunt-webpack": "8.0.0", "install-changed": "1.1.0", "json2php": "0.0.12", - "minimizer-webpack-plugin": "5.6.1", + "minimizer-webpack-plugin": "5.14.0", "php-array-reader": "2.1.4", - "postcss": "8.5.19", + "postcss": "8.5.33", "prettier": "npm:wp-prettier@3.0.3", - "qunit": "~2.26.0", + "qunit": "3.0.0", "react-refresh": "0.14.0", - "sass": "1.101.0", + "sass": "1.108.2", "sinon": "16.1.3", "sinon-test": "~3.1.6", "source-map-loader": "5.0.0", "typescript": "6.0.3", - "update-browserslist-db": "1.3.1", - "wait-on": "9.0.10", - "webpack": "5.108.4" + "update-browserslist-db": "1.4.0", + "wait-on": "9.5.1", + "webpack": "5.109.2" }, "engines": { "node": ">=24.18.0", @@ -2708,9 +2708,9 @@ "license": "BSD-3-Clause" }, "node_modules/@hapi/tlds": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@hapi/tlds/-/tlds-1.1.4.tgz", - "integrity": "sha512-Fq+20dxsxLaUn5jSSWrdtSRcIUba2JquuorF9UW1wIJS5cSUwxIsO2GIhaWynPRflvxSzFN+gxKte2HEW1OuoA==", + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/@hapi/tlds/-/tlds-1.1.7.tgz", + "integrity": "sha512-MgNjRwy9Ti92yVAixLmDc8dd1bJIKwO9qlWCfFQRwRmUEDPQHYn4G6hwPFvFGUTzAa0FsS+inMjLin7GnyBRhA==", "dev": true, "license": "BSD-3-Clause", "engines": { @@ -4028,9 +4028,9 @@ } }, "node_modules/@napi-rs/image": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image/-/image-1.14.0.tgz", - "integrity": "sha512-pmwJPWY6R063luNBEP9msq9lFu+kYVMiQTJRSpyGnzYnnerYpT3U4vCgFhhVR3jypCgCVWi9viDLoEJoZoIA1w==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image/-/image-1.16.0.tgz", + "integrity": "sha512-kciiEskvG7m6t0+VwJ/dUT5Zn79mKr1/RAAmjvG8TfK6aG9dI1lZqohtt8QGSQjdhRkyYJ85YKW686gQGFgzWw==", "dev": true, "license": "MIT", "engines": { @@ -4041,25 +4041,24 @@ "url": "https://github.com/sponsors/Brooooooklyn" }, "optionalDependencies": { - "@napi-rs/image-android-arm64": "1.14.0", - "@napi-rs/image-darwin-arm64": "1.14.0", - "@napi-rs/image-darwin-x64": "1.14.0", - "@napi-rs/image-freebsd-x64": "1.14.0", - "@napi-rs/image-linux-arm-gnueabihf": "1.14.0", - "@napi-rs/image-linux-arm64-gnu": "1.14.0", - "@napi-rs/image-linux-arm64-musl": "1.14.0", - "@napi-rs/image-linux-x64-gnu": "1.14.0", - "@napi-rs/image-linux-x64-musl": "1.14.0", - "@napi-rs/image-wasm32-wasi": "1.14.0", - "@napi-rs/image-win32-arm64-msvc": "1.14.0", - "@napi-rs/image-win32-ia32-msvc": "1.14.0", - "@napi-rs/image-win32-x64-msvc": "1.14.0" + "@napi-rs/image-android-arm64": "1.16.0", + "@napi-rs/image-darwin-arm64": "1.16.0", + "@napi-rs/image-darwin-x64": "1.16.0", + "@napi-rs/image-freebsd-x64": "1.16.0", + "@napi-rs/image-linux-arm-gnueabihf": "1.16.0", + "@napi-rs/image-linux-arm64-gnu": "1.16.0", + "@napi-rs/image-linux-arm64-musl": "1.16.0", + "@napi-rs/image-linux-x64-gnu": "1.16.0", + "@napi-rs/image-linux-x64-musl": "1.16.0", + "@napi-rs/image-win32-arm64-msvc": "1.16.0", + "@napi-rs/image-win32-ia32-msvc": "1.16.0", + "@napi-rs/image-win32-x64-msvc": "1.16.0" } }, "node_modules/@napi-rs/image-android-arm64": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-android-arm64/-/image-android-arm64-1.14.0.tgz", - "integrity": "sha512-LBWu1fNR7uC6kNQy+axDqXKU7Kj1x3UdD3xGKw/bks6YAUG15m92qwSwINDEB4Jqgl29vCeSNFItJZRm3byfJQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-android-arm64/-/image-android-arm64-1.16.0.tgz", + "integrity": "sha512-pwn/41RoGaE0gHlJBvEIikYXASeiHhs1lyo5+fWZZSXsS9hpJt0zQqWiSr7cCdCwLdg84pQwPbqd32Kp+scLSw==", "cpu": [ "arm64" ], @@ -4074,9 +4073,9 @@ } }, "node_modules/@napi-rs/image-darwin-arm64": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-darwin-arm64/-/image-darwin-arm64-1.14.0.tgz", - "integrity": "sha512-0f7SqjtXHelxbwkqdpUb/5yhVK7ciVoe902hqCeffhAFsJA7HQbEbzfM8W1MDawI6Ghenr5zHYQimWf1W1vaow==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-darwin-arm64/-/image-darwin-arm64-1.16.0.tgz", + "integrity": "sha512-JJesjwlmWA9m0iN4y0GvHpfZkgAviU4Yhk+qvV+D44obYPisqAhJdMCQMY1/u8Yj/PblijimCMY05fMRvCmrdQ==", "cpu": [ "arm64" ], @@ -4091,9 +4090,9 @@ } }, "node_modules/@napi-rs/image-darwin-x64": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-darwin-x64/-/image-darwin-x64-1.14.0.tgz", - "integrity": "sha512-wi6w06N516QzSd/QMre/Ye92mA4b5E2yQfr1+Hhml3tWrIM2Po2QvxBO9ns0AaG8u6y8b545bDzQCGLTfBykyQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-darwin-x64/-/image-darwin-x64-1.16.0.tgz", + "integrity": "sha512-EV/SHAnsIoadlJdyeSVtHo2RE+N6BAWTK6S3y52vvCF8/s3z38fe9o1tbk40xxPpcSXdu+gh6ASBeFHic2/NOQ==", "cpu": [ "x64" ], @@ -4108,9 +4107,9 @@ } }, "node_modules/@napi-rs/image-freebsd-x64": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-freebsd-x64/-/image-freebsd-x64-1.14.0.tgz", - "integrity": "sha512-Sz1XSGF6/Xmjb33CbWLOb7h6+ekmoJRGsN0bdnzn8W86OHPTSsIbTOMtqp9ZXTLQNJgeXQhprQhhmRFNRqq0Gg==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-freebsd-x64/-/image-freebsd-x64-1.16.0.tgz", + "integrity": "sha512-2Q2XcPqeFfr5U8oL9zwZgbnfJLvFrA85+XPaOgjaUiIhEFfRKDgp5l7R0jDFZvymCw0ljMKtVzUD+Id2LUQasg==", "cpu": [ "x64" ], @@ -4125,9 +4124,9 @@ } }, "node_modules/@napi-rs/image-linux-arm-gnueabihf": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-linux-arm-gnueabihf/-/image-linux-arm-gnueabihf-1.14.0.tgz", - "integrity": "sha512-ZsJ+0Rl3Ke1DN+W4lQMSzsfrwskjP4CkUsqOT7Y/HpziwirQn9R2fl2QU2Kb2eDSQvwSvGbRCkMLqH+4V4rzHg==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-linux-arm-gnueabihf/-/image-linux-arm-gnueabihf-1.16.0.tgz", + "integrity": "sha512-qOXhoEXK66U396sBtL1wDvho4yooW6EPse0Ue23kRHlRHbR6SiDKz6mKcEoB1MrQzZGeKOYRh2F9rk0iHlsPiw==", "cpu": [ "arm" ], @@ -4142,9 +4141,9 @@ } }, "node_modules/@napi-rs/image-linux-arm64-gnu": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-linux-arm64-gnu/-/image-linux-arm64-gnu-1.14.0.tgz", - "integrity": "sha512-J06fGFXt76fAGEaCb3uyPQgZrwvGbpYZycA4Xz6F5dauVgcLPw75syXmggode5G+a0cSg40fjddXMvSWhPwHGQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-linux-arm64-gnu/-/image-linux-arm64-gnu-1.16.0.tgz", + "integrity": "sha512-S0j/r3ciH+WW/NnsOaLwhol0wly0x0YtljZnfQ4o1YCfkVrcAPMQGgGmPyjKIG/TLQ8tqPd6liuUL4Nms017lA==", "cpu": [ "arm64" ], @@ -4162,9 +4161,9 @@ } }, "node_modules/@napi-rs/image-linux-arm64-musl": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-linux-arm64-musl/-/image-linux-arm64-musl-1.14.0.tgz", - "integrity": "sha512-AH8WvQb58ix9/RHB+9XNF2rOB8aAnFHzj0hDCCZCplRGHmv9BzOtA+IWdf5l4f7KmEJUohY+MxVWJ1jfpgn+JQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-linux-arm64-musl/-/image-linux-arm64-musl-1.16.0.tgz", + "integrity": "sha512-ILcos5cDYUQw6h2aty8BBlm5B4l4I5y52i0tSSU44HBM8tmGE6sUU1DREPfMx1NLhB2HX4xu1Y9DNQq7tIXhpQ==", "cpu": [ "arm64" ], @@ -4182,9 +4181,9 @@ } }, "node_modules/@napi-rs/image-linux-x64-gnu": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-linux-x64-gnu/-/image-linux-x64-gnu-1.14.0.tgz", - "integrity": "sha512-oU3wnQcDeZf+t8vyKMP4A6okY7JNjRbiiC7j8UsJ2lDf0no3GDQEJCCFDrQ7gCKQZAI7cr0rFbI75l2KlTM0PQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-linux-x64-gnu/-/image-linux-x64-gnu-1.16.0.tgz", + "integrity": "sha512-R2LnMJzHxztTYyySZnyWIiZmDxgK7pq8DWYT1jAuryCXcGmhUhM14BgEnQKj5h3zvDVbtf1czm6DSD9f8PDl4g==", "cpu": [ "x64" ], @@ -4202,9 +4201,9 @@ } }, "node_modules/@napi-rs/image-linux-x64-musl": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-linux-x64-musl/-/image-linux-x64-musl-1.14.0.tgz", - "integrity": "sha512-iuDTfVmFm9W6S4gzLNdSFt+Wr86LtciJJ+u2i0KBixpFYoHzeIkUr6LHBIkYg3eNdi7xHBb9qFBvxxhFQg4tUQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-linux-x64-musl/-/image-linux-x64-musl-1.16.0.tgz", + "integrity": "sha512-UXcwFSIEEHia8/JhJO6H3uehQmTrsG8UK8tpD1qpzi8WHxUVgLJyuoVS3zKm8cmqlYq0No1cyqU6h2OnArShOw==", "cpu": [ "x64" ], @@ -4221,63 +4220,10 @@ "node": ">= 10" } }, - "node_modules/@napi-rs/image-wasm32-wasi": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-wasm32-wasi/-/image-wasm32-wasi-1.14.0.tgz", - "integrity": "sha512-XRAbAQVWSm4wQzYwnTtOHD+ev6dRHUxLxmFQe5Nbev12dspqkB40zsDJ/yr4VwnV80gIfEfg7BvRLw9FFvLRlg==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "1.11.1", - "@emnapi/runtime": "1.11.1", - "@napi-rs/wasm-runtime": "^1.1.6" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@napi-rs/image-wasm32-wasi/node_modules/@emnapi/core": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz", - "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.2", - "tslib": "^2.4.0" - } - }, - "node_modules/@napi-rs/image-wasm32-wasi/node_modules/@emnapi/runtime": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz", - "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@napi-rs/image-wasm32-wasi/node_modules/@emnapi/wasi-threads": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", - "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, "node_modules/@napi-rs/image-win32-arm64-msvc": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-win32-arm64-msvc/-/image-win32-arm64-msvc-1.14.0.tgz", - "integrity": "sha512-Wuq0AfN5rjrv2SkJTubIIYW//B5aBloPxND9GxRHKgGkLhyiSxBD6iOCQA1M/n12rvF9BWeadDDO8JLoO3iRHA==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-win32-arm64-msvc/-/image-win32-arm64-msvc-1.16.0.tgz", + "integrity": "sha512-C1lmWAajIqkiYyVb0aBz0svCWIbzFAT6YpNoQ/QC/QsyNaQ602WSLSoq4ixnNhBPQrlro/Va3n/KANv4iqp4GA==", "cpu": [ "arm64" ], @@ -4292,9 +4238,9 @@ } }, "node_modules/@napi-rs/image-win32-ia32-msvc": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-win32-ia32-msvc/-/image-win32-ia32-msvc-1.14.0.tgz", - "integrity": "sha512-Idb+OyISq24YRdO8iU+BC6QaN4pU6HpC+SRrxFOftWJg0xXPzfPfpwpwdviduJK/SjJcHe02nhUq3HKHtUEnWQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-win32-ia32-msvc/-/image-win32-ia32-msvc-1.16.0.tgz", + "integrity": "sha512-j6OMycTmw47pY4m3yw4FnurkikzA8r36xgtbHqxsXWg1TGdY2uQq37Or56USNjLIeA6Oyv4az5YXc7L1oVv03w==", "cpu": [ "ia32" ], @@ -4309,9 +4255,9 @@ } }, "node_modules/@napi-rs/image-win32-x64-msvc": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@napi-rs/image-win32-x64-msvc/-/image-win32-x64-msvc-1.14.0.tgz", - "integrity": "sha512-Hq5BY3+FeNehRe1VPhVQ28dGTSWlxnGAHeoF7/GpgeWBfltLT5+DpkV+FPyq6ju49kG1aFofE+IlSGi5sMJ0Kw==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@napi-rs/image-win32-x64-msvc/-/image-win32-x64-msvc-1.16.0.tgz", + "integrity": "sha512-jdmbjZhvR1T++hTZpi5CYASA+2Js9tuUQGtQ0fVtrtbGt82sGkYrrax8gAVNsgyvEu9/B2yxbB/4mlJcXkwt0Q==", "cpu": [ "x64" ], @@ -4737,13 +4683,13 @@ } }, "node_modules/@playwright/test": { - "version": "1.64.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", - "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz", + "integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright": "1.64.1" + "playwright": "1.65.1" }, "bin": { "playwright": "cli.js" @@ -4753,9 +4699,9 @@ } }, "node_modules/@pmmmwh/react-refresh-webpack-plugin": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/@pmmmwh/react-refresh-webpack-plugin/-/react-refresh-webpack-plugin-0.6.2.tgz", - "integrity": "sha512-IhIAD5n4XvGHuL9nAgWfsBR0TdxtjrUWETYKCBHxauYXEv+b+ctEbs9neEgPC7Ecgzv4bpZTBwesAoGDeFymzA==", + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/@pmmmwh/react-refresh-webpack-plugin/-/react-refresh-webpack-plugin-0.6.3.tgz", + "integrity": "sha512-k1EEmFS9K7685tqJM55DCA3sYlTNZb7aFj1M3HNFwMqH+fGgMEvemIQ5kurIzKc9wYRSmfKpSZN3WUyY/GHlvg==", "dev": true, "license": "MIT", "dependencies": { @@ -4775,7 +4721,7 @@ "sockjs-client": "^1.4.0", "type-fest": ">=0.17.0 <6.0.0", "webpack": "^5.0.0", - "webpack-dev-server": "^4.8.0 || 5.x", + "webpack-dev-server": "^4.8.0 || 5.x || 6.x", "webpack-hot-middleware": "2.x", "webpack-plugin-serve": "1.x" }, @@ -5754,9 +5700,9 @@ } }, "node_modules/@types/codemirror": { - "version": "5.60.17", - "resolved": "https://registry.npmjs.org/@types/codemirror/-/codemirror-5.60.17.tgz", - "integrity": "sha512-AZq2FIsUHVMlp7VSe2hTfl5w4pcUkoFkM3zVsRKsn1ca8CXRDYvnin04+HP2REkwsxemuHqvDofdlhUWNpbwfw==", + "version": "5.60.18", + "resolved": "https://registry.npmjs.org/@types/codemirror/-/codemirror-5.60.18.tgz", + "integrity": "sha512-aSBOPXH2PXRYixxUpVP1sJ5+S0vEfKDvR+lABZ7Kju/9Qb0SSbZk72NihWaKoQbANyibs92q4DBfYasywxnNkA==", "dev": true, "license": "MIT", "dependencies": { @@ -5979,13 +5925,13 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "20.19.43", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", - "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~6.21.0" + "undici-types": ">=7.24.0 <7.24.7" } }, "node_modules/@types/node-forge": { @@ -8671,19 +8617,6 @@ "node": ">=0.4.0" } }, - "node_modules/acorn-import-phases": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/acorn-import-phases/-/acorn-import-phases-1.0.4.tgz", - "integrity": "sha512-wKmbr/DDiIXzEOiWrTTUcDm24kQ2vGfZQvM2fwg2vXqR5uW6aapr7ObPtj1th32b9u90/Pf4AItvdTh42fBmVQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10.13.0" - }, - "peerDependencies": { - "acorn": "^8.14.0" - } - }, "node_modules/acorn-jsx": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", @@ -9189,9 +9122,9 @@ "dev": true }, "node_modules/autoprefixer": { - "version": "10.5.3", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.5.3.tgz", - "integrity": "sha512-bJRzflk8GgE4JX+iZNEwz9f9p460NCHnU7bd+CZ9vIjIlZuTkt6F3WSl2oNO8StZBFx17nLEsiQ6H2wcZiY7nA==", + "version": "10.6.2", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.6.2.tgz", + "integrity": "sha512-VOw9/yGTGwPPgzFcODtcv6zhEPIeIWkRSe10L2ri2f5vZ7ID7lCt6jZzRF5/ubgOZ+szYydmEF5AYsA5jxX1tA==", "dev": true, "funding": [ { @@ -9209,8 +9142,8 @@ ], "license": "MIT", "dependencies": { - "browserslist": "^4.28.6", - "caniuse-lite": "^1.0.30001805", + "browserslist": "^4.28.9", + "caniuse-lite": "^1.0.30001810", "fraction.js": "^5.3.4", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" @@ -9265,14 +9198,14 @@ } }, "node_modules/axios": { - "version": "1.18.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.1.tgz", - "integrity": "sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==", + "version": "1.21.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.21.1.tgz", + "integrity": "sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ==", "dev": true, "license": "MIT", "dependencies": { - "follow-redirects": "^1.16.0", - "form-data": "^4.0.5", + "follow-redirects": "^1.16.2", + "form-data": "^4.0.6", "https-proxy-agent": "^5.0.1", "proxy-from-env": "^2.1.0" } @@ -9759,9 +9692,9 @@ ] }, "node_modules/baseline-browser-mapping": { - "version": "2.10.43", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.43.tgz", - "integrity": "sha512-AjYpR78kDWAY3Efj+cDTFH9t9SCoL7OoTp1BOb0mQV7S+6CiLwnWM3FyxhJtdPufDFKzmCSFoUncKjWgJEZTCQ==", + "version": "2.11.37", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.37.tgz", + "integrity": "sha512-QYph+vfurmaxhNwi9FprfmtkT5cx2Keg8FzZ0vnjO8ukscIybVyZGMFwdllKGlTI6qyU8ck43OM9UXh+IFJihQ==", "dev": true, "license": "Apache-2.0", "bin": { @@ -9951,9 +9884,9 @@ } }, "node_modules/browserslist": { - "version": "4.28.6", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.6.tgz", - "integrity": "sha512-FQBYNK15VMslhLHpA7+n+n1GOlF1kId2xcCg7/j95f24AOF6VDYMNH4mFxF7KuaTdv627faazpOAjFzMrfJOUw==", + "version": "4.29.6", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz", + "integrity": "sha512-CmVVIQ3RVc5HxYEc9X84GvxK/C8C1wH8TlKAiO7uTxF8PDwt7r8t9Qk3J9NkMOVzX5O/HbLv3yzxZg9HPrnI9w==", "dev": true, "funding": [ { @@ -9971,11 +9904,11 @@ ], "license": "MIT", "dependencies": { - "baseline-browser-mapping": "^2.10.42", - "caniuse-lite": "^1.0.30001803", - "electron-to-chromium": "^1.5.389", - "node-releases": "^2.0.51", - "update-browserslist-db": "^1.2.3" + "baseline-browser-mapping": "^2.11.37", + "caniuse-lite": "^1.0.30001826", + "electron-to-chromium": "^1.5.486", + "node-releases": "^2.0.64", + "update-browserslist-db": "^1.4.0" }, "bin": { "browserslist": "cli.js" @@ -10166,9 +10099,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001805", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001805.tgz", - "integrity": "sha512-52noaS3DubycKSXaU30TwPGIp+POyQSUVa5jBEq3vkRkY0kjyb3LQgvhU6WGyCcyXqVLWO0Cw0Q6BSdD0kUfVA==", + "version": "1.0.30001826", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001826.tgz", + "integrity": "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==", "dev": true, "funding": [ { @@ -11914,9 +11847,9 @@ "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.389", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.389.tgz", - "integrity": "sha512-cEto7aeOqBfU1D+c5py5pE+ooscKE75JifxLBdFUZsqAxRS6y7kebtxAZvICszSl05gPjYHDTjY+lXpyGvpJbg==", + "version": "1.5.486", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.486.tgz", + "integrity": "sha512-rpybw4Ac4ak/An6G1Me2+61xzwobowDGyuJe71QHHOVpkZv4fPVobsLl7WH6zHSKusAMpaHxGKTpOvpy7+r3dQ==", "dev": true, "license": "ISC" }, @@ -11986,9 +11919,9 @@ } }, "node_modules/enhanced-resolve": { - "version": "5.24.2", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.2.tgz", - "integrity": "sha512-rpsZEGT1jFuve6QlpyRp9ckQ+kN61hvF9BzCPyMdaKTm8UJce96KBn3sorXOFXlzjPrs3Vc4T1NsSroZ3PxlFw==", + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", + "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==", "dev": true, "license": "MIT", "dependencies": { @@ -13964,9 +13897,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", + "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", "dev": true, "funding": [ { @@ -14512,9 +14445,9 @@ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" }, "node_modules/grunt": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/grunt/-/grunt-1.6.2.tgz", - "integrity": "sha512-bUzh5nA/P5L66ihXTDP6J5BGnMB/8lXJXejYWSbH4Y4TvWM9t2S39sggQDYYQlx06cYcCsmu63HMYHGCIzUVfg==", + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/grunt/-/grunt-1.6.3.tgz", + "integrity": "sha512-ng0CbpyNp/ox5e5CBY9TkZgVdAL4wK+nBHO6rNE8cXGa5kM++Lxlp0MpFBVZbpgOR2oCp/91V+T3CZVSWWLqMA==", "dev": true, "license": "MIT", "dependencies": { @@ -14528,7 +14461,7 @@ "grunt-legacy-log": "~3.0.0", "grunt-legacy-util": "~2.0.1", "iconv-lite": "~0.6.3", - "js-yaml": "~3.14.0", + "js-yaml": "^3.15.0", "minimatch": "^3.1.5", "nopt": "^5.0.0" }, @@ -15443,9 +15376,9 @@ } }, "node_modules/grunt-webpack": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/grunt-webpack/-/grunt-webpack-7.0.1.tgz", - "integrity": "sha512-3Mo0UfZE7v5CnSCIkN6tGMlKDOCr0okvk8SQrL9X/6JhrE2sQlGwFEI5Q6j89rZ9DTl9jEjkIev/hfR0x85wKg==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/grunt-webpack/-/grunt-webpack-8.0.0.tgz", + "integrity": "sha512-pcDVu1DPcDaEik29MDwMPuYwYCYW2Xhoze9UjWGGVJLK7XR/dpQ6kCwT3IDqByrVhDwobtKqFtk3b7l75OiJcw==", "dev": true, "license": "MIT", "dependencies": { @@ -15453,11 +15386,7 @@ "webpack-merge": "^6.0.1" }, "engines": { - "node": ">=18.19.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" + "node": "^22.13.0 || >=24" }, "peerDependencies": { "webpack": "^5.0.0" @@ -19377,9 +19306,9 @@ } }, "node_modules/joi": { - "version": "18.2.3", - "resolved": "https://registry.npmjs.org/joi/-/joi-18.2.3.tgz", - "integrity": "sha512-N5A3KTWQpPWT4ExxxPlUx7WmykGXRzhNidWhV41d6Abu9YfI2NyWCJuxdPnslJCPWtbRpSVOWSnSS6GakLM/Rg==", + "version": "18.3.2", + "resolved": "https://registry.npmjs.org/joi/-/joi-18.3.2.tgz", + "integrity": "sha512-iUivApKYw5GpZmq2Sy6El99j7noo8QSUFZlyQtr3HCkosC/b5wKF6/Y3teiHIlaM8WI38sAT3P+51rB0lhAhJA==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -19458,9 +19387,9 @@ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "node_modules/js-yaml": { - "version": "3.14.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", - "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", "dev": true, "license": "MIT", "dependencies": { @@ -20174,20 +20103,6 @@ "uc.micro": "^1.0.1" } }, - "node_modules/loader-runner": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.2.tgz", - "integrity": "sha512-DFEqQ3ihfS9blba08cLfYf1NRAIEm+dDjic073DRDc3/JspI/8wYmtDsHwd3+4hwvdxSK7PGaElfTmm0awWJ4w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.11.5" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, "node_modules/loader-utils": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.4.tgz", @@ -21043,16 +20958,15 @@ } }, "node_modules/minimizer-webpack-plugin": { - "version": "5.6.1", - "resolved": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.6.1.tgz", - "integrity": "sha512-DoeAZz8Q1C1znwsUzej1fdoi4jCf7/+Em27ouLqfK/+3m8G+D7yDhUwrc3CNhjSzGUN1kn7Iv4sWmjflQHenpw==", + "version": "5.14.0", + "resolved": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.14.0.tgz", + "integrity": "sha512-PnvQXCJxhgH2ZVVO7Lj0sM6q8L1XGxnUvd8wVQIRwi8khMCLq5wg0Ngxe44bcuZL2FSN81RdVE7YHEVzTKsQDQ==", "dev": true, "license": "MIT", "dependencies": { - "@jridgewell/trace-mapping": "^0.3.25", "jest-worker": "^27.4.5", - "schema-utils": "^4.3.0", - "terser": "^5.31.1" + "schema-utils": "^4.6.0", + "terser": "^5.51.0" }, "engines": { "node": ">= 10.13.0" @@ -21068,6 +20982,9 @@ "@minify-html/node": { "optional": true }, + "@napi-rs/image": { + "optional": true + }, "@swc/core": { "optional": true }, @@ -21092,12 +21009,21 @@ "html-minifier-terser": { "optional": true }, + "imagemin": { + "optional": true + }, "lightningcss": { "optional": true }, "postcss": { "optional": true }, + "sharp": { + "optional": true + }, + "svgo": { + "optional": true + }, "uglify-js": { "optional": true } @@ -21120,6 +21046,24 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/minimizer-webpack-plugin/node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, "node_modules/minimizer-webpack-plugin/node_modules/ajv-keywords": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", @@ -21141,23 +21085,34 @@ "license": "MIT" }, "node_modules/minimizer-webpack-plugin/node_modules/schema-utils": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz", - "integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==", + "version": "4.8.3", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.8.3.tgz", + "integrity": "sha512-qIfo3f+lRNqnMPgpXSKvUhsT3pY5U+ppmgGr4j8LanFP3W/Ze+xj8DY/dPb5qVu3m6qFIMyMWKVRLNKxrNhxWg==", "dev": true, "license": "MIT", "dependencies": { - "@types/json-schema": "^7.0.9", - "ajv": "^8.9.0", - "ajv-formats": "^2.1.1", + "@types/json-schema": "^7.0.15", + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1", "ajv-keywords": "^5.1.0" }, + "bin": { + "schema-utils": "bin/schema-utils.js" + }, "engines": { "node": ">= 10.13.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.0.0" + }, + "peerDependenciesMeta": { + "webpack": { + "optional": true + } } }, "node_modules/minipass": { @@ -21247,9 +21202,9 @@ "dev": true }, "node_modules/nanoid": { - "version": "3.3.16", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz", - "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==", + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", "dev": true, "funding": [ { @@ -21430,9 +21385,9 @@ "dev": true }, "node_modules/node-releases": { - "version": "2.0.51", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.51.tgz", - "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==", + "version": "2.0.64", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.64.tgz", + "integrity": "sha512-zAPCKqMcnqs2nGy6nlkm7JduFseiBJy3EXHGLh+8pFR+TxGCBxxiEN21+UROU5CKwX/f4TlUcYjiM+vs/tsyxw==", "dev": true, "license": "MIT", "engines": { @@ -21488,10 +21443,11 @@ } }, "node_modules/node-watch": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/node-watch/-/node-watch-0.7.3.tgz", - "integrity": "sha512-3l4E8uMPY1HdMMryPRUAl+oIHtXtyiTlIiESNSVSNxcPfzAFzeTbXFQkZfAwBbo0B1qMSG8nUABx+Gd+YrbKrQ==", + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/node-watch/-/node-watch-0.7.4.tgz", + "integrity": "sha512-RinNxoz4W1cep1b928fuFhvAQ5ag/+1UlMDV7rbyGthBIgsiEouS4kvRayvvboxii4m8eolKOIBo3OjDqbc+uQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } @@ -22831,13 +22787,13 @@ } }, "node_modules/playwright": { - "version": "1.64.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", - "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz", + "integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.64.1" + "playwright-core": "1.65.1" }, "bin": { "playwright": "cli.js" @@ -22847,9 +22803,9 @@ } }, "node_modules/playwright-core": { - "version": "1.64.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", - "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", "dev": true, "license": "Apache-2.0", "bin": { @@ -22902,9 +22858,9 @@ } }, "node_modules/postcss": { - "version": "8.5.19", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.19.tgz", - "integrity": "sha512-Mz8SaolMd8nB+G13WkORcxQKHZ/NE4xXevtkJHVuG+guo9/wYKlIMTKAqGdEmYOXR2ijPjTYNHssizdaVSUNdQ==", + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", "dev": true, "funding": [ { @@ -22922,9 +22878,9 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.12", + "nanoid": "^3.3.20", "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" + "source-map-js": "^1.2.2" }, "engines": { "node": "^10 || ^12 || >=14" @@ -23472,30 +23428,31 @@ } }, "node_modules/qunit": { - "version": "2.26.0", - "resolved": "https://registry.npmjs.org/qunit/-/qunit-2.26.0.tgz", - "integrity": "sha512-KSv16YomcYmiK90qTOJl3Bm5IvTf2upqQDdBQWCvSQWe94FWobnUgKOpvpvZdG7VkDt3TJSI8k8g9+GGGEd7Fw==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/qunit/-/qunit-3.0.0.tgz", + "integrity": "sha512-g4Fgw3uhqwdjzhUDa0bYGQyGzs1xRcIY/32c5zUydnnrgzcA8updYF9nIeUis+PfwuqX6UB/4JpCNMnrVBY6iA==", "dev": true, "license": "MIT", "dependencies": { - "commander": "7.2.0", - "node-watch": "0.7.3", + "commander": "12.1.0", + "node-watch": "0.7.4", "tiny-glob": "0.2.9" }, "bin": { "qunit": "bin/qunit.js" }, "engines": { - "node": ">=10" + "node": ">=18" } }, "node_modules/qunit/node_modules/commander": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", "dev": true, + "license": "MIT", "engines": { - "node": ">= 10" + "node": ">=18" } }, "node_modules/randombytes": { @@ -24318,9 +24275,9 @@ "dev": true }, "node_modules/sass": { - "version": "1.101.0", - "resolved": "https://registry.npmjs.org/sass/-/sass-1.101.0.tgz", - "integrity": "sha512-OL3GoQyoUdDt843DpVmDO6y2k1sc5IhUDSpu8XucEI+35neq5QivZ1iuegnpraEVTJXlQGK1gl27zKcTLEPbQw==", + "version": "1.108.2", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.108.2.tgz", + "integrity": "sha512-kugK8djotnG9HQRPTOf36asKYlxg8rWWsNLYHOgWDIVOiZQqlRfKBgF4XXM6kfw146kIDMvm57B4GIkvDSyTzA==", "dev": true, "license": "MIT", "dependencies": { @@ -25034,10 +24991,11 @@ } }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "dev": true, + "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" } @@ -26211,14 +26169,14 @@ } }, "node_modules/terser": { - "version": "5.37.0", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.37.0.tgz", - "integrity": "sha512-B8wRRkmre4ERucLM/uXx4MOV5cbnOlVAqUst+1+iLKPI0dOgFO28f84ptoQt9HEI537PMzfYa/d+GEPKTRXmYA==", + "version": "5.51.2", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz", + "integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==", "dev": true, "license": "BSD-2-Clause", "dependencies": { "@jridgewell/source-map": "^0.3.3", - "acorn": "^8.8.2", + "acorn": "^8.15.0", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, @@ -26876,9 +26834,9 @@ } }, "node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", "dev": true, "license": "MIT" }, @@ -26993,9 +26951,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.1.tgz", - "integrity": "sha512-ZZ61DsRsOnakl74HAmp3oSN4aXUmEWXf+i/yv0h7tIBfICc3VdrFErQKUUKPgu3AMsTUMbcongALEN4l6GSUrQ==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.4.0.tgz", + "integrity": "sha512-WPJuOnjI9FWDct4fB+ej4Mz8opLaw5CDcZ2t44tFZ0vIQVYWzBhWR3mkixuUj/A7+vY4V9+ApOZ2YYLwdgq46w==", "dev": true, "funding": [ { @@ -27195,16 +27153,15 @@ } }, "node_modules/wait-on": { - "version": "9.0.10", - "resolved": "https://registry.npmjs.org/wait-on/-/wait-on-9.0.10.tgz", - "integrity": "sha512-rCoJEhvMr0X6alHmwc9abbrA5ZrLZFKpFQVKPNFwl2h7DapXOGdmimIHDtLOWhT4PjhZhxFEtZoQgEXbkDWdZw==", + "version": "9.5.1", + "resolved": "https://registry.npmjs.org/wait-on/-/wait-on-9.5.1.tgz", + "integrity": "sha512-bOtj1wRY6u+GPnNskZLcgZNHOaL5NC4+5hRCbEpVoVX6MbMrCLCqIBM2bjsAfrgst3ZC0siIo7vLb4LuYFfIow==", "dev": true, "license": "MIT", "dependencies": { - "axios": "^1.16.0", - "joi": "^18.2.1", + "axios": "^1.20.0", + "joi": "^18.2.9", "lodash": "^4.18.1", - "minimist": "^1.2.8", "rxjs": "^7.8.2" }, "bin": { @@ -27280,9 +27237,9 @@ } }, "node_modules/webpack": { - "version": "5.108.4", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.108.4.tgz", - "integrity": "sha512-yur8LyJoeiWh47dErD+Ok7vlbmDsJ3UbbRPAoxbGJ54WpE2y5yVo5G/inUzujnYgw3tPmBRdn+G7PoxXaYC33w==", + "version": "5.109.2", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.109.2.tgz", + "integrity": "sha512-U9/cvLzxObKNEZ9+TtdqrHM5/9z3lgl2c+c4BzbqGxFQvQvBAq87yql5A8pQ+rrMbS496MZJeF5enVBndIy2hw==", "dev": true, "license": "MIT", "dependencies": { @@ -27292,22 +27249,20 @@ "@webassemblyjs/wasm-edit": "^1.14.1", "@webassemblyjs/wasm-parser": "^1.14.1", "acorn": "^8.16.0", - "acorn-import-phases": "^1.0.3", "browserslist": "^4.28.1", "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.22.2", + "enhanced-resolve": "^5.24.4", "es-module-lexer": "^2.1.0", "eslint-scope": "5.1.1", "events": "^3.2.0", "graceful-fs": "^4.2.11", - "loader-runner": "^4.3.2", "mime-db": "^1.54.0", "minimizer-webpack-plugin": "^5.6.1", "neo-async": "^2.6.2", "schema-utils": "^4.3.3", "tapable": "^2.3.0", "watchpack": "^2.5.2", - "webpack-sources": "^3.5.0" + "webpack-sources": "^3.5.1" }, "bin": { "webpack": "bin/webpack.js" diff --git a/package.json b/package.json index 5011ea5452e2d..30e853bd255bd 100644 --- a/package.json +++ b/package.json @@ -1,13 +1,13 @@ { "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", "url": "https://develop.svn.wordpress.org/trunk" }, "gutenberg": { - "sha": "61aba5422836aeed76a794f98d3fe0da3eb5f5d1", + "sha": "c5bdc7f4898ec98114cdccbe1cacec7a979b85cc", "ghcrRepo": "WordPress/gutenberg/gutenberg-wp-develop-build" }, "engines": { @@ -41,24 +41,24 @@ "devDependencies": { "@343dev/gifsicle": "1.2.0", "@lodder/grunt-postcss": "^3.1.1", - "@napi-rs/image": "1.14.0", - "@playwright/test": "1.64.1", - "@pmmmwh/react-refresh-webpack-plugin": "0.6.2", + "@napi-rs/image": "1.16.0", + "@playwright/test": "1.65.1", + "@pmmmwh/react-refresh-webpack-plugin": "0.6.3", "@types/backbone": "1.4.23", - "@types/codemirror": "5.60.17", + "@types/codemirror": "5.60.18", "@types/espree": "10.1.0", "@types/htmlhint": "1.1.5", "@types/jquery": "3.5.34", - "@types/node": "20.19.43", + "@types/node": "24.19.2", "@types/underscore": "1.13.0", "@wordpress/e2e-test-utils-playwright": "1.51.0", "@wordpress/prettier-config": "4.51.0", "@wordpress/scripts": "33.0.0", - "autoprefixer": "10.5.3", + "autoprefixer": "10.6.2", "chokidar": "4.0.3", "dotenv": "17.4.2", "dotenv-expand": "13.0.0", - "grunt": "1.6.2", + "grunt": "1.6.3", "grunt-banner": "^0.6.0", "grunt-contrib-clean": "~2.0.1", "grunt-contrib-concat": "2.1.0", @@ -73,23 +73,23 @@ "grunt-replace-lts": "~1.1.0", "grunt-rtlcss": "~2.0.2", "grunt-sass": "~4.1.0", - "grunt-webpack": "7.0.1", + "grunt-webpack": "8.0.0", "install-changed": "1.1.0", "json2php": "0.0.12", - "minimizer-webpack-plugin": "5.6.1", + "minimizer-webpack-plugin": "5.14.0", "php-array-reader": "2.1.4", - "postcss": "8.5.19", + "postcss": "8.5.33", "prettier": "npm:wp-prettier@3.0.3", - "qunit": "~2.26.0", + "qunit": "3.0.0", "react-refresh": "0.14.0", - "sass": "1.101.0", + "sass": "1.108.2", "sinon": "16.1.3", "sinon-test": "~3.1.6", "source-map-loader": "5.0.0", "typescript": "6.0.3", - "update-browserslist-db": "1.3.1", - "wait-on": "9.0.10", - "webpack": "5.108.4" + "update-browserslist-db": "1.4.0", + "wait-on": "9.5.1", + "webpack": "5.109.2" }, "dependencies": { "backbone": "1.6.1", 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/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 cbaa19f3e8db1..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. @@ -18,44 +21,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/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/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/about.php b/src/wp-admin/about.php index 1bfc3018e0556..a2cf8c5ca1ec4 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 ); ?>

@@ -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/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/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/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( 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 + + + + + + diff --git a/src/wp-admin/images/arrows-2x.png b/src/wp-admin/images/arrows-2x.png index 0b0c53d1a6b19..3c1981c906fe1 100644 Binary files a/src/wp-admin/images/arrows-2x.png and b/src/wp-admin/images/arrows-2x.png differ diff --git a/src/wp-admin/images/icons32-vs-2x.png b/src/wp-admin/images/icons32-vs-2x.png index 9b2dc61f39805..25ea3d299bbb6 100644 Binary files a/src/wp-admin/images/icons32-vs-2x.png and b/src/wp-admin/images/icons32-vs-2x.png differ diff --git a/src/wp-admin/images/list-2x.png b/src/wp-admin/images/list-2x.png index 05c6eb37ffda0..451116870fa82 100644 Binary files a/src/wp-admin/images/list-2x.png and b/src/wp-admin/images/list-2x.png differ diff --git a/src/wp-admin/images/list.png b/src/wp-admin/images/list.png index 85d1295e8131f..6386e484657ea 100644 Binary files a/src/wp-admin/images/list.png and b/src/wp-admin/images/list.png differ diff --git a/src/wp-admin/images/media-button-2x.png b/src/wp-admin/images/media-button-2x.png index b8f8ed4df8c50..88d1755f07625 100644 Binary files a/src/wp-admin/images/media-button-2x.png and b/src/wp-admin/images/media-button-2x.png differ diff --git a/src/wp-admin/images/no.png b/src/wp-admin/images/no.png index 59c35bdccc6d4..3e63e3ea242ab 100644 Binary files a/src/wp-admin/images/no.png and b/src/wp-admin/images/no.png differ diff --git a/src/wp-admin/images/w-logo-blue.png b/src/wp-admin/images/w-logo-blue.png index 11e550c74e07c..ad3e07cc4beb0 100644 Binary files a/src/wp-admin/images/w-logo-blue.png and b/src/wp-admin/images/w-logo-blue.png differ diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index 076549b218b82..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.) } /** @@ -1310,12 +1312,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( @@ -2663,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']; @@ -2684,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; @@ -2783,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'] ) ) { @@ -2828,8 +2855,6 @@ function wp_ajax_set_attachment_thumbnail() { } else { wp_send_json_success(); } - - wp_send_json_error(); } /** 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/comment.php b/src/wp-admin/includes/comment.php index 1cfc93144e978..49c2b3d32c421 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,55 @@ function edit_comment() { $_POST['comment_ID'] = (int) $_POST['comment_ID']; } + $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 + * 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.' ) ); @@ -97,10 +140,10 @@ 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 !== (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 ) @@ -158,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'; @@ -183,6 +239,85 @@ 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.' ) ); + } + + // 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; +} + /** * Returns a WP_Comment object based on comment ID. * 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/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/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-admin/includes/privacy-tools.php b/src/wp-admin/includes/privacy-tools.php index 17e660c8c0d0e..f0a53f265185c 100644 --- a/src/wp-admin/includes/privacy-tools.php +++ b/src/wp-admin/includes/privacy-tools.php @@ -587,6 +587,7 @@ function wp_privacy_generate_personal_data_export_file( $request_id ) { * Send an email to the user with a link to the personal data export file * * @since 4.9.6 + * @since 7.2.0 Returns a `WP_Error` if the request is not confirmed or completed. * * @param int $request_id The request ID for this personal data export. * @return true|WP_Error True on success or `WP_Error` on failure. @@ -599,6 +600,10 @@ function wp_privacy_send_personal_data_export_email( $request_id ) { return new WP_Error( 'invalid_request', __( 'Invalid request ID when sending personal data export email.' ) ); } + if ( ! in_array( $request->status, array( 'request-confirmed', 'request-completed' ), true ) ) { + return new WP_Error( 'invalid_request', __( 'Invalid request status when sending personal data export email.' ) ); + } + // Localize message content for user; fallback to site default for visitors. if ( ! empty( $request->user_id ) ) { $switched_locale = switch_to_user_locale( $request->user_id ); 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-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', ); 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-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-content/themes/ipsum/screenshot.jpg b/src/wp-content/themes/ipsum/screenshot.jpg index ef35dbd2410c7..e429a7485398b 100644 Binary files a/src/wp-content/themes/ipsum/screenshot.jpg and b/src/wp-content/themes/ipsum/screenshot.jpg differ 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/twentyeleven/images/comment-arrow-dark.png b/src/wp-content/themes/twentyeleven/images/comment-arrow-dark.png index f9b624be92ad5..5fc0424e29bd8 100644 Binary files a/src/wp-content/themes/twentyeleven/images/comment-arrow-dark.png and b/src/wp-content/themes/twentyeleven/images/comment-arrow-dark.png differ diff --git a/src/wp-content/themes/twentyeleven/images/comment-bubble-dark-rtl.png b/src/wp-content/themes/twentyeleven/images/comment-bubble-dark-rtl.png index f8c5061eb87c1..2af9cca6dc37a 100644 Binary files a/src/wp-content/themes/twentyeleven/images/comment-bubble-dark-rtl.png and b/src/wp-content/themes/twentyeleven/images/comment-bubble-dark-rtl.png differ diff --git a/src/wp-content/themes/twentyeleven/images/comment-bubble-dark.png b/src/wp-content/themes/twentyeleven/images/comment-bubble-dark.png index 2d1ca1a269d00..399dafda89e27 100644 Binary files a/src/wp-content/themes/twentyeleven/images/comment-bubble-dark.png and b/src/wp-content/themes/twentyeleven/images/comment-bubble-dark.png differ diff --git a/src/wp-content/themes/twentyeleven/images/comment-bubble-rtl.png b/src/wp-content/themes/twentyeleven/images/comment-bubble-rtl.png index 55ff63fbbe37f..3dd3d8009e7a6 100644 Binary files a/src/wp-content/themes/twentyeleven/images/comment-bubble-rtl.png and b/src/wp-content/themes/twentyeleven/images/comment-bubble-rtl.png differ diff --git a/src/wp-content/themes/twentyeleven/images/comment-bubble.png b/src/wp-content/themes/twentyeleven/images/comment-bubble.png index 1798846a5ade6..c0e13edf55e1e 100644 Binary files a/src/wp-content/themes/twentyeleven/images/comment-bubble.png and b/src/wp-content/themes/twentyeleven/images/comment-bubble.png differ diff --git a/src/wp-content/themes/twentyeleven/images/search.png b/src/wp-content/themes/twentyeleven/images/search.png index 5036704b959b1..e407448d8de26 100644 Binary files a/src/wp-content/themes/twentyeleven/images/search.png and b/src/wp-content/themes/twentyeleven/images/search.png differ diff --git a/src/wp-content/themes/twentyeleven/images/wordpress.png b/src/wp-content/themes/twentyeleven/images/wordpress.png index 4a15056adb872..bc5f40d97f0fc 100644 Binary files a/src/wp-content/themes/twentyeleven/images/wordpress.png and b/src/wp-content/themes/twentyeleven/images/wordpress.png differ 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/twentyten/images/wordpress.png b/src/wp-content/themes/twentyten/images/wordpress.png index ac9d227805c22..bc5f40d97f0fc 100644 Binary files a/src/wp-content/themes/twentyten/images/wordpress.png and b/src/wp-content/themes/twentyten/images/wordpress.png differ 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/twentythirteen/images/search-icon-2x.png b/src/wp-content/themes/twentythirteen/images/search-icon-2x.png index 02b63b8027efb..6903b9f9a9bb3 100644 Binary files a/src/wp-content/themes/twentythirteen/images/search-icon-2x.png and b/src/wp-content/themes/twentythirteen/images/search-icon-2x.png differ diff --git a/src/wp-content/themes/twentythirteen/images/search-icon.png b/src/wp-content/themes/twentythirteen/images/search-icon.png index 11d8dc8e508ef..63cc3f4791c5c 100644 Binary files a/src/wp-content/themes/twentythirteen/images/search-icon.png and b/src/wp-content/themes/twentythirteen/images/search-icon.png differ 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' ); } diff --git a/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-a.png b/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-a.png index e89c08688f05e..6701875333217 100644 Binary files a/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-a.png and b/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-a.png differ diff --git a/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-b.png b/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-b.png index 00dfd88af328f..abec60558dde3 100644 Binary files a/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-b.png and b/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-b.png differ diff --git a/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-c.png b/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-c.png index 5cb608fbd2e6b..73ffd9365b965 100644 Binary files a/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-c.png and b/src/wp-content/themes/twentytwentytwo/assets/images/flight-path-on-transparent-c.png differ 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/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/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/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/src/wp-includes/assets/script-loader-packages.php b/src/wp-includes/assets/script-loader-packages.php index 9512d25d2c5ce..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' => '8118001470fde50b42fe' + 'version' => '9ad7f7e62e9fbecbab34' ), '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' => '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/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/src/wp-includes/blocks.php b/src/wp-includes/blocks.php index ba63ddc331636..3b6ee11138000 100644 --- a/src/wp-includes/blocks.php +++ b/src/wp-includes/blocks.php @@ -2356,24 +2356,147 @@ function excerpt_remove_blocks( $content ) { } /** - * Parses footnotes markup out of a content string, - * and renders those appropriate for the excerpt. + * Removes recognized footnote reference markup from a given string. + * + * Example: + * + * $content = 'Never1 say never.'; + * 'Never say never' === excerpt_remove_footnotes( $content ); * * @since 6.3.0 * - * @param string $content The content to parse. - * @return string The parsed and filtered content. + * @param string $content HTML which might contain footnote references from the block editor. + * @return string Given input HTML without the footnote references. */ function excerpt_remove_footnotes( $content ) { - if ( ! str_contains( $content, 'data-fn=' ) ) { + if ( ! str_contains( $content, 'data-fn' ) ) { return $content; } - return preg_replace( - '_\s*\d+\s*_', - '', - $content - ); + $processor = new class( $content ) extends WP_HTML_Tag_Processor { + public function is_whitespace_text_node(): bool { + if ( self::STATE_TEXT_NODE !== $this->parser_state ) { + return false; + } + + $this->subdivide_text_appropriately(); + return self::TEXT_IS_WHITESPACE === $this->text_node_classification; + } + + public function get_span(): WP_HTML_Span { + $this->set_bookmark( 'here' ); + + return $this->bookmarks['here']; + } + }; + + $output = ''; + $at = 0; + $reprocess_token = false; + + while ( $reprocess_token || $processor->next_token() ) { + $reprocess_token = false; + + // Match the opening tag. + if ( + $processor->is_tag_closer() || + 'SUP' !== $processor->get_tag() || + null === $processor->get_attribute( 'data-fn' ) || + null === $processor->get_attribute( 'class' ) + ) { + continue; + } + + $footnote_opening = $processor->get_span(); + + if ( ! $processor->next_token() ) { + break; + } + + // Skip any whitespace-only text between the tags. + if ( '#text' === $processor->get_token_name() ) { + if ( ! $processor->is_whitespace_text_node() ) { + $reprocess_token = true; + continue; + } + + $processor->next_token(); + } + + // Match the opening tag. + if ( + $processor->is_tag_closer() || + 'A' !== $processor->get_token_name() || + null === $processor->get_attribute( 'href' ) || + null === $processor->get_attribute( 'id' ) + ) { + $reprocess_token = true; + continue; + } + + // Match an all-digit text node. + if ( ! $processor->next_token() || '#text' !== $processor->get_token_name() ) { + $reprocess_token = true; + continue; + } + + $footnote_number = $processor->get_modifiable_text(); + $digit_count = strspn( $footnote_number, '0123456789' ); + if ( 0 === $digit_count || strlen( $footnote_number ) !== $digit_count ) { + $reprocess_token = true; + continue; + } + + // Match the closing tag. + if ( + ! $processor->next_token() || + 'A' !== $processor->get_token_name() || + ! $processor->is_tag_closer() + ) { + $reprocess_token = true; + continue; + } + + if ( ! $processor->next_token() ) { + break; + } + + // Skip any whitespace-only text between the tags. + if ( '#text' === $processor->get_token_name() ) { + if ( ! $processor->is_whitespace_text_node() ) { + $reprocess_token = true; + continue; + } + + $processor->next_token(); + } + + // Match the closing tag. + if ( + 'SUP' !== $processor->get_token_name() || + ! $processor->is_tag_closer() + ) { + $reprocess_token = true; + continue; + } + + $footnote_closing = $processor->get_span(); + + // Remove the section and continue. + $output .= substr( $content, $at, $footnote_opening->start - $at ); + $at = $footnote_closing->start + $footnote_closing->length; + } + + // No footnotes were found and removed: return the original input. + if ( 0 === $at ) { + return $content; + } + + if ( $at < strlen( $content ) ) { + $output .= substr( $content, $at ); + } + + return $output; } /** 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( 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/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 @@ 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-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 ) ); } /** diff --git a/src/wp-includes/class-wp-customize-setting.php b/src/wp-includes/class-wp-customize-setting.php index 2658eb20fd02d..77a544bfbae0e 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. * @@ -178,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 ) ); @@ -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; + } + + /** @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->update( $value ); + $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/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-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/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 diff --git a/src/wp-includes/class-wp-http-curl.php b/src/wp-includes/class-wp-http-curl.php index 4296bf42f2b00..cb6a9ac6056c4 100644 --- a/src/wp-includes/class-wp-http-curl.php +++ b/src/wp-includes/class-wp-http-curl.php @@ -228,6 +228,7 @@ public function request( $url, $args = array() ) { * plugins to handle cookies themselves. * * @since 2.8.0 + * @since 7.3.0 Also fires for each request sent by {@see WP_Http::request_multiple()}. * * @param resource $handle The cURL handle returned by curl_init() (passed by reference). * @param array $parsed_args The HTTP request arguments. diff --git a/src/wp-includes/class-wp-http-requests-hooks.php b/src/wp-includes/class-wp-http-requests-hooks.php index aac172892f293..be6341ec27ebb 100644 --- a/src/wp-includes/class-wp-http-requests-hooks.php +++ b/src/wp-includes/class-wp-http-requests-hooks.php @@ -53,7 +53,12 @@ public function dispatch( $hook, $parameters = array() ) { // Handle back-compat actions. switch ( $hook ) { + /** + * Requests fires 'curl.before_multi_add' instead of 'curl.before_send' for the + * requests of a batch, see {@see WP_Http::request_multiple()}. + */ case 'curl.before_send': + case 'curl.before_multi_add': /** This action is documented in wp-includes/class-wp-http-curl.php */ do_action_ref_array( 'http_api_curl', array( &$parameters[0], $this->request, $this->url ) ); break; diff --git a/src/wp-includes/class-wp-http.php b/src/wp-includes/class-wp-http.php index 66cf907d0e00a..681b501a37aff 100644 --- a/src/wp-includes/class-wp-http.php +++ b/src/wp-includes/class-wp-http.php @@ -29,6 +29,64 @@ * 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, + * } + * @phpstan-type HTTP_Request_Args array{ + * method?: string, + * timeout?: float|int, + * redirection?: int, + * httpversion?: string, + * 'user-agent'?: string, + * reject_unsafe_urls?: bool, + * blocking?: bool, + * headers?: string|mixed[]|null, + * cookies?: mixed[], + * body?: string|mixed[]|null, + * compress?: bool, + * decompress?: bool, + * sslverify?: bool, + * sslcertificates?: string, + * stream?: bool, + * filename?: string|null, + * limit_response_size?: int|null, + * ... + * } + * @phpstan-type Parsed_HTTP_Request_Args array{ + * method: string, + * timeout: float|int, + * redirection: int, + * httpversion: string, + * 'user-agent': string, + * reject_unsafe_urls: bool, + * blocking: bool, + * headers: string|mixed[]|null, + * cookies: mixed[], + * body: string|mixed[]|null, + * compress: bool, + * decompress: bool, + * sslverify: bool, + * sslcertificates: string, + * stream: bool, + * filename: string|null, + * limit_response_size: int|null, + * _redirection: int, + * ... + * } + * @phpstan-type Prepared_Request array{ + * url: string, + * headers: mixed[], + * data: mixed, + * type: mixed, + * options: array, + * args: Parsed_HTTP_Request_Args, + * } */ #[AllowDynamicProperties] class WP_Http { @@ -166,8 +224,235 @@ class WP_Http { * @type string|null $filename Optional. Filename of the response. * @type WP_HTTP_Requests_Response|null $http_response Response object. * } + * + * @phpstan-param string|HTTP_Request_Args $args + * @phpstan-return HTTP_Response|WP_Error */ public function request( $url, $args = array() ) { + if ( ! is_array( $args ) ) { + $args = wp_parse_args( $args ); + } + + $prepared = $this->prepare_request( $url, $args ); + + if ( is_wp_error( $prepared ) ) { + return $prepared; + } + + // The request was short-circuited by the 'pre_http_request' filter. + if ( array_key_exists( 'response', $prepared ) ) { + return $prepared['response']; + } + + // Avoid issues where mbstring.func_overload is enabled. + mbstring_binary_safe_encoding(); + + try { + $response = WpOrg\Requests\Requests::request( + $prepared['url'], + $prepared['headers'], + $prepared['data'], + $prepared['type'], + $prepared['options'] + ); + } catch ( WpOrg\Requests\Exception $e ) { + $response = new WP_Error( 'http_request_failed', $e->getMessage() ); + } finally { + reset_mbstring_encoding(); + } + + return $this->finalize_response( $response, $prepared['args'], $prepared['url'] ); + } + + /** + * Sends multiple HTTP requests concurrently and returns their responses. + * + * Every request is prepared, and its response processed, exactly like a request + * sent through WP_Http::request(): the 'http_request_args', 'pre_http_request' and + * 'http_response' filters and the 'http_api_debug' action apply to each request + * individually. The requests that were not short-circuited are then sent side by + * side, at most $concurrency at a time. + * + * Non-blocking requests are not supported: every request is performed in full. + * + * @since 7.3.0 + * + * @see WP_Http::request() For the accepted request arguments and the response format. + * + * @param array $requests Requests to send, keyed by an identifier of the caller's choosing. + * Each request is either a URL string, for a GET request with the + * default arguments, or an array with the request URL under 'url' + * and, optionally, the request arguments under 'args'. + * See {@see WP_Http::request()} for the accepted request arguments. + * @param array $options { + * Optional. Options that apply to the batch of requests. + * + * @type int $concurrency Maximum number of requests to send at once. Default 6. Minimum 1. + * } + * @return array Responses keyed like $requests. Each is a response array, or a WP_Error + * on failure. See {@see WP_Http::request()} for the response format. + * @phpstan-param array $requests + * @phpstan-return array + */ + public function request_multiple( array $requests, array $options = array() ): array { + $responses = array(); + $pending = array(); + + foreach ( $requests as $id => $request ) { + if ( ! is_array( $request ) ) { + $request = array( 'url' => $request ); + } + + $url = $request['url'] ?? ''; + $args = $request['args'] ?? array(); + + if ( ! is_array( $args ) ) { + $args = wp_parse_args( $args ); + } + + // Batches cannot send non-blocking requests, each request is performed in full. + $args['blocking'] = true; + + $prepared = $this->prepare_request( $url, $args ); + + if ( is_wp_error( $prepared ) ) { + $responses[ $id ] = $prepared; + } elseif ( array_key_exists( 'response', $prepared ) ) { + // The request was short-circuited by the 'pre_http_request' filter. + $responses[ $id ] = $prepared['response']; + } else { + $pending[ $id ] = $prepared; + } + } + + if ( ! empty( $pending ) ) { + $concurrency = max( 1, (int) ( $options['concurrency'] ?? 6 ) ); + + /** + * Filters the maximum number of HTTP requests that WP_Http::request_multiple() sends at once. + * + * @since 7.3.0 + * + * @param int $concurrency Maximum number of requests to send at once. Default 6. Minimum 1. + * @param array $requests The requests to send. See WP_Http::request_multiple(). + * @phpstan-param positive-int $concurrency + * @phpstan-param array $requests + */ + $concurrency = (int) apply_filters( 'http_request_multiple_concurrency', $concurrency, $requests ); + $concurrency = max( 1, $concurrency ); + + foreach ( array_chunk( $pending, $concurrency, true ) as $batch ) { + $results = array(); + $batch_requests = array(); + + // Avoid issues where mbstring.func_overload is enabled. + mbstring_binary_safe_encoding(); + + try { + 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 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. + */ + foreach ( $batch as $id => $prepared ) { + if ( ! isset( $results[ $id ] ) ) { + $results[ $id ] = $e; + } + } + } finally { + reset_mbstring_encoding(); + } + + foreach ( $batch as $id => $prepared ) { + if ( isset( $results[ $id ] ) ) { + $result = $results[ $id ]; + } else { + $result = new WP_Error( 'http_request_failed', __( 'No response was received.' ) ); + } + + $responses[ $id ] = $this->finalize_response( $result, $prepared['args'], $prepared['url'] ); + } + } + } + + // Return the responses in the order the requests were given. + $ordered = array(); + + foreach ( $requests as $id => $request ) { + $ordered[ $id ] = $responses[ $id ]; + } + + return $ordered; + } + + /** + * Prepares a request for the Requests library. + * + * Parses and filters the request arguments, lets the 'pre_http_request' filter + * short-circuit the request, validates the URL, checks whether the request is + * blocked, and translates the arguments into options for the Requests library. + * + * @since 7.3.0 + * + * @param string $url The request URL. + * @param array $args Optional. Request arguments. See {@see WP_Http::request()}. + * @return array|WP_Error { + * The prepared request, or a WP_Error if the request cannot be sent. If the request was + * short-circuited by the 'pre_http_request' filter, only the 'response' key is present. + * + * @type string $url The validated request URL. + * @type array $headers Request headers. + * @type mixed $data Request body. + * @type string $type Request method. + * @type array $options Options for the Requests library. + * @type array $args The parsed request arguments, after the 'http_request_args' filter. + * @type array|WP_Error $response Optional. The response returned by the 'pre_http_request' filter. + * } + * @phpstan-param HTTP_Request_Args $args + * @phpstan-return Prepared_Request|array{ response: HTTP_Response|WP_Error }|WP_Error + */ + protected function prepare_request( $url, array $args = array() ) { $defaults = array( 'method' => 'GET', /** @@ -233,9 +518,6 @@ public function request( $url, $args = array() ) { 'limit_response_size' => null, ); - // Pre-parse for the HEAD checks. - $args = wp_parse_args( $args ); - // By default, HEAD requests do not cause redirections. if ( isset( $args['method'] ) && 'HEAD' === $args['method'] ) { $defaults['redirection'] = 0; @@ -274,11 +556,14 @@ public function request( $url, $args = array() ) { * @param false|array|WP_Error $response A preemptive return value of an HTTP request. Default false. * @param array $parsed_args HTTP request arguments. * @param string $url The request URL. + * @phpstan-param false|HTTP_Response|WP_Error $response */ $pre = apply_filters( 'pre_http_request', false, $parsed_args, $url ); if ( false !== $pre ) { - return $pre; + return array( + 'response' => $pre, + ); } if ( function_exists( 'wp_kses_bad_protocol' ) ) { @@ -410,24 +695,46 @@ public function request( $url, $args = array() ) { } } - // Avoid issues where mbstring.func_overload is enabled. - mbstring_binary_safe_encoding(); + return array( + 'url' => $url, + 'headers' => $headers, + 'data' => $data, + 'type' => $type, + 'options' => $options, + 'args' => $parsed_args, + ); + } - try { - $requests_response = WpOrg\Requests\Requests::request( $url, $headers, $data, $type, $options ); + /** + * Turns the result of a request into a WP_Http response array. + * + * Fires the 'http_api_debug' action and applies the 'http_response' filter. + * + * @since 7.3.0 + * + * @param \WpOrg\Requests\Response|\WpOrg\Requests\Exception|WP_Error $response The response, or the error the + * request failed with. + * @param mixed[] $parsed_args The parsed request arguments, as + * returned by {@see WP_Http::prepare_request()}. + * @param string $url The request URL. + * @return array|WP_Error The response array, or a WP_Error on failure. See {@see WP_Http::request()}. + * @phpstan-param Parsed_HTTP_Request_Args $parsed_args + * @phpstan-return HTTP_Response|WP_Error + */ + protected function finalize_response( $response, array $parsed_args, string $url ) { + if ( $response instanceof WpOrg\Requests\Exception ) { + $response = new WP_Error( 'http_request_failed', $response->getMessage() ); + } + if ( ! is_wp_error( $response ) ) { // Convert the response into an array. - $http_response = new WP_HTTP_Requests_Response( $requests_response, $parsed_args['filename'] ); + $http_response = new WP_HTTP_Requests_Response( $response, $parsed_args['filename'] ); $response = $http_response->to_array(); // Add the original object to the array. $response['http_response'] = $http_response; - } catch ( WpOrg\Requests\Exception $e ) { - $response = new WP_Error( 'http_request_failed', $e->getMessage() ); } - reset_mbstring_encoding(); - /** * Fires after an HTTP API response is received and before the response is returned. * @@ -647,6 +954,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 +974,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 +994,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-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-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. 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-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 ); 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"; 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 15d08fba457a9..85dc55bce5501 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. @@ -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/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/class-wp-xmlrpc-server.php b/src/wp-includes/class-wp-xmlrpc-server.php index 4ac680065f036..56448aa6e2520 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 * @@ -1243,6 +1254,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 +1269,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 +3798,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 +3809,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 +3841,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 ); } } @@ -3930,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.' ) ); } @@ -3938,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( @@ -7067,6 +7115,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 ); 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/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/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 ecae45083a6ca..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 ); @@ -2835,6 +2837,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 +3009,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 = ''; @@ -4965,6 +4970,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 +5211,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'; diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index d9927baffbcd5..9f05a8c592a86 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 ''; @@ -8379,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 { @@ -9641,6 +9657,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 +9742,8 @@ function wp_application_password_created_notification( $user_id, $new_item ) { $email['message'], $email['headers'] ); + + if ( $switched_locale ) { + restore_previous_locale(); + } } diff --git a/src/wp-includes/html-api/class-wp-html-tag-processor.php b/src/wp-includes/html-api/class-wp-html-tag-processor.php index 7e047c4808081..34429f2b31aed 100644 --- a/src/wp-includes/html-api/class-wp-html-tag-processor.php +++ b/src/wp-includes/html-api/class-wp-html-tag-processor.php @@ -956,6 +956,8 @@ public function next_tag( $query = null ): bool { * @since 7.1.0 Recognizes processing instructions. * * @return bool Whether a token was parsed. + * + * @phpstan-impure */ public function next_token(): bool { return $this->base_class_next_token(); diff --git a/src/wp-includes/http.php b/src/wp-includes/http.php index 34e1f452a797f..5796edb36176d 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; @@ -142,6 +178,56 @@ function wp_safe_remote_head( $url, $args = array() ) { return $http->head( $url, $args ); } +/** + * Performs multiple HTTP requests concurrently using the safe variant of the HTTP API. + * + * Like wp_remote_request_multiple(), but every URL is validated to avoid redirection + * and request forgery attacks. See wp_safe_remote_request(). + * + * @since 7.3.0 + * + * @see wp_remote_request_multiple() For information on the request and response format. + * + * @param array $requests Requests to send. See {@see wp_remote_request_multiple()}. + * @param array $options { + * Optional. Options that apply to the batch of requests. See {@see WP_Http::request_multiple()}. + * Default empty array. + * + * @type int $concurrency Maximum number of requests to send at once. Default 6. + * } + * @return array Responses keyed like $requests. Each is a response array, or a WP_Error on failure. + * @phpstan-param array $requests + * @phpstan-return 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_multiple( array $requests, array $options = array() ): array { + foreach ( $requests as $id => $request ) { + if ( ! is_array( $request ) ) { + $request = array( 'url' => $request ); + } + + $args = $request['args'] ?? array(); + + if ( ! is_array( $args ) ) { + $args = wp_parse_args( $args ); + } + + $args['reject_unsafe_urls'] = true; + $request['args'] = $args; + + $requests[ $id ] = $request; + } + + $http = _wp_http_get_object(); + return $http->request_multiple( $requests, $options ); +} + /** * Performs an HTTP request and returns its response. * @@ -162,6 +248,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 +278,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 +308,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,12 +338,61 @@ 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(); return $http->head( $url, $args ); } +/** + * Performs multiple HTTP requests concurrently and returns their responses. + * + * The requests are sent side by side rather than one after the other, so a batch of + * requests takes about as long as its slowest request instead of the sum of all of them. + * + * Each request is filtered, and its response processed, individually and exactly as + * if it had been sent with wp_remote_request(). + * + * @since 7.3.0 + * + * @see WP_Http::request_multiple() For information on the request format and the batch options. + * @see WP_Http::request() For information on accepted request arguments and the response format. + * + * @param array $requests Requests to send, keyed by an identifier of the caller's choosing. + * Each request is either a URL string, for a GET request with the + * default arguments, or an array with a 'url' key and an optional + * 'args' key holding the request arguments. + * @param array $options { + * Optional. Options that apply to the batch of requests. See {@see WP_Http::request_multiple()}. + * Default empty array. + * + * @type int $concurrency Maximum number of requests to send at once. Default 6. + * } + * @return array Responses keyed like $requests. Each is a response array, or a WP_Error on failure. + * @phpstan-param array $requests + * @phpstan-return 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_multiple( array $requests, array $options = array() ): array { + $http = _wp_http_get_object(); + return $http->request_multiple( $requests, $options ); +} + /** * Retrieves only the headers from the raw response. * diff --git a/src/wp-includes/images/crystal/archive.png b/src/wp-includes/images/crystal/archive.png index ca038c7dac562..853594a6c9ba3 100644 Binary files a/src/wp-includes/images/crystal/archive.png and b/src/wp-includes/images/crystal/archive.png differ diff --git a/src/wp-includes/images/crystal/interactive.png b/src/wp-includes/images/crystal/interactive.png index 184e76ab9cbbe..4d1778daab6b5 100644 Binary files a/src/wp-includes/images/crystal/interactive.png and b/src/wp-includes/images/crystal/interactive.png differ diff --git a/src/wp-includes/images/crystal/spreadsheet.png b/src/wp-includes/images/crystal/spreadsheet.png index bae1f6d11b143..da1c7230b866b 100644 Binary files a/src/wp-includes/images/crystal/spreadsheet.png and b/src/wp-includes/images/crystal/spreadsheet.png differ diff --git a/src/wp-includes/images/icon-library/update.svg b/src/wp-includes/images/icon-library/update.svg index abf7d3491b6ce..0658ad2f1ed6d 100644 --- a/src/wp-includes/images/icon-library/update.svg +++ b/src/wp-includes/images/icon-library/update.svg @@ -1,3 +1,4 @@ - + + diff --git a/src/wp-includes/images/w-logo-blue.png b/src/wp-includes/images/w-logo-blue.png index 11e550c74e07c..ad3e07cc4beb0 100644 Binary files a/src/wp-includes/images/w-logo-blue.png and b/src/wp-includes/images/w-logo-blue.png differ 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 ) ) . '\''; } diff --git a/src/wp-includes/load.php b/src/wp-includes/load.php index ce309d2ecd2ae..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() ) { @@ -2007,7 +2013,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 ]; diff --git a/src/wp-includes/ms-files.php b/src/wp-includes/ms-files.php index d17d9f95f7e35..497cc43e8083a 100644 --- a/src/wp-includes/ms-files.php +++ b/src/wp-includes/ms-files.php @@ -30,6 +30,11 @@ die( '500 — Directory not configured.' ); } +if ( ! isset( $_GET['file'] ) || ! is_string( $_GET['file'] ) ) { + status_header( 404 ); + die( '404 — File not found.' ); +} + $file = rtrim( BLOGUPLOADDIR, '/' ) . '/' . str_replace( '..', '', $_GET['file'] ); if ( ! is_file( $file ) ) { status_header( 404 ); 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. */ diff --git a/src/wp-includes/nav-menu.php b/src/wp-includes/nav-menu.php index 40612d5b8d937..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; @@ -734,12 +734,8 @@ function wp_get_nav_menu_items( $menu, $args = array() ) { ), ); $args = wp_parse_args( $args, $defaults ); - if ( $menu->count > 0 ) { - $items = get_posts( $args ); - } else { - $items = array(); - } + $items = get_posts( $args ); $items = array_map( 'wp_setup_nav_menu_item', $items ); if ( ! is_admin() ) { // Remove invalid items only on front end. diff --git a/src/wp-includes/pluggable.php b/src/wp-includes/pluggable.php index 0aaeabbb3b9c0..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 ) { @@ -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; @@ -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 ) { @@ -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,11 +1927,14 @@ 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"; - /* 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( __( 'Email: %s' ), $comment_author_email ) . "\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 ); @@ -1928,11 +1944,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 +2072,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 +2122,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 +2134,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 +2146,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. */ @@ -2477,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 f8d5e0a383e81..4438594baeda3 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; } @@ -1550,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/rest-api/endpoints/class-wp-rest-comments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php index f5739e6b3a3f3..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 @@ -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. */ @@ -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', @@ -1168,6 +1179,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 +1244,49 @@ 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 + * 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 ) ) { @@ -1983,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, ), @@ -2162,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, ), ); @@ -2347,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 ) { @@ -2385,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; } } @@ -2459,6 +2547,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. * @@ -2660,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/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/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.' ), 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' ); 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/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/shortcodes.php b/src/wp-includes/shortcodes.php index d6bb8db1e6b91..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, '[' ) ) { @@ -616,6 +618,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 +626,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] ); } } 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/src/wp-includes/version.php b/src/wp-includes/version.php index 31eacd36c6a5f..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-beta5-65392-src'; +$wp_version = '7.3-alpha-65762-src'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. 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/e2e/README.md b/tests/e2e/README.md index b4dece7e23667..b0bf60e2ebafa 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -1 +1,121 @@ -# E2E Tests End-To-End (E2E) tests for WordPress. ## Running the tests The e2e tests require a production-like environment to run. By default, they will assume an environment is available at `http://localhost:8889`, with username `admin` and password `password`. If you don't already have an environment ready, you can set one up by following [these instructions](https://github.com/WordPress/wordpress-develop/blob/master/README.md). Then you can launch the tests by running: ``` npm run test:e2e ``` which will run the test suite using a headless browser. If your environment has a different url, username or password to the default, you can provide the base URL, username and password like this: ``` WP_BASE_URL=http://mycustomurl WP_USERNAME=username WP_PASSWORD=password npm run test:e2e ``` **DO NOT run these tests in an actual production environment, as they will delete all your content.** For debugging purposes, you might want to follow the test visually. You can do so by running the tests in an interactive mode: ``` npm run test:e2e -- --ui ``` [UI Mode](https://playwright.dev/docs/test-ui-mode) let's you explore, run and debug tests with a time travel experience complete with watch mode. All test files are loaded into the testing sidebar where you can expand each file and describe block to individually run, view, watch and debug each test. You can also run a single test file separately: ``` npm run test:e2e tests/e2e/specs/hello.test.js ``` ## Projects The suite has three Playwright projects, defined in `playwright.config.js`: * `all`: every spec, one at a time on one worker. `npm run test:e2e` runs this project. * `parallel`: specs that can share the site with other tests. Tests run at the same time on several workers, one for every two CPU cores. Run it with `npm run test:e2e -- --project=parallel`. * `serial`: specs that break the site for other tests. They run one at a time on one worker. Run it with `npm run test:e2e -- --project=serial`. CI runs `parallel` and `serial` in separate jobs. New specs go in `parallel` by default. Add a spec to `SERIAL_SPECS` if it makes the site unusable for other tests. If it changes content or settings that other tests use, for example with `requestUtils.deleteAllPosts()`, follow [Parallel safety](#parallel-safety). Before you open a pull request with a new spec, run its project a few times with `--shuffle`. Playwright then runs the spec files in a random order, so a spec that needs another spec to run first, or that breaks a spec that runs after it, fails: ``` npm run test:e2e -- --project=parallel --shuffle ``` Playwright prints the seed of each run, for example `shuffle seed 317753389`. To run the same order again, give the seed: `--shuffle 317753389`. ## Parallel safety Specs in `parallel` share one site. A test that changes shared data can break another test that runs at the same time. The `parallel` project sets `fullyParallel: true`, so this can be a test in another file or a test in the same file. To make a spec safe, use the first of these that works: 1. Scope the data. Let the test create its own data, for example a post with a unique title, and read only that data. 2. If the test must change shared data, such as a site setting, give it a lock. Do this only if every spec that writes the same data holds the same lock. 3. If you cannot lock every spec that writes the data, add the spec to `SERIAL_SPECS`. A lock is a name. Playwright never runs two tests that hold the same lock name at the same time. A lock on a `describe` group applies to each test in the group, not to the group as a whole. A lock only schedules tests. It does not isolate data: a test without the lock can still change the data while a locked test runs. The lock names are in `utils/locks.js`. Import the constant, so that all specs use the same name. Playwright gives no error for a lock name that no other test uses, or for an import name that is not in `utils/locks.js`: ``` import { GENERAL_SETTINGS } from '../utils/locks'; 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. ## Logged-out pages Most specs run logged in as the admin user. There are two ways to run a test logged out: * To make the `page` of a whole `describe` group logged out, add `test.use( { storageState: { cookies: [], origins: [] } } )` to the group. See `specs/dashboard.test.js`. * To use a logged-out page next to the logged-in `page` in one test, import `test` and `expect` from `../fixtures` and use the `loggedOutPage` fixture. Its browser context has no cookies, and it closes when the test ends. Unlike `page`, it resolves a URL that starts with `/` against the host only, not the full `WP_BASE_URL`, so it does not work with a site in a subdirectory. See `specs/cache-control-headers-directives.test.js`. ## Fixtures To create posts, pages or users, to upload attachments, or to change a setting, an option, or a must-use plugin, import `test` and `expect` from `../fixtures`, and use one of the fixtures below. Each fixture cleans up when the test ends, also if the test fails. If the cleanup fails, the test fails. * `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`. * `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`. If the test changes a setting or an option through a form, first call `remember` with an array of the keys that the form changes. The fixture then reads the current value, without a write, and restores it when the test ends. `remember` returns the current values. A fixture goes in `fixtures/` only when 2 or more spec files use it. A fixture that only one spec uses stays in that spec. ## Documentation * Block Editor Handbook end to end testing overview: https://developer.wordpress.org/block-editor/contributors/code/testing-overview/#end-to-end-testing * Gutenberg e2e-test-utils-playwright package API docs: https://github.com/WordPress/gutenberg/tree/trunk/packages/e2e-test-utils-playwright * Playwright API docs: https://playwright.dev/docs (the version we are using is indicated in the `@wordpress/scripts` package: https://github.com/WordPress/gutenberg/blob/trunk/packages/scripts/package.json) \ No newline at end of file +# E2E Tests + +End-To-End (E2E) tests for WordPress. + + +## Running the tests + +The e2e tests require a production-like environment to run. By default, they will assume an environment is available at `http://localhost:8889`, with username `admin` and password `password`. + +If you don't already have an environment ready, you can set one up by following [these instructions](https://github.com/WordPress/wordpress-develop/blob/master/README.md). + +Then you can launch the tests by running: + +``` +npm run test:e2e +``` + +which will run the test suite using a headless browser. + +If your environment has a different url, username or password to the default, you can provide the base URL, username and password like this: + +``` +WP_BASE_URL=http://mycustomurl WP_USERNAME=username WP_PASSWORD=password npm run test:e2e +``` +**DO NOT run these tests in an actual production environment, as they will delete all your content.** + +For debugging purposes, you might want to follow the test visually. You can do so by running the tests in an interactive mode: + +``` +npm run test:e2e -- --ui +``` + +[UI Mode](https://playwright.dev/docs/test-ui-mode) let's you explore, run and debug tests with a time travel experience complete with watch mode. +All test files are loaded into the testing sidebar where you can expand each file and describe block to individually run, view, watch and debug each test. + +You can also run a single test file separately: + +``` +npm run test:e2e tests/e2e/specs/hello.test.js +``` + + +## Projects + +The suite has three Playwright projects, defined in `playwright.config.js`: + +* `all`: every spec, one at a time on one worker. `npm run test:e2e` runs this project. +* `parallel`: specs that can share the site with other tests. Tests run at the same time on several workers, one for every two CPU cores. Run it with `npm run test:e2e -- --project=parallel`. +* `serial`: specs that break the site for other tests. They run one at a time on one worker. Run it with `npm run test:e2e -- --project=serial`. + +CI runs `parallel` and `serial` in separate jobs. + +New specs go in `parallel` by default. Add a spec to `SERIAL_SPECS` if it makes the site unusable for other tests. If it changes content or settings that other tests use, for example with `requestUtils.deleteAllPosts()`, follow [Parallel safety](#parallel-safety). + +Before you open a pull request with a new spec, run its project a few times with `--shuffle`. Playwright then runs the spec files in a random order, so a spec that needs another spec to run first, or that breaks a spec that runs after it, fails: + +``` +npm run test:e2e -- --project=parallel --shuffle +``` + +Playwright prints the seed of each run, for example `shuffle seed 317753389`. To run the same order again, give the seed: `--shuffle 317753389`. + +## Parallel safety + +Specs in `parallel` share one site. A test that changes shared data can break another test that runs at the same time. The `parallel` project sets `fullyParallel: true`, so this can be a test in another file or a test in the same file. To make a spec safe, use the first of these that works: + +1. Scope the data. Let the test create its own data, for example a post with a unique title, and read only that data. +2. If the test must change shared data, such as a site setting, give it a lock. Do this only if every spec that writes the same data holds the same lock. +3. If you cannot lock every spec that writes the data, add the spec to `SERIAL_SPECS`. + +A lock is a name. Playwright never runs two tests that hold the same lock name at the same time. A lock on a `describe` group applies to each test in the group, not to the group as a whole. A lock only schedules tests. It does not isolate data: a test without the lock can still change the data while a locked test runs. + +The lock names are in `utils/locks.js`. Import the constant, so that all specs use the same name. Playwright gives no error for a lock name that no other test uses, or for an import name that is not in `utils/locks.js`: + +``` +import { GENERAL_SETTINGS } from '../utils/locks'; + +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`. + +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: + +* To make the `page` of a whole `describe` group logged out, add `test.use( { storageState: { cookies: [], origins: [] } } )` to the group. See `specs/dashboard.test.js`. +* To use a logged-out page next to the logged-in `page` in one test, import `test` and `expect` from `../fixtures` and use the `loggedOutPage` fixture. Its browser context has no cookies, and it closes when the test ends. Unlike `page`, it resolves a URL that starts with `/` against the host only, not the full `WP_BASE_URL`, so it does not work with a site in a subdirectory. See `specs/cache-control-headers-directives.test.js`. + +## Fixtures + +To create posts, pages or users, to upload attachments, or to change a setting, an option, or a must-use plugin, import `test` and `expect` from `../fixtures`, and use one of the fixtures below. Each fixture cleans up when the test ends, also if the test fails. If the cleanup fails, the test fails. + +* `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 )`. 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`. + +If the test changes a setting or an option through a form, first call `remember` with an array of the keys that the form changes. The fixture then reads the current value, without a write, and restores it when the test ends. `remember` returns the current values. + +A fixture goes in `fixtures/` only when 2 or more spec files use it. A fixture that only one spec uses stays in that spec. + +## Locators + +Find elements with `getByRole`, `getByLabel` or `getByText`. Use a CSS selector only when the element has no unique accessible name. For example, the bulk action controls at the top and bottom of a list table have the same name. For admin screens, import the locators from `utils/admin.js`: `adminNotice`, `postRow`, `commentRow`, `bulkActionSelect` and `bulkActionApply`. See `specs/edit-posts.test.js`. + +A locator goes in `utils/` only when 2 or more spec files use it. + +## Documentation + +* Block Editor Handbook end to end testing overview: https://developer.wordpress.org/block-editor/contributors/code/testing-overview/#end-to-end-testing + +* Gutenberg e2e-test-utils-playwright package API docs: https://github.com/WordPress/gutenberg/tree/trunk/packages/e2e-test-utils-playwright + +* Playwright API docs: https://playwright.dev/docs (the version we are using is indicated in the `@wordpress/scripts` package: https://github.com/WordPress/gutenberg/blob/trunk/packages/scripts/package.json) 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..c4c8e4a1441bc 100644 --- a/tests/e2e/playwright.config.js +++ b/tests/e2e/playwright.config.js @@ -18,13 +18,8 @@ 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', - // This deletes all posts, including other workers' content. - 'empty-trash.test.js', + 'theme-activation.test.js', ]; const config = defineConfig( { @@ -32,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', diff --git a/tests/e2e/specs/classic-menus.test.js b/tests/e2e/specs/classic-menus.test.js index df02d659141fa..2e71ed0bceef6 100644 --- a/tests/e2e/specs/classic-menus.test.js +++ b/tests/e2e/specs/classic-menus.test.js @@ -12,6 +12,7 @@ import { test, expect } from '@wordpress/e2e-test-utils-playwright'; * Internal dependencies */ import { NAV_MENU_LOCATIONS } from '../utils/locks'; +import { adminNotice } from '../utils/admin'; /** * The classic menus admin screen (nav-menus.php). Relies on Twenty @@ -102,7 +103,7 @@ test.describe( 'Classic Menus', { lock: NAV_MENU_LOCATIONS }, () => { // See https://core.trac.wordpress.org/ticket/65684. await page.locator( '#save_menu_footer' ).focus(); await page.keyboard.press( 'Enter' ); - await expect( page.locator( '#message' ) ).toContainText( + await expect( adminNotice( page ) ).toContainText( `${ menuName } has been updated.` ); diff --git a/tests/e2e/specs/comments.test.js b/tests/e2e/specs/comments.test.js index cd007b4d75efd..5e4737ddf9331 100644 --- a/tests/e2e/specs/comments.test.js +++ b/tests/e2e/specs/comments.test.js @@ -8,6 +8,11 @@ import { randomUUID } from 'node:crypto'; */ import { test, expect } from '@wordpress/e2e-test-utils-playwright'; +/** + * Internal dependencies + */ +import { commentRow } from '../utils/admin'; + test.describe( 'Front-end comments', () => { let postId; @@ -86,7 +91,7 @@ test.describe( 'Front-end comments', () => { } ); await admin.visitAdminPage( '/edit-comments.php' ); - const row = page.locator( `#comment-${ commentId }` ); + const row = commentRow( page, commentId ); await expect( row ).toBeVisible(); await expect( row diff --git a/tests/e2e/specs/edit-posts.test.js b/tests/e2e/specs/edit-posts.test.js index 792deca7a1f2d..282f0b1de26a4 100644 --- a/tests/e2e/specs/edit-posts.test.js +++ b/tests/e2e/specs/edit-posts.test.js @@ -7,6 +7,12 @@ import { randomUUID } from 'node:crypto'; * Internal dependencies */ import { test, expect } from '../fixtures'; +import { + adminNotice, + bulkActionApply, + bulkActionSelect, + postRow, +} from '../utils/admin'; test.describe( 'Edit Posts', () => { async function visitPostList( admin, title ) { @@ -43,7 +49,7 @@ test.describe( 'Edit Posts', () => { await expect( listTable.locator( '#the-list' ).getByRole( 'row' ) ).toHaveCount( 1 ); - const row = listTable.locator( `#post-${ post.id }` ); + const row = postRow( listTable, post.id ); // Expect the title of the post to be correct. const postLink = row.getByRole( 'link', { @@ -72,8 +78,7 @@ test.describe( 'Edit Posts', () => { await expect( listTable ).toBeVisible(); // Click the post title (edit) link - await listTable - .locator( `#post-${ post.id }` ) + await postRow( listTable, post.id ) .getByRole( 'link', { name: title, exact: true } ) .click(); @@ -97,7 +102,7 @@ test.describe( 'Edit Posts', () => { const listTable = page.getByRole( 'table', { name: 'Table ordered by' } ); await expect( listTable ).toBeVisible(); - const row = listTable.locator( `#post-${ post.id }` ); + const row = postRow( listTable, post.id ); // // Focus on the post title link. await row.getByRole( 'link', { name: title, exact: true } ).focus(); @@ -146,7 +151,7 @@ test.describe( 'Edit Posts', () => { const listTable = page.getByRole( 'table', { name: 'Table ordered by' } ); await expect( listTable ).toBeVisible(); - const row = listTable.locator( `#post-${ post.id }` ); + const row = postRow( listTable, post.id ); await row.getByRole( 'link', { name: title, exact: true } ).hover(); await row @@ -185,13 +190,10 @@ test( 'bulk edits only the selected posts', async ( { new URLSearchParams( { s: titlePrefix } ).toString() ); for ( const post of posts.slice( 0, 2 ) ) { - await page - .locator( `#post-${ post.id }` ) - .getByRole( 'checkbox' ) - .check(); + await postRow( page, post.id ).getByRole( 'checkbox' ).check(); } - await page.locator( '#bulk-action-selector-top' ).selectOption( 'edit' ); - await page.locator( '#doaction' ).click(); + await bulkActionSelect( page ).selectOption( 'edit' ); + await bulkActionApply( page ).click(); const bulkEdit = page.getByRole( 'region', { name: 'Bulk Edit', exact: true, @@ -202,15 +204,14 @@ test( 'bulk edits only the selected posts', async ( { await bulkEdit .getByRole( 'button', { name: 'Update', exact: true } ) .click(); - await expect( page.locator( '#message' ) ).toContainText( + await expect( adminNotice( page ) ).toContainText( '2 posts updated.' ); await page.reload(); for ( const post of posts.slice( 0, 2 ) ) { await expect( - page - .locator( `#post-${ post.id }` ) + postRow( page, post.id ) .getByText( 'Draft', { exact: true } ) ).toBeVisible(); const savedPost = await requestUtils.rest( { 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 2703b525b6dcc..8c74bcf694c61 100644 --- a/tests/e2e/specs/empty-trash-restore-trashed-posts.test.js +++ b/tests/e2e/specs/empty-trash-restore-trashed-posts.test.js @@ -2,6 +2,12 @@ * Internal dependencies */ import { test, expect } from '../fixtures'; +import { + adminNotice, + bulkActionApply, + bulkActionSelect, + postRow, +} from '../utils/admin'; test( 'Undo restores a trashed post to its published status', async ( { page, @@ -20,7 +26,7 @@ test( 'Undo restores a trashed post to its published status', async ( { 'edit.php', new URLSearchParams( { s: title } ).toString() ); - const row = page.locator( `#post-${ postId }` ); + const row = postRow( page, postId ); await row.getByRole( 'link', { name: title, exact: true } ).hover(); await row .getByRole( 'link', { @@ -28,7 +34,7 @@ test( 'Undo restores a trashed post to its published status', async ( { exact: true, } ) .click(); - await expect( page.locator( '#message' ) ).toContainText( + await expect( adminNotice( page ) ).toContainText( '1 post moved to the Trash.' ); await expect( row ).toHaveCount( 0 ); @@ -39,7 +45,7 @@ test( 'Undo restores a trashed post to its published status', async ( { expect( trashedPost.status ).toBe( 'trash' ); await page.getByRole( 'link', { name: 'Undo', exact: true } ).click(); - await expect( page.locator( '#message' ) ).toContainText( + await expect( adminNotice( page ) ).toContainText( '1 post restored from the Trash.' ); await admin.visitAdminPage( @@ -79,29 +85,63 @@ test( 'bulk trashes only the selected posts', async ( { new URLSearchParams( { s: titlePrefix } ).toString() ); for ( const post of posts.slice( 0, 2 ) ) { - await page - .locator( `#post-${ post.id }` ) - .getByRole( 'checkbox' ) - .check(); + await postRow( page, post.id ).getByRole( 'checkbox' ).check(); } - await page.locator( '#bulk-action-selector-top' ).selectOption( 'trash' ); - await page.locator( '#doaction' ).click(); - await expect( page.locator( '#message' ) ).toContainText( + await bulkActionSelect( page ).selectOption( 'trash' ); + await bulkActionApply( page ).click(); + await expect( adminNotice( page ) ).toContainText( '2 posts moved to the Trash.' ); for ( const post of posts.slice( 0, 2 ) ) { - await expect( page.locator( `#post-${ post.id }` ) ).toHaveCount( 0 ); + await expect( postRow( page, post.id ) ).toHaveCount( 0 ); const savedPost = await requestUtils.rest( { path: `/wp/v2/posts/${ post.id }`, params: { context: 'edit' }, } ); expect( savedPost.status ).toBe( 'trash' ); } - await expect( page.locator( `#post-${ posts[ 2 ].id }` ) ).toBeVisible(); + await expect( postRow( page, posts[ 2 ].id ) ).toBeVisible(); const control = await requestUtils.rest( { path: `/wp/v2/posts/${ posts[ 2 ].id }`, params: { context: 'edit' }, } ); 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 d0fee6a7ad919..d23d249495910 100644 --- a/tests/e2e/specs/empty-trash.test.js +++ b/tests/e2e/specs/empty-trash.test.js @@ -1,55 +1,86 @@ +/** + * External dependencies + */ +import { randomUUID } from 'node:crypto'; + /** * Internal dependencies */ import { test, expect } from '../fixtures'; - -const POST_TITLE = 'Test Title'; +import { adminNotice } from '../utils/admin'; 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( page.locator( '#message' ) ).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( page.locator( '#message' ) ).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; + } + } ); + } } ); } ); 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(); diff --git a/tests/e2e/specs/media-library.test.js b/tests/e2e/specs/media-library.test.js index f8a9ad038c4b0..c8fd459671169 100644 --- a/tests/e2e/specs/media-library.test.js +++ b/tests/e2e/specs/media-library.test.js @@ -9,6 +9,16 @@ import path from 'node:path'; */ import { test, expect } from '@wordpress/e2e-test-utils-playwright'; +/** + * Internal dependencies + */ +import { + adminNotice, + bulkActionApply, + bulkActionSelect, + postRow, +} from '../utils/admin'; + test.describe( 'Media library', () => { let ids; let prefix; @@ -69,7 +79,7 @@ test.describe( 'Media library', () => { } ) => { const id = await upload( requestUtils, 'delete' ); await admin.visitAdminPage( '/upload.php', `mode=list&s=${ prefix }` ); - const row = page.locator( `#post-${ id }` ); + const row = postRow( page, id ); await expect( row ).toBeVisible(); await row.hover(); await confirmDelete( @@ -79,7 +89,7 @@ test.describe( 'Media library', () => { exact: true, } ) ); - await expect( page.locator( '#message' ) ).toContainText( + await expect( adminNotice( page ) ).toContainText( 'Media file permanently deleted.' ); await expect( row ).toBeHidden(); @@ -102,16 +112,14 @@ test.describe( 'Media library', () => { const second = await upload( requestUtils, 'second' ); const control = await upload( requestUtils, 'control' ); await admin.visitAdminPage( '/upload.php', `mode=list&s=${ prefix }` ); - const firstRow = page.locator( `#post-${ first }` ); - const secondRow = page.locator( `#post-${ second }` ); - const controlRow = page.locator( `#post-${ control }` ); + const firstRow = postRow( page, first ); + const secondRow = postRow( page, second ); + const controlRow = postRow( page, control ); await firstRow.getByRole( 'checkbox' ).check(); await secondRow.getByRole( 'checkbox' ).check(); - await page - .locator( '#bulk-action-selector-top' ) - .selectOption( 'delete' ); - await confirmDelete( page, page.locator( '#doaction' ) ); - await expect( page.locator( '#message' ) ).toContainText( + await bulkActionSelect( page ).selectOption( 'delete' ); + await confirmDelete( page, bulkActionApply( page ) ); + await expect( adminNotice( page ) ).toContainText( '2 media files permanently deleted.' ); await expect( firstRow ).toBeHidden(); @@ -172,7 +180,7 @@ test.describe( 'Media library', () => { '/upload.php', `mode=list&s=${ encodeURIComponent( title ) }` ); - const row = page.locator( `#post-${ id }` ); + const row = postRow( page, id ); await expect( row ).toBeVisible(); await expect( row.getByRole( 'link', { name: title, exact: true } ) @@ -219,7 +227,7 @@ test.describe( 'Media library', () => { .getByRole( 'button', { name: 'Update', exact: true } ) .click(); - await expect( page.locator( '#message' ) ).toContainText( + await expect( adminNotice( page ) ).toContainText( 'Media file updated.' ); await expect( page.getByLabel( 'Add title' ) ).toHaveValue( title ); 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, diff --git a/tests/e2e/specs/moderate-comments.test.js b/tests/e2e/specs/moderate-comments.test.js index a5405962e746a..98772ed2dfbfc 100644 --- a/tests/e2e/specs/moderate-comments.test.js +++ b/tests/e2e/specs/moderate-comments.test.js @@ -2,6 +2,11 @@ * Internal dependencies */ import { test, expect } from '../fixtures'; +import { + bulkActionApply, + bulkActionSelect, + commentRow, +} from '../utils/admin'; /** The comment content used across tests. */ const COMMENT_CONTENT = 'A comment awaiting moderation.'; @@ -79,7 +84,7 @@ test.describe( 'Moderate Comments', () => { 'comment_status=moderated' ); - const row = page.locator( `#comment-${ comment.id }` ); + const row = commentRow( page, comment.id ); await expect( row ).toBeVisible(); // Row actions appear on hover. @@ -118,7 +123,7 @@ test.describe( 'Moderate Comments', () => { await admin.visitAdminPage( '/edit-comments.php' ); - const row = page.locator( `#comment-${ comment.id }` ); + const row = commentRow( page, comment.id ); await expect( row ).toBeVisible(); await row.hover(); @@ -153,7 +158,7 @@ test.describe( 'Moderate Comments', () => { await admin.visitAdminPage( '/edit-comments.php' ); - const row = page.locator( `#comment-${ comment.id }` ); + const row = commentRow( page, comment.id ); await expect( row ).toBeVisible(); await row.hover(); @@ -214,8 +219,7 @@ test.describe( 'Moderate Comments', () => { status: 'approved', } ); await expect( - page - .locator( `#comment-${ replyId }` ) + commentRow( page, replyId ) .getByRole( 'paragraph' ) .filter( { hasText: /^An admin reply\.$/ } ) ).toBeVisible(); @@ -248,14 +252,12 @@ test.describe( 'Moderate Comments', () => { 'comment_status=moderated' ); - const firstRow = page.locator( `#comment-${ comment.id }` ); - const secondRow = page.locator( `#comment-${ secondComment.id }` ); + const firstRow = commentRow( page, comment.id ); + const secondRow = commentRow( page, secondComment.id ); await firstRow.getByRole( 'checkbox' ).check(); await secondRow.getByRole( 'checkbox' ).check(); - await page - .locator( '#bulk-action-selector-top' ) - .selectOption( 'spam' ); - await page.locator( '#doaction' ).click(); + await bulkActionSelect( page ).selectOption( 'spam' ); + await bulkActionApply( page ).click(); await expect .poll( () => getCommentStatus( requestUtils, comment.id ), { @@ -293,7 +295,7 @@ test.describe( 'Moderate Comments', () => { `p=${ post.id }` ); - const row = page.locator( `#comment-${ comment.id }` ); + const row = commentRow( page, comment.id ); await row.hover(); await row .getByRole( 'button', { name: 'Quick edit this comment inline' } ) diff --git a/tests/e2e/specs/pages/quick-edit-page.test.js b/tests/e2e/specs/pages/quick-edit-page.test.js index 351b95ae6e2f4..4533c2db2c8bb 100644 --- a/tests/e2e/specs/pages/quick-edit-page.test.js +++ b/tests/e2e/specs/pages/quick-edit-page.test.js @@ -2,6 +2,7 @@ * Internal dependencies */ import { test, expect } from '../../fixtures'; +import { postRow } from '../../utils/admin'; test.describe( 'Quick Edit page', () => { test( 'saves a page parent using Quick Edit', async ( { @@ -20,7 +21,7 @@ test.describe( 'Quick Edit page', () => { const pageId = createdPage.id; await admin.visitAdminPage( 'edit.php?post_type=page' ); - const row = page.locator( `#post-${ pageId }` ); + const row = postRow( page, pageId ); await row .getByRole( 'link', { name: 'Quick Edit page', exact: true } ) .hover(); diff --git a/tests/e2e/specs/personal-data-requests.test.js b/tests/e2e/specs/personal-data-requests.test.js index f74c630105c7f..7e33312b780e3 100644 --- a/tests/e2e/specs/personal-data-requests.test.js +++ b/tests/e2e/specs/personal-data-requests.test.js @@ -8,6 +8,11 @@ import { randomUUID } from 'node:crypto'; */ import { test, expect } from '@wordpress/e2e-test-utils-playwright'; +/** + * Internal dependencies + */ +import { bulkActionApply, bulkActionSelect } from '../utils/admin'; + for ( const { label, screen, confirmationLabel, usernamePrefix } of [ { label: 'Export Personal Data', @@ -49,10 +54,8 @@ for ( const { label, screen, confirmationLabel, usernamePrefix } of [ .filter( { hasText: email } ); if ( await row.count() ) { await row.first().getByRole( 'checkbox' ).check(); - await page - .locator( '#bulk-action-selector-top' ) - .selectOption( 'delete' ); - await page.locator( '#doaction' ).click(); + await bulkActionSelect( page ).selectOption( 'delete' ); + await bulkActionApply( page ).click(); } } finally { if ( userId ) { diff --git a/tests/e2e/specs/plugins.test.js b/tests/e2e/specs/plugins.test.js index a954315d77617..51f91d5b3c194 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, UPGRADER } 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, 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/taxonomies.test.js b/tests/e2e/specs/taxonomies.test.js index 2849e086e01b5..12f5fa9c0a435 100644 --- a/tests/e2e/specs/taxonomies.test.js +++ b/tests/e2e/specs/taxonomies.test.js @@ -8,6 +8,11 @@ import { randomUUID } from 'node:crypto'; */ import { test, expect } from '@wordpress/e2e-test-utils-playwright'; +/** + * Internal dependencies + */ +import { bulkActionApply, bulkActionSelect } from '../utils/admin'; + for ( const { taxonomy, endpoint, label } of [ { taxonomy: 'category', endpoint: 'categories', label: 'Category' }, { taxonomy: 'post_tag', endpoint: 'tags', label: 'Tag' }, @@ -275,10 +280,8 @@ for ( const { taxonomy, endpoint, label } of [ .locator( `#tag-${ second.id }` ) .getByRole( 'checkbox' ) .check(); - await page - .locator( '#bulk-action-selector-top' ) - .selectOption( 'delete' ); - await page.locator( '#doaction' ).click(); + await bulkActionSelect( page ).selectOption( 'delete' ); + await bulkActionApply( page ).click(); await expect( page.locator( `#tag-${ first.id }` ) 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/specs/users.test.js b/tests/e2e/specs/users.test.js index f96649315282f..6482e4b8fa023 100644 --- a/tests/e2e/specs/users.test.js +++ b/tests/e2e/specs/users.test.js @@ -8,6 +8,11 @@ import { randomUUID } from 'node:crypto'; */ import { test, expect } from '../fixtures'; import { signIn } from '../fixtures/user'; +import { + adminNotice, + bulkActionApply, + bulkActionSelect, +} from '../utils/admin'; test.describe( 'User management', () => { let prefix; @@ -40,7 +45,7 @@ test.describe( 'User management', () => { await page .getByRole( 'button', { name: 'Add User', exact: true } ) .click(); - await expect( page.locator( '#message' ) ).toContainText( + await expect( adminNotice( page ) ).toContainText( 'New user created.' ); @@ -87,17 +92,15 @@ test.describe( 'User management', () => { .locator( `#user-${ users[ 1 ].id }` ) .getByRole( 'checkbox' ) .check(); - await page - .locator( '#bulk-action-selector-top' ) - .selectOption( 'delete' ); - await page.locator( '#doaction' ).click(); + await bulkActionSelect( page ).selectOption( 'delete' ); + await bulkActionApply( page ).click(); await expect( page.getByRole( 'heading', { name: 'Delete Users', exact: true } ) ).toBeVisible(); await page .getByRole( 'button', { name: 'Confirm Deletion', exact: true } ) .click(); - await expect( page.locator( '#message' ) ).toContainText( + await expect( adminNotice( page ) ).toContainText( '2 users deleted.' ); await expect( page.locator( `#user-${ users[ 0 ].id }` ) ).toBeHidden(); diff --git a/tests/e2e/utils/admin.js b/tests/e2e/utils/admin.js new file mode 100644 index 0000000000000..cfef2d318ee1e --- /dev/null +++ b/tests/e2e/utils/admin.js @@ -0,0 +1,39 @@ +/** + * Locators for WP admin screens. + * + * These elements have no unique accessible name, or share it with a twin control + * at the bottom of the table, so they are found by ID. + */ + +/** + * @param {import('@playwright/test').Page} page The page to search in. + * @return {import('@playwright/test').Locator} The `#message` admin notice. + */ +export const adminNotice = ( page ) => page.locator( '#message' ); + +/** + * @param {import('@playwright/test').Page|import('@playwright/test').Locator} scope Page, or a locator to search in. + * @param {number} id Post ID. + * @return {import('@playwright/test').Locator} The post's list table row. + */ +export const postRow = ( scope, id ) => scope.locator( `#post-${ id }` ); + +/** + * @param {import('@playwright/test').Page|import('@playwright/test').Locator} scope Page, or a locator to search in. + * @param {number} id Comment ID. + * @return {import('@playwright/test').Locator} The comment's list table row. + */ +export const commentRow = ( scope, id ) => scope.locator( `#comment-${ id }` ); + +/** + * @param {import('@playwright/test').Page} page The page to search in. + * @return {import('@playwright/test').Locator} The top bulk action dropdown. + */ +export const bulkActionSelect = ( page ) => + page.locator( '#bulk-action-selector-top' ); + +/** + * @param {import('@playwright/test').Page} page The page to search in. + * @return {import('@playwright/test').Locator} The top bulk action "Apply" button. + */ +export const bulkActionApply = ( page ) => page.locator( '#doaction' ); diff --git a/tests/e2e/utils/locks.js b/tests/e2e/utils/locks.js index b118484eb05ea..039141eda4ee9 100644 --- a/tests/e2e/utils/locks.js +++ b/tests/e2e/utils/locks.js @@ -1,3 +1,5 @@ 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(); +} diff --git a/tests/phpstan/README.md b/tests/phpstan/README.md index 62003ca812d6a..520f8c76ebdb5 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 @@ -204,6 +227,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 @@ -232,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. -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. -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. +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. 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`. @@ -290,7 +314,9 @@ 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. + +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. @@ -310,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. 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/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-strict/argument.type.neon b/tests/phpstan/baselines-strict/argument.type.neon new file mode 100644 index 0000000000000..967bf80d53e61 --- /dev/null +++ b/tests/phpstan/baselines-strict/argument.type.neon @@ -0,0 +1,55 @@ +# 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 \#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 aece929f18751..7d4b6aa03dccb 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 +# 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 this file suppressed so the errors surface again. +# This reruns the analysis with the baselines in this directory suppressed, so +# that their errors surface again, and rewrites only this file. parameters: ignoreErrors: @@ -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/phpstan/baselines/argument.unresolvableType.neon b/tests/phpstan/baselines/argument.unresolvableType.neon index 3e8cdcb76c85d..f6ca492a525ce 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 +# 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 this file suppressed so the errors surface again. +# This 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..a9a89163f9df1 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 +# 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 this file suppressed so the errors surface again. +# This 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..bfcd43d16d874 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 +# 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 this file suppressed so the errors surface again. +# This 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..1f55c01be4124 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 +# 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 this file suppressed so the errors surface again. +# This 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..7db8291d66e7c 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 +# 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 this file suppressed so the errors surface again. +# This 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..97a6745e87a0d 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 +# 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 this file suppressed so the errors surface again. +# This 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 deleted file mode 100644 index ef8ca56577602..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, along with the `includes` entry -# for it in phpstan.neon.dist. -# -# 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. - -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 diff --git a/tests/phpstan/baselines/empty.property.neon b/tests/phpstan/baselines/empty.property.neon index 5bc6d4e3cbdd3..29c45b3128ea4 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 +# 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 this file suppressed so the errors surface again. +# This 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..47f6187fd5310 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 +# 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 this file suppressed so the errors surface again. +# This 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..3c1a44fe8f871 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 +# 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 this file suppressed so the errors surface again. +# This 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..045ad4b731459 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 +# 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 this file suppressed so the errors surface again. +# This 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..0d305bff88893 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 +# 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 this file suppressed so the errors surface again. +# This 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..ed8b9f60e0c1c 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 +# 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 this file suppressed so the errors surface again. +# This 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..a86c1b801ab98 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 +# 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 this file suppressed so the errors surface again. +# This 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..4cf68462ad846 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 +# 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 this file suppressed so the errors surface again. +# This 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 @@ +, 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 73746ef20c078..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, along with the `includes` entry -# for it in phpstan.neon.dist. -# -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with -# -# composer phpstan:baselines -- --identifier=parameterByRef.unusedType -# -# which reruns the analysis with this file suppressed so the errors surface again. - -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/phpstan/baselines/property.defaultValue.neon b/tests/phpstan/baselines/property.defaultValue.neon index e604833eade20..5c7ebe5274920 100644 --- a/tests/phpstan/baselines/property.defaultValue.neon +++ b/tests/phpstan/baselines/property.defaultValue.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 +# 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 this file suppressed so the errors surface again. +# This 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/property.nonObject.neon b/tests/phpstan/baselines/property.nonObject.neon index e17cdfa2c2458..2acecd3a68838 100644 --- a/tests/phpstan/baselines/property.nonObject.neon +++ b/tests/phpstan/baselines/property.nonObject.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 +# 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 this file suppressed so the errors surface again. +# This 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/property.notFound.neon b/tests/phpstan/baselines/property.notFound.neon index 425d00444ca8e..6686c06ba9431 100644 --- a/tests/phpstan/baselines/property.notFound.neon +++ b/tests/phpstan/baselines/property.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 +# 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 this file suppressed so the errors surface again. +# This 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/property.private.neon b/tests/phpstan/baselines/property.private.neon index 7549ab9c5ddd5..6d08652de08d5 100644 --- a/tests/phpstan/baselines/property.private.neon +++ b/tests/phpstan/baselines/property.private.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 +# 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 this file suppressed so the errors surface again. +# This 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/return.type.neon b/tests/phpstan/baselines/return.type.neon index a395fbd5ca63a..9143cbd2bbad7 100644 --- a/tests/phpstan/baselines/return.type.neon +++ b/tests/phpstan/baselines/return.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 +# 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 this file suppressed so the errors surface again. +# This 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/varTag.noVariable.neon b/tests/phpstan/baselines/varTag.noVariable.neon index 36e0f9fed1382..5078f4df8beb9 100644 --- a/tests/phpstan/baselines/varTag.noVariable.neon +++ b/tests/phpstan/baselines/varTag.noVariable.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 +# 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 this file suppressed so the errors surface again. +# This 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/variable.undefined.neon b/tests/phpstan/baselines/variable.undefined.neon index 94ac3791e4bed..a46e0e5fa2283 100644 --- a/tests/phpstan/baselines/variable.undefined.neon +++ b/tests/phpstan/baselines/variable.undefined.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 +# 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 this file suppressed so the errors surface again. +# This 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/generate-baselines.php b/tests/phpstan/generate-baselines.php index 7f28af6bcdc47..f59ae0331c3b3 100644 --- a/tests/phpstan/generate-baselines.php +++ b/tests/phpstan/generate-baselines.php @@ -7,22 +7,25 @@ * refreshing one baseline among several: rerunning it would sweep every other * kind of error into the same file. * - * This wrapper runs the analysis with the existing per-identifier baselines + * This wrapper runs the analysis with the baselines being regenerated * suppressed, so their errors surface again, then splits the result by * identifier and writes one file per kind. Each file is self-describing and is * meant to shrink to nothing and then be deleted. * - * Baselines whose identifier no longer reports anything are removed, and the - * list of them between the `# phpstan:baselines` markers in the configuration's - * `includes` is rewritten to match what is on disk. Adding a newly split out - * baseline, and retiring one that has reached zero, therefore need no manual - * edit of the configuration. + * Baselines whose identifier no longer reports anything are removed. The + * configuration includes them through `tests/phpstan/baselines/loader.php`, which + * 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, and the list in the configuration is updated to match. That - * completes running PHPStan with `--fix`, which removes the entries of fixed - * errors in place but leaves a baseline it has emptied behind, and so - * `composer phpstan:fix` runs it with `--prune` after `--fix`. + * 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 + * behind, and so `composer phpstan:fix` runs it with `--prune` after `--fix`. * * The intermediate baseline is generated in PHPStan's PHP format and read back * with `require`, so the entries arrive as an array. Nothing has to parse, or @@ -42,25 +45,37 @@ namespace WordPress\PHPStan; +// GENERATING_BASELINES_ENV and find_baselines(), shared with the loaders. +require_once __DIR__ . '/baseline-includes.php'; + /** - * Opening marker of the region of the configuration's `includes` this script owns. + * The directory baselines are written to when `--output-dir` does not name one. * - * Everything between this and the closing marker is generated: it is rewritten to - * match the baselines on disk, and suppressed while the analysis runs. + * Relative to the repository root. */ -const BASELINES_START_MARKER = '# phpstan:baselines start'; +const DEFAULT_OUTPUT_DIR = 'tests/phpstan/baselines'; /** - * Closing marker of the region of the configuration's `includes` this script owns. + * The configuration analyzed when `--config` does not name one. + * + * Relative to the repository root. */ -const BASELINES_END_MARKER = '# phpstan:baselines end'; +const DEFAULT_CONFIG = 'phpstan.neon.dist'; /** - * The configuration analyzed when `--config` does not name one. + * 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_CONFIG = 'phpstan.neon.dist'; +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" ); @@ -79,7 +94,8 @@ array_shift( $args ); $config_option = DEFAULT_CONFIG; -$output_option = 'tests/phpstan/baselines'; +$output_option = null; +$config_given = false; $memory_limit = '2G'; $only_identifiers = array(); $combined = false; @@ -104,20 +120,35 @@ if ( 1 === preg_match( '/^--identifier=(.+)$/', $arg, $matches ) ) { foreach ( explode( ',', $matches[1] ) as $identifier ) { $identifier = trim( $identifier ); - if ( '' !== $identifier ) { - $only_identifiers[] = $identifier; + if ( '' === $identifier ) { + continue; } + + /* + * The identifier names the file a baseline is written to and retired + * from, so one that is not an identifier, such as `../../../phpstan`, + * could name a file outside the baselines, which would be deleted when + * no such identifier is reported. + */ + if ( 1 !== preg_match( BASELINE_FILE_PATTERN, $identifier . '.neon' ) ) { + fwrite( STDERR, "Not an error identifier: $identifier\n" ); + exit( 1 ); + } + + $only_identifiers[] = $identifier; } continue; } 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; } @@ -130,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, '/' ); @@ -143,8 +226,8 @@ * entries whose errors were fixed and removes those that no longer match, but when * it removes the last entry of a baseline it leaves the file behind, as * `ignoreErrors: []`. That file suppresses nothing, so all that remains is to - * delete it and drop it from the configuration's `includes`, which is known from - * the file alone. + * delete it, which is known from the file alone. The loader stops including it + * once it is gone. */ if ( $prune ) { if ( $combined ) { @@ -154,17 +237,19 @@ $pruned = 0; - foreach ( find_baselines( $output_dir ) as $file ) { - $identifier = basename( $file, '.neon' ); + // A directory not written to yet has no baselines to prune. + foreach ( is_dir( $output_dir ) ? find_baselines( $output_dir ) : array() as $name ) { + $identifier = basename( $name, '.neon' ); if ( $only_identifiers && ! in_array( $identifier, $only_identifiers, true ) ) { continue; } + $file = $output_dir . '/' . $name; $is_empty = is_empty_baseline( read_file( $file ) ); if ( null === $is_empty ) { - fwrite( STDERR, sprintf( "%s: no `ignoreErrors` list found, left untouched.\n", $output_option . '/' . basename( $file ) ) ); + fwrite( STDERR, sprintf( "%s: no `ignoreErrors` list found, left untouched.\n", $output_option . '/' . $name ) ); continue; } @@ -173,11 +258,11 @@ } if ( ! unlink( $file ) ) { - fwrite( STDERR, sprintf( "%s: could not be deleted.\n", $output_option . '/' . basename( $file ) ) ); + fwrite( STDERR, sprintf( "%s: could not be deleted.\n", $output_option . '/' . $name ) ); exit( 1 ); } - printf( "%s: no entries remain, file deleted.\n", $output_option . '/' . basename( $file ) ); + printf( "%s: no entries remain, file deleted.\n", $output_option . '/' . $name ); ++$pruned; } @@ -185,17 +270,15 @@ echo "No empty baselines found.\n"; } - update_config_includes( $config_path, $config_option, $output_dir ); exit( 0 ); } /* - * All three temporary files sit beside the configuration, and so inside the + * Both temporary files sit beside the configuration, and so inside the * repository, for two separate reasons. * - * A neon file's `includes` resolve relative to its own directory, so the copy of - * the configuration, and the wrapper including it, have to live where the - * original did. + * A neon file's `includes` resolve relative to its own directory, so the wrapper + * including the configuration has to live where the configuration does. * * PHPStan writes a PHP baseline's paths as __DIR__ followed by a relative chain, * which it can only produce when the baseline shares an ancestry with the files @@ -205,12 +288,11 @@ */ $temp_prefix = dirname( $config_path ) . '/.phpstan-baselines-' . getmypid(); $temp_config = $temp_prefix . '.neon'; -$temp_stripped = $temp_prefix . '-stripped.neon'; $temp_baseline = $temp_prefix . '.php'; register_shutdown_function( - static function () use ( $temp_config, $temp_stripped, $temp_baseline ): void { - foreach ( array( $temp_config, $temp_stripped, $temp_baseline ) as $file ) { + static function () use ( $temp_config, $temp_baseline ): void { + foreach ( array( $temp_config, $temp_baseline ) as $file ) { if ( is_file( $file ) ) { unlink( $file ); } @@ -218,8 +300,6 @@ static function () use ( $temp_config, $temp_stripped, $temp_baseline ): void { } ); -file_put_contents( $temp_stripped, strip_baseline_includes( $config_path, $output_dir ) ); - /* * The analysis gets a scratch directory of its own, rather than the `tmpDir` that * `tests/phpstan/base.neon` configures for everything else. @@ -253,18 +333,19 @@ static function () use ( $temp_config, $temp_stripped, $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 ); } /* - * `tmpDir` is set in a wrapper including the stripped copy, rather than in the - * copy itself, because neon rejects a duplicated key and the copy already carries - * the `parameters` section it was made from. A file's own parameters win over - * those of the files it includes, so the wrapper's `tmpDir` is the one that takes + * `tmpDir` is set in a wrapper including the configuration, so that the + * configuration itself is left untouched. A file's own parameters win over those + * of the files it includes, so the wrapper's `tmpDir` is the one that takes * effect. + * + * The baselines being regenerated need no removing from the configuration: + * GENERATING_BASELINES_ENV names their directory for the analysis, and the loader + * there includes nothing while it does. */ file_put_contents( $temp_config, @@ -275,7 +356,7 @@ static function () use ( $temp_config, $temp_stripped, $temp_baseline ): void { parameters: tmpDir: %s NEON, - basename( $temp_stripped ), + basename( $config_path ), quote_neon_value( $analysis_tmp_dir ) ) ); @@ -293,7 +374,75 @@ static function () use ( $temp_config, $temp_stripped, $temp_baseline ): void { escapeshellarg( $memory_limit ) ); -fwrite( STDERR, "Analyzing with $config_option, existing baselines suppressed...\n" ); +/* + * 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 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 ); +if ( false !== $resolved_output_dir ) { + putenv( GENERATING_BASELINES_ENV . '=' . $resolved_output_dir ); +} + +$is_default_output_dir = DEFAULT_OUTPUT_DIR === trim( normalize_path( $output_option ), '/' ); + +/* + * The baselines in any other directory the configuration includes stay in force, + * so a run expecting every error, rather than those the others leave, would come + * up short with nothing to say why. The default configuration includes only the + * default directory's, so that is the one combination with nothing to say. Any + * other, whether a configuration including the default one alongside a loader of + * its own, or a directory other than the default, may well leave some in force. + */ +if ( DEFAULT_CONFIG !== $config_relative || ! $is_default_output_dir ) { + fwrite( STDERR, "Baselines in any other directory the configuration includes stay in force, so only the errors they leave are written.\n" ); +} $exit_code = 0; passthru( $command, $exit_code ); @@ -328,17 +477,30 @@ static function () use ( $temp_config, $temp_stripped, $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 command each header gives for regenerating its baseline has to name the + * 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 = ' --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 ) { - 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 +521,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 +539,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 +548,14 @@ 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. + + 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 [-- ] @@ -403,17 +567,24 @@ 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. - Default: tests/phpstan/baselines + 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: 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, 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 +641,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 +696,52 @@ function read_baseline( string $path ): array { } /** - * Returns the configuration with the baseline `includes` removed. + * Builds the loader for a baselines directory. * - * Those files suppress the very errors being regenerated, so they have to be out - * of the way for the analysis to report anything. + * 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. * - * 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 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. * - * 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. - * - * @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; - } +function build_loader( string $output_dir ): string { + $from = realpath( $output_dir ); + $to = realpath( __DIR__ . '/baseline-includes.php' ); - 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; - } - } - - $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. * @@ -857,14 +894,32 @@ 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. * * @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 << $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/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/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. 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.' ); } /** 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. * 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; - } -} diff --git a/tests/phpunit/tests/ajax/wpAjaxCropImage.php b/tests/phpunit/tests/ajax/wpAjaxCropImage.php index 7ccea87533f2a..145e694818e83 100644 --- a/tests/phpunit/tests/ajax/wpAjaxCropImage.php +++ b/tests/phpunit/tests/ajax/wpAjaxCropImage.php @@ -4,8 +4,6 @@ * Admin Ajax functions to be tested. */ require_once ABSPATH . 'wp-admin/includes/ajax-actions.php'; -require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php'; -require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php'; /** * Class for testing ajax crop image functionality. @@ -146,19 +144,7 @@ public function test_it_doesnt_generate_new_metadata_if_metadata_is_empty() { private function make_attachment( $with_metadata = true ) { $uniq_id = uniqid( 'crop-image-ajax-action-test-' ); - $test_file = DIR_TESTDATA . '/images/test-image.jpg'; - $upload_directory = wp_upload_dir(); - $uploaded_file = $upload_directory['path'] . '/' . $uniq_id . '.jpg'; - $filesystem = new WP_Filesystem_Direct( true ); - $filesystem->copy( $test_file, $uploaded_file ); - - $attachment_data = array( - 'file' => $uploaded_file, - 'type' => 'image/jpg', - 'url' => 'http://localhost/foo.jpg', - ); - - $attachment_id = $this->_make_attachment( $attachment_data ); + $attachment_id = self::factory()->attachment->create_upload_object( DIR_TESTDATA . '/images/test-image.jpg' ); $post_data = array( 'ID' => $attachment_id, 'post_title' => $with_metadata ? 'Title ' . $uniq_id : '', @@ -167,7 +153,7 @@ private function make_attachment( $with_metadata = true ) { 'post_excerpt' => $with_metadata ? 'Caption ' . $uniq_id : '', ); - // Update the post because _make_attachment method doesn't support these arguments. + // Update the post because create_upload_object() doesn't support these arguments. wp_update_post( $post_data ); if ( $with_metadata ) { 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/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/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/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/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'] ); 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 ); } diff --git a/tests/phpunit/tests/comment.php b/tests/phpunit/tests/comment.php index c5c40b9b34da6..fd403088b5ce3 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 * @@ -2654,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/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" ), + ); + } +} diff --git a/tests/phpunit/tests/customize/manager.php b/tests/phpunit/tests/customize/manager.php index 91d0157b2719a..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; @@ -925,6 +926,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/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/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/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(); } /** 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; } } 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/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. 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' ) ) ); + } } diff --git a/tests/phpunit/tests/formatting/excerptRemoveFootnotes.php b/tests/phpunit/tests/formatting/excerptRemoveFootnotes.php index eabf3bfc2f47d..97066c5e407db 100644 --- a/tests/phpunit/tests/formatting/excerptRemoveFootnotes.php +++ b/tests/phpunit/tests/formatting/excerptRemoveFootnotes.php @@ -16,7 +16,7 @@ class Tests_Formatting_ExcerptRemoveFootnotes extends WP_UnitTestCase { * @param string $content Content to run strip_shortcodes() on. */ public function test_remove_footnotes( $expected, $content ) { - $this->assertSame( $expected, excerpt_remove_footnotes( $content ) ); + $this->assertEqualHTML( $expected, excerpt_remove_footnotes( $content ) ); } /** 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 ); + } +} 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.' ); + } } 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 ); + } +} diff --git a/tests/phpunit/tests/general/template.php b/tests/phpunit/tests/general/template.php index 750b45f7f239b..54ef91cb8a05c 100644 --- a/tests/phpunit/tests/general/template.php +++ b/tests/phpunit/tests/general/template.php @@ -16,7 +16,6 @@ class Tests_General_Template extends WP_UnitTestCase { public $site_icon_url; public $custom_logo_id; - public $custom_logo_url; /** * Blog page used by aria tests. @@ -377,14 +376,9 @@ private function remove_site_icon() { * @since 4.3.0 */ private function insert_attachment() { - $filename = DIR_TESTDATA . '/images/test-image.jpg'; - $contents = file_get_contents( $filename ); + $this->site_icon_id = self::factory()->attachment->create_upload_object( DIR_TESTDATA . '/images/test-image.jpg' ); + $this->site_icon_url = wp_upload_dir()['url'] . '/' . wp_basename( get_attached_file( $this->site_icon_id ) ); - $upload = wp_upload_bits( wp_basename( $filename ), null, $contents ); - $this->site_icon_url = $upload['url']; - - // Save the data. - $this->site_icon_id = $this->_make_attachment( $upload ); return $this->site_icon_id; } @@ -563,13 +557,8 @@ private function remove_custom_logo() { * @since 4.5.0 */ private function insert_custom_logo() { - $filename = DIR_TESTDATA . '/images/test-image.jpg'; - $contents = file_get_contents( $filename ); - $upload = wp_upload_bits( wp_basename( $filename ), null, $contents ); + $this->custom_logo_id = self::factory()->attachment->create_upload_object( DIR_TESTDATA . '/images/test-image.jpg' ); - // Save the data. - $this->custom_logo_url = $upload['url']; - $this->custom_logo_id = $this->_make_attachment( $upload ); return $this->custom_logo_id; } 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() ); + } +} 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() ); + } +} 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'] ); + } +} 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 ); + } +} 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, diff --git a/tests/phpunit/tests/http/wpRemoteRequestMultiple.php b/tests/phpunit/tests/http/wpRemoteRequestMultiple.php new file mode 100644 index 0000000000000..7e68683a0f7dc --- /dev/null +++ b/tests/phpunit/tests/http/wpRemoteRequestMultiple.php @@ -0,0 +1,566 @@ +assertSame( array(), wp_remote_request_multiple( array() ) ); + } + + /** + * @ticket 37459 + */ + public function test_should_key_and_order_the_responses_like_the_requests() { + $this->allow_requests_rejected_before_sending(); + add_filter( 'pre_http_request', array( $this, 'short_circuit_example_org' ), 10, 3 ); + + $responses = wp_remote_request_multiple( + array( + 'first' => 'https://example.org/first', + // This request is not short-circuited and is answered after the others, but must keep its place. + 'second' => 'ssl://example.org/second', + 7 => array( 'url' => 'https://example.org/third' ), + 'fourth' => array( + 'url' => 'https://example.org/fourth', + 'args' => array( 'method' => 'POST' ), + ), + ) + ); + + $this->assertSame( array( 'first', 'second', 7, 'fourth' ), array_keys( $responses ), 'The responses should be keyed and ordered like the requests.' ); + $this->assertSame( 'https://example.org/first', wp_remote_retrieve_response_message( $responses['first'] ) ); + $this->assertWPError( $responses['second'] ); + $this->assertSame( 'https://example.org/third', wp_remote_retrieve_response_message( $responses[7] ) ); + $this->assertSame( 'https://example.org/fourth', wp_remote_retrieve_response_message( $responses['fourth'] ) ); + } + + /** + * @ticket 37459 + */ + public function test_should_filter_each_request_individually() { + $methods = array(); + + add_filter( + 'http_request_args', + static function ( $parsed_args, $url ) use ( &$methods ) { + $methods[ $url ] = $parsed_args['method']; + return $parsed_args; + }, + 10, + 2 + ); + add_filter( 'pre_http_request', array( $this, 'short_circuit_example_org' ), 10, 3 ); + + wp_remote_request_multiple( + array( + 'https://example.org/get', + array( + 'url' => 'https://example.org/post', + 'args' => array( 'method' => 'POST' ), + ), + array( + 'url' => 'https://example.org/head', + 'args' => 'method=HEAD', + ), + ) + ); + + $this->assertSame( + array( + 'https://example.org/get' => 'GET', + 'https://example.org/post' => 'POST', + 'https://example.org/head' => 'HEAD', + ), + $methods + ); + } + + /** + * @ticket 37459 + */ + public function test_should_perform_each_request_in_full() { + $blocking = null; + + add_filter( + 'pre_http_request', + static function ( $response, $parsed_args ) use ( &$blocking ) { + $blocking = $parsed_args['blocking']; + + return array( + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + ); + }, + 10, + 2 + ); + + wp_remote_request_multiple( + array( + array( + 'url' => 'https://example.org/', + 'args' => array( 'blocking' => false ), + ), + ) + ); + + $this->assertTrue( $blocking, 'Batched requests should always be blocking.' ); + } + + /** + * @ticket 37459 + */ + public function test_should_return_a_null_short_circuit_value_as_is() { + add_filter( 'pre_http_request', '__return_null' ); + + $responses = wp_remote_request_multiple( array( 'first' => 'https://example.org/first' ) ); + + $this->assertSame( array( 'first' => null ), $responses, 'A null short-circuit value should be returned like any other.' ); + $this->assertNull( wp_remote_request( 'https://example.org/first' ), 'A single request should still return a null short-circuit value as is.' ); + } + + /** + * @ticket 37459 + */ + public function test_should_return_a_wp_error_for_a_request_that_cannot_be_prepared() { + $this->allow_requests_rejected_before_sending(); + add_filter( 'pre_http_request', array( $this, 'short_circuit_example_org' ), 10, 3 ); + + $responses = wp_remote_request_multiple( + array( + 'valid' => 'https://example.org/', + 'invalid' => 'not a url', + 'missing' => array( 'args' => array( 'method' => 'POST' ) ), + ) + ); + + $this->assertSame( 200, wp_remote_retrieve_response_code( $responses['valid'] ) ); + $this->assertWPError( $responses['invalid'] ); + $this->assertSame( 'http_request_failed', $responses['invalid']->get_error_code() ); + $this->assertWPError( $responses['missing'] ); + $this->assertSame( 'http_request_failed', $responses['missing']->get_error_code() ); + } + + /** + * @ticket 37459 + */ + public function test_should_return_a_wp_error_for_a_request_the_requests_library_rejects() { + $this->allow_requests_rejected_before_sending(); + + $responses = wp_remote_request_multiple( array( 'ssl' => 'ssl://example.org/' ) ); + + $this->assertWPError( $responses['ssl'] ); + $this->assertSame( 'http_request_failed', $responses['ssl']->get_error_code() ); + $this->assertSame( 'Only HTTP(S) requests are handled.', $responses['ssl']->get_error_message() ); + } + + /** + * @ticket 37459 + */ + public function test_safe_variant_should_reject_unsafe_urls_for_every_request() { + $reject_unsafe_urls = array(); + + add_filter( + 'http_request_args', + static function ( $parsed_args, $url ) use ( &$reject_unsafe_urls ) { + $reject_unsafe_urls[ $url ] = $parsed_args['reject_unsafe_urls']; + return $parsed_args; + }, + 10, + 2 + ); + add_filter( 'pre_http_request', array( $this, 'short_circuit_example_org' ), 10, 3 ); + + $responses = wp_safe_remote_request_multiple( + array( + 'https://example.org/string', + array( 'url' => 'https://example.org/no-args' ), + array( + 'url' => 'https://example.org/string-args', + 'args' => 'method=HEAD', + ), + array( + 'url' => 'https://example.org/array-args', + 'args' => array( 'reject_unsafe_urls' => false ), + ), + ) + ); + + $this->assertSame( + array( + 'https://example.org/string' => true, + 'https://example.org/no-args' => true, + 'https://example.org/string-args' => true, + 'https://example.org/array-args' => true, + ), + $reject_unsafe_urls + ); + + foreach ( $responses as $response ) { + $this->assertSame( 200, wp_remote_retrieve_response_code( $response ) ); + } + } + + /** + * @ticket 37459 + * @group external-http + */ + public function test_should_send_the_requests_and_return_their_responses() { + $file = $this->temp_filename(); + + $responses = wp_remote_request_multiple( + array( + 'redirected' => array( + 'url' => self::REDIRECTION_SCRIPT . '?code=301&rt=2', + 'args' => array( 'redirection' => 5 ), + ), + 'not_followed' => array( + 'url' => self::REDIRECTION_SCRIPT . '?code=302&rt=1', + 'args' => array( 'redirection' => 0 ), + ), + 'head' => array( + 'url' => self::FILE_URL, + 'args' => array( 'method' => 'HEAD' ), + ), + 'stream' => array( + 'url' => self::FILE_URL, + 'args' => array( + 'stream' => true, + 'filename' => $file, + 'timeout' => 30, + ), + ), + ) + ); + + foreach ( $responses as $response ) { + $this->skipTestOnTimeout( $response ); + } + + $this->assertSame( array( 'redirected', 'not_followed', 'head', 'stream' ), array_keys( $responses ) ); + + $this->assertNotWPError( $responses['redirected'] ); + $this->assertSame( 200, wp_remote_retrieve_response_code( $responses['redirected'] ) ); + + $this->assertNotWPError( $responses['not_followed'] ); + $this->assertSame( 302, wp_remote_retrieve_response_code( $responses['not_followed'] ) ); + + $this->assertNotWPError( $responses['head'] ); + $this->assertSame( 200, wp_remote_retrieve_response_code( $responses['head'] ) ); + $this->assertSame( 'image/png', wp_remote_retrieve_header( $responses['head'], 'Content-Type' ) ); + $this->assertSame( '', wp_remote_retrieve_body( $responses['head'] ) ); + + $this->assertNotWPError( $responses['stream'] ); + $this->assertSame( 200, wp_remote_retrieve_response_code( $responses['stream'] ) ); + $this->assertSame( $file, $responses['stream']['filename'] ); + $this->assertSame( 153204, filesize( $file ) ); + + unlink( $file ); + } + + /** + * @ticket 37459 + * @group external-http + */ + public function test_should_process_each_response_individually() { + $filtered = array(); + $debugged = array(); + + add_filter( + 'http_response', + static function ( $response, $parsed_args, $url ) use ( &$filtered ) { + $filtered[] = $url; + return $response; + }, + 10, + 3 + ); + add_action( + 'http_api_debug', + static function ( $response, $context, $transport, $parsed_args, $url ) use ( &$debugged ) { + $debugged[] = $url; + }, + 10, + 5 + ); + + $requests = $this->get_head_requests( 2 ); + $responses = wp_remote_request_multiple( $requests ); + + foreach ( $responses as $response ) { + $this->skipTestOnTimeout( $response ); + } + + $urls = wp_list_pluck( $requests, 'url' ); + + $this->assertSame( $urls, $filtered, "The 'http_response' filter should be applied to each response." ); + $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 + */ + public function test_should_send_the_other_requests_when_one_cannot_be_batched() { + $responses = wp_remote_request_multiple( + array( + 'ssl' => 'ssl://example.org/', + 'head' => array( + 'url' => self::FILE_URL, + 'args' => array( 'method' => 'HEAD' ), + ), + ) + ); + + $this->skipTestOnTimeout( $responses['head'] ); + + $this->assertWPError( $responses['ssl'] ); + $this->assertNotWPError( $responses['head'] ); + $this->assertSame( 200, wp_remote_retrieve_response_code( $responses['head'] ) ); + } + + /** + * @ticket 37459 + * @group external-http + * + * @covers WP_HTTP_Requests_Hooks::dispatch + */ + public function test_should_fire_http_api_curl_for_each_batched_request() { + $this->skip_without_curl(); + + $count = 0; + + add_action( + 'http_api_curl', + static function () use ( &$count ) { + ++$count; + } + ); + + $responses = wp_remote_request_multiple( $this->get_head_requests( 2 ) ); + + foreach ( $responses as $response ) { + $this->skipTestOnTimeout( $response ); + } + + $this->assertSame( 2, $count ); + } + + /** + * @ticket 37459 + * @group external-http + */ + public function test_should_send_at_most_concurrency_requests_at_once() { + $this->skip_without_curl(); + + $batches = 0; + + add_action( + 'requests-curl.before_multi_exec', + static function () use ( &$batches ) { + ++$batches; + } + ); + + $responses = wp_remote_request_multiple( $this->get_head_requests( 3 ), array( 'concurrency' => 2 ) ); + + foreach ( $responses as $response ) { + $this->skipTestOnTimeout( $response ); + } + + $this->assertSame( 2, $batches ); + } + + /** + * @ticket 37459 + * @group external-http + */ + public function test_should_apply_the_concurrency_filter() { + $this->skip_without_curl(); + + $batches = 0; + + add_action( + 'requests-curl.before_multi_exec', + static function () use ( &$batches ) { + ++$batches; + } + ); + add_filter( + 'http_request_multiple_concurrency', + static function () { + return 1; + } + ); + + $responses = wp_remote_request_multiple( $this->get_head_requests( 3 ) ); + + foreach ( $responses as $response ) { + $this->skipTestOnTimeout( $response ); + } + + $this->assertSame( 3, $batches ); + } + + /** + * Short-circuits requests to example.org with a 200 response whose message is the request URL. + * + * @param false|array|WP_Error $response A preemptive return value of an HTTP request. + * @param array $parsed_args HTTP request arguments. + * @param string $url The request URL. + * @return false|array|WP_Error The short-circuited response for example.org, $response otherwise. + */ + public function short_circuit_example_org( $response, $parsed_args, $url ) { + if ( 0 !== strpos( $url, 'https://example.org/' ) ) { + return $response; + } + + return array( + 'headers' => array(), + 'body' => '', + 'response' => array( + 'code' => 200, + 'message' => $url, + ), + 'cookies' => array(), + 'filename' => null, + ); + } + + /** + * Returns HEAD requests for distinct URLs that are served with a direct 200 response. + * + * @param int $count Number of requests. + * @return array Requests, see wp_remote_request_multiple(). + */ + private function get_head_requests( $count ) { + $requests = array(); + + for ( $i = 1; $i <= $count; $i++ ) { + $requests[] = array( + 'url' => self::FILE_URL . '?' . $i, + 'args' => array( 'method' => 'HEAD' ), + ); + } + + return $requests; + } + + /** + * Lets requests reach WP_Http, for tests whose URLs are rejected before anything is sent. + * + * The test suite blocks external requests on the 'pre_http_request' filter, which runs + * before WP_Http validates the URL. The tests calling this only use URLs that WP_Http or + * the Requests library reject before a transport is used, so no request leaves the process. + */ + private function allow_requests_rejected_before_sending() { + remove_filter( 'pre_http_request', array( $this, 'block_external_http_request' ), PHP_INT_MAX ); + } + + /** + * Skips the current test when the cURL transport of the Requests library is not available. + */ + private function skip_without_curl() { + if ( ! WpOrg\Requests\Transport\Curl::test() ) { + $this->markTestSkipped( 'This test requires the cURL transport.' ); + } + } +} 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 ); /* 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; 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/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' ); 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 { 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; } /** 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. * diff --git a/tests/phpunit/tests/post/getAvailablePostMimeTypes.php b/tests/phpunit/tests/post/getAvailablePostMimeTypes.php index cf6f46b920324..4946efcdfe037 100644 --- a/tests/phpunit/tests/post/getAvailablePostMimeTypes.php +++ b/tests/phpunit/tests/post/getAvailablePostMimeTypes.php @@ -20,18 +20,10 @@ public function tear_down() { public function test_should_return_expected_post_mime_types() { // Upload a JPEG image. - $filename = DIR_TESTDATA . '/images/test-image.jpg'; - $contents = file_get_contents( $filename ); - $upload = wp_upload_bits( wp_basename( $filename ), null, $contents ); - $this->assertEmpty( $upload['error'], 'Uploading a JPEG file should not result in an error.' ); - $this->_make_attachment( $upload ); + self::factory()->attachment->create_upload_object( DIR_TESTDATA . '/images/test-image.jpg' ); // Upload a PDF file. - $filename = DIR_TESTDATA . '/images/test-alpha.pdf'; - $contents = file_get_contents( $filename ); - $upload = wp_upload_bits( wp_basename( $filename ), null, $contents ); - $this->assertEmpty( $upload['error'], 'Uploading a PDF file should not result in an error.' ); - $this->_make_attachment( $upload ); + self::factory()->attachment->create_upload_object( DIR_TESTDATA . '/images/test-alpha.pdf' ); $mime_types = get_available_post_mime_types(); diff --git a/tests/phpunit/tests/post/isPostStatusViewable.php b/tests/phpunit/tests/post/isPostStatusViewable.php index 0cb2d505a134d..c4e983cd56361 100644 --- a/tests/phpunit/tests/post/isPostStatusViewable.php +++ b/tests/phpunit/tests/post/isPostStatusViewable.php @@ -9,21 +9,10 @@ class Tests_Post_IsPostStatusViewable extends WP_UnitTestCase { public function tear_down() { _unregister_post_status( 'wp_tests_ps' ); - _unregister_post_status( 'WP_Tests_ps' ); parent::tear_down(); } - /** - * Remove the test status from the global when finished. - * - * @global $wp_post_statuses - */ - public static function wpTearDownAfterClass() { - _unregister_post_status( 'wp_tests_ps' ); - _unregister_post_status( 'WP_Tests_ps' ); - } - /** * Test custom post status. * diff --git a/tests/phpunit/tests/post/nav-menu.php b/tests/phpunit/tests/post/nav-menu.php index 1dab2f8b442ad..87282bccff6c0 100644 --- a/tests/phpunit/tests/post/nav-menu.php +++ b/tests/phpunit/tests/post/nav-menu.php @@ -1393,4 +1393,235 @@ public function test_wp_update_nav_menu_item_with_post_date() { $post = get_post( $menu_item_id ); $this->assertEqualsWithDelta( strtotime( gmdate( 'Y-m-d H:i:s' ) ), strtotime( $post->post_date ), 2, 'The dates should be equal' ); } + + /** + * Adds a nav menu item via the public API. + * + * @param int $menu_id Menu term ID. + * @param array $args Overrides for wp_update_nav_menu_item() data. + * @return int Menu item post ID. + */ + protected function add_nav_menu_item( $menu_id, $args = array() ) { + $id = wp_update_nav_menu_item( + $menu_id, + 0, + array_merge( + array( + 'menu-item-type' => 'custom', + 'menu-item-title' => 'Item', + 'menu-item-url' => 'https://example.org/', + 'menu-item-status' => 'publish', + ), + $args + ) + ); + $this->assertNotWPError( $id ); + return (int) $id; + } + + /** + * Plucks db_id values from a wp_get_nav_menu_items() result. + * + * @param int|string|WP_Term $menu Menu. + * @param array $args Args. + * @return int[] + */ + protected function get_nav_menu_item_db_ids( $menu, $args = array() ) { + $items = wp_get_nav_menu_items( $menu, $args ); + $this->assertIsArray( $items, 'wp_get_nav_menu_items() did not return an array.' ); + return array_map( 'intval', wp_list_pluck( $items, 'db_id' ) ); + } + + /** + * Runs the same query wp_get_nav_menu_items() would run, directly through + * get_posts(), bypassing the menu term count. + * + * @param WP_Term $menu Menu term object. + * @param array $extra_args Args merged over the function's own defaults. + * @return int[] Post IDs the direct query returns. + */ + protected function direct_nav_menu_item_query_ids( $menu, $extra_args = array() ) { + $args = wp_parse_args( + $extra_args, + array( + 'order' => 'ASC', + 'orderby' => 'menu_order', + 'post_type' => 'nav_menu_item', + 'post_status' => 'publish', + 'nopaging' => true, + 'tax_query' => array( + array( + 'taxonomy' => 'nav_menu', + 'field' => 'term_taxonomy_id', + 'terms' => $menu->term_taxonomy_id, + ), + ), + ) + ); + return array_map( 'intval', wp_list_pluck( get_posts( $args ), 'ID' ) ); + } + + /** + * Draft-only menu: the term count is 0 because only published items are + * counted, but a caller asking for 'draft' items must still get them. + * + * @ticket 66102 + * @covers ::wp_get_nav_menu_items + */ + public function test_wp_get_nav_menu_items_draft_only_menu_draft_query() { + $d = $this->add_nav_menu_item( $this->menu_id, array( 'menu-item-status' => 'draft' ) ); + + $menu = wp_get_nav_menu_object( $this->menu_id ); + $this->assertSame( 0, (int) $menu->count, 'Premise failed: draft item was counted.' ); + + // Premise: a direct identical query does return the item. + $this->assertSame( array( $d ), $this->direct_nav_menu_item_query_ids( $menu, array( 'post_status' => 'draft' ) ) ); + + $this->assertSame( + array( $d ), + $this->get_nav_menu_item_db_ids( $this->menu_id, array( 'post_status' => 'draft' ) ), + 'Draft item in a draft-only menu was hidden by the $menu->count > 0 gate.' + ); + } + + /** + * Draft-only menu queried with post_status 'any'. + * + * @ticket 66102 + * @covers ::wp_get_nav_menu_items + */ + public function test_wp_get_nav_menu_items_draft_only_menu_any_query() { + $d = $this->add_nav_menu_item( $this->menu_id, array( 'menu-item-status' => 'draft' ) ); + + $menu = wp_get_nav_menu_object( $this->menu_id ); + $this->assertSame( 0, (int) $menu->count, 'Premise failed: draft item was counted.' ); + $this->assertSame( array( $d ), $this->direct_nav_menu_item_query_ids( $menu, array( 'post_status' => 'any' ) ) ); + + $this->assertSame( + array( $d ), + $this->get_nav_menu_item_db_ids( $this->menu_id, array( 'post_status' => 'any' ) ), + 'Draft item hidden from post_status=any by the $menu->count > 0 gate.' + ); + } + + /** + * Draft-only menu queried with 'publish,draft' — the same post_status core + * itself uses inside wp_update_nav_menu_item(). + * + * @ticket 66102 + * @covers ::wp_get_nav_menu_items + */ + public function test_wp_get_nav_menu_items_draft_only_menu_publish_draft_query() { + $d = $this->add_nav_menu_item( $this->menu_id, array( 'menu-item-status' => 'draft' ) ); + + $menu = wp_get_nav_menu_object( $this->menu_id ); + $this->assertSame( 0, (int) $menu->count, 'Premise failed: draft item was counted.' ); + $this->assertSame( array( $d ), $this->direct_nav_menu_item_query_ids( $menu, array( 'post_status' => 'publish,draft' ) ) ); + + $this->assertSame( + array( $d ), + $this->get_nav_menu_item_db_ids( $this->menu_id, array( 'post_status' => 'publish,draft' ) ), + 'Draft item hidden from post_status=publish,draft by the $menu->count > 0 gate.' + ); + } + + /** + * Adding a second draft item to a draft-only menu must position it after + * the first. wp_update_nav_menu_item() computes the position from the + * publish,draft item list, which the count gate must not empty. + * + * @ticket 66102 + * @covers ::wp_get_nav_menu_items + */ + public function test_wp_get_nav_menu_items_second_draft_item_position() { + $d1 = $this->add_nav_menu_item( $this->menu_id, array( 'menu-item-status' => 'draft' ) ); + $d2 = $this->add_nav_menu_item( $this->menu_id, array( 'menu-item-status' => 'draft' ) ); + + $pos1 = (int) get_post( $d1 )->menu_order; + $pos2 = (int) get_post( $d2 )->menu_order; + + $this->assertGreaterThan( + $pos1, + $pos2, + "Second draft item got menu_order {$pos2} <= first item's {$pos1} — the count gate hid the first item from wp_update_nav_menu_item()." + ); + } + + /** + * A published item attached while wp_defer_term_counting() is enabled + * leaves the term count stale at 0; the default publish query must still + * return the item. + * + * @ticket 66102 + * @covers ::wp_get_nav_menu_items + */ + public function test_wp_get_nav_menu_items_deferred_term_counting() { + wp_defer_term_counting( true ); + $item = $this->add_nav_menu_item( $this->menu_id ); + + $menu = wp_get_nav_menu_object( $this->menu_id ); + $this->assertSame( 0, (int) $menu->count, 'Premise failed: count was not deferred.' ); + $this->assertSame( array( $item ), $this->direct_nav_menu_item_query_ids( $menu ), 'Premise failed: direct query does not see the item.' ); + + $items = $this->get_nav_menu_item_db_ids( $this->menu_id ); + wp_defer_term_counting( false ); + + $this->assertSame( + array( $item ), + $items, + 'Published item attached during deferred term counting was hidden by the stale $menu->count gate.' + ); + } + + /** + * A caller holding a stale WP_Term snapshot (count fetched before the item + * was added) must still get the item: wp_get_nav_menu_object() returns a + * passed object verbatim, so a stale count must not short-circuit the + * query. + * + * @ticket 66102 + * @covers ::wp_get_nav_menu_items + */ + public function test_wp_get_nav_menu_items_stale_term_object() { + $stale_obj = wp_get_nav_menu_object( $this->menu_id ); // count = 0 snapshot. + $this->assertSame( 0, (int) $stale_obj->count, 'Premise failed.' ); + + $a = $this->add_nav_menu_item( $this->menu_id ); // count is now 1 in DB. + + // Sanity: a fresh fetch sees count 1 and returns the item. + $this->assertSame( array( $a ), $this->get_nav_menu_item_db_ids( $this->menu_id ) ); + + $items = wp_get_nav_menu_items( $stale_obj ); + $this->assertIsArray( $items ); + $this->assertSame( + array( $a ), + array_map( 'intval', wp_list_pluck( $items, 'db_id' ) ), + 'A stale WP_Term snapshot hid a real published item.' + ); + } + + /** + * Trash-only menu: once the last published item is trashed the term count + * returns to 0, but a post_status 'trash' query must still see the + * trashed item. + * + * @ticket 66102 + * @covers ::wp_get_nav_menu_items + */ + public function test_wp_get_nav_menu_items_trash_only_menu_trash_query() { + $a = $this->add_nav_menu_item( $this->menu_id ); + $this->assertSame( array( $a ), $this->get_nav_menu_item_db_ids( $this->menu_id ) ); + + wp_trash_post( $a ); + + $menu = wp_get_nav_menu_object( $this->menu_id ); + $this->assertSame( 0, (int) $menu->count, 'Premise failed: trashed item still counted.' ); + $this->assertSame( array( $a ), $this->direct_nav_menu_item_query_ids( $menu, array( 'post_status' => 'trash' ) ) ); + + $this->assertSame( + array( $a ), + $this->get_nav_menu_item_db_ids( $this->menu_id, array( 'post_status' => 'trash' ) ), + 'Trashed item hidden by the $menu->count > 0 gate.' + ); + } } 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/post/wpListPages.php b/tests/phpunit/tests/post/wpListPages.php index 6a5c66324d5f1..c22d11aa5b192 100644 --- a/tests/phpunit/tests/post/wpListPages.php +++ b/tests/phpunit/tests/post/wpListPages.php @@ -341,7 +341,7 @@ public function test_wp_list_pages_exclude_should_accept_a_comma_separated_strin * * @return array */ - public function data_wp_list_pages_exclude_separators(): array { + public static function data_wp_list_pages_exclude_separators(): array { return array( 'comma' => array( ',' ), 'comma and spaces' => array( ' , ' ), @@ -353,7 +353,7 @@ public function data_wp_list_pages_exclude_separators(): array { * * @return array */ - public function data_wp_list_pages_id_list_callbacks(): array { + public static function data_wp_list_pages_id_list_callbacks(): array { return array( 'integers' => array( 'intval' ), 'numeric strings' => array( @@ -504,7 +504,7 @@ public function test_wp_page_menu_should_not_exclude_front_page( bool $show_home * * @return array */ - public function data_wp_page_menu_without_front_page_exclusion(): array { + public static function data_wp_page_menu_without_front_page_exclusion(): array { return array( 'no Home link, static front page' => array( 'show_home' => false, @@ -541,7 +541,7 @@ private function get_listed_page_ids( string $html ): array { * * @return array */ - public function data_wp_page_menu_exclude_formats(): array { + public static function data_wp_page_menu_exclude_formats(): array { return array( 'array of integers' => array( 'array_values' ), 'array of numeric strings' => array( diff --git a/tests/phpunit/tests/privacy/wpPrivacyProcessPersonalDataExportPage.php b/tests/phpunit/tests/privacy/wpPrivacyProcessPersonalDataExportPage.php index d49fa1d51aca2..d38625fcd2455 100644 --- a/tests/phpunit/tests/privacy/wpPrivacyProcessPersonalDataExportPage.php +++ b/tests/phpunit/tests/privacy/wpPrivacyProcessPersonalDataExportPage.php @@ -195,6 +195,14 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { public function set_up() { parent::set_up(); + // Ensure the request is confirmed so that email sending succeeds. + wp_update_post( + array( + 'ID' => self::$request_id, + 'post_status' => 'request-confirmed', + ) + ); + // Avoid writing export files to disk. Using `WP_Filesystem_MockFS` is blocked by #44204. remove_action( 'wp_privacy_personal_data_export_file', 'wp_privacy_generate_personal_data_export_file', 10 ); @@ -515,6 +523,40 @@ public function test_send_error_on_last_page_of_last_exporter_when_mail_delivery ); } + /** + * When the request has not been confirmed, the function should send a JSON error on the last page + * of the last exporter when sending as email, and leave the request status unchanged. + * + * @ticket 65758 + */ + public function test_send_error_on_last_page_of_last_exporter_when_request_is_not_confirmed() { + wp_update_post( + array( + 'ID' => self::$request_id, + 'post_status' => 'request-pending', + ) + ); + + $this->expectOutputString( '{"success":false,"data":"Invalid request status when sending personal data export email."}' ); + + try { + wp_privacy_process_personal_data_export_page( + self::$response_last_page, + self::$exporter_index_last, + self::$requester_email, + self::$page_index_last, + self::$request_id, + true, + self::$exporter_key_last + ); + $this->fail( 'Expected a WPDieException.' ); + } catch ( WPDieException $e ) { + // Expected; fall through to check the request status. + } + + $this->assertSame( 'request-pending', get_post_status( self::$request_id ) ); + } + /** * The function should return the response, containing the export file URL, when not sent as email * for the last exporter on the last page. @@ -645,20 +687,20 @@ public static function data_export_page_status_transitions() { true, 'last', ), - // Leave the request as pending for the last exporter on the last page, without email. + // Leave the request as confirmed for the last exporter on the last page, without email. // This check was updated to account for admin vs user export. // Don't mark the request as completed when it's an admin download. array( - 'request-pending', + 'request-confirmed', 'last', 'last', 'last', false, 'last', ), - // Leave the request as pending when not the last exporter and not on the last page. + // Leave the request as confirmed when not the last exporter and not on the last page. array( - 'request-pending', + 'request-confirmed', 'first', 'first', 'first', @@ -666,16 +708,16 @@ public static function data_export_page_status_transitions() { 'first', ), array( - 'request-pending', + 'request-confirmed', 'first', 'first', 'first', false, 'first', ), - // Leave the request as pending when last exporter and not on the last page. + // Leave the request as confirmed when last exporter and not on the last page. array( - 'request-pending', + 'request-confirmed', 'first', 'last', 'first', @@ -683,16 +725,16 @@ public static function data_export_page_status_transitions() { 'last', ), array( - 'request-pending', + 'request-confirmed', 'first', 'last', 'first', false, 'last', ), - // Leave the request as pending when not last exporter on the last page. + // Leave the request as confirmed when not last exporter on the last page. array( - 'request-pending', + 'request-confirmed', 'last', 'first', 'last', @@ -700,7 +742,7 @@ public static function data_export_page_status_transitions() { 'last', ), array( - 'request-pending', + 'request-confirmed', 'last', 'first', 'last', diff --git a/tests/phpunit/tests/privacy/wpPrivacySendPersonalDataExportEmail.php b/tests/phpunit/tests/privacy/wpPrivacySendPersonalDataExportEmail.php index 37e2e4c282bd5..45b81cffeea00 100644 --- a/tests/phpunit/tests/privacy/wpPrivacySendPersonalDataExportEmail.php +++ b/tests/phpunit/tests/privacy/wpPrivacySendPersonalDataExportEmail.php @@ -129,6 +129,84 @@ public function test_should_return_wp_error_when_not_a_user_request() { $this->assertSame( 'invalid_request', $email_sent->get_error_code() ); } + /** + * The function should error, without sending an email, when the request has not been confirmed. + * + * @ticket 65758 + * + * @dataProvider data_unconfirmed_request_statuses + * + * @param string $status The request status. + */ + public function test_should_return_wp_error_when_request_is_not_confirmed( $status ) { + $request_id = wp_create_user_request( "export-$status@example.com", 'export_personal_data' ); + wp_update_post( + array( + 'ID' => $request_id, + 'post_status' => $status, + ) + ); + + $email_sent = wp_privacy_send_personal_data_export_email( $request_id ); + $mailer = tests_retrieve_phpmailer_instance(); + + $this->assertWPError( $email_sent ); + $this->assertSame( 'invalid_request', $email_sent->get_error_code() ); + $this->assertSame( 'Invalid request status when sending personal data export email.', $email_sent->get_error_message() ); + $this->assertFalse( $mailer->get_sent() ); + $this->assertSame( $status, get_post_status( $request_id ) ); + } + + /** + * Data provider for test_should_return_wp_error_when_request_is_not_confirmed(). + * + * @return array[] + */ + public static function data_unconfirmed_request_statuses() { + return array( + 'pending' => array( 'request-pending' ), + 'failed' => array( 'request-failed' ), + ); + } + + /** + * The function should send the email when the request has been confirmed or already completed. + * + * @ticket 65758 + * + * @dataProvider data_confirmed_request_statuses + * + * @param string $status The request status. + */ + public function test_should_send_email_when_request_is_confirmed_or_completed( $status ) { + $email = "export-$status@example.com"; + $request_id = wp_create_user_request( $email, 'export_personal_data' ); + wp_update_post( + array( + 'ID' => $request_id, + 'post_status' => $status, + ) + ); + + $email_sent = wp_privacy_send_personal_data_export_email( $request_id ); + $mailer = tests_retrieve_phpmailer_instance(); + + $this->assertTrue( $email_sent ); + $this->assertSame( $email, $mailer->get_recipient( 'to' )->address ); + } + + /** + * Data provider for test_should_send_email_when_request_is_confirmed_or_completed(). + * + * @return array[] + */ + public static function data_confirmed_request_statuses() { + return array( + 'confirmed' => array( 'request-confirmed' ), + 'completed' => array( 'request-completed' ), + ); + } + /** * The function should error when the email was not sent. * @@ -438,7 +516,7 @@ public function test_should_send_personal_data_export_email_in_site_locale() { $request_id = wp_create_user_request( 'export-user-not-registered@example.com', 'export_personal_data' ); - _wp_privacy_account_request_confirmed( self::$request_id ); + _wp_privacy_account_request_confirmed( $request_id ); wp_privacy_send_personal_data_export_email( $request_id ); $mailer = tests_retrieve_phpmailer_instance(); @@ -463,7 +541,7 @@ public function test_should_send_personal_data_export_email_in_site_locale_when_ $request_id = wp_create_user_request( 'export-user-not-registered@example.com', 'export_personal_data' ); - _wp_privacy_account_request_confirmed( self::$request_id ); + _wp_privacy_account_request_confirmed( $request_id ); wp_privacy_send_personal_data_export_email( $request_id ); $mailer = tests_retrieve_phpmailer_instance(); 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/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/rest-comments-controller.php b/tests/phpunit/tests/rest-api/rest-comments-controller.php index 898b344842f9a..513bdbfd51220 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() { @@ -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/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/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/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 ) { 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 ); } /** 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/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/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', 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/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' ) ); 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' ); } /** 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(); 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 */ 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 807eda9d2cf92..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": { @@ -13134,11 +13139,13 @@ mockedApiResponse.Schema = { "kind": { "description": "Entity kind.", "type": "string", + "minLength": 1, "required": true }, "name": { "description": "Entity name.", "type": "string", + "minLength": 1, "required": true } } 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",