From d4fac42a3811cae0e462da853c61067ccc512cbe Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 06:14:04 +0530 Subject: [PATCH 01/80] refactor(compat-scanner): drop the walk budgets and size caps The scan deadline is now the only bound on the walk, so a big media site, a large mixed file or a busy cache no longer gives "can't confirm" or "didn't finish" because of its size. - Directories searched by name (uploads/, cache/, node_modules/, ...) lose their file, byte and time budgets (COMPAT_SKIPPED_FILES, COMPAT_SKIPPED_BYTES, COMPAT_SKIPPED_SECONDS). - The www-data home dirs in /var/www (.wp-cli, .composer, .cache, ...) are searched by name like uploads/. - Mixed files over 1 MiB are scanned, data-only stubs are read to the end, and the file list is spooled to disk with no size cap. - Backup copies (last extension bak, orig, old, save, swp, log, sql or dist) aren't read, so a stale copy can't give "not safe". - A file deleted after the listing is dropped instead of reported unreadable. - The manifest is written only with COMPAT_MANIFEST=1, which the fixture tests set. --- compat-scanner/bin/compat-scanner.php | 236 +++++--------------------- compat-scanner/tests/assert.php | 100 +++++------ compat-scanner/tests/fixture.sh | 26 +-- compat-scanner/tests/run.sh | 13 +- 4 files changed, 109 insertions(+), 266 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 0f1b1c99..dab93f36 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -41,11 +41,8 @@ const BUFFER_MAX = 262144; // File extensions checked as PHP code, matched case-insensitively. const CODE_EXTENSIONS = [ 'php', 'inc', 'phtml', 'module', 'install', 'theme', 'engine', 'php5', 'php7' ]; -// Other files are read this far for a PHP open tag; one that has it later than the start and is larger than SNIFF_MAX isn't checked. +// Other files are read this far for a PHP open tag. const SNIFF_BYTES = 8192; -const SNIFF_MAX = 1048576; -// A data-only candidate larger than this isn't read to the end: it is scanned (and counted) like other code. -const DATA_MAX = 8388608; // A file PHPCS reads through STDIN is copied to /out first; past this it is refused by size (`memory`), not copied. // Real PHP code of 8 MiB already exceeds 960M, though a mostly-comment file that large could be checked. const STDIN_MAX = 16777216; @@ -55,6 +52,10 @@ const SNIFF_REGEX = '/\\A(?=[^\\x00]*\\z)[\\s\\S]*?<\\?(?:php(?:\\s|\\z)|=)/i'; const PHAR_REGEX = '/\\.phar(?:\\.(?:tar|zip))?(?:\\.(?:gz|bz2))?\\z/i'; // Never PHP templates, so not sniffed: docs, scripts and styles quote ` Manifest spools (`checked`, `not_checked`) not yet written, by name. */ private $manBuf = [ 'checked' => '', 'not_checked' => '' ]; - /** @var int */ - private $manBytes = 0; /** @var string[] Real paths (with `/`) of the directories searched by name only, where nothing is sniffed. */ private $skippedDirs = []; @@ -137,8 +132,6 @@ final class Scanner { private $listFh; /** @var string */ private $listBuf = ''; - /** @var int Bytes of the file list spool. */ - private $listBytes = 0; /** @var int Bytes of findings and not_checked entries spooled so far. */ private $reportBytes = 0; @@ -151,8 +144,6 @@ public function __construct( array $cfg ) { $this->timeoutLabel = $limit; $this->deadline = $this->start + $limit; $this->listDeadline = $this->isScan ? $this->deadline : $this->deadline - min( CALIBRATION_RESERVE, $limit / 4 ); - $this->skippedBudget = (float) $cfg['skipped_seconds']; - $this->homeBudget = (float) $cfg['home_seconds']; } public function run(): array { @@ -344,7 +335,10 @@ private function enterContent( string $root ): bool { return true; } - /** Php sites: what lies in /var/www beside htdocs (code above the public dir). */ + /** + * Php sites: what lies in /var/www beside htdocs (code above the public dir). Links come last, so a directory is + * listed under its own name before a link to it. + */ private function scanBeside(): void { $this->markDir( MOUNT_ROOT ); $loose = $this->comp( 'directory', '..', null, MOUNT_ROOT ); @@ -358,119 +352,15 @@ private function scanBeside(): void { if ( 'htdocs' === $name ) { continue; } - $path = MOUNT_ROOT . '/' . $name; - if ( '.' !== $name[0] || in_array( $name, ANY_SKIPS, true ) ) { - $this->scanTop( MOUNT_ROOT, [ $name ], $loose, '../' ); - continue; - } - $real = $this->resolve( $path ); - if ( is_link( $path ) ) { - // Home rule: a dot link that doesn't resolve counts only by a code name (dotfile managers, tool links). - if ( null === $real ? $this->isPhpName( $name ) || $this->isPharName( $name ) : ! is_dir( $real ) ) { - $this->scanTop( MOUNT_ROOT, [ $name ], $loose, '../' ); - } elseif ( null !== $real ) { - $links[] = $name; - } - } elseif ( null !== $real && is_dir( $real ) && ! $this->holdsRoot( $real ) && ! $this->outOfScope( $real ) ) { - $this->homeDir( $path, $name, $loose ); + if ( is_link( MOUNT_ROOT . '/' . $name ) ) { + $links[] = $name; + } elseif ( in_array( $name, HOME_DIRS, true ) ) { + $this->skipped( MOUNT_ROOT . '/' . $name, $name, $loose ); } else { - // A dot dir holding the scan root is walked like any directory above it (the root itself gives nothing); dot files are site code. $this->scanTop( MOUNT_ROOT, [ $name ], $loose, '../' ); } } - // A dot link to a directory: after the rest, so a target walked by its own name gives nothing more. One into a - // dot dir of /var/www is that dir's business. - foreach ( $links as $name ) { - $real = (string) $this->resolve( MOUNT_ROOT . '/' . $name ); - $top = strstr( substr( $real . '/', strlen( MOUNT_ROOT ) + 1 ), '/', true ); - if ( MOUNT_ROOT === $real || '.' !== $top[0] || in_array( $top, ANY_SKIPS, true ) ) { - $this->scanTop( MOUNT_ROOT, [ $name ], $loose, '../' ); - } - } - } - - /** - * A dot dir of /var/www, the www-data user's home (Composer and WP-CLI caches): tool code, not the site's, so it - * isn't scanned. It is one `skipped` entry when it holds a code file (by name or sniff, as the manifest defines one), - * or one `unreadable` entry when part of it can't be searched. - */ - private function homeDir( string $path, string $name, int $comp ): void { - $reason = $this->homeCode( $path ); - if ( null !== $reason ) { - $this->notChecked( $comp, $name . '/', $reason ); - } - } - - /** - * 'skipped' when a home dot dir holds a code file, stopping at the first, or its search outruns the budget all dot - * dirs share (COMPAT_HOME_SECONDS, apart from the skipped dirs' one); 'unreadable' when part of it can't be - * searched; else null. A link that doesn't resolve counts only by a code name (home rule). - */ - private function homeCode( string $dir ): ?string { - $seen = []; - $stack = [ $dir ]; - $stop = microtime( true ) + $this->homeBudget; - $found = false; - $unreadable = false; - while ( $stack && ! $found ) { - $d = array_pop( $stack ); - $st = @stat( $d ); - if ( false === $st || isset( $seen[ $st['dev'] ][ $st['ino'] ] ) ) { - continue; - } - $seen[ $st['dev'] ][ $st['ino'] ] = true; - - $handle = @opendir( $d ); - if ( false === $handle ) { - $unreadable = true; - continue; - } - if ( ! $this->searchable( $d ) ) { - $unreadable = $unreadable || $this->hasEntries( $handle ); - closedir( $handle ); - continue; - } - while ( ! $found && false !== ( $name = readdir( $handle ) ) ) { - if ( '.' === $name || '..' === $name ) { - continue; - } - $this->tick(); - if ( microtime( true ) > $stop ) { - $found = true; - break; - } - $path = $d . '/' . $name; - // One lstat for most entries; only links are resolved. - $lst = @lstat( $path ); - if ( false === $lst ) { - continue; - } - $type = $lst['mode'] & 0170000; - $real = $path; - if ( 0120000 === $type ) { - $real = $this->resolve( $path ); - if ( null === $real ) { - $found = $this->isPhpName( $name ) || $this->isPharName( $name ); - continue; - } - $type = is_dir( $real ) ? 0040000 : ( is_file( $real ) ? 0100000 : 0 ); - } - if ( 0040000 === $type ) { - // A real subdir is in scope with its parent; a link is checked by its target. - if ( $real === $path || ! $this->outOfScope( $real ) ) { - $stack[] = $path; - } - } elseif ( 0100000 === $type ) { - $found = $this->codeLike( $name, $real ); - } - } - closedir( $handle ); - } - $this->homeBudget = max( 0.0, $stop - microtime( true ) ); - if ( $found ) { - return 'skipped'; - } - return $unreadable ? 'unreadable' : null; + $this->scanTop( MOUNT_ROOT, $links, $loose, '../' ); } /** @@ -817,7 +707,8 @@ private function visit( string $path, string $name, int $comp ): void { $mixed = false; if ( ! $this->isPhpName( $name ) && ! $this->isPhpName( $real ) ) { // Any name can be included. One PHP can't read can't run either, so it isn't reported. - if ( in_array( strtolower( (string) pathinfo( $name, PATHINFO_EXTENSION ) ), NO_SNIFF_EXTENSIONS, true ) ) { + $ext = strtolower( (string) pathinfo( $name, PATHINFO_EXTENSION ) ); + if ( in_array( $ext, NO_SNIFF_EXTENSIONS, true ) || in_array( $ext, BACKUP_EXTENSIONS, true ) ) { return; } $tag = $this->sniff( $real ); @@ -827,10 +718,6 @@ private function visit( string $path, string $name, int $comp ): void { $mixed = 'mixed' === $tag; } $this->seenFiles[ $st['dev'] ][ $st['ino'] ] = true; - if ( $mixed && $st['size'] > SNIFF_MAX ) { - $this->notChecked( $comp, $this->rel( $comp, $path ), 'php_tag' ); - return; - } if ( ! is_readable( $real ) ) { $this->notChecked( $comp, $this->rel( $comp, $path ), 'unreadable' ); @@ -858,15 +745,9 @@ private function visit( string $path, string $name, int $comp ): void { $this->stdinFiles++; } if ( $this->isScan ) { - // Relative to the component's base; the spool counts against the report cap too. + // Relative to the component's base. $rel = $this->rel( $comp, $path ); - $entry = pack( 'VPV', $comp, $st['size'], strlen( $rel ) | ( $mixed ? MIXED_FLAG : 0 ) ) . $rel; - - $this->listBytes += strlen( $entry ); - if ( $this->listBytes > $this->cfg['report_max'] ) { - throw new ToolError( sprintf( 'file list larger than %d bytes', $this->cfg['report_max'] ) ); - } - $this->listBuf .= $entry; + $this->listBuf .= pack( 'VPV', $comp, $st['size'], strlen( $rel ) | ( $mixed ? MIXED_FLAG : 0 ) ) . $rel; if ( strlen( $this->listBuf ) >= BUFFER_MAX ) { $this->flushList(); } @@ -874,8 +755,8 @@ private function visit( string $path, string $name, int $comp ): void { } /** - * A directory skipped by name (uploads/, cache/, node_modules/, ...): only its code-named files are listed (no sniff), - * e.g. Wordfence's wflogs/*.php or W3TC's cache files. Past the bounds the directory is one not_checked entry instead. + * A directory searched by name only (uploads/, cache/, node_modules/, ...): only its code-named files are listed (no + * sniff), e.g. Wordfence's wflogs/*.php or W3TC's cache files. */ private function skipped( string $path, string $file, int $comp ): void { // A link that dangles or leaves the mount can't be searched (uploads -> /mnt/... included). @@ -895,13 +776,8 @@ private function skipped( string $path, string $file, int $comp ): void { if ( $this->isScan ) { $this->skippedDirs[] = $real . '/'; } - $hits = $this->codeIn( $path ); - if ( null === $hits ) { - $this->notChecked( $comp, $file . '/', 'skipped' ); - return; - } $this->inSkipped = true; - foreach ( $hits as $hit => $unlistable ) { + foreach ( $this->codeIn( $path ) as $hit => $unlistable ) { if ( $unlistable ) { $this->notChecked( $comp, $this->rel( $comp, $hit ) . '/', 'unreadable' ); } else { @@ -913,18 +789,14 @@ private function skipped( string $path, string $file, int $comp ): void { /** * Code-named and .phar entries of a tree (and bad links that may be code), sorted, each => whether it is a - * directory that can't be listed; null past COMPAT_SKIPPED_FILES files, COMPAT_SKIPPED_BYTES bytes of files - * PHPCS would read (data-only files don't count) or the COMPAT_SKIPPED_SECONDS all skipped dirs share. + * directory that can't be listed. * - * @return array|null + * @return array */ - private function codeIn( string $dir ): ?array { + private function codeIn( string $dir ): array { $hits = []; - $bytes = 0; $seen = []; $stack = [ $dir ]; - $start = microtime( true ); - $stop = $start + $this->skippedBudget; while ( $stack ) { $d = array_pop( $stack ); $st = @stat( $d ); @@ -951,11 +823,6 @@ private function codeIn( string $dir ): ?array { continue; } $this->tick(); - if ( microtime( true ) > $stop ) { - closedir( $handle ); - $this->skippedBudget = 0.0; - return null; - } $path = $d . '/' . $name; // One stat for most entries: only directories and code or extension-less names need more. if ( is_dir( $path ) ) { @@ -967,25 +834,13 @@ private function codeIn( string $dir ): ?array { } continue; } - if ( $this->isPhpName( $name ) || $this->isPharName( $name ) ) { - $size = @filesize( $path ); - $r = $this->resolve( $path ); - if ( false !== $size && ! ( null !== $r && $this->dataOnly( $r ) ) ) { - $bytes += $size; - } - } elseif ( preg_match( '/\.[A-Za-z0-9]{1,8}\z/', $name ) || ! is_link( $path ) || null !== $this->resolve( $path ) ) { - continue; - } - $hits[ $path ] = false; - if ( count( $hits ) > $this->cfg['skipped_files'] || $bytes > $this->cfg['skipped_bytes'] || microtime( true ) > $stop ) { - closedir( $handle ); - $this->skippedBudget = max( 0.0, $stop - microtime( true ) ); - return null; + $badLink = ! preg_match( '/\.[A-Za-z0-9]{1,8}\z/', $name ) && is_link( $path ) && null === $this->resolve( $path ); + if ( $badLink || $this->isPhpName( $name ) || $this->isPharName( $name ) ) { + $hits[ $path ] = false; } } closedir( $handle ); } - $this->skippedBudget = max( 0.0, $stop - microtime( true ) ); ksort( $hits, SORT_STRING ); return $hits; } @@ -1004,7 +859,6 @@ private function dataOnly( string $path ): bool { $ok = (bool) preg_match( '/\A(?:\xEF\xBB\xBF)?<\?php\s+(?:exit|die)\s*(?:\(\s*(?:\'[^\'\\\\]*\'|"[^"\\\\$]*"|\d+)?\s*\))?\s*;?\s*(__halt_compiler\s*\(\s*\)\s*;?\s*)?\?>/i', $head, $m ); if ( $ok && empty( $m[1] ) ) { $rest = substr( $head, strlen( $m[0] ) ); - $read = strlen( $head ); while ( true ) { if ( preg_match( '/<\?(?:php(?:\s|\z)|=)/i', $rest ) ) { $ok = false; @@ -1018,11 +872,6 @@ private function dataOnly( string $path ): bool { if ( '' === $more ) { break; } - $read += strlen( $more ); - if ( $read > DATA_MAX ) { - $ok = false; // Not read to the end: never counted as checked unread. - break; - } $rest = substr( $rest, -5 ) . $more; // A tag split across reads. } } @@ -1527,7 +1376,10 @@ private function runBatch( array $batch ): void { $remaining = $plain; foreach ( $batch as $f ) { if ( null === $f['real'] ) { - $this->spoolNotChecked( $f['comp'], $this->rel( $f['comp'], $f['path'] ), 'unreadable' ); + // A deleted file can't run; one that can't be reached or is no longer a regular file isn't checked. + if ( file_exists( $f['path'] ) || is_link( $f['path'] ) || $this->denied( $f['path'] ) ) { + $this->spoolNotChecked( $f['comp'], $this->rel( $f['comp'], $f['path'] ), 'unreadable' ); + } continue; } if ( null !== $reader && ! $f['stdin'] ) { @@ -1710,6 +1562,9 @@ private function spoolNotChecked( int $comp, string $file, string $reason, ?stri $this->addReportBytes( strlen( $entry ) ); $this->append( $this->work . '/not_checked', $entry ); $this->notCheckedCount++; + if ( ! $this->cfg['manifest'] ) { + return; + } // The manifest names it by real path; a directory (`…/`) covers everything below it. $dir = '/' === substr( $file, -1 ); @@ -1724,7 +1579,7 @@ private function spoolNotChecked( int $comp, string $file, string $reason, ?stri /** A file counted as checked, once per inode (hard links and two routes to one file). */ private function manifestChecked( string $real, array $st ): void { - if ( ! $this->isScan || 'm' === ( $this->seenFiles[ $st['dev'] ][ $st['ino'] ] ?? null ) ) { + if ( ! $this->cfg['manifest'] || 'm' === ( $this->seenFiles[ $st['dev'] ][ $st['ino'] ] ?? null ) ) { return; } $this->seenFiles[ $st['dev'] ][ $st['ino'] ] = 'm'; @@ -1732,20 +1587,14 @@ private function manifestChecked( string $real, array $st ): void { } private function manifestAdd( string $list, string $path ): void { - $entry = ',' . json_encode( manifest_path( $path ), JSON_FLAGS ); - - $this->manBytes += strlen( $entry ); - if ( $this->manBytes > $this->cfg['report_max'] ) { - throw new ToolError( sprintf( 'file manifest larger than %d bytes', $this->cfg['report_max'] ) ); - } - $this->manBuf[ $list ] .= $entry; + $this->manBuf[ $list ] .= ',' . json_encode( manifest_path( $path ), JSON_FLAGS ); if ( strlen( $this->manBuf[ $list ] ) >= BUFFER_MAX ) { $this->append( $this->work . "/m-$list", $this->manBuf[ $list ] ); $this->manBuf[ $list ] = ''; } } - /** /out/manifest.json: what the scan covered, by real path, with the rules to re-derive the code files. */ + /** /out/manifest.json (COMPAT_MANIFEST=1, for tests): what the scan covered, by real path, with the rules to re-derive the code files. */ private function writeManifest(): void { foreach ( $this->manBuf as $list => $data ) { if ( '' !== $data ) { @@ -1762,7 +1611,7 @@ private function writeManifest(): void { 'sniff' => [ 'bytes' => SNIFF_BYTES, 'regex' => SNIFF_REGEX, - 'exclude_extensions' => NO_SNIFF_EXTENSIONS, + 'exclude_extensions' => array_merge( NO_SNIFF_EXTENSIONS, BACKUP_EXTENSIONS ), 'scope' => 'except_skipped_dirs', 'skipped_dirs' => array_values( array_unique( array_map( 'manifest_path', $this->skippedDirs ) ) ), ], @@ -1862,7 +1711,9 @@ static function ( $a, $b ) use ( $comps ) { } ); - $this->writeManifest(); + if ( $this->cfg['manifest'] ) { + $this->writeManifest(); + } $this->writeReport( $doc, $listed ); $this->removeWork(); $this->debug( sprintf( 'entrypoint peak memory %d bytes', memory_get_peak_usage() ) ); @@ -2533,12 +2384,9 @@ function parse_args( array $argv, array &$cfg ): void { $cfg['low_factor'] = env_float( 'COMPAT_LOW_FACTOR', 0.8 ); $cfg['high_factor'] = env_float( 'COMPAT_HIGH_FACTOR', 1.5 ); $cfg['report_max'] = env_int( 'COMPAT_REPORT_MAX', REPORT_MAX, 1024 ); - $cfg['skipped_files'] = env_int( 'COMPAT_SKIPPED_FILES', 100000 ); - $cfg['skipped_bytes'] = env_int( 'COMPAT_SKIPPED_BYTES', 67108864 ); - $cfg['skipped_seconds'] = env_int( 'COMPAT_SKIPPED_SECONDS', 60, 0 ); $cfg['sniffed_timeout'] = env_int( 'COMPAT_SNIFFED_TIMEOUT', 30 ); $cfg['file_timeout'] = env_int( 'COMPAT_FILE_TIMEOUT', 120 ); - $cfg['home_seconds'] = env_int( 'COMPAT_HOME_SECONDS', 60, 0 ); + $cfg['manifest'] = 'scan' === $cfg['mode'] && '1' === getenv( 'COMPAT_MANIFEST' ); if ( $cfg['low_factor'] > 1 || $cfg['high_factor'] < 1 ) { throw new BadArgs( 'COMPAT_LOW_FACTOR must be at most 1 and COMPAT_HIGH_FACTOR at least 1' ); } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 36cc323e..83d6d726 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -280,7 +280,8 @@ static function ( $a, $b ) { check( null !== $fc_rc && ( 25 === ( $fc_rc & 0x7f ) || ( 255 === $fc_rc && false !== strpos( $fc_err, 'errno=27 File too large' ) ) ), "flood-cap: PHPCS stopped at the file size limit (rc=$fc_rc)" ); check( false !== strpos( raw( 'flood-cap.stderr' ), 'core limit 0' ), 'flood-cap: core dumps disabled' ); tool_error( 'full-cap', 'report larger than 100000 bytes', 1 ); -tool_error( 'wide-cap', 'file list larger than 100000 bytes', 1 ); +$wc = out( 'wide-cap' ); +eq( [ $wc['status'] ?? null, $wc['files_checked'] ?? null ], [ 'ok', 20000 ], 'wide-cap: no cap on the file list, only on findings' ); tool_error( 'fullout', 'could not write', 1, false ); // ------------------------------------------------------------- wp-config.php @@ -437,12 +438,13 @@ static function ( $a, $b ) { } $pb = out( 'phpbeside' ); -eq( [ $pb['status'] ?? null, field( $pb, 'safe_to_upgrade' ), $pb['errors'] ?? null, $pb['files_checked'] ?? null, $pb['files_not_checked'] ?? null ], [ 'ok', false, 2, 3, 2 ], 'phpbeside: code beside htdocs checked, tool dirs with code not_checked' ); -eq( report( 'phpbeside' )['not_checked'] ?? null, [ nc( 'directory', '..', null, '.composer/', 'skipped' ), nc( 'directory', '..', null, '.wp-cli/', 'skipped' ) ], 'phpbeside: dot dirs of /var/www holding code are skipped entries' ); +eq( [ $pb['status'] ?? null, field( $pb, 'safe_to_upgrade' ), $pb['errors'] ?? null, $pb['files_checked'] ?? null, $pb['files_not_checked'] ?? null ], [ 'ok', false, 4, 5, 0 ], 'phpbeside: code beside htdocs checked, and the code-named files of the home dirs' ); +eq( report( 'phpbeside' )['not_checked'] ?? null, [], 'phpbeside: home dirs holding code are no entries' ); +eq( finding_files( report( 'phpbeside' ) ), [ 'directory:../app::src/boot.php', 'directory:..::.composer/vendor/x/y.php', 'directory:..::.wp-cli/packages/z.php', 'directory:..::lib.php' ], 'phpbeside: findings in the home dirs count' ); eq( comp_rows( report( 'phpbeside' ) ), [ - [ 'directory', '..', null, null, null, 1, 1, 0 ], + [ 'directory', '..', null, null, null, 3, 3, 0 ], [ 'directory', '../app', null, null, null, 1, 1, 0 ], [ 'other', '', null, null, null, 1, 0, 0 ], ], @@ -475,7 +477,7 @@ static function ( $a, $b ) { $ext = out( 'ext' ); $r = report( 'ext' ); -eq( [ $ext['status'] ?? null, field( $ext, 'safe_to_upgrade' ), $ext['errors'] ?? null, $ext['warnings'] ?? null, $ext['files_checked'] ?? null, $ext['files_not_checked'] ?? null, $ext['components_checked'] ?? null, $ext['components_with_errors'] ?? null ], [ 'ok', false, 15, 0, 19, 3, 4, 3 ], 'ext: verdict and counts' ); +eq( [ $ext['status'] ?? null, field( $ext, 'safe_to_upgrade' ), $ext['errors'] ?? null, $ext['warnings'] ?? null, $ext['files_checked'] ?? null, $ext['files_not_checked'] ?? null, $ext['components_checked'] ?? null, $ext['components_with_errors'] ?? null ], [ 'ok', false, 15, 0, 19, 4, 4, 3 ], 'ext: verdict and counts' ); eq( comp_rows( $r ), [ @@ -498,10 +500,11 @@ static function ( $a, $b ) { $r['not_checked'] ?? null, [ [ 'type' => 'plugin', 'slug' => 'ext', 'branch' => null, 'file' => 'gone.inc', 'reason' => 'unreadable' ], + [ 'type' => 'plugin', 'slug' => 'ext', 'branch' => null, 'file' => 'gone.old', 'reason' => 'unreadable' ], [ 'type' => 'other', 'slug' => '', 'branch' => null, 'file' => 'plugins/gone.inc', 'reason' => 'unreadable' ], [ 'type' => 'other', 'slug' => '', 'branch' => null, 'file' => 'themes/gone.inc', 'reason' => 'unreadable' ], ], - 'ext: dangling code-named links are unreadable, in plugins/ and themes/ under other' + 'ext: dangling code-named links, and one with a backup name, are unreadable, in plugins/ and themes/ under other' ); $err = raw( 'ext.stderr' ); preg_match_all( '/\] single (\S+) at /', $err, $m ); @@ -539,8 +542,8 @@ static function ( $f ) { return "/var/www/htdocs/wp-content/plugins/$f"; }, eq( trim( raw( 'changed-gone.sync' ) ), 'ok', 'changed-gone: the change lands after the listing, before the next file' ); $cg = out( 'changed-gone' ); -eq( [ $cg['status'] ?? null, field( $cg, 'safe_to_upgrade' ), $cg['files_checked'] ?? null ], [ 'ok', null, 1 ], 'changed-gone: no verdict, the remaining file checked' ); -eq( report( 'changed-gone' )['not_checked'] ?? null, [ [ 'type' => 'plugin', 'slug' => 'p', 'branch' => null, 'file' => 'z.php', 'reason' => 'unreadable' ] ], 'changed-gone: a file deleted since the listing is unreadable' ); +eq( [ $cg['status'] ?? null, field( $cg, 'safe_to_upgrade' ), $cg['files_checked'] ?? null ], [ 'ok', true, 1 ], 'changed-gone: the remaining file checked' ); +eq( report( 'changed-gone' )['not_checked'] ?? null, [], 'changed-gone: a file deleted since the listing can\'t run, so it is dropped' ); $sl = out( 'slashes' ); $r = report( 'slashes' ); @@ -596,30 +599,6 @@ function finding_files( array $report ): array { ); $e = out( 'est-skipdirs' ); eq( [ $e['php_files'] ?? null, $e['php_bytes'] ?? null, $e['components'] ?? null ], [ 19, $sd['php_bytes'] ?? null, 3 ], 'est-skipdirs: counts equal the scan' ); -foreach ( [ 'skipdirs-files' => 'more than COMPAT_SKIPPED_FILES', 'skipdirs-bytes' => 'more than COMPAT_SKIPPED_BYTES (data-only files not counted)' ] as $name => $what ) { - $b = out( $name ); - eq( [ $b['errors'] ?? null, $b['files_checked'] ?? null, $b['files_not_checked'] ?? null ], [ 6, 8, 3 ], "$name: uploads/ not listed" ); - eq( report( $name )['not_checked'][1] ?? null, nc( 'other', '', null, 'uploads/', 'skipped' ), "$name: a skipped dir with $what of code is one entry" ); -} - -eq( - report( 'skipdirs-time' )['not_checked'] ?? null, - [ - nc( 'plugin', 'p', null, '.git/', 'skipped' ), - nc( 'plugin', 'p', null, 'node_modules/', 'skipped' ), - nc( 'plugin', 'q', null, 'node_modules/', 'skipped' ), - nc( 'other', '', null, '.git/', 'skipped' ), - nc( 'other', '', null, 'cache/', 'skipped' ), - nc( 'other', '', null, 'node_modules/', 'skipped' ), - nc( 'other', '', null, 'upgrade-temp-backup/', 'skipped' ), - nc( 'other', '', null, 'upgrade/', 'skipped' ), - nc( 'other', '', null, 'uploads/', 'skipped' ), - nc( 'directory', 'htdocs', null, '.git/', 'unreadable' ), - nc( 'directory', 'htdocs', null, 'node_modules/', 'skipped' ), - ], - 'skipdirs-time: with no time left for skipped dirs, each one with anything in it is a skipped entry, code or not' -); - $sp = out( 'skipdirs-php' ); eq( [ $sp['status'] ?? null, field( $sp, 'safe_to_upgrade' ), $sp['errors'] ?? null, $sp['files_checked'] ?? null, $sp['files_not_checked'] ?? null ], [ 'ok', false, 7, 18, 2 ], 'skipdirs-php: a php site walks uploads/ and cache/ whole (a .txt is never sniffed); node_modules/ and .git/ code files checked' ); eq( @@ -650,25 +629,25 @@ function finding_files( array $report ): array { $sn = out( 'sniff' ); $r = report( 'sniff' ); -eq( [ $sn['status'] ?? null, field( $sn, 'safe_to_upgrade' ), $sn['errors'] ?? null, $sn['files_checked'] ?? null, $sn['files_not_checked'] ?? null ], [ 'ok', false, 4, 6, 5 ], 'sniff: verdict and counts (README.md, notes.txt, app.js, app.ts, style.css, data.json, big.txt and logo.png are not sniffed or not PHP)' ); +eq( [ $sn['status'] ?? null, field( $sn, 'safe_to_upgrade' ), $sn['errors'] ?? null, $sn['files_checked'] ?? null, $sn['files_not_checked'] ?? null ], [ 'ok', false, 4, 7, 4 ], 'sniff: verdict and counts (README.md, notes.txt, app.js, app.ts, style.css, data.json, big.txt and logo.png are not sniffed or not PHP)' ); eq( array_column( array_filter( comp_of( $r, 'plugin', 'p' )['findings'] ?? [], static function ( $f ) { return 'WARNING' === $f['type']; } ), 'file' ), [ 'views/warn.html' ], 'sniff: a later tag with warnings only is checked and its warnings kept' ); eq( finding_files( $r ), [ 'plugin:p::a-tpl.txt', 'plugin:p::bin/tool', 'plugin:p::views/admin.tpl', 'plugin:p::views/bom.html', 'plugin:p::views/warn.html' ], 'sniff: files starting with 2506, 'cache50k' => 50006 ] as $name => $n ) { $ca = out( $name ); - eq( [ $ca['status'] ?? null, field( $ca, 'safe_to_upgrade' ), $ca['errors'] ?? null, $ca['files_checked'] ?? null, $ca['files_not_checked'] ?? null ], [ 'ok', false, 1, $n, 0 ], "$name: W3TC, WP Super Cache and Wordfence-style data files are checked without PHPCS; Docket Cache code and a data file too large to read to the end are scanned" ); + eq( [ $ca['status'] ?? null, field( $ca, 'safe_to_upgrade' ), $ca['errors'] ?? null, $ca['files_checked'] ?? null, $ca['files_not_checked'] ?? null ], [ 'ok', false, 1, $n, 0 ], "$name: W3TC, WP Super Cache and Wordfence-style data files, a 9 MB one too, are checked without PHPCS; Docket Cache code is scanned" ); eq( finding_files( report( $name ) ), [ 'other:::cache/object/tail.php' ], "$name: a data header followed by another open tag is scanned" ); check( ( $ca['duration_s'] ?? 999 ) < 120, "$name: done in " . ( $ca['duration_s'] ?? '?' ) . ' s' ); } -check( 1 === preg_match_all( '/\] batch 4 files rc=/', raw( 'cache.stderr' ) ), 'cache: one PHPCS batch, of p.php, the Docket Cache file, tail.php and huge.php (data-only files take no run)' ); +check( 1 === preg_match_all( '/\] batch 3 files rc=/', raw( 'cache.stderr' ) ), 'cache: one PHPCS batch, of p.php, the Docket Cache file and tail.php (data-only files, huge.php too, take no run)' ); $e = out( 'est-cache' ); eq( [ $e['php_files'] ?? null, $e['components'] ?? null ], [ 2506, 2 ], 'est-cache: counts equal the scan' ); @@ -735,14 +714,14 @@ function finding_files( array $report ): array { // Php sites: dot dirs of /var/www (the www-data home) are one entry when they hold code; one holding the public dir is walked. $pd = out( 'phpdot' ); -eq( [ $pd['status'] ?? null, field( $pd, 'safe_to_upgrade' ), $pd['errors'] ?? null, $pd['files_checked'] ?? null, $pd['files_not_checked'] ?? null ], [ 'ok', false, 2, 3, 2 ], 'phpdot: verdict and counts' ); -eq( finding_files( report( 'phpdot' ) ), [ 'directory:../.release::lib/helper.php', 'directory:..::.user.php' ], 'phpdot: code beside the public dir in .release, and a dot file, are checked' ); -eq( report( 'phpdot' )['not_checked'] ?? null, [ nc( 'directory', '..', null, '.composer/', 'skipped' ), nc( 'directory', '..', null, '.wp-cli/', 'skipped' ) ], 'phpdot: dot dirs holding code (a code name, or a sniffed vendor/bin script) are entries; caches are not' ); -$m = json_decode( raw( 'phpdot.manifest.json' ), true ); -eq( [ $m['sniff']['skipped_dirs'] ?? null, $m['not_checked'] ?? null ], [ [], [ '/var/www/.composer/', '/var/www/.wp-cli/' ] ], 'phpdot: manifest not_checked; dot dirs are not skipped dirs (the sniff applies there)' ); +eq( [ $pd['status'] ?? null, field( $pd, 'safe_to_upgrade' ), $pd['errors'] ?? null, $pd['files_checked'] ?? null, $pd['files_not_checked'] ?? null ], [ 'ok', false, 3, 4, 0 ], 'phpdot: verdict and counts' ); +eq( finding_files( report( 'phpdot' ) ), [ 'directory:../.release::lib/helper.php', 'directory:..::.user.php', 'directory:..::.wp-cli/packages/vendor/v/v.php' ], 'phpdot: code beside the public dir in .release, a dot file and a code file in the home are checked; the home\'s extension-less script isn\'t sniffed' ); +$home = [ '/var/www/.cache/', '/var/www/.composer/', '/var/www/.npm/', '/var/www/.wp-cli/' ]; +$m = json_decode( raw( 'phpdot.manifest.json' ), true ); +eq( [ $m['sniff']['skipped_dirs'] ?? null, $m['not_checked'] ?? null ], [ $home, [] ], 'phpdot: the home dirs are searched by name only' ); $pr = out( 'phpdot-root' ); eq( [ $pr['status'] ?? null, field( $pr, 'safe_to_upgrade' ), $pr['files_checked'] ?? null, $pr['files_not_checked'] ?? null ], [ 'ok', true, 1, 0 ], 'phpdot-root: htdocs -> .release is scanned as the root; tool caches give no entry' ); -eq( json_decode( raw( 'phpdot-root.manifest.json' ), true )['sniff']['skipped_dirs'] ?? null, [], 'phpdot-root: no skipped dirs' ); +eq( json_decode( raw( 'phpdot-root.manifest.json' ), true )['sniff']['skipped_dirs'] ?? null, $home, 'phpdot-root: the home dirs are searched by name only' ); // A directory uid 33 can list but not search is one entry, also inside a skipped dir. $ut = out( 'untrav' ); @@ -756,6 +735,11 @@ function finding_files( array $report ): array { // ----------------------------------------------------------- file manifest +$bk = out( 'bak' ); +eq( [ $bk['status'] ?? null, field( $bk, 'safe_to_upgrade' ), $bk['errors'] ?? null, $bk['files_checked'] ?? null, $bk['files_not_checked'] ?? null ], [ 'ok', true, 0, 2, 0 ], 'bak: backup-named files (bak, orig, SAVE, sql) aren\'t read, also one wp-config.php requires' ); +eq( json_decode( raw( 'bak.manifest.json' ), true )['checked'] ?? null, [ '/var/www/htdocs/wp-config.php', '/var/www/htdocs/wp-content/themes/t/functions.php' ], 'bak: only the code files checked' ); +eq( [ out( 'nomanifest' )['status'] ?? null, trim( raw( 'nomanifest.outdir' ) ) ], [ 'ok', './report.json' ], 'nomanifest: without COMPAT_MANIFEST, /out holds only report.json' ); + // r7: a link into an old release or the root's core is an entry by the link's own path (a release pointer beside // current, and a non-code file link, aren't); php home dot dirs; the per-file cap; the STDIN copy cap. $ol = out( 'oldlink' ); @@ -767,14 +751,20 @@ function finding_files( array $report ): array { eq( report( 'corelink' )['not_checked'] ?? null, [ nc( 'other', '', null, 'mu-plugins/', 'unreadable' ), nc( 'plugin', 'clean', null, 'boot.php', 'unreadable' ), nc( 'plugin', 'clean', null, 'inc/', 'unreadable' ), nc( 'other', '', null, 'plugins/coreplug/', 'unreadable' ), nc( 'plugin', 'lnk', null, 'lib.d', 'unreadable' ), nc( 'plugin', 'lnk', null, 'part', 'unreadable' ), nc( 'plugin', 'lnk', null, 'shm', 'unreadable' ), nc( 'other', '', null, 'themes/t/', 'unreadable' ), nc( 'other', '', null, 'cache/', 'unreadable' ), nc( 'other', '', null, 'uploads/d/', 'unreadable' ), nc( 'other', '', null, 'uploads/x.php', 'unreadable' ) ], 'corelink: core links (file, dir, plugin dir, theme dir, mu-plugins, a skipped name, links in uploads/) and lib.d/part/shm leaving the mount; not v.txt, out.log, readme.txt, or links to exactly /dev/null, /dev/stdout, /dev/stderr (debug.log, error_log, access, trace)' ); eq( json_decode( raw( 'corelink.manifest.json' ), true )['not_checked'] ?? null, [ '/var/www/htdocs/wp-content/mu-plugins/', '/var/www/htdocs/wp-content/plugins/clean/boot.php', '/var/www/htdocs/wp-content/plugins/clean/inc/', '/var/www/htdocs/wp-content/plugins/coreplug/', '/var/www/htdocs/wp-content/plugins/lnk/lib.d', '/var/www/htdocs/wp-content/plugins/lnk/part', '/var/www/htdocs/wp-content/plugins/lnk/shm', '/var/www/htdocs/wp-content/themes/t/', '/var/www/htdocs/wp-content/cache/', '/var/www/htdocs/wp-content/uploads/d/', '/var/www/htdocs/wp-content/uploads/x.php' ], 'corelink: manifest by link path, never a core path' ); $ph = out( 'phphome' ); -eq( [ $ph['status'] ?? null, field( $ph, 'safe_to_upgrade' ), $ph['files_checked'] ?? null, $ph['files_not_checked'] ?? null ], [ 'ok', null, 2, 3 ], 'phphome: verdict and counts' ); -eq( report( 'phphome' )['not_checked'] ?? null, [ nc( 'directory', '..', null, '.emptylocked/', 'unreadable' ), nc( 'directory', '..', null, '.locked2/', 'unreadable' ), nc( 'directory', '..', null, '.x.php', 'unreadable' ) ], 'phphome: dot dirs uid 33 can\'t open are unreadable; dangling non-code links and a dot link to a walked dir give nothing' ); +eq( [ $ph['status'] ?? null, field( $ph, 'safe_to_upgrade' ), $ph['files_checked'] ?? null, $ph['files_not_checked'] ?? null ], [ 'ok', null, 2, 6 ], 'phphome: verdict and counts' ); +eq( + report( 'phphome' )['not_checked'] ?? null, + [ + nc( 'directory', '..', null, '.config/chromium/SingletonLock', 'unreadable' ), + nc( 'directory', '../.emptylocked', null, './', 'unreadable' ), + nc( 'directory', '../.locked2', null, './', 'unreadable' ), + nc( 'directory', '../.venv', null, 'bin/python', 'unreadable' ), + nc( 'directory', '../.bashrc', null, './', 'unreadable' ), + nc( 'directory', '..', null, '.x.php', 'unreadable' ), + ], + 'phphome: dangling links follow the rules of uploads/ in a home dir and of any dir elsewhere; dirs uid 33 can\'t open are unreadable; a dot link to a walked dir gives nothing' +); eq( json_decode( raw( 'phphome.manifest.json' ), true )['checked'] ?? null, [ '/var/www/htdocs/index.php', '/var/www/lib/l.php' ], 'phphome: the dot link\'s target is checked by its own name' ); -foreach ( [ 'homebudget-skipped0' => [ nc( 'other', '', null, 'node_modules/', 'skipped' ) ], 'homebudget-home0' => [ nc( 'directory', '..', null, '.cache/', 'skipped' ) ] ] as $name => $want ) { - $hb = out( $name ); - eq( [ $hb['status'] ?? null, field( $hb, 'safe_to_upgrade' ), $hb['files_checked'] ?? null ], [ 'ok', null, 1 ], "$name: verdict and counts" ); - eq( report( $name )['not_checked'] ?? null, $want, "$name: dot dirs and skipped dirs have separate time budgets" ); -} $sc = out( 'slowcode' ); eq( [ $sc['status'] ?? null, field( $sc, 'safe_to_upgrade' ), $sc['errors'] ?? null, $sc['files_checked'] ?? null, $sc['files_not_checked'] ?? null ], [ 'ok', false, 1, 3, 1 ], 'slowcode: a code-named file past COMPAT_FILE_TIMEOUT doesn\'t stop the scan' ); eq( report( 'slowcode' )['not_checked'] ?? null, [ nc( 'plugin', 'p', null, 'slow.php', 'timeout' ) ], 'slowcode: the slow file alone is timeout; its batch neighbours are checked' ); @@ -794,7 +784,7 @@ function finding_files( array $report ): array { foreach ( glob( "$dir/*.stdout" ) as $f ) { $name = basename( $f, '.stdout' ); $doc = json_decode( (string) file_get_contents( $f ), true ); - if ( ! is_array( $doc ) || 'ok' !== ( $doc['status'] ?? null ) || ! empty( $doc['estimate'] ) ) { + if ( ! is_array( $doc ) || 'ok' !== ( $doc['status'] ?? null ) || ! empty( $doc['estimate'] ) || 'nomanifest' === $name ) { check( ! is_file( "$dir/$name.manifest.json" ), "$name: no manifest unless the scan is ok" ); continue; } @@ -819,7 +809,7 @@ function finding_files( array $report ): array { static function ( $f ) { return "/var/www/htdocs/wp-content/plugins/p/$f"; }, - [ 'bin/tool', 'p.php', 'tpl.php', 'views/admin.tpl', 'views/bom.html', 'views/warn.html' ] + [ 'big-mixed.tpl', 'bin/tool', 'p.php', 'tpl.php', 'views/admin.tpl', 'views/bom.html', 'views/warn.html' ] ), 'manifest: sniff checked (the link a-tpl.txt as its target tpl.php)' ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index b301856f..1ab5bab3 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -427,6 +427,8 @@ ext_fixture() { # Not code: never listed. for f in readme.txt x.phps x.js; do php_file "$wc/plugins/ext/$f" 'each( $a );'; done ln -s nowhere.inc "$wc/plugins/ext/gone.inc" + # A dangling link under a backup name still counts: the php container may see a file there. + ln -s nowhere.old "$wc/plugins/ext/gone.old" # Only a lowercase .php file is a single-file plugin or a header candidate, as in WordPress. php_file "$wc/plugins/legacy.inc" '/* Plugin Name: Not A Plugin */ @@ -791,16 +793,6 @@ phphome_fixture() { chmod 0700 "$a/.emptylocked" "$a/.locked2" } -# homebudget_fixture : a php site with a code-free dot dir and a code-free node_modules beside the code. -homebudget_fixture() { - local a=$1 - php_file "$a/htdocs/index.php" 'echo 1;' - mkdir -p "$a/.cache" "$a/htdocs/node_modules/a" - printf 'data\n' > "$a/.cache/blob.bin" - printf 'readme\n' > "$a/htdocs/node_modules/a/readme" - chmod -R a+rX "$a" -} - # slowcode_fixture : a code-named file that keeps PHPCompatibility looping (an unterminated nested string, as in # PHPCS's own DoubleQuotedStringTest.inc), beside clean files and one with an error, all in one batch. slowcode_fixture() { @@ -821,3 +813,17 @@ bigstdin_fixture() { { printf ' "$p/HUGE.PHP" chmod -R a+rX "$1" } + +# bak_fixture : backup copies with errors, never read, even one wp-config.php requires (an accepted miss). +bak_fixture() { + local h="$1/htdocs" + php_file "$h/wp-settings.php" + mkdir -p "$h/wp-includes" + php_file "$h/wp-config.php" "require __DIR__ . '/wp-config.php.orig';" + php_file "$h/wp-config.php.orig" 'each( $a );' + php_file "$h/wp-content/themes/t/functions.php" 'echo 1;' + php_file "$h/wp-content/themes/t/functions.php.bak" 'each( $a );' + php_file "$h/wp-content/themes/t/OLD.PHP.SAVE" 'each( $a );' + php_file "$h/dump.sql" 'each( $a );' + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 7475cc6a..e5869c50 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -48,7 +48,7 @@ scan() { --cap-drop ALL --security-opt no-new-privileges --pids-limit 64 \ --memory 1g --memory-swap 1g --cpus 1 --cpu-shares 256 \ --user 33:33 \ - -e COMPAT_SITE=fixture.test -e COMPAT_IMAGE="$IMAGE" "$@" \ + -e COMPAT_SITE=fixture.test -e COMPAT_IMAGE="$IMAGE" -e COMPAT_MANIFEST="${MANIFEST-1}" "$@" \ --mount "type=bind,src=$(realpath "$app"),dst=/var/www,readonly" \ --mount "type=bind,src=$out,dst=/out" \ $(entry) scan "$type" "$path" "$ver" "$timeout" > "$RES/$name.stdout" 2> "$RES/$name.stderr" || rc=$? @@ -275,9 +275,6 @@ sniff_fixture "$WORK/sniff" nested_fixture "$WORK/nested" wordfence_fixture "$WORK/wordfence" scan skipdirs "$WORK/skipdirs" wp /var/www/htdocs 8.4 600 -scan skipdirs-files "$WORK/skipdirs" wp /var/www/htdocs 8.4 600 -e COMPAT_SKIPPED_FILES=7 -scan skipdirs-bytes "$WORK/skipdirs" wp /var/www/htdocs 8.4 600 -e COMPAT_SKIPPED_BYTES=5000 -scan skipdirs-time "$WORK/skipdirs" wp /var/www/htdocs 8.4 600 -e COMPAT_SKIPPED_SECONDS=0 scan wordfence "$WORK/wordfence" wp /var/www/htdocs 8.4 600 estimate est-skipdirs "$WORK/skipdirs" wp /var/www/htdocs 8.4 scan skipdirs-php "$WORK/skipdirs" php /var/www/htdocs 8.4 600 @@ -315,18 +312,20 @@ ENTRY_MEMORY=10M scan pharflood "$WORK/pharflood" wp /var/www/htdocs 8.4 600 oldlink_fixture "$WORK/oldlink" corelink_fixture "$WORK/corelink" phphome_fixture "$WORK/phphome" -homebudget_fixture "$WORK/homebudget" slowcode_fixture "$WORK/slowcode" bigstdin_fixture "$WORK/bigstdin" scan oldlink "$WORK/oldlink" php /var/www/htdocs/current/public 8.4 600 scan corelink "$WORK/corelink" wp /var/www/htdocs 8.4 600 scan phphome "$WORK/phphome" php /var/www/htdocs 8.4 600 -scan homebudget-skipped0 "$WORK/homebudget" php /var/www/htdocs 8.4 600 -e COMPAT_SKIPPED_SECONDS=0 -scan homebudget-home0 "$WORK/homebudget" php /var/www/htdocs 8.4 600 -e COMPAT_HOME_SECONDS=0 scan slowcode "$WORK/slowcode" wp /var/www/htdocs 8.4 600 -e COMPAT_FILE_TIMEOUT=5 -e COMPAT_DEBUG=1 scan bigstdin "$WORK/bigstdin" wp /var/www/htdocs 8.4 600 estimate est-bigstdin "$WORK/bigstdin" wp /var/www/htdocs 8.4 +# Backup copies aren't read; production runs write no manifest. +bak_fixture "$WORK/bak" +scan bak "$WORK/bak" wp /var/www/htdocs 8.4 600 +MANIFEST= scan nomanifest "$WORK/wp-clean" wp /var/www/htdocs/current 8.4 600 + # An estimate keeps time for calibration: throttled, the listing of 20,000 files can't finish in its share of 1 s. estimate est-listing "$WORK/wide" wp /var/www/htdocs 8.4 -e COMPAT_ESTIMATE_TIMEOUT=1 --cpus 0.05 From 32aed79fe1873cc81a12a376e2a8e2f9a0063182 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 06:17:25 +0530 Subject: [PATCH 02/80] feat(compat-scanner): scan all of app/ and judge every WordPress by its version WordPress sites are now scanned beyond the WordPress directory, so EE no longer has to prove anything about the layout before a scan. - wp mode also walks the rest of /var/www (vendor/, config/, adminer.php, a backup copy of the site), with components named by their path under /var/www. - The scan path is the live root only when the scanner sees an install there (wp-settings.php and wp-includes/), with the php container's mounts bound, so the version is read where PHP reads it. - Installs are found everywhere the walk goes, php sites included. Another install's core is left out when its branch is in COMPAT_WP_SUPPORTED, else it stays nested_wordpress. The report lists every install in wordpress_installs. - COMPAT_SERVED decides which old releases are left out: only when `current` lies on that path. The report names them in excluded_old_releases. - COMPAT_EXTRA_ROOTS lists the php container's mounts outside /var/www; they are searched by name. - COMPAT_REQUIRE and .user.ini auto_prepend_file/auto_append_file targets must be files the scan read, else each is one unreadable entry. - A phar is information (listed in phars) unless a scanned file mentions `phar://` or `.phar` (named in phar_named_by). - Malformed COMPAT_SERVED, COMPAT_EXTRA_ROOTS or COMPAT_WP_SUPPORTED is bad arguments. A caller that passes none of the new env (site-command v3.11.1) gets the old behaviour, and the fixture tests cover both. --- compat-scanner/bin/compat-scanner.php | 397 +++++++++++++++++++----- compat-scanner/tests/assert.php | 123 ++++++-- compat-scanner/tests/fixture.sh | 113 ++++++- compat-scanner/tests/manifest-check.php | 29 +- compat-scanner/tests/run.sh | 68 +++- 5 files changed, 609 insertions(+), 121 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index dab93f36..b6e82f37 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -94,9 +94,19 @@ final class Scanner { private $rootReal; /** @var array Directories holding WordPress core, by real path. */ private $coreDirs = []; + /** @var string|null Real path of the scan path when it is a WordPress install: the live root, whose core EE judges. */ + private $live; /** @var array Other WordPress installs whose core was met (and skipped), by real path. */ private $nested = []; - /** @var string[] Real paths of the releases a php site's `current` doesn't point to. */ + /** @var string[] Other installs whose core is left out silently: their branch supports the target. */ + private $leftOut = []; + /** @var array */ + private $installs = []; + /** @var string[] Prepend and append values of the .user.ini files met. */ + private $required = []; + /** @var string[] /var/www and COMPAT_EXTRA_ROOTS: what links may resolve into. */ + private $roots; + /** @var string[] Real paths of the releases `current` doesn't point to, when nginx serves through it. */ private $oldReleases = []; /** @var array> Visited directories by device and inode. */ private $seenDirs = []; @@ -117,12 +127,16 @@ final class Scanner { private $dataFiles = 0; /** @var int */ private $dataBytes = 0; + /** @var int Phars collected, when they may be information (spooled to work/phars in a scan). */ + private $pharCount = 0; + /** @var string|null The first scanned file naming a phar, which makes every phar not_checked. */ + private $pharNamedBy; /** @var int Listed files PHPCS reads through STDIN, one run each (for the estimate). */ private $stdinFiles = 0; /** @var bool Listing the code files found in a skipped directory (where caches keep data-only files). */ private $inSkipped = false; /** @var array Manifest spools (`checked`, `not_checked`) not yet written, by name. */ - private $manBuf = [ 'checked' => '', 'not_checked' => '' ]; + private $manBuf = [ 'checked' => '', 'not_checked' => '', 'information' => '' ]; /** @var string[] Real paths (with `/`) of the directories searched by name only, where nothing is sniffed. */ private $skippedDirs = []; @@ -138,6 +152,7 @@ final class Scanner { public function __construct( array $cfg ) { $this->cfg = $cfg; $this->isScan = 'scan' === $cfg['mode']; + $this->roots = array_merge( [ MOUNT_ROOT ], $cfg['extra_roots'] ); $this->start = microtime( true ); $limit = $this->isScan ? $cfg['timeout'] : $cfg['estimate_timeout']; @@ -161,7 +176,8 @@ public function run(): array { } $this->listFiles(); - if ( 0 === $this->listedFiles && 0 === $this->notCheckedCount && 0 === $this->dataFiles ) { + // WordPress core is code too: its version must reach EE. + if ( 0 === $this->listedFiles && 0 === $this->notCheckedCount && 0 === $this->dataFiles && 0 === $this->pharCount && ! $this->installs ) { $this->removeWork(); return $this->reduced( 'no_code_found' ); } @@ -176,38 +192,113 @@ public function run(): array { // ---------------------------------------------------------------- listing - /** - * Lists the files in scope. For WordPress, plugins, themes and mu-plugins of - * every content root are walked before anything else, so a directory reached - * both from there and through another path belongs to the component; the rest - * of the WordPress directory (everything but core) comes last. - */ + /** Lists the files in scope: the site's root (WordPress or htdocs) first, then the rest of /var/www. */ private function listFiles(): void { $this->pins[ $this->cfg['path'] ] = @realpath( $this->cfg['path'] ); + $served = $this->servedPath(); + if ( '' !== $served ) { + $this->pins[ $served ] = realpath( $served ); + $this->oldReleases = $this->oldReleases( $served ); + } if ( 'php' === $this->cfg['site_type'] ) { $root = MOUNT_ROOT . '/htdocs'; if ( ! $this->enterRoot( $root ) ) { return; } - $this->rootReal = $this->contentReal; - $this->oldReleases = $this->oldReleases( $this->cfg['path'] ); - $other = $this->comp( 'other', '', null, $root ); - $entries = $this->readDir( $root ); + $this->rootReal = $this->contentReal; + $other = $this->comp( 'other', '', null, $root ); + $entries = $this->readDir( $root ); if ( null === $entries ) { $this->notChecked( $other, './', 'unreadable' ); return; } $this->scanTop( $root, $entries, $other, '' ); - $this->scanBeside(); - return; + $this->scanBeside( $this->comp( 'directory', '..', null, MOUNT_ROOT ), '../' ); + } else { + $top = $this->wpDir( $this->cfg['path'] ); + if ( null !== $top ) { + $this->live = $this->coreDir( $this->rootReal ) ? $this->rootReal : null; + $this->wpTree( $this->cfg['path'], $top ); + } + $this->scanBeside( $this->comp( 'directory', '', null, MOUNT_ROOT ), '' ); + } + // Directories the php container mounts outside /var/www: searched by name, after /var/www so a link into one + // keeps its own component. + foreach ( $this->cfg['extra_roots'] as $root ) { + $this->skipped( $root, '.', $this->comp( 'directory', $root, null, $root ) ); + } + $this->checkRequired(); + $this->judgeInstalls(); + } + + /** + * Files PHP loads before or after every script (COMPAT_REQUIRE from EE's ini files, and every .user.ini's): each + * must be a file the scan reads, else it is unreadable, naming the value. Nothing is scanned for them. + */ + private function checkRequired(): void { + $other = $this->comp( 'other', '', null, MOUNT_ROOT ); + foreach ( array_unique( array_merge( $this->cfg['require'], $this->required ) ) as $target ) { + $st = '/' === $target[0] && is_file( $target ) ? stat( $target ) : false; + $seen = false === $st ? null : ( $this->seenFiles[ $st['dev'] ][ $st['ino'] ] ?? null ); + if ( true !== $seen && 'm' !== $seen ) { + $this->notChecked( $other, $target, 'unreadable', $target ); + } } + } - $wp = $this->cfg['path']; - $top = $this->wpDir( $wp ); - $root = $wp . '/wp-content'; - if ( null === $top ) { + /** Collects a .user.ini's auto_prepend_file and auto_append_file values. */ + private function userIni( string $real ): void { + $fh = open_regular( $real ); + if ( null === $fh ) { return; } + while ( false !== ( $line = fgets( $fh ) ) ) { + if ( preg_match( '/^\s*auto_(?:prepend|append)_file\s*=(.*)$/i', $line, $m ) && '' !== ini_value( $m[1] ) ) { + $this->required[] = ini_value( $m[1] ); + } + } + fclose( $fh ); + } + + /** + * What nginx serves, which decides whether old releases are left out: COMPAT_SERVED; a v3.11.1 call has none, and + * then php sites use the scan path and WordPress sites leave nothing out. '' leaves nothing out. + */ + private function servedPath(): string { + if ( false !== $this->cfg['served'] ) { + return $this->cfg['served']; + } + return 'php' === $this->cfg['site_type'] ? $this->cfg['path'] : ''; + } + + /** + * Another install's core is left out, silently when EE says its branch supports the target, else as one + * nested_wordpress entry. Every install, the live one first, goes to the report with its version. + */ + private function judgeInstalls(): void { + if ( null !== $this->live ) { + $this->installs[] = [ 'dir' => $this->live, 'version' => wp_version( $this->live ), 'live' => true ]; + } + $nested = array_keys( $this->nested ); + sort( $nested, SORT_STRING ); + foreach ( $nested as $dir ) { + $version = wp_version( $dir ); + $this->installs[] = [ 'dir' => $dir, 'version' => $version, 'live' => false ]; + if ( in_array( wp_branch( $version ), $this->cfg['wp_supported'], true ) ) { + $this->leftOut[] = $dir; + } else { + $this->notChecked( $this->comp( 'directory', $this->relMount( $dir ), null, $dir ), './', 'nested_wordpress' ); + } + } + } + + /** + * The WordPress directory. Plugins, themes and mu-plugins of every content root are walked before anything else, so + * a directory reached both from there and through another path belongs to the component; the rest of the WordPress + * directory (everything but the live root's core) comes last. + */ + private function wpTree( string $wp, array $top ): void { + $root = $wp . '/wp-content'; $config = $this->wpConfig( $wp ); if ( null !== $config ) { // Reported by its real path relative to /var/www (the file to edit), e.g. htdocs/wp-config.php. @@ -280,11 +371,6 @@ private function listFiles(): void { } // Everything else in the WordPress directory but core: custom endpoints, a second app, a linked target's siblings. $this->scanTop( $wp, $rest, $this->comp( 'directory', $this->relMount( $wp ), null, $wp ), $this->relMount( $wp ) . '/' ); - - // Core of another install isn't scanned (too large) but isn't silent either. - foreach ( array_keys( $this->nested ) as $dir ) { - $this->notChecked( $this->comp( 'directory', $this->relMount( $dir ), null, $dir ), './', 'nested_wordpress' ); - } } /** A directory in scope holding plugins/ or themes/: a content root. */ @@ -293,9 +379,12 @@ private function contentLike( string $path ): bool { return null !== $real && is_dir( $real ) && ! $this->outOfScope( $real ) && ( is_dir( $path . '/plugins' ) || is_dir( $path . '/themes' ) ); } - /** Path relative to /var/www, as given (unresolved). */ + /** Path relative to /var/www, as given (unresolved); a path outside it stays absolute. */ private function relMount( string $path ): string { - return MOUNT_ROOT === $path ? '' : substr( $path, strlen( MOUNT_ROOT ) + 1 ); + if ( MOUNT_ROOT === $path ) { + return ''; + } + return 0 === strpos( $path, MOUNT_ROOT . '/' ) ? substr( $path, strlen( MOUNT_ROOT ) + 1 ) : $path; } /** @@ -336,12 +425,11 @@ private function enterContent( string $root ): bool { } /** - * Php sites: what lies in /var/www beside htdocs (code above the public dir). Links come last, so a directory is - * listed under its own name before a link to it. + * What lies in /var/www beside the root (code above the public dir, a second app, the www-data home), as components + * named $prefix . name. Links come last, so a directory is listed under its own name before a link to it. */ - private function scanBeside(): void { + private function scanBeside( int $loose, string $prefix ): void { $this->markDir( MOUNT_ROOT ); - $loose = $this->comp( 'directory', '..', null, MOUNT_ROOT ); $entries = $this->readDir( MOUNT_ROOT ); if ( null === $entries ) { $this->notChecked( $loose, './', 'unreadable' ); @@ -349,18 +437,15 @@ private function scanBeside(): void { } $links = []; foreach ( $entries as $name ) { - if ( 'htdocs' === $name ) { - continue; - } if ( is_link( MOUNT_ROOT . '/' . $name ) ) { $links[] = $name; } elseif ( in_array( $name, HOME_DIRS, true ) ) { $this->skipped( MOUNT_ROOT . '/' . $name, $name, $loose ); } else { - $this->scanTop( MOUNT_ROOT, [ $name ], $loose, '../' ); + $this->scanTop( MOUNT_ROOT, [ $name ], $loose, $prefix ); } } - $this->scanTop( MOUNT_ROOT, $links, $loose, '../' ); + $this->scanTop( MOUNT_ROOT, $links, $loose, $prefix ); } /** @@ -458,14 +543,14 @@ private function denied( string $path ): bool { return function_exists( 'posix_access' ) && ! @posix_access( $path ) && 13 === posix_get_last_error(); } - /** A content root's `other` component, its entries and the names skipped in it (TOP_SKIPS only in the main wp-content). */ + /** A content root's `other` component, its entries and the names skipped in it (TOP_SKIPS only in the live root's wp-content). */ private function wpRoot( string $path, ?string $branch ): array { return [ 'path' => $path, 'branch' => $branch, 'other' => $this->comp( 'other', '', $branch, $path ), 'entries' => $this->readDir( $path ), - 'skips' => null === $branch ? array_merge( TOP_SKIPS, ANY_SKIPS ) : ANY_SKIPS, + 'skips' => null === $branch && null !== $this->live ? array_merge( TOP_SKIPS, ANY_SKIPS ) : ANY_SKIPS, 'plugins' => null, 'themes' => null, ]; @@ -697,11 +782,15 @@ private function visit( string $path, string $name, int $comp ): void { if ( isset( $this->seenFiles[ $st['dev'] ][ $st['ino'] ] ) ) { return; } + if ( '.user.ini' === $name ) { + $this->userIni( $real ); + return; + } // A phar's code is in the archive, which PHPCS can't read (only its `isPharName( $name ) || $this->isPharName( $real ) ) { - $this->seenFiles[ $st['dev'] ][ $st['ino'] ] = true; - $this->notChecked( $comp, $this->rel( $comp, $path ), 'phar' ); + $this->seenFiles[ $st['dev'] ][ $st['ino'] ] = 'phar'; + $this->phar( $comp, $this->rel( $comp, $path ) ); return; } $mixed = false; @@ -835,7 +924,7 @@ private function codeIn( string $dir ): array { continue; } $badLink = ! preg_match( '/\.[A-Za-z0-9]{1,8}\z/', $name ) && is_link( $path ) && null === $this->resolve( $path ); - if ( $badLink || $this->isPhpName( $name ) || $this->isPharName( $name ) ) { + if ( $badLink || $this->isPhpName( $name ) || $this->isPharName( $name ) || '.user.ini' === $name ) { $hits[ $path ] = false; } } @@ -845,6 +934,49 @@ private function codeIn( string $dir ): array { return $hits; } + /** + * A phar is information unless scanned code names one (decided in finish()). A v3.11.1 call can't show + * information, so there it is not_checked at once. + */ + private function phar( int $comp, string $rel ): void { + if ( false === $this->cfg['served'] ) { + $this->notChecked( $comp, $rel, 'phar' ); + return; + } + $this->pharCount++; + if ( $this->isScan ) { + $this->append( $this->work . '/phars', $comp . ' ' . base64_encode( $rel ) . "\n" ); + } + } + + /** Whether a file names `phar://` or `.phar`, in any case. */ + private function namesPhar( string $real ): bool { + $fh = open_regular( $real ); + if ( null === $fh ) { + return false; + } + $tail = ''; + $found = false; + while ( ! $found && '' !== ( $chunk = (string) fread( $fh, 65536 ) ) ) { + $found = (bool) preg_match( '#phar://|\.phar#i', $tail . $chunk ); + $tail = substr( $chunk, -6 ); + } + fclose( $fh ); + return $found; + } + + /** @return Generator The collected phars: component and path relative to it. */ + private function phars(): Generator { + $fh = $this->pharCount > 0 ? fopen( $this->work . '/phars', 'rb' ) : false; + while ( false !== $fh && false !== ( $line = fgets( $fh ) ) ) { + list( $comp, $rel ) = explode( ' ', rtrim( $line, "\n" ) ); + yield [ (int) $comp, (string) base64_decode( $rel ) ]; + } + if ( false !== $fh ) { + fclose( $fh ); + } + } + /** * A data file PHP never runs past its first statement: ``, ``, `` * (W3TC, WP Super Cache, Wordfence), optionally with `__halt_compiler();` before the `?>`. Without @@ -916,7 +1048,7 @@ private function outOfScope( string $real ): bool { /** * Why a real path is out of scope: 'old' (an old release), 'anchor' (the content root, the scanned directory or an - * ancestor, walked anyway), 'core' (the WordPress root's core) or 'nested' (another install's core); null when in scope. + * ancestor, walked anyway), 'core' (the live root's core) or 'nested' (another install's core); null when in scope. */ private function scopeWhy( string $real ): ?string { foreach ( $this->oldReleases as $old ) { @@ -933,7 +1065,7 @@ private function scopeWhy( string $real ): ?string { if ( null === $install ) { return null; } - return $install === $this->rootReal ? 'core' : 'nested'; + return $install === $this->live ? 'core' : 'nested'; } /** @@ -974,12 +1106,9 @@ private function codeLike( string $name, string $real ): bool { /** * The install whose core holds a real path: wp-admin/, wp-includes/ (and anything in them) and the core files beside - * them, wherever WordPress is installed. Another install than the root is recorded for a nested_wordpress entry. + * them, wherever WordPress is installed, on php sites too. Installs other than the live root are recorded. */ private function coreOf( string $real ): ?string { - if ( 'wp' !== $this->cfg['site_type'] ) { - return null; - } $install = null; if ( in_array( basename( $real ), CORE_FILES, true ) && $this->coreDir( dirname( $real ) ) ) { $install = dirname( $real ); @@ -992,7 +1121,7 @@ private function coreOf( string $real ): ?string { } } } - if ( null !== $install && $install !== $this->rootReal ) { + if ( null !== $install && $install !== $this->live ) { $this->nested[ $install ] = true; } return $install; @@ -1047,7 +1176,12 @@ private function phpcsTakes( string $path ): bool { } private function inside( string $real ): bool { - return MOUNT_ROOT === $real || 0 === strpos( $real, MOUNT_ROOT . '/' ); + foreach ( $this->roots as $root ) { + if ( $root === $real || 0 === strpos( $real, $root . '/' ) ) { + return true; + } + } + return false; } /** Marks a real directory visited; false when it already was (loops, double paths). */ @@ -1327,13 +1461,8 @@ private function nextFile(): ?array { return [ 'comp' => $h['comp'], 'size' => $h['size'], 'path' => $this->comps[ $h['comp'] ]['base'] . '/' . $rel, 'mixed' => 0 !== ( $h['len'] & MIXED_FLAG ) ]; } - /** - * Steps 1 and 2: the batch, then on their own the files it didn't finish. - * Files are recorded in list order, so findings stay sorted by file. - */ - private function runBatch( array $batch ): void { - $this->checkPins(); - $plain = []; + /** Each listed file as it is now: real path, stat, size, PHPCS route and time cap; null real when it is gone. */ + private function prepare( array $batch ): array { foreach ( $batch as $k => $f ) { $real = $this->resolve( $f['path'] ); $st = null === $real ? false : @stat( $real ); @@ -1349,9 +1478,28 @@ private function runBatch( array $batch ): void { // file whose real name has no --extensions match: such files go through STDIN. $batch[ $k ]['stdin'] = odd_path( $real ) || ! $this->phpcsTakes( $real ); // Every file's run has a time cap; a sniffed file (not code by name) gets a shorter one. - $batch[ $k ]['cap'] = (float) ( $this->isPhpName( basename( $f['path'] ) ) || $this->isPhpName( $real ) ? $this->cfg['file_timeout'] : $this->cfg['sniffed_timeout'] ); - if ( ! $batch[ $k ]['stdin'] ) { - $plain[ $real ] = $k; + $code = $this->isPhpName( basename( $f['path'] ) ) || $this->isPhpName( $real ); + $batch[ $k ]['cap'] = (float) ( $code ? $this->cfg['file_timeout'] : $this->cfg['sniffed_timeout'] ); + // Searched only on a site holding a phar, up to the first hit; not in a file refused by size. + $search = $this->pharCount > 0 && null === $this->pharNamedBy && ! ( $batch[ $k ]['stdin'] && $st['size'] > STDIN_MAX ); + if ( $search && $this->namesPhar( $real ) ) { + $this->pharNamedBy = $f['path']; + } + } + return $batch; + } + + /** + * Steps 1 and 2: the batch, then on their own the files it didn't finish. + * Files are recorded in list order, so findings stay sorted by file. + */ + private function runBatch( array $batch ): void { + $this->checkPins(); + $batch = $this->prepare( $batch ); + $plain = []; + foreach ( $batch as $k => $f ) { + if ( null !== $f['real'] && ! $f['stdin'] ) { + $plain[ $f['real'] ] = $k; } } @@ -1465,7 +1613,7 @@ private function checkPins(): void { } private function timedOutAt( string $path ): TimedOut { - return new TimedOut( sprintf( 'timed out after %d s at %s', $this->timeoutLabel, clean_text( substr( $path, strlen( MOUNT_ROOT ) + 1 ) ) ) ); + return new TimedOut( sprintf( 'timed out after %d s at %s', $this->timeoutLabel, clean_text( $this->relMount( $path ) ) ) ); } /** A file missing from a finished run on a nearly full disk is a write failure, not `error`. */ @@ -1601,8 +1749,7 @@ private function writeManifest(): void { $this->append( $this->work . "/m-$list", $data ); } } - $wp = 'wp' === $this->cfg['site_type']; - $core = $wp && null !== $this->rootReal && $this->coreDir( $this->rootReal ) ? $this->rootReal . '/' : null; + $core = array_merge( null === $this->live ? [] : [ $this->live ], $this->leftOut ); $head = [ 'v' => 1, 'code_extensions' => CODE_EXTENSIONS, @@ -1615,15 +1762,10 @@ private function writeManifest(): void { 'scope' => 'except_skipped_dirs', 'skipped_dirs' => array_values( array_unique( array_map( 'manifest_path', $this->skippedDirs ) ) ), ], - 'roots' => $wp ? ( null === $this->rootReal ? [] : [ manifest_path( $this->rootReal . '/' ) ] ) : [ MOUNT_ROOT . '/' ], + 'roots' => array_map( 'manifest_dir', $this->roots ), 'excluded' => [], - 'old_releases' => array_map( - static function ( $d ) { - return manifest_path( $d . '/' ); - }, - $this->oldReleases - ), - 'core' => [ 'root' => null === $core ? null : manifest_path( $core ), 'dirs' => CORE_DIRS, 'files' => CORE_FILES ], + 'old_releases' => array_map( 'manifest_dir', $this->oldReleases ), + 'core' => [ 'roots' => array_map( 'manifest_dir', $core ), 'dirs' => CORE_DIRS, 'files' => CORE_FILES ], ]; $tmp = OUT_DIR . '/manifest.json.tmp'; @@ -1644,6 +1786,9 @@ static function ( $d ) { $write( '],"not_checked":[' ); $first = true; $this->copySpool( $this->work . '/m-not_checked', $write, $first ); + $write( '],"information":[' ); + $first = true; + $this->copySpool( $this->work . '/m-information', $write, $first ); $write( "]}\n" ); } catch ( Throwable $e ) { fclose( $out ); @@ -1665,6 +1810,7 @@ private function addReportBytes( int $n ): void { /** Builds the summary and streams the report from the spool. */ private function finish(): array { + $this->settlePhars(); $listed = $this->listedComponents(); $errors = $warnings = $checked = $bytes = $withErrors = 0; @@ -1768,7 +1914,11 @@ private function writeReport( array $summary, array $order ): void { $write( '],"not_checked":[' ); $first = true; $this->copySpool( $this->work . '/not_checked', $write, $first ); - $write( "]}\n" ); + $write( '],' . substr( json_encode( $this->reportTail(), JSON_FLAGS ), 1, -1 ) ); + if ( false !== $this->cfg['served'] ) { + $this->writePhars( $write ); + } + $write( "}\n" ); } catch ( Throwable $e ) { fclose( $out ); @unlink( $tmp ); @@ -1780,6 +1930,40 @@ private function writeReport( array $summary, array $order ): void { } } + /** Report keys after not_checked: the WordPress installs and, for a caller that sets COMPAT_SERVED, the old releases left out. */ + private function reportTail(): array { + $tail = [ 'wordpress_installs' => [] ]; + foreach ( $this->installs as $i ) { + $tail['wordpress_installs'][] = [ 'dir' => clean_text( $i['dir'] ), 'version' => clean_text( $i['version'] ), 'live' => $i['live'] ]; + } + if ( false !== $this->cfg['served'] ) { + $tail['excluded_old_releases'] = array_map( 'clean_text', $this->oldReleases ); + } + return $tail; + } + + /** With a phar named by scanned code, every phar is not_checked; else the manifest lists each as information. */ + private function settlePhars(): void { + foreach ( $this->phars() as list( $comp, $rel ) ) { + if ( null !== $this->pharNamedBy ) { + $this->spoolNotChecked( $comp, $rel, 'phar' ); + } elseif ( $this->cfg['manifest'] ) { + $this->manifestAdd( 'information', (string) realpath( $this->comps[ $comp ]['base'] . '/' . $rel ) ); + } + } + } + + /** `phars` (the phars kept as information, streamed: a site may hold thousands) and `phar_named_by`. */ + private function writePhars( callable $write ): void { + $write( ',"phars":[' ); + $sep = ''; + foreach ( null === $this->pharNamedBy ? $this->phars() : [] as list( $comp, $rel ) ) { + $write( $sep . json_encode( clean_text( $this->comps[ $comp ]['base'] . '/' . $rel ), JSON_FLAGS ) ); + $sep = ','; + } + $write( '],"phar_named_by":' . json_encode( clean_nullable( $this->pharNamedBy ), JSON_FLAGS ) ); + } + /** Appends a spool of `,{...}` items, dropping the leading comma of the first; then deletes it. */ private function copySpool( string $file, callable $write, bool &$first ): void { if ( ! is_file( $file ) ) { @@ -2203,6 +2387,20 @@ function manifest_path( string $path ): string { return preg_match( '//u', $path ) ? $path : 'b64:' . base64_encode( $path ); } +function manifest_dir( string $dir ): string { + return manifest_path( $dir . '/' ); +} + +/** An ini value as PHP reads it: quoted, or up to a `;` comment; none, off, no, false and null are empty. */ +function ini_value( string $raw ): string { + $raw = trim( $raw ); + if ( preg_match( '/^"([^"]*)"|^\'([^\']*)\'/', $raw, $m ) ) { + return $m[1] . ( $m[2] ?? '' ); + } + $value = trim( (string) strstr( $raw . ';', ';', true ) ); + return preg_match( '/^(?:none|off|no|false|null)?\z/i', $value ) ? '' : $value; +} + function clean_nullable( ?string $s ): ?string { return null === $s ? null : clean_text( $s ); } @@ -2346,6 +2544,39 @@ function env_memory( string $name, string $default ): string { return $v; } +/** A path under /var/www; site-command keeps a --public-dir like `a//b` as typed. */ +function mount_path( string $path, string $what ): string { + $path = rtrim( (string) preg_replace( '#/+#', '/', $path ), '/' ); + if ( ( MOUNT_ROOT !== $path && 0 !== strpos( $path, MOUNT_ROOT . '/' ) ) || preg_match( '#/\.\.?(/|\z)|[\x00-\x1F\x7F]#', $path ) ) { + throw new BadArgs( "$what must be an absolute path under " . MOUNT_ROOT ); + } + return $path; +} + +/** An install's version: exactly one `$wp_version = '…';` line in its version.php, else '' (unknown). */ +function wp_version( string $dir ): string { + $fh = open_regular( $dir . '/wp-includes/version.php' ); + if ( null === $fh ) { + return ''; + } + $lines = []; + while ( false !== ( $line = fgets( $fh ) ) ) { + if ( preg_match( '/\$wp_version\s*=/', $line ) ) { + $lines[] = $line; + } + } + fclose( $fh ); + if ( 1 !== count( $lines ) || ! preg_match( '/^\s*\$wp_version\s*=\s*\'(\d+\.\d+[0-9A-Za-z.+-]*)\'\s*;\s*$/', $lines[0], $m ) ) { + return ''; + } + return $m[1]; +} + +/** major.minor of a WordPress version, as EE's support table names branches. */ +function wp_branch( string $version ): string { + return preg_match( '/^\d+\.\d+/', $version, $m ) ? $m[0] : ''; +} + function parse_args( array $argv, array &$cfg ): void { $cfg['mode'] = $argv[0] ?? ''; $cfg['site_type'] = $argv[1] ?? ''; @@ -2359,12 +2590,28 @@ function parse_args( array $argv, array &$cfg ): void { if ( ! in_array( $cfg['site_type'], [ 'wp', 'php' ], true ) ) { throw new BadArgs( 'site type must be wp or php' ); } - // site-command keeps a --public-dir like `a//b` as typed. - $path = rtrim( (string) preg_replace( '#/+#', '/', $cfg['path'] ), '/' ); - if ( ( MOUNT_ROOT !== $path && 0 !== strpos( $path, MOUNT_ROOT . '/' ) ) || preg_match( '#/\.\.?(/|\z)|[\x00-\x1F\x7F]#', $path ) ) { - throw new BadArgs( 'path must be an absolute path under ' . MOUNT_ROOT ); + $cfg['path'] = mount_path( $cfg['path'], 'path' ); + // False when absent: a v3.11.1 call, unlike an empty value. + $cfg['served'] = getenv( 'COMPAT_SERVED' ); + if ( is_string( $cfg['served'] ) && '' !== $cfg['served'] ) { + $cfg['served'] = mount_path( $cfg['served'], 'COMPAT_SERVED' ); + } + $cfg['require'] = array_values( array_filter( array_map( 'trim', explode( "\n", (string) getenv( 'COMPAT_REQUIRE' ) ) ), 'strlen' ) ); + $cfg['extra_roots'] = []; + foreach ( array_filter( explode( "\n", (string) getenv( 'COMPAT_EXTRA_ROOTS' ) ), 'strlen' ) as $root ) { + $malformed = '/' !== $root[0] || preg_match( '#//|/\.\.?(/|\z)|/\z|[\x00-\x1F\x7F]#', $root ); + if ( $malformed || MOUNT_ROOT === $root || 0 === strpos( $root, MOUNT_ROOT . '/' ) ) { + throw new BadArgs( 'COMPAT_EXTRA_ROOTS must be absolute paths outside ' . MOUNT_ROOT . ', one per line' ); + } + $cfg['extra_roots'][] = $root; + } + $supported = (string) getenv( 'COMPAT_WP_SUPPORTED' ); + $cfg['wp_supported'] = '' === $supported ? [] : explode( ',', $supported ); + foreach ( $cfg['wp_supported'] as $branch ) { + if ( ! preg_match( '/^\d+\.\d+\z/', $branch ) ) { + throw new BadArgs( 'COMPAT_WP_SUPPORTED must be branches like 6.8, comma-separated' ); + } } - $cfg['path'] = $path; if ( ! preg_match( '/^\d+\.\d+\z/', $cfg['version'] ) ) { throw new BadArgs( 'version must look like 8.4' ); } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 83d6d726..a386b50e 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -82,7 +82,7 @@ function tool_error( string $name, string $detail_prefix, int $code, bool $repor } function summary_of( array $report ): array { - unset( $report['components'], $report['not_checked'] ); + unset( $report['components'], $report['not_checked'], $report['wordpress_installs'], $report['excluded_old_releases'], $report['phars'], $report['phar_named_by'] ); return $report; } @@ -100,7 +100,7 @@ function without_duration( array $doc ): array { eq( field( $full, 'safe_to_upgrade' ), false, 'full: safe_to_upgrade false' ); eq( array_keys( $full ), [ 'v', 'status', 'site', 'target', 'safe_to_upgrade', 'errors', 'warnings', 'files_checked', 'files_not_checked', 'php_bytes', 'components_checked', 'components_with_errors', 'duration_s', 'tool' ], 'full: summary keys and order' ); eq( [ $full['v'], $full['site'], $full['target'] ], [ 1, 'fixture.test', '8.4' ], 'full: v, site, target' ); -eq( [ $full['errors'], $full['warnings'], $full['files_checked'], $full['files_not_checked'], $full['components_checked'], $full['components_with_errors'] ], [ 1132, 3, 48, 4, 22, 18 ], 'full: counts' ); +eq( [ $full['errors'], $full['warnings'], $full['files_checked'], $full['files_not_checked'], $full['components_checked'], $full['components_with_errors'] ], [ 1133, 3, 49, 4, 23, 19 ], 'full: counts' ); check( $full['php_bytes'] > 0 && is_int( $full['duration_s'] ), 'full: php_bytes and duration_s' ); eq( array_keys( $full['tool'] ), [ 'phpcs', 'phpcompatibility', 'phpcompatibility_wp', 'image' ], 'full: tool keys' ); check( 0 === strpos( $full['tool']['phpcs'], '4.0.' ) && '10.0.0-alpha3' === $full['tool']['phpcompatibility'] && '3.0.0-alpha3' === $full['tool']['phpcompatibility_wp'], 'full: tool versions' ); @@ -125,6 +125,7 @@ function without_duration( array $doc ): array { [ 'plugin', 'utf', null, 'Utf', null, 2, 1, 0 ], [ 'plugin', 'branchy', 'main', 'Branchy', '0.1', 1, 1, 0 ], [ 'theme', 'demo', null, 'Demo Theme', '2.1', 1, 1, 0 ], + [ 'directory', 'htdocs', null, null, null, 1, 1, 0 ], [ 'other', 'wp-config.php', null, null, null, 1, 1, 0 ], [ 'other', '', 'main', null, null, 2, 1, 0 ], [ 'plugin', 'warnonly', null, 'Warn Only', '3.0', 1, 0, 2 ], @@ -156,7 +157,7 @@ static function ( $a, $b ) { $files[ $c['type'] . ':' . $c['slug'] . ':' . $c['branch'] . ':' . $f['file'] ] = true; } } -eq( $total, 1135, 'full: report has every finding (>1,000, uncapped)' ); +eq( $total, 1136, 'full: report has every finding (>1,000, uncapped)' ); eq( count( $rep['components'][0]['findings'] ?? [] ), 1100, 'full: 1,100 findings of one component all listed' ); ksort( $files ); @@ -171,6 +172,7 @@ static function ( $a, $b ) { 'plugin:clean::.git/hooks/y.php', 'plugin:clean::node_modules/pkg/x.php', 'other:wp-config.php::htdocs/wp-config.php', + 'directory:htdocs::wp-content/plugins/outside/outside.php', 'plugin:annotated::annotated.php', 'plugin:annotated::disable.php', 'plugin:annotated::inline.php', @@ -196,7 +198,7 @@ static function ( $a, $b ) { 'theme:demo::functions.php', ]; sort( $expect_files ); -eq( array_keys( $files ), $expect_files, 'full: findings per file (paths relative to the component; core, links to core/ancestors and outside code absent; code files in skipped dirs, languages/ and a branch\'s uploads/ checked; invalid UTF-8 and control characters substituted)' ); +eq( array_keys( $files ), $expect_files, 'full: findings per file (paths relative to the component; core and links to core/ancestors absent; code beside the WordPress root present; code files in skipped dirs, languages/ and a branch\'s uploads/ checked; invalid UTF-8 and control characters substituted)' ); $legacy = comp_of( $rep, 'plugin', 'legacy' )['findings'] ?? []; eq( @@ -205,6 +207,7 @@ static function ( $a, $b ) { 'full: legacy findings' ); eq( comp_of( $rep, 'plugin', 'broken' )['findings'][0]['source'] ?? '', 'PHPCompatibility.FunctionUse.RemovedFunctions.eachDeprecatedRemoved', 'full: syntax-error file still sniffed' ); +eq( [ $rep['wordpress_installs'] ?? null, $rep['excluded_old_releases'] ?? null, $rep['phars'] ?? null, field( $rep, 'phar_named_by' ) ], [ [ [ 'dir' => '/var/www/htdocs/releases/1', 'version' => '', 'live' => true ] ], [], [], null ], 'full: the live root (no version.php: unknown version), no old release, no phar' ); eq( array_column( comp_of( $rep, 'plugin', 'annotated' )['findings'] ?? [], 'file' ), [ 'annotated.php', 'disable.php', 'inline.php', 'late.php', 'whole.php' ], 'full: annotations ignored (targeted phpcs:ignore, phpcs:ignoreFile on line 1 and line 6, blanket phpcs:disable, bare phpcs:ignore)' ); eq( array_column( comp_of( $rep, 'plugin', 'order' )['findings'] ?? [], 'file' ), [ "a\u{FFFD}b.php", 'b.php', 'c.php' ], 'full: findings in file order with a STDIN file first' ); eq( array_column( comp_of( $rep, 'plugin', 'incl' )['findings'] ?? [], 'file' ), [ 'link.php' ], 'full: .php link to a .inc file checked under the link name' ); @@ -246,9 +249,9 @@ static function ( $a, $b ) { $all = out( 'allmem' ); $r = report( 'allmem' ); -eq( [ field( $all, 'safe_to_upgrade' ), $all['errors'] ?? null, $all['files_checked'] ?? null, $all['files_not_checked'] ?? null ], [ null, 0, 0, 52 ], 'allmem: nothing checked, verdict null' ); +eq( [ field( $all, 'safe_to_upgrade' ), $all['errors'] ?? null, $all['files_checked'] ?? null, $all['files_not_checked'] ?? null ], [ null, 0, 0, 53 ], 'allmem: nothing checked, verdict null' ); $reasons = array_count_values( array_column( $r['not_checked'] ?? [], 'reason' ) ); -eq( $reasons, [ 'unreadable' => 4, 'memory' => 48 ], 'allmem: every file in not_checked with reason memory' ); +eq( $reasons, [ 'unreadable' => 4, 'memory' => 49 ], 'allmem: every file in not_checked with reason memory' ); $oom = out( 'oom' ); eq( field( $oom, 'safe_to_upgrade' ), null, 'oom: verdict null' ); @@ -260,7 +263,7 @@ static function ( $a, $b ) { eq( rc( 'timeout' ), 1, 'timeout: exit 1' ); eq( array_keys( $t ), [ 'v', 'status', 'site', 'target', 'safe_to_upgrade', 'detail' ], 'timeout: reduced keys only, no counts' ); eq( [ $t['status'] ?? null, field( $t, 'safe_to_upgrade' ) ], [ 'tool_error', null ], 'timeout: tool_error, no verdict' ); -check( (bool) preg_match( '#^timed out after 1 s at htdocs/current/wp-content/\S+\.php$#', $t['detail'] ?? '' ), 'timeout: detail names the file (' . ( $t['detail'] ?? '' ) . ')' ); +check( (bool) preg_match( '#^timed out after 1 s at htdocs/\S+\.php$#', $t['detail'] ?? '' ), 'timeout: detail names the file (' . ( $t['detail'] ?? '' ) . ')' ); eq( report( 'timeout' ), $t, 'timeout: report.json equals stdout, no not_checked' ); // ------------------------------------------------------- memory and size bounds @@ -289,7 +292,7 @@ static function ( $a, $b ) { foreach ( [ 'wpcfg-dir' => [ 'htdocs/wp-config.php', 'PHPCompatibility.FunctionUse.RemovedFunctions.create_functionDeprecatedRemoved' ], 'wpcfg-parent' => [ 'wp-config.php', 'PHPCompatibility.FunctionUse.RemovedFunctions.eachDeprecatedRemoved' ] ] as $name => list( $file, $source ) ) { $doc = out( $name ); $c = comp_of( report( $name ), 'other', 'wp-config.php' ); - eq( [ $doc['errors'] ?? null, $doc['files_checked'] ?? null ], [ 1, 2 ], "$name: only the loaded wp-config.php is scanned" ); + eq( [ $doc['errors'] ?? null, $doc['files_checked'] ?? null ], 'wpcfg-dir' === $name ? [ 2, 3 ] : [ 1, 2 ], "$name: every wp-config.php in /var/www is scanned" ); eq( [ $c['files'] ?? null, array_column( $c['findings'] ?? [], 'file' ), array_column( $c['findings'] ?? [], 'source' ) ], [ 1, [ $file ], [ $source ] ], "$name: component other/wp-config.php, file $file" ); } @@ -585,7 +588,7 @@ function finding_files( array $report ): array { eq( report( 'wordfence' )['not_checked'] ?? null, [], 'wordfence: not_checked empty' ); $sd = out( 'skipdirs' ); -eq( [ $sd['status'] ?? null, field( $sd, 'safe_to_upgrade' ), $sd['errors'] ?? null, $sd['files_checked'] ?? null, $sd['files_not_checked'] ?? null ], [ 'ok', false, 7, 17, 2 ], 'skipdirs: code files in skipped dirs are checked' ); +eq( [ $sd['status'] ?? null, field( $sd, 'safe_to_upgrade' ), $sd['errors'] ?? null, $sd['files_checked'] ?? null, $sd['files_not_checked'] ?? null ], [ 'ok', false, 7, 17, 1 ], 'skipdirs: code files in skipped dirs are checked' ); eq( finding_files( report( 'skipdirs' ) ), [ 'directory:htdocs::node_modules/x.php', 'other:::.git/hooks/h.php', 'other:::cache/object/c.php', 'other:::node_modules/n.php', 'other:::uploads/2026/11/deep/shell.PHP', 'plugin:p::.git/y.php', 'plugin:p::node_modules/pkg/x.php' ], @@ -594,18 +597,15 @@ function finding_files( array $report ): array { eq( comp_of( report( 'skipdirs' ), 'other', '' )['files'] ?? null, 13, 'skipdirs: other has wflogs (8), upgrade-temp-backup, uploads, cache, node_modules and .git files' ); eq( report( 'skipdirs' )['not_checked'] ?? null, - [ nc( 'other', '', null, 'upgrade/pkg.phar', 'phar' ), nc( 'directory', 'htdocs', null, '.git/', 'unreadable' ) ], - 'skipdirs: a phar in a skipped dir; a dangling skipped name is unreadable' + [ nc( 'directory', 'htdocs', null, '.git/', 'unreadable' ) ], + 'skipdirs: a dangling skipped name is unreadable' ); +eq( report( 'skipdirs' )['phars'] ?? null, [ '/var/www/htdocs/wp-content/upgrade/pkg.phar' ], 'skipdirs: a phar in a skipped dir is found' ); $e = out( 'est-skipdirs' ); -eq( [ $e['php_files'] ?? null, $e['php_bytes'] ?? null, $e['components'] ?? null ], [ 19, $sd['php_bytes'] ?? null, 3 ], 'est-skipdirs: counts equal the scan' ); +eq( [ $e['php_files'] ?? null, $e['php_bytes'] ?? null, $e['components'] ?? null ], [ 18, $sd['php_bytes'] ?? null, 3 ], 'est-skipdirs: counts equal the scan' ); $sp = out( 'skipdirs-php' ); -eq( [ $sp['status'] ?? null, field( $sp, 'safe_to_upgrade' ), $sp['errors'] ?? null, $sp['files_checked'] ?? null, $sp['files_not_checked'] ?? null ], [ 'ok', false, 7, 18, 2 ], 'skipdirs-php: a php site walks uploads/ and cache/ whole (a .txt is never sniffed); node_modules/ and .git/ code files checked' ); -eq( - report( 'skipdirs-php' )['not_checked'] ?? null, - [ nc( 'other', '', null, '.git/', 'unreadable' ), nc( 'directory', 'wp-content', null, 'upgrade/pkg.phar', 'phar' ) ], - 'skipdirs-php: not_checked' -); +eq( [ $sp['status'] ?? null, field( $sp, 'safe_to_upgrade' ), $sp['errors'] ?? null, $sp['files_checked'] ?? null, $sp['files_not_checked'] ?? null ], [ 'ok', false, 7, 17, 2 ], 'skipdirs-php: a php site walks uploads/ and cache/ whole (a .txt is never sniffed); node_modules/ and .git/ code files checked' ); +eq( report( 'skipdirs-php' )['not_checked'] ?? null, [ nc( 'other', '', null, '.git/', 'unreadable' ), nc( 'directory', 'htdocs', null, './', 'nested_wordpress' ) ], 'skipdirs-php: not_checked; the WordPress core in htdocs is judged as an install, not scanned' ); $cl = out( 'contentlike' ); eq( [ $cl['status'] ?? null, field( $cl, 'safe_to_upgrade' ), $cl['errors'] ?? null, $cl['files_checked'] ?? null, $cl['files_not_checked'] ?? null ], [ 'ok', false, 2, 3, 0 ], 'contentlike: verdict and counts' ); @@ -629,25 +629,24 @@ function finding_files( array $report ): array { $sn = out( 'sniff' ); $r = report( 'sniff' ); -eq( [ $sn['status'] ?? null, field( $sn, 'safe_to_upgrade' ), $sn['errors'] ?? null, $sn['files_checked'] ?? null, $sn['files_not_checked'] ?? null ], [ 'ok', false, 4, 7, 4 ], 'sniff: verdict and counts (README.md, notes.txt, app.js, app.ts, style.css, data.json, big.txt and logo.png are not sniffed or not PHP)' ); +eq( [ $sn['status'] ?? null, field( $sn, 'safe_to_upgrade' ), $sn['errors'] ?? null, $sn['files_checked'] ?? null, $sn['files_not_checked'] ?? null ], [ 'ok', false, 4, 7, 2 ], 'sniff: verdict and counts (README.md, notes.txt, app.js, app.ts, style.css, data.json, big.txt and logo.png are not sniffed or not PHP)' ); eq( array_column( array_filter( comp_of( $r, 'plugin', 'p' )['findings'] ?? [], static function ( $f ) { return 'WARNING' === $f['type']; } ), 'file' ), [ 'views/warn.html' ], 'sniff: a later tag with warnings only is checked and its warnings kept' ); eq( finding_files( $r ), [ 'plugin:p::a-tpl.txt', 'plugin:p::bin/tool', 'plugin:p::views/admin.tpl', 'plugin:p::views/bom.html', 'plugin:p::views/warn.html' ], 'sniff: files starting with null, 'phar-named' => 'boot.php', 'phar-upper' => 'boot.php', 'phar-split' => 'boot.php' ] as $name => $by ) { + $r = report( $name ); + $phars = [ '/var/www/htdocs/wp-content/plugins/p/lib.phar', '/var/www/htdocs/wp-cli.phar' ]; + $named = null === $by ? null : "/var/www/htdocs/wp-content/plugins/p/$by"; + $nc = null === $by ? [] : [ nc( 'plugin', 'p', null, 'lib.phar', 'phar' ), nc( 'directory', 'htdocs', null, 'wp-cli.phar', 'phar' ) ]; + eq( [ $r['phars'] ?? null, field( $r, 'phar_named_by' ), $r['not_checked'] ?? null ], [ null === $by ? $phars : [], $named, $nc ], "$name: phars are information unless scanned code names one" ); + eq( field( out( $name ), 'safe_to_upgrade' ), null === $by ? true : null, "$name: verdict" ); +} +$r = report( 'phar-r5call' ); +eq( [ array_key_exists( 'phars', $r ), array_column( $r['not_checked'] ?? [], 'reason' ) ], [ false, [ 'phar', 'phar' ] ], 'phar-r5call: a v3.11.1 call keeps phar entries' ); + +tool_error( 'badargs-served', 'bad arguments: COMPAT_SERVED must be', 2, false ); +tool_error( 'badargs-supported', 'bad arguments: COMPAT_WP_SUPPORTED must be', 2, false ); +tool_error( 'badargs-roots', 'bad arguments: COMPAT_EXTRA_ROOTS must be', 2, false ); + echo "\n", $count - $fails, '/', $count, " checks passed\n"; exit( $fails ? 1 : 0 ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 1ab5bab3..420d2fcd 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -19,7 +19,7 @@ wp_fixture() { mkdir -p "$wc" ln -s /var/www/htdocs/releases/1 "$app/htdocs/current" - # Core and code outside the public dir: never scanned. + # Core: never scanned. Code outside the public dir is. php_file "$rel/wp-includes/core.php" 'each( $a );' php_file "$rel/wp-settings.php" 'each( $a );' @@ -27,7 +27,7 @@ wp_fixture() { php_file "$app/htdocs/wp-config.php" "define( 'DB_NAME', 'wp' ); $bad" ln -s ../wp-config.php "$app/htdocs/releases/wp-config.php" - php_file "$app/htdocs/wp-content/plugins/outside/outside.php" 'each( $a );' + php_file "$app/htdocs/wp-content/plugins/outside/outside.php" "$bad" # Plugin with a header and two removed functions. php_file "$wc/plugins/legacy/legacy.php" "/** @@ -464,6 +464,7 @@ ext_php_fixture() { # tempbackup_fixture : a clean plugin beside WordPress' rollback copies in wp-content/upgrade-temp-backup/. tempbackup_fixture() { local wc="$1/htdocs/wp-content" + wp_core "$1/htdocs" 6.8.3 php_file "$wc/plugins/p/p.php" '/* Plugin Name: P */' php_file "$wc/upgrade-temp-backup/plugins/old/old.php" '/* Plugin Name: Old */ each( $a );' @@ -827,3 +828,111 @@ bak_fixture() { php_file "$h/dump.sql" 'each( $a );' chmod -R a+rX "$1" } + +# wp_core : a WordPress install's core, with each() in it, which is never scanned. +wp_core() { + php_file "$1/wp-settings.php" 'each( $a );' + php_file "$1/wp-includes/version.php" "\$wp_version = '$2';" + php_file "$1/wp-admin/admin.php" 'each( $a );' +} + +# wpapp_fixture : WordPress in htdocs, and code beside it in /var/www: a vendor/ dir, adminer.php, a full copy +# of an older install, and a WP-CLI package in the www-data home. +wpapp_fixture() { + local a=$1 + wp_core "$a/htdocs" 6.8.3 + php_file "$a/htdocs/wp-config.php" "require __DIR__ . '/../vendor/autoload.php';" + php_file "$a/htdocs/wp-content/plugins/p/p.php" '/* Plugin Name: P */' + php_file "$a/htdocs/wp-content/uploads/u.php" 'each( $a );' + printf ' "$a/htdocs/wp-content/uploads/not-sniffed" + php_file "$a/vendor/autoload.php" 'each( $a );' + php_file "$a/adminer.php" 'each( $a );' + wp_core "$a/htdocs-backup" 6.1.1 + php_file "$a/htdocs-backup/wp-content/plugins/q/q.php" 'each( $a );' + php_file "$a/.wp-cli/packages/vendor/x/legacy.php" 'each( $a );' + chmod -R a+rX "$a" +} + +# nolive_fixture : the scan path isn't an install (no wp-settings.php there); one install beside it. +nolive_fixture() { + local a=$1 + php_file "$a/htdocs/wp-content/uploads/u.php" 'each( $a );' + printf ' "$a/htdocs/wp-content/uploads/sniffed" + wp_core "$a/htdocs/wp" 6.8.1 + chmod -R a+rX "$a" +} + +# phpwpcore_fixture : a php site holding a WordPress copy, whose core PHPCompatibility would flag. +phpwpcore_fixture() { + local h="$1/htdocs" + php_file "$h/index.php" 'echo 1;' + wp_core "$h/blog" 6.8.3 + php_file "$h/blog/wp-includes/class-x.php" 'each( $a );' + php_file "$h/blog/wp-content/plugins/p/p.php" '/* Plugin Name: P */' + chmod -R a+rX "$1" +} + +# mountcore_fixture : WordPress 6.8.3 in htdocs; -61 holds a 6.1.1 wp-includes that run.sh mounts over it. +mountcore_fixture() { + wp_core "$1/htdocs" 6.8.3 + php_file "$1/htdocs/wp-content/plugins/p/p.php" '/* Plugin Name: P */' + php_file "$1-61/version.php" "\$wp_version = '6.1.1';" + chmod -R a+rX "$1" "$1-61" +} + +# wpold_fixture : a WordPress CI/CD site, htdocs/current -> releases/3, with errors in the old releases. +wpold_fixture() { + local h="$1/htdocs" + wp_core "$h/releases/3" 6.8.3 + php_file "$h/releases/3/wp-content/plugins/p/p.php" '/* Plugin Name: P */' + php_file "$h/releases/1/wp-content/plugins/old/old.php" 'each( $a );' + php_file "$h/releases/2/x.php" 'each( $a );' + ln -s releases/3 "$h/current" + chmod -R a+rX "$1" +} + +# extraroot_fixture : /app with uploads linked to /mnt/media/uploads; /media and /shared, mounted +# by run.sh at /mnt/media and /srv/shared. +extraroot_fixture() { + local wc="$1/app/htdocs/wp-content" + wp_core "$1/app/htdocs" 6.8.3 + php_file "$wc/plugins/p/p.php" '/* Plugin Name: P */' + ln -s /mnt/media/uploads "$wc/uploads" + php_file "$1/media/uploads/2026/x.php" 'each( $a );' + printf 'GIF89a' > "$1/media/uploads/2026/a.gif" + php_file "$1/shared/lib/y.inc" 'each( $a );' + printf ' "$1/shared/lib/noext" + chmod -R a+rX "$1" +} + +# require_fixture : prepend and append values in .user.ini files; run.sh adds COMPAT_REQUIRE. +require_fixture() { + local h="$1/htdocs" + wp_core "$h" 6.8.3 + php_file "$h/wordfence-waf.php" 'echo 1;' + printf 'notes\n' > "$h/notes.txt" + printf ' "$h/wp-cli.phar" + printf 'auto_prepend_file = "/var/www/htdocs/wordfence-waf.php" ; Wordfence\nauto_append_file = none\n' > "$h/.user.ini" + mkdir -p "$h/wp-content/uploads" + printf "auto_prepend_file='waf.php'\nAUTO_APPEND_FILE = /opt/append.php\n" > "$h/wp-content/uploads/.user.ini" + chmod -R a+rX "$1" +} + +# phar_fixture : phars, and a plugin file naming one (or not). +phar_fixture() { + local p="$1/htdocs/wp-content/plugins/p" pad + wp_core "$1/htdocs" 6.8.3 + php_file "$p/p.php" '/* Plugin Name: P */' + printf ' "$1/htdocs/wp-cli.phar" + printf ' "$p/lib.phar" + case $2 in + named) php_file "$p/boot.php" "include 'phar://' . __DIR__ . '/lib.phar/x.php';" ;; + upper) php_file "$p/boot.php" "\$x = 'LIB.PHAR';" ;; + split) + # `.phar` across the first 64 KiB read: 8 bytes of tag and comment start, then the pad, then `*/ $x = 'l`. + pad=$(head -c 65516 /dev/zero | tr '\0' a) + printf " "$p/boot.php" + ;; + esac + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/manifest-check.php b/compat-scanner/tests/manifest-check.php index bf417b72..9d28fa63 100644 --- a/compat-scanner/tests/manifest-check.php +++ b/compat-scanner/tests/manifest-check.php @@ -1,9 +1,6 @@ Prints one JSON object: counts and problems. +// Checks a scan's manifest.json against its tree: each code file, by the manifest's rules, is checked, not_checked or +// information, unless in a core judged by version or an old release. Usage: php manifest-check.php $m = json_decode( (string) file_get_contents( $argv[1] ), true ); $problems = []; @@ -18,7 +15,10 @@ JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE ), "\n"; }; -$keys = [ 'v', 'code_extensions', 'extensions_case_insensitive', 'phar_regex', 'sniff', 'roots', 'excluded', 'old_releases', 'core', 'checked', 'not_checked' ]; +$keys = [ + 'v', 'code_extensions', 'extensions_case_insensitive', 'phar_regex', 'sniff', 'roots', 'excluded', 'old_releases', 'core', + 'checked', 'not_checked', 'information', +]; if ( ! is_array( $m ) || array_keys( $m ) !== $keys ) { $problems[] = 'manifest keys: ' . json_encode( is_array( $m ) ? array_keys( $m ) : null ); $out(); @@ -29,11 +29,11 @@ $decode = static function ( $p ) { return is_string( $p ) && 0 === strpos( $p, 'b64:' ) ? base64_decode( substr( $p, 4 ), true ) : $p; }; -foreach ( [ 'checked', 'not_checked', 'roots', 'excluded', 'old_releases' ] as $list ) { +foreach ( [ 'checked', 'not_checked', 'information', 'roots', 'excluded', 'old_releases' ] as $list ) { $m[ $list ] = array_map( $decode, $m[ $list ] ); } $m['sniff']['skipped_dirs'] = array_map( $decode, $m['sniff']['skipped_dirs'] ); -$m['core']['root'] = $decode( $m['core']['root'] ); +$m['core']['roots'] = array_map( $decode, $m['core']['roots'] ); // uid 33 (gid 33, no other groups) may read the file: by mode bits, with search permission on every directory above it. $root = 0 === posix_geteuid(); @@ -73,7 +73,7 @@ } foreach ( $m['checked'] as $p ) { $st = @lstat( $p ); - if ( 0 !== strpos( $p, '/var/www/' ) || false === $st || 0100000 !== ( $st['mode'] & 0170000 ) || realpath( $p ) !== $p ) { + if ( ! $under( $p, $m['roots'] ) || false === $st || 0100000 !== ( $st['mode'] & 0170000 ) || realpath( $p ) !== $p ) { $problems[] = "checked entry not a real regular file: $p"; continue; } @@ -81,7 +81,7 @@ } $ncDirs = []; $ncFiles = []; -foreach ( $m['not_checked'] as $p ) { +foreach ( array_merge( $m['not_checked'], $m['information'] ) as $p ) { if ( '/' === substr( $p, -1 ) ) { $ncDirs[] = $p; } else { @@ -100,7 +100,7 @@ $codeRe = '/\.(?:' . implode( '|', array_map( 'preg_quote', $m['code_extensions'] ) ) . ')\z/' . ( $m['extensions_case_insensitive'] ? 'i' : '' ); $sniff = $m['sniff']; -$core = $m['core']['root']; +$cores = $m['core']['roots']; $skipped = $m['old_releases']; $isCode = static function ( string $path, string $name ) use ( $codeRe, $m, $sniff, $under, $readable ): bool { @@ -154,8 +154,11 @@ continue; } $codeFiles++; - if ( null !== $core && ( $under( $path, [ $core . 'wp-admin/', $core . 'wp-includes/' ] ) || ( dirname( $path ) . '/' === $core && in_array( $name, $m['core']['files'], true ) ) ) ) { - continue; // The scanned root's core: exempt by shape. + foreach ( $cores as $core ) { + $coreFile = dirname( $path ) . '/' === $core && in_array( $name, $m['core']['files'], true ); + if ( $coreFile || $under( $path, [ $core . 'wp-admin/', $core . 'wp-includes/' ] ) ) { + continue 2; // An install's core judged by version: exempt by shape. + } } $ino = $st['dev'] . ':' . $st['ino']; if ( ! isset( $inodes[ $ino ] ) && ! isset( $ncFiles[ $path ] ) && ! isset( $ncFiles[ $ino ] ) && ! $under( $path, $ncDirs ) ) { diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index e5869c50..37899151 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -33,11 +33,19 @@ entry() { fi } +# The env site-command v3.11.2 passes: COMPAT_SERVED is the scan path unless the caller's own -e follows. R5=1 calls the +# way v3.11.1 does, with none of it. +v2_env() { [ -n "${R5:-}" ] || printf -- '-e COMPAT_SERVED=%s' "$1"; } + +# The --mount arguments among docker args, for the manifest check to see the same tree. +mounts_of() { while [ $# -gt 0 ]; do [ "$1" = --mount ] && echo --mount "$2"; shift; done; } + # scan [docker args...] scan() { local name=$1 app=$2 type=$3 path=$4 ver=$5 timeout=$6 shift 6 - local out rc=0 + local out rc=0 mounts + mapfile -t mounts < <(mounts_of "$@" | tr ' ' '\n') out=$(new_out "$name") # OUT_DIR_AT=report.json: a directory already there, so publishing the report fails. if [ -n "${OUT_DIR_AT:-}" ]; then mkdir "$out/$OUT_DIR_AT" && chmod 0777 "$out/$OUT_DIR_AT"; fi @@ -48,7 +56,7 @@ scan() { --cap-drop ALL --security-opt no-new-privileges --pids-limit 64 \ --memory 1g --memory-swap 1g --cpus 1 --cpu-shares 256 \ --user 33:33 \ - -e COMPAT_SITE=fixture.test -e COMPAT_IMAGE="$IMAGE" -e COMPAT_MANIFEST="${MANIFEST-1}" "$@" \ + -e COMPAT_SITE=fixture.test -e COMPAT_IMAGE="$IMAGE" -e COMPAT_MANIFEST="${MANIFEST-1}" $(v2_env "$path") "$@" \ --mount "type=bind,src=$(realpath "$app"),dst=/var/www,readonly" \ --mount "type=bind,src=$out,dst=/out" \ $(entry) scan "$type" "$path" "$ver" "$timeout" > "$RES/$name.stdout" 2> "$RES/$name.stderr" || rc=$? @@ -62,7 +70,7 @@ scan() { local who for who in 33 0; do docker run --rm --network none --read-only --user "$who:$who" \ - --mount "type=bind,src=$(realpath "$app"),dst=/var/www,readonly" \ + --mount "type=bind,src=$(realpath "$app"),dst=/var/www,readonly" "${mounts[@]}" \ --mount "type=bind,src=$out/manifest.json,dst=/m.json,readonly" \ --mount "type=bind,src=$HERE/manifest-check.php,dst=/t/manifest-check.php,readonly" \ --entrypoint php "$IMAGE" /t/manifest-check.php /m.json > "$RES/$name.mcheck$( [ "$who" = 0 ] && echo -root )" 2>&1 || true @@ -116,7 +124,7 @@ estimate() { --cap-drop ALL --security-opt no-new-privileges --pids-limit 64 \ --memory 1g --memory-swap 1g --cpus 1 --cpu-shares 256 \ --user 33:33 \ - -e COMPAT_SITE=fixture.test "$@" \ + -e COMPAT_SITE=fixture.test $(v2_env "$path") "$@" \ --mount "type=bind,src=$(realpath "$app"),dst=/var/www,readonly" \ $(entry) estimate "$type" "$path" "$ver" 120 > "$RES/$name.stdout" 2> "$RES/$name.stderr" || rc=$? echo "$rc" > "$RES/$name.rc" @@ -305,7 +313,8 @@ scan stdin "$WORK/stdin" wp /var/www/htdocs 8.4 600 scan phpdot "$WORK/phpdot" php /var/www/htdocs 8.4 600 scan phpdot-root "$WORK/phpdot-root" php /var/www/htdocs 8.4 600 scan untrav "$WORK/untrav" wp /var/www/htdocs 8.4 600 -ENTRY_MEMORY=10M scan pharflood "$WORK/pharflood" wp /var/www/htdocs 8.4 600 +R5=1 ENTRY_MEMORY=10M scan pharflood "$WORK/pharflood" wp /var/www/htdocs 8.4 600 +ENTRY_MEMORY=10M scan pharflood-info "$WORK/pharflood" wp /var/www/htdocs 8.4 600 # r7: links into old releases and core are entries; links leaving /var/www by non-asset names; php home dot dirs (dot # links, dirs uid 33 can't open, links that don't resolve, their own time budget); the per-file cap; the STDIN copy cap. @@ -326,6 +335,55 @@ bak_fixture "$WORK/bak" scan bak "$WORK/bak" wp /var/www/htdocs 8.4 600 MANIFEST= scan nomanifest "$WORK/wp-clean" wp /var/www/htdocs/current 8.4 600 +# The whole of /var/www on WordPress sites; every install found and judged by its version (COMPAT_WP_SUPPORTED). +wpapp_fixture "$WORK/wpapp" +scan wpapp "$WORK/wpapp" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.8,6.9 +scan wpapp-supported "$WORK/wpapp" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.1,6.8 +estimate est-wpapp "$WORK/wpapp" wp /var/www/htdocs 8.4 -e COMPAT_WP_SUPPORTED=6.8,6.9 +R5=1 scan r5call "$WORK/wpapp" wp /var/www/htdocs 8.4 600 +nolive_fixture "$WORK/nolive" +scan nolive "$WORK/nolive" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.8 +phpwpcore_fixture "$WORK/phpwpcore" +scan phpwpcore "$WORK/phpwpcore" php /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.8,6.9 +scan phpwpcore-old "$WORK/phpwpcore" php /var/www/htdocs 8.4 600 +R5=1 scan r5call-php "$WORK/phpwpcore" php /var/www/htdocs 8.4 600 +# A mount over the live root's wp-includes: the version PHP runs, not the one left underneath. +mountcore_fixture "$WORK/mountcore" +scan mountcore "$WORK/mountcore" wp /var/www/htdocs 8.4 600 --mount "type=bind,src=$WORK/mountcore-61,dst=/var/www/htdocs/wp-includes,readonly" + +# Old releases: left out only when what nginx serves (COMPAT_SERVED) passes `current`. +wpold_fixture "$WORK/wpold" +scan wpold-served "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 +scan wpold-noserved "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 -e COMPAT_SERVED= +scan wpold-above "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 -e COMPAT_SERVED=/var/www/htdocs +R5=1 scan wpold-r5 "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 +scan phpold-noserved "$WORK/php-rel" php /var/www/htdocs/current/public 8.4 600 -e COMPAT_SERVED= + +# Mounts outside /var/www (COMPAT_EXTRA_ROOTS), searched by name; without the mount, the link dangles. +extraroot_fixture "$WORK/extraroot" +scan extraroot "$WORK/extraroot/app" wp /var/www/htdocs 8.4 600 \ + --mount "type=bind,src=$WORK/extraroot/media,dst=/mnt/media,readonly" --mount "type=bind,src=$WORK/extraroot/shared,dst=/srv/shared,readonly" \ + -e COMPAT_EXTRA_ROOTS=$'/mnt/media\n/srv/shared' +scan extraroot-none "$WORK/extraroot/app" wp /var/www/htdocs 8.4 600 + +# Prepend and append targets (COMPAT_REQUIRE, .user.ini): each must be a file the scan read. +require_fixture "$WORK/require" +scan require "$WORK/require" wp /var/www/htdocs 8.4 600 \ + -e COMPAT_REQUIRE=$'/var/www/htdocs/wordfence-waf.php\n/usr/local/etc/php/xhprof.php\n/var/www/htdocs/wp-includes/version.php\n/var/www/htdocs/wp-cli.phar\n/var/www/htdocs/notes.txt\nrel.php\n' + +# Phars are information unless scanned code names one (in any case, also across a 64 KiB read). +phar_fixture "$WORK/phar-info" none +phar_fixture "$WORK/phar-named" named +phar_fixture "$WORK/phar-upper" upper +phar_fixture "$WORK/phar-split" split +for f in info named upper split; do scan "phar-$f" "$WORK/phar-$f" wp /var/www/htdocs 8.4 600; done +R5=1 scan phar-r5call "$WORK/phar-info" wp /var/www/htdocs 8.4 600 + +# Malformed new env. +scan badargs-served "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_SERVED=/etc +scan badargs-supported "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6 +scan badargs-roots "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_EXTRA_ROOTS=/var/www/x + # An estimate keeps time for calibration: throttled, the listing of 20,000 files can't finish in its share of 1 s. estimate est-listing "$WORK/wide" wp /var/www/htdocs 8.4 -e COMPAT_ESTIMATE_TIMEOUT=1 --cpus 0.05 From a25bebe3c12dec005f4bb725a5f7268ccc290835 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 06:20:08 +0530 Subject: [PATCH 03/80] feat(compat-scanner): lint for PHP 8 parse errors and count every file once - For targets 8.0 and newer, files go through `php -l` before PHPCS. A file that fails is a CompatScanner.Syntax.ParseError finding on its line and isn't also run through PHPCS. - PHPCS and the lint share one runner under `timeout -s KILL` with the time left. - Every listed file must end exactly once (checked, not checked, or deleted since the listing), else the run is an internal error. - The deadline message says how far the scan got and points at --timeout. - The image carries LABEL io.easyengine.compat-scanner.contract="2", which site-command checks before a scan. --- compat-scanner/Dockerfile | 2 + compat-scanner/bin/compat-scanner.php | 197 ++++++++++++++++++++------ compat-scanner/tests/assert.php | 23 ++- compat-scanner/tests/fixture.sh | 25 +++- compat-scanner/tests/run.sh | 12 +- 5 files changed, 205 insertions(+), 54 deletions(-) diff --git a/compat-scanner/Dockerfile b/compat-scanner/Dockerfile index 0d1e0813..dbf268a8 100644 --- a/compat-scanner/Dockerfile +++ b/compat-scanner/Dockerfile @@ -20,6 +20,8 @@ FROM php:8.4.28-cli-alpine3.24 LABEL org.label-schema.schema-version="1.0.0" LABEL org.label-schema.vendor="EasyEngine" LABEL org.label-schema.name="compat-scanner" +# What site-command checks before a scan: bump it when the env, arguments or report change incompatibly. +LABEL io.easyengine.compat-scanner.contract="2" COPY --from=composer /opt/compat-scanner /opt/compat-scanner COPY bin/ /opt/compat-scanner/bin/ diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index b6e82f37..78f88210 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -127,6 +127,8 @@ final class Scanner { private $dataFiles = 0; /** @var int */ private $dataBytes = 0; + /** @var int Listed files deleted before their batch. */ + private $dropped = 0; /** @var int Phars collected, when they may be information (spooled to work/phars in a scan). */ private $pharCount = 0; /** @var string|null The first scanned file naming a phar, which makes every phar not_checked. */ @@ -1419,6 +1421,7 @@ private function timed( array $paths ): float { // ------------------------------------------------------------------- scan private function scan(): array { + $atListing = $this->notCheckedCount; rewind( $this->listFh ); $batch = []; $read = 0; @@ -1438,6 +1441,11 @@ private function scan(): array { if ( $read !== $this->listedFiles ) { throw new ToolError( 'could not read the file list' ); } + // Every listed file ends exactly once: checked, not_checked, or dropped because it is gone. + $settled = array_sum( array_column( $this->comps, 'files' ) ) + $this->notCheckedCount - $atListing + $this->dropped; + if ( $settled !== $this->listedFiles + $this->dataFiles ) { + throw new ToolError( 'internal error: the file counts don\'t add up' ); + } $this->checkPins(); return $this->finish(); @@ -1496,9 +1504,13 @@ private function prepare( array $batch ): array { private function runBatch( array $batch ): void { $this->checkPins(); $batch = $this->prepare( $batch ); + foreach ( $this->lint( $batch ) as $k => $result ) { + $batch[ $k ]['lint'] = $result; + } + $plain = []; foreach ( $batch as $k => $f ) { - if ( null !== $f['real'] && ! $f['stdin'] ) { + if ( null !== $f['real'] && ! $f['stdin'] && ! isset( $f['lint'] ) ) { $plain[ $f['real'] ] = $k; } } @@ -1527,9 +1539,15 @@ private function runBatch( array $batch ): void { // A deleted file can't run; one that can't be reached or is no longer a regular file isn't checked. if ( file_exists( $f['path'] ) || is_link( $f['path'] ) || $this->denied( $f['path'] ) ) { $this->spoolNotChecked( $f['comp'], $this->rel( $f['comp'], $f['path'] ), 'unreadable' ); + } else { + $this->dropped++; } continue; } + if ( isset( $f['lint'] ) ) { + $this->recordLint( $f ); + continue; + } if ( null !== $reader && ! $f['stdin'] ) { // Skip report blocks of files that aren't still expected; a block of a // later file means PHPCS didn't report this one. @@ -1612,8 +1630,13 @@ private function checkPins(): void { } } + /** The deadline is the only bound on a huge site, so the detail says how far the scan got. */ private function timedOutAt( string $path ): TimedOut { - return new TimedOut( sprintf( 'timed out after %d s at %s', $this->timeoutLabel, clean_text( $this->relMount( $path ) ) ) ); + $done = array_sum( array_column( $this->comps, 'files' ) ); + $all = $this->listedFiles + $this->dataFiles; + $at = clean_text( $this->relMount( $path ) ); + $text = 'timed out after %d s at %s, with %d of %d files checked; run it again with a longer --timeout'; + return new TimedOut( sprintf( $text, $this->timeoutLabel, $at, $done, $all ) ); } /** A file missing from a finished run on a nearly full disk is a write failure, not `error`. */ @@ -1634,6 +1657,43 @@ private function tooLarge(): ToolError { return new ToolError( sprintf( 'report larger than %d bytes', $this->cfg['report_max'] ) ); } + /** A file the lint failed, not run through PHPCS: an ERROR finding, or a not_checked reason (php_tag in a mixed file). */ + private function recordLint( array $f ): void { + $rel = $this->rel( $f['comp'], $f['path'] ); + $reason = $f['lint']; + if ( is_array( $reason ) && $f['mixed'] ) { + $reason = 'php_tag'; + } + if ( is_string( $reason ) ) { + $this->spoolNotChecked( $f['comp'], $rel, $reason, $f['real'] ); + return; + } + list( $line, $text ) = $reason; + $entry = ',' . json_encode( + [ + 'file' => clean_text( $rel ), + 'line' => $line, + 'type' => 'ERROR', + 'source' => 'CompatScanner.Syntax.ParseError', + 'message' => clean_text( $text ), + ], + JSON_FLAGS + ); + $this->addReportBytes( strlen( $entry ) ); + $this->append( $this->work . "/c{$f['comp']}.e", $entry ); + $this->counted( $f, 1, 0 ); + } + + private function counted( array $f, int $errors, int $warnings ): void { + $c = &$this->comps[ $f['comp'] ]; + $c['files']++; + $c['errors'] += $errors; + $c['warnings'] += $warnings; + $c['bytes'] += $f['size']; + unset( $c ); + $this->manifestChecked( $f['real'], $f['st'] ); + } + /** Counts one finished file and spools its findings from the report block. */ private function record( array $f, ReportReader $reader ): void { $comp = $f['comp']; @@ -1691,13 +1751,7 @@ private function record( array $f, ReportReader $reader ): void { } } - $c = &$this->comps[ $comp ]; - $c['files']++; - $c['errors'] += $errors; - $c['warnings'] += $warnings; - $c['bytes'] += $f['size']; - unset( $c ); - $this->manifestChecked( $f['real'], $f['st'] ); + $this->counted( $f, $errors, $warnings ); } /** @param string|null $manifestPath What the manifest lists, when it isn't the component's base plus `$file`. */ @@ -2010,25 +2064,9 @@ private function phpcs( array $paths, string $memory, string $tag, bool $stdin = return $res; } } - $left = $this->deadline - microtime( true ); - if ( $left <= 0 ) { - if ( is_resource( $in ) ) { - fclose( $in ); - @unlink( $this->work . '/stdin' ); - } - $res['timeout'] = true; - return $res; - } - $capped = $cap > 0 && $cap < $left; - if ( $capped ) { - $left = $cap; - } - @unlink( $report ); $cmd = [ - // The exact time left (busybox takes fractions), so no run finishes past the deadline. - 'timeout', '-s', 'KILL', sprintf( '%.3F', ceil( $left * 1000 ) / 1000 ), PHP_BINARY, '-d', 'memory_limit=' . $memory, '-d', 'display_errors=stderr', '-d', 'log_errors=0', PHPCS_BIN, '--standard=' . ( 'php' === $this->cfg['site_type'] ? 'PHPCompatibility' : 'PHPCompatibilityWP' ), @@ -2048,27 +2086,14 @@ private function phpcs( array $paths, string $memory, string $tag, bool $stdin = } $err = $this->cfg['debug'] ? STDERR : [ 'file', '/dev/null', 'w' ]; - $t = hrtime( true ); - - // Bounds what PHPCS can write (SIGXFSZ past the limit); set only around the fork. + // Bounds what PHPCS can write (SIGXFSZ past the limit). $fsize = $this->cfg['report_max'] + max( FSIZE_SLACK, count( $paths ) * HEADER_MAX ); - set_fsize( $fsize ); - $proc = proc_open( $cmd, [ 0 => $in, 1 => [ 'file', '/dev/null', 'w' ], 2 => $err ], $pipes ); - set_fsize( null ); + $res = array_merge( $res, $this->runTimed( $cmd, $cap, [ 0 => $in, 1 => [ 'file', '/dev/null', 'w' ], 2 => $err ], $fsize ) ); if ( is_resource( $in ) ) { fclose( $in ); @unlink( $this->work . '/stdin' ); } - if ( ! is_resource( $proc ) ) { - throw new ToolError( 'could not start phpcs' ); - } - $rc = proc_close( $proc ); - - $res['rc'] = $rc; - $res['seconds'] = ( hrtime( true ) - $t ) / 1e9; - // Killed by its own cap, not the scan deadline (busybox timeout reports SIGKILL as 9 or 137). - if ( $capped && in_array( $rc, [ 9, 137 ], true ) && $res['seconds'] >= $cap * 0.99 ) { - $res['capped'] = true; + if ( $res['capped'] || $res['timeout'] ) { return $res; } @@ -2076,12 +2101,100 @@ private function phpcs( array $paths, string $memory, string $tag, bool $stdin = $size = @filesize( $report ); if ( false !== $size && $size >= $fsize ) { $res['too_large'] = true; - } elseif ( $rc >= 0 && $rc <= 3 && false !== $size ) { + } elseif ( $res['rc'] >= 0 && $res['rc'] <= 3 && false !== $size ) { $res['ok'] = true; } return $res; } + /** + * Runs a command under `timeout -s KILL` with the time left, at most $cap seconds when $cap > 0. + * + * @return array{rc:int,seconds:float,capped:bool,timeout:bool} capped: killed by $cap; timeout: no time was left. + */ + private function runTimed( array $cmd, float $cap, array $spec, int $fsize = 0 ): array { + $res = [ 'rc' => -1, 'seconds' => 0.0, 'capped' => false, 'timeout' => false ]; + $left = $this->deadline - microtime( true ); + if ( $left <= 0 ) { + $res['timeout'] = true; + return $res; + } + $capped = $cap > 0 && $cap < $left; + // The exact time left (busybox takes fractions), so no run finishes past the deadline. + $limit = sprintf( '%.3F', ceil( ( $capped ? $cap : $left ) * 1000 ) / 1000 ); + $t = hrtime( true ); + // Set only around the fork, so the entrypoint's own writes aren't bound by it. + set_fsize( $fsize > 0 ? $fsize : null ); + $proc = proc_open( array_merge( [ 'timeout', '-s', 'KILL', $limit ], $cmd ), $spec, $pipes ); + set_fsize( null ); + if ( ! is_resource( $proc ) ) { + throw new ToolError( 'could not start ' . basename( end( $cmd ) ) ); + } + $res['rc'] = proc_close( $proc ); + $res['seconds'] = ( hrtime( true ) - $t ) / 1e9; + // Killed by its own cap, not the scan deadline (busybox timeout reports SIGKILL as 9 or 137). + $res['capped'] = $capped && in_array( $res['rc'], [ 9, 137 ], true ) && $res['seconds'] >= $cap * 0.99; + return $res; + } + + /** + * `php -l` over a batch, then over each file on its own when the batch fails, since PHPCompatibility misses some parse + * errors (`#[` before PHP 8 code, an unclosed final comment). Targets before 8.0 aren't linted: PHP 8.4 rejects + * syntax they allow. + * + * @return array By batch key, the files that fail: [ line, message ] or a not_checked reason. + */ + private function lint( array $batch ): array { + $paths = array_filter( array_column( $batch, 'real' ) ); + if ( ! $paths || version_compare( $this->cfg['version'], '8.0', '<' ) ) { + return []; + } + $res = $this->lintRun( array_values( $paths ), (float) $this->cfg['file_timeout'] ); + if ( 0 === $res['rc'] ) { + return []; + } + $failed = []; + foreach ( $paths as $k => $real ) { + $res = $this->lintRun( [ $real ], $batch[ $k ]['cap'] ); + if ( $res['timeout'] ) { + throw $this->timedOutAt( $batch[ $k ]['path'] ); + } + if ( 0 !== $res['rc'] ) { + $failed[ $k ] = $this->lintResult( $res, $real ); + } + } + return $failed; + } + + private function lintRun( array $paths, float $cap ): array { + $err = $this->work . '/lint.err'; + $args = [ '-d', 'memory_limit=' . $this->cfg['retry_memory'], '-d', 'display_errors=stderr', '-d', 'log_errors=0' ]; + // EE's php images turn short tags off; on, PHP would parse a template's `runTimed( $cmd, $cap, [ 0 => [ 'file', '/dev/null', 'r' ], 1 => [ 'file', '/dev/null', 'w' ], 2 => [ 'file', $err, 'w' ] ] ); + + $res['stderr'] = (string) file_get_contents( $err, false, null, 0, 65536 ); + return $res; + } + + /** @return array{0:int,1:string}|string The finding, or `unparseable` for a target newer than this PHP, which can't parse its syntax. */ + private function lintResult( array $res, string $real ) { + if ( $res['capped'] ) { + return 'timeout'; + } + if ( in_array( $res['rc'], [ 9, 137 ], true ) || false !== strpos( $res['stderr'], 'Allowed memory size' ) ) { + return 'memory'; + } + if ( 255 !== $res['rc'] ) { + return 'error'; + } + if ( version_compare( $this->cfg['version'], PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION, '>' ) ) { + return 'unparseable'; + } + preg_match( '/^(.*?)(?: on line (\d+))?$/s', trim( str_replace( ' in ' . $real, '', $res['stderr'] ) ), $m ); + return [ (int) ( $m[2] ?? 0 ), $m[1] ]; + } + /** * STDIN for PHPCS: a copy behind our own `phpcs_input_file:` line, which PHPCS drops instead of the file's first line. * A constant name, as a path may hold an end of line. A file, not a pipe: PHPCS stops reading after 200 ms without data. diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index a386b50e..e4414a6d 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -206,7 +206,7 @@ static function ( $a, $b ) { [ '6 PHPCompatibility.FunctionUse.RemovedFunctions.create_functionDeprecatedRemoved', '7 PHPCompatibility.FunctionUse.RemovedFunctions.eachDeprecatedRemoved' ], 'full: legacy findings' ); -eq( comp_of( $rep, 'plugin', 'broken' )['findings'][0]['source'] ?? '', 'PHPCompatibility.FunctionUse.RemovedFunctions.eachDeprecatedRemoved', 'full: syntax-error file still sniffed' ); +eq( array_intersect_key( comp_of( $rep, 'plugin', 'broken' )['findings'][0] ?? [], [ 'line' => 0, 'source' => 0 ] ), [ 'line' => 3, 'source' => 'CompatScanner.Syntax.ParseError' ], 'full: a syntax error is the lint\'s finding, on its line' ); eq( [ $rep['wordpress_installs'] ?? null, $rep['excluded_old_releases'] ?? null, $rep['phars'] ?? null, field( $rep, 'phar_named_by' ) ], [ [ [ 'dir' => '/var/www/htdocs/releases/1', 'version' => '', 'live' => true ] ], [], [], null ], 'full: the live root (no version.php: unknown version), no old release, no phar' ); eq( array_column( comp_of( $rep, 'plugin', 'annotated' )['findings'] ?? [], 'file' ), [ 'annotated.php', 'disable.php', 'inline.php', 'late.php', 'whole.php' ], 'full: annotations ignored (targeted phpcs:ignore, phpcs:ignoreFile on line 1 and line 6, blanket phpcs:disable, bare phpcs:ignore)' ); eq( array_column( comp_of( $rep, 'plugin', 'order' )['findings'] ?? [], 'file' ), [ "a\u{FFFD}b.php", 'b.php', 'c.php' ], 'full: findings in file order with a STDIN file first' ); @@ -249,9 +249,9 @@ static function ( $a, $b ) { $all = out( 'allmem' ); $r = report( 'allmem' ); -eq( [ field( $all, 'safe_to_upgrade' ), $all['errors'] ?? null, $all['files_checked'] ?? null, $all['files_not_checked'] ?? null ], [ null, 0, 0, 53 ], 'allmem: nothing checked, verdict null' ); +eq( [ field( $all, 'safe_to_upgrade' ), $all['errors'] ?? null, $all['files_checked'] ?? null, $all['files_not_checked'] ?? null ], [ false, 1, 1, 52 ], 'allmem: only the lint\'s finding checked' ); $reasons = array_count_values( array_column( $r['not_checked'] ?? [], 'reason' ) ); -eq( $reasons, [ 'unreadable' => 4, 'memory' => 49 ], 'allmem: every file in not_checked with reason memory' ); +eq( $reasons, [ 'unreadable' => 4, 'memory' => 48 ], 'allmem: every other file in not_checked with reason memory' ); $oom = out( 'oom' ); eq( field( $oom, 'safe_to_upgrade' ), null, 'oom: verdict null' ); @@ -263,7 +263,7 @@ static function ( $a, $b ) { eq( rc( 'timeout' ), 1, 'timeout: exit 1' ); eq( array_keys( $t ), [ 'v', 'status', 'site', 'target', 'safe_to_upgrade', 'detail' ], 'timeout: reduced keys only, no counts' ); eq( [ $t['status'] ?? null, field( $t, 'safe_to_upgrade' ) ], [ 'tool_error', null ], 'timeout: tool_error, no verdict' ); -check( (bool) preg_match( '#^timed out after 1 s at htdocs/\S+\.php$#', $t['detail'] ?? '' ), 'timeout: detail names the file (' . ( $t['detail'] ?? '' ) . ')' ); +check( (bool) preg_match( '#^timed out after 1 s at htdocs/\S+\.php, with \d+ of \d+ files checked; run it again with a longer --timeout$#', $t['detail'] ?? '' ), 'timeout: detail names the file and how far the scan got (' . ( $t['detail'] ?? '' ) . ')' ); eq( report( 'timeout' ), $t, 'timeout: report.json equals stdout, no not_checked' ); // ------------------------------------------------------- memory and size bounds @@ -767,7 +767,7 @@ function finding_files( array $report ): array { ); eq( json_decode( raw( 'phphome.manifest.json' ), true )['checked'] ?? null, [ '/var/www/htdocs/index.php', '/var/www/lib/l.php' ], 'phphome: the dot link\'s target is checked by its own name' ); $sc = out( 'slowcode' ); -eq( [ $sc['status'] ?? null, field( $sc, 'safe_to_upgrade' ), $sc['errors'] ?? null, $sc['files_checked'] ?? null, $sc['files_not_checked'] ?? null ], [ 'ok', false, 1, 3, 1 ], 'slowcode: a code-named file past COMPAT_FILE_TIMEOUT doesn\'t stop the scan' ); +eq( [ $sc['status'] ?? null, field( $sc, 'safe_to_upgrade' ), $sc['errors'] ?? null, $sc['files_checked'] ?? null, $sc['files_not_checked'] ?? null ], [ 'ok', false, 2, 3, 1 ], 'slowcode: a code-named file past COMPAT_FILE_TIMEOUT doesn\'t stop the scan' ); eq( report( 'slowcode' )['not_checked'] ?? null, [ nc( 'plugin', 'p', null, 'slow.php', 'timeout' ) ], 'slowcode: the slow file alone is timeout; its batch neighbours are checked' ); check( false !== strpos( raw( 'slowcode.stderr' ), ' capped' ), 'slowcode: the batch run was capped' ); check( ( $sc['duration_s'] ?? 99 ) < 60, 'slowcode: the scan ends soon after the caps (' . ( $sc['duration_s'] ?? '?' ) . ' s)' ); @@ -890,6 +890,19 @@ function counts( string $name ): array { $r = report( 'phar-r5call' ); eq( [ array_key_exists( 'phars', $r ), array_column( $r['not_checked'] ?? [], 'reason' ) ], [ false, [ 'phar', 'phar' ] ], 'phar-r5call: a v3.11.1 call keeps phar entries' ); +$li = report( 'lint' ); +eq( counts( 'lint' ), [ 'ok', false, 3, 7, 1 ], 'lint: verdict and counts' ); +eq( + array_map( static function ( $f ) { return $f['file'] . ':' . $f['line'] . ':' . $f['source']; }, comp_of( $li, 'plugin', 'p' )['findings'] ?? [] ), + [ 'attr.php:3:CompatScanner.Syntax.ParseError', 'pipe.php:2:CompatScanner.Syntax.ParseError', 'unclosed.php:3:CompatScanner.Syntax.ParseError' ], + 'lint: `#[` before code, the pipe operator and an unclosed comment fail on 8.4; an cached page' > "$wc/cache/wp-cache-1a2b.php" printf "\\n" > "$wc/cache/supercache/page.php" printf "'k','group'=>'options','data'=>array('a'=>1));\\n/*@DOCKET_CACHE_EOF*/" > "$wc/cache/docket-cache/0a1b2c.php" - printf 'data\\n "$wc/cache/object/tail.php" + printf 'data\n "$wc/cache/object/tail.php" # Too large to read to the end: scanned like other code, not counted as data. { printf ''; head -c 9000000 /dev/zero | tr '\0' a; } > "$wc/cache/object/huge.php" chmod -R a+rX "$1" @@ -801,7 +801,7 @@ slowcode_fixture() { php_file "$p/p.php" '/* Plugin Name: P */' php_file "$p/a.php" 'echo 1;' printf ' "$p/slow.php" - php_file "$p/z.php" 'each( $a );' + php_file "$p/z.php" 'ereg( "a", "b" );' chmod -R a+rX "$1" } @@ -936,3 +936,18 @@ phar_fixture() { esac chmod -R a+rX "$1" } + +# lint_fixture : files PHP 8.4 can't parse though PHPCompatibility passes them, and files it can. +lint_fixture() { + local p="$1/htdocs/wp-content/plugins/p" + wp_core "$1/htdocs" 6.8.3 + php_file "$p/p.php" '/* Plugin Name: P */' + printf ' "$p/attr.php" + printf ' "$p/unclosed.php" + printf ' strtoupper(...);\n' > "$p/pipe.php" + printf '\n\n' > "$p/feed.php" + php_file "$p/dup1.php" 'function same() {}' + php_file "$p/dup2.php" 'function same() {}' + mkdir -p "$p/views" && printf '

\n\n' > "$p/views/broken.tpl" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 37899151..7e2de893 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -184,7 +184,8 @@ scan rootlock "$WORK/rootlock" wp /var/www/htdocs 8.4 600 estimate est-rootlock "$WORK/rootlock" wp /var/www/htdocs 8.4 OUT_DIR_AT=report.json scan reportdir "$WORK/empty" wp /var/www/htdocs 8.4 600 # A message longer than the reader's line limit is cut, not a failed scan. -scan bigmsg "$WORK/bigmsg" wp /var/www/htdocs 8.4 600 +# 7.4: no lint, which would stop at the parse error PHP 7 gives that line. +scan bigmsg "$WORK/bigmsg" wp /var/www/htdocs 7.4 600 # Estimate settings: non-finite, and a range that doesn't contain the estimate. estimate est-inf "$WORK/wp" wp /var/www/htdocs/current 8.4 -e COMPAT_SECONDS_PER_BATCH=1e309 estimate est-factors "$WORK/wp" wp /var/www/htdocs/current 8.4 -e COMPAT_LOW_FACTOR=2 -e COMPAT_HIGH_FACTOR=0.5 @@ -326,7 +327,8 @@ bigstdin_fixture "$WORK/bigstdin" scan oldlink "$WORK/oldlink" php /var/www/htdocs/current/public 8.4 600 scan corelink "$WORK/corelink" wp /var/www/htdocs 8.4 600 scan phphome "$WORK/phphome" php /var/www/htdocs 8.4 600 -scan slowcode "$WORK/slowcode" wp /var/www/htdocs 8.4 600 -e COMPAT_FILE_TIMEOUT=5 -e COMPAT_DEBUG=1 +# 7.4: no lint, which would find the unterminated string before PHPCS loops on it. +scan slowcode "$WORK/slowcode" wp /var/www/htdocs 7.4 600 -e COMPAT_FILE_TIMEOUT=5 -e COMPAT_DEBUG=1 scan bigstdin "$WORK/bigstdin" wp /var/www/htdocs 8.4 600 estimate est-bigstdin "$WORK/bigstdin" wp /var/www/htdocs 8.4 @@ -379,6 +381,12 @@ phar_fixture "$WORK/phar-split" split for f in info named upper split; do scan "phar-$f" "$WORK/phar-$f" wp /var/www/htdocs 8.4 600; done R5=1 scan phar-r5call "$WORK/phar-info" wp /var/www/htdocs 8.4 600 +# The syntax lint: PHP 8 parse errors PHPCompatibility misses; above the scanner's PHP, unparseable instead. +lint_fixture "$WORK/lint" +scan lint "$WORK/lint" wp /var/www/htdocs 8.4 600 +scan lint-85 "$WORK/lint" wp /var/www/htdocs 8.5 600 +scan lint-74 "$WORK/lint" wp /var/www/htdocs 7.4 600 + # Malformed new env. scan badargs-served "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_SERVED=/etc scan badargs-supported "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6 From 6465a9de85074b11e0d304edba536636f2ba3872 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 06:23:35 +0530 Subject: [PATCH 04/80] ci: assert that every php image loads redis site-command ignores errors in nginx-helper's bundled Predis because every EasyEngine php image loads the redis extension. Check that on each built image, read from the image itself since 8.6 builds redis differently. --- .github/workflows/test_and_publish.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/test_and_publish.yml b/.github/workflows/test_and_publish.yml index 5c2b1869..9b9e891a 100644 --- a/.github/workflows/test_and_publish.yml +++ b/.github/workflows/test_and_publish.yml @@ -59,6 +59,10 @@ jobs: - name: Check PHP - ${{ matrix.php }} modules and startup run: .github/scripts/check-php-image.sh easyengine/php${{ steps.img-tag.outputs.tag }}:test php/${{ matrix.php }}/expected-modules.txt + # site-command ignores nginx-helper's bundled Predis errors because every EE php image loads redis. + - name: Check PHP - ${{ matrix.php }} loads redis + run: docker run --rm --pull=never --entrypoint php easyengine/php${{ steps.img-tag.outputs.tag }}:test -m | grep -x redis + - name: Build and push PHP - ${{ matrix.php }} image uses: docker/build-push-action@v7 if: github.event_name != 'pull_request' From 7b563ed6eddeae82fc3c53c02975aeddb4687dab Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 06:26:53 +0530 Subject: [PATCH 05/80] fix(compat-scanner): never leave out the release that holds the scan path When nginx serves through `current` and EE's WordPress hint names another release (a stale wp-cli.yml `path:`), that release was both the live root and an old release, so every file in it was skipped as out of scope and the scan could say "no problems found". A release holding the scan path is now always walked; the other releases are still left out. --- compat-scanner/bin/compat-scanner.php | 6 ++++-- compat-scanner/tests/assert.php | 1 + compat-scanner/tests/run.sh | 1 + 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 78f88210..7e3ef98c 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -495,10 +495,12 @@ private function oldReleases( string $publicDir ): array { if ( is_link( $releases ) || ! is_dir( $releases ) || ! $this->inside( $releases ) || dirname( $live ) !== $releases ) { return []; } - $old = []; + // A release holding the scan path is walked: EE's WordPress hint may name an old one (a stale wp-cli.yml path). + $scan = realpath( $this->cfg['path'] ) . '/'; + $old = []; foreach ( (array) $this->readDir( $releases ) as $name ) { $dir = $releases . '/' . $name; - if ( $dir !== $live && ! is_link( $dir ) && is_dir( $dir ) ) { + if ( $dir !== $live && ! is_link( $dir ) && is_dir( $dir ) && 0 !== strpos( $scan, $dir . '/' ) ) { $old[] = $dir; } } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index e4414a6d..83a1695d 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -864,6 +864,7 @@ function counts( string $name ): array { eq( [ counts( $name ), finding_files( report( $name ) ) ], [ [ 'ok', false, 2, 3, 0 ], [ 'directory:htdocs::releases/1/wp-content/plugins/old/old.php', 'directory:htdocs::releases/2/x.php' ] ], "$name: not sure, above current, or a v3.11.1 call: every release scanned" ); } eq( report( 'wpold-noserved' )['excluded_old_releases'] ?? null, [], 'wpold-noserved: none left out' ); +eq( [ counts( 'wpold-hint' ), report( 'wpold-hint' )['excluded_old_releases'] ?? null ], [ [ 'ok', false, 1, 2, 0 ], [ '/var/www/htdocs/releases/2' ] ], 'wpold-hint: a scan path in an old release keeps that release scanned' ); eq( out( 'phpold-noserved' )['errors'] ?? null, 3, 'phpold-noserved: an empty COMPAT_SERVED leaves no release out on php sites either' ); $er = report( 'extraroot' ); diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 7e2de893..0833cb16 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -356,6 +356,7 @@ scan mountcore "$WORK/mountcore" wp /var/www/htdocs 8.4 600 --mount "type=bind,s # Old releases: left out only when what nginx serves (COMPAT_SERVED) passes `current`. wpold_fixture "$WORK/wpold" scan wpold-served "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 +scan wpold-hint "$WORK/wpold" wp /var/www/htdocs/releases/1 8.4 600 -e COMPAT_SERVED=/var/www/htdocs/current -e COMPAT_WP_SUPPORTED=6.8 scan wpold-noserved "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 -e COMPAT_SERVED= scan wpold-above "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 -e COMPAT_SERVED=/var/www/htdocs R5=1 scan wpold-r5 "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 From 14046ccb337195071a840a28463ad59f9d002ca1 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 06:29:29 +0530 Subject: [PATCH 06/80] test(compat-scanner): name the v3.11.1-style runs after what they do OLD_CALL=1 and the oldcall fixtures replace a revision label that meant nothing outside the release work. --- compat-scanner/tests/assert.php | 12 ++++++------ compat-scanner/tests/run.sh | 16 ++++++++-------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 83a1695d..8f53b8af 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -850,17 +850,17 @@ function counts( string $name ): array { eq( installs( 'wpapp' ), [ '/var/www/htdocs 6.8.3 live', '/var/www/htdocs-backup 6.1.1' ], 'wpapp: both installs with their versions, the live one first' ); eq( [ counts( 'wpapp-supported' ), report( 'wpapp-supported' )['not_checked'] ?? null ], [ [ 'ok', false, 5, 7, 0 ], [] ], 'wpapp-supported: a supported branch\'s core is left out silently' ); eq( out( 'est-wpapp' )['php_files'] ?? null, 8, 'est-wpapp: counts equal the scan' ); -$r5 = report( 'r5call' ); -eq( [ counts( 'r5call' ), array_key_exists( 'phars', $r5 ) || array_key_exists( 'excluded_old_releases', $r5 ), installs( 'r5call' ) ], [ [ 'ok', false, 5, 7, 1 ], false, [ '/var/www/htdocs 6.8.3 live', '/var/www/htdocs-backup 6.1.1' ] ], 'r5call: a v3.11.1 call: no supported branches, no phar or release keys' ); +$old = report( 'oldcall' ); +eq( [ counts( 'oldcall' ), array_key_exists( 'phars', $old ) || array_key_exists( 'excluded_old_releases', $old ), installs( 'oldcall' ) ], [ [ 'ok', false, 5, 7, 1 ], false, [ '/var/www/htdocs 6.8.3 live', '/var/www/htdocs-backup 6.1.1' ] ], 'oldcall: a v3.11.1 call: no supported branches, no phar or release keys' ); eq( counts( 'nolive' ), [ 'ok', false, 2, 2, 0 ], 'nolive: the scan path isn\'t an install: no live root, so uploads/ is sniffed; the install below it is supported' ); eq( installs( 'nolive' ), [ '/var/www/htdocs/wp 6.8.1' ], 'nolive: no live install' ); eq( [ counts( 'phpwpcore' ), installs( 'phpwpcore' ) ], [ [ 'ok', true, 0, 2, 0 ], [ '/var/www/htdocs/blog 6.8.3' ] ], 'phpwpcore: WordPress inside a php site: its core judged by version, not scanned' ); eq( [ counts( 'phpwpcore-old' ), report( 'phpwpcore-old' )['not_checked'] ?? null ], [ [ 'ok', null, 0, 2, 1 ], [ nc( 'directory', 'htdocs/blog', null, './', 'nested_wordpress' ) ] ], 'phpwpcore-old: without a supported branch, nested_wordpress' ); -eq( [ counts( 'r5call-php' ), array_key_exists( 'phars', report( 'r5call-php' ) ) ], [ [ 'ok', null, 0, 2, 1 ], false ], 'r5call-php: a v3.11.1 call on a php site' ); +eq( [ counts( 'oldcall-php' ), array_key_exists( 'phars', report( 'oldcall-php' ) ) ], [ [ 'ok', null, 0, 2, 1 ], false ], 'oldcall-php: a v3.11.1 call on a php site' ); eq( [ counts( 'mountcore' ), installs( 'mountcore' ) ], [ [ 'ok', true, 0, 1, 0 ], [ '/var/www/htdocs 6.1.1 live' ] ], 'mountcore: the version is read where PHP reads it, through a mount over wp-includes' ); eq( [ counts( 'wpold-served' ), report( 'wpold-served' )['excluded_old_releases'] ?? null ], [ [ 'ok', true, 0, 1, 0 ], [ '/var/www/htdocs/releases/1', '/var/www/htdocs/releases/2' ] ], 'wpold-served: nginx serves current: the old releases are left out' ); -foreach ( [ 'wpold-noserved', 'wpold-above', 'wpold-r5' ] as $name ) { +foreach ( [ 'wpold-noserved', 'wpold-above', 'wpold-oldcall' ] as $name ) { eq( [ counts( $name ), finding_files( report( $name ) ) ], [ [ 'ok', false, 2, 3, 0 ], [ 'directory:htdocs::releases/1/wp-content/plugins/old/old.php', 'directory:htdocs::releases/2/x.php' ] ], "$name: not sure, above current, or a v3.11.1 call: every release scanned" ); } eq( report( 'wpold-noserved' )['excluded_old_releases'] ?? null, [], 'wpold-noserved: none left out' ); @@ -888,8 +888,8 @@ function counts( string $name ): array { eq( [ $r['phars'] ?? null, field( $r, 'phar_named_by' ), $r['not_checked'] ?? null ], [ null === $by ? $phars : [], $named, $nc ], "$name: phars are information unless scanned code names one" ); eq( field( out( $name ), 'safe_to_upgrade' ), null === $by ? true : null, "$name: verdict" ); } -$r = report( 'phar-r5call' ); -eq( [ array_key_exists( 'phars', $r ), array_column( $r['not_checked'] ?? [], 'reason' ) ], [ false, [ 'phar', 'phar' ] ], 'phar-r5call: a v3.11.1 call keeps phar entries' ); +$r = report( 'phar-oldcall' ); +eq( [ array_key_exists( 'phars', $r ), array_column( $r['not_checked'] ?? [], 'reason' ) ], [ false, [ 'phar', 'phar' ] ], 'phar-oldcall: a v3.11.1 call keeps phar entries' ); $li = report( 'lint' ); eq( counts( 'lint' ), [ 'ok', false, 3, 7, 1 ], 'lint: verdict and counts' ); diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 0833cb16..7be18a5c 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -33,9 +33,9 @@ entry() { fi } -# The env site-command v3.11.2 passes: COMPAT_SERVED is the scan path unless the caller's own -e follows. R5=1 calls the -# way v3.11.1 does, with none of it. -v2_env() { [ -n "${R5:-}" ] || printf -- '-e COMPAT_SERVED=%s' "$1"; } +# The env site-command v3.11.2 passes: COMPAT_SERVED is the scan path unless the caller's own -e follows. +# OLD_CALL=1 calls the way v3.11.1 does, with none of it. +v2_env() { [ -n "${OLD_CALL:-}" ] || printf -- '-e COMPAT_SERVED=%s' "$1"; } # The --mount arguments among docker args, for the manifest check to see the same tree. mounts_of() { while [ $# -gt 0 ]; do [ "$1" = --mount ] && echo --mount "$2"; shift; done; } @@ -314,7 +314,7 @@ scan stdin "$WORK/stdin" wp /var/www/htdocs 8.4 600 scan phpdot "$WORK/phpdot" php /var/www/htdocs 8.4 600 scan phpdot-root "$WORK/phpdot-root" php /var/www/htdocs 8.4 600 scan untrav "$WORK/untrav" wp /var/www/htdocs 8.4 600 -R5=1 ENTRY_MEMORY=10M scan pharflood "$WORK/pharflood" wp /var/www/htdocs 8.4 600 +OLD_CALL=1 ENTRY_MEMORY=10M scan pharflood "$WORK/pharflood" wp /var/www/htdocs 8.4 600 ENTRY_MEMORY=10M scan pharflood-info "$WORK/pharflood" wp /var/www/htdocs 8.4 600 # r7: links into old releases and core are entries; links leaving /var/www by non-asset names; php home dot dirs (dot @@ -342,13 +342,13 @@ wpapp_fixture "$WORK/wpapp" scan wpapp "$WORK/wpapp" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.8,6.9 scan wpapp-supported "$WORK/wpapp" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.1,6.8 estimate est-wpapp "$WORK/wpapp" wp /var/www/htdocs 8.4 -e COMPAT_WP_SUPPORTED=6.8,6.9 -R5=1 scan r5call "$WORK/wpapp" wp /var/www/htdocs 8.4 600 +OLD_CALL=1 scan oldcall "$WORK/wpapp" wp /var/www/htdocs 8.4 600 nolive_fixture "$WORK/nolive" scan nolive "$WORK/nolive" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.8 phpwpcore_fixture "$WORK/phpwpcore" scan phpwpcore "$WORK/phpwpcore" php /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.8,6.9 scan phpwpcore-old "$WORK/phpwpcore" php /var/www/htdocs 8.4 600 -R5=1 scan r5call-php "$WORK/phpwpcore" php /var/www/htdocs 8.4 600 +OLD_CALL=1 scan oldcall-php "$WORK/phpwpcore" php /var/www/htdocs 8.4 600 # A mount over the live root's wp-includes: the version PHP runs, not the one left underneath. mountcore_fixture "$WORK/mountcore" scan mountcore "$WORK/mountcore" wp /var/www/htdocs 8.4 600 --mount "type=bind,src=$WORK/mountcore-61,dst=/var/www/htdocs/wp-includes,readonly" @@ -359,7 +359,7 @@ scan wpold-served "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 scan wpold-hint "$WORK/wpold" wp /var/www/htdocs/releases/1 8.4 600 -e COMPAT_SERVED=/var/www/htdocs/current -e COMPAT_WP_SUPPORTED=6.8 scan wpold-noserved "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 -e COMPAT_SERVED= scan wpold-above "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 -e COMPAT_SERVED=/var/www/htdocs -R5=1 scan wpold-r5 "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 +OLD_CALL=1 scan wpold-oldcall "$WORK/wpold" wp /var/www/htdocs/current 8.4 600 scan phpold-noserved "$WORK/php-rel" php /var/www/htdocs/current/public 8.4 600 -e COMPAT_SERVED= # Mounts outside /var/www (COMPAT_EXTRA_ROOTS), searched by name; without the mount, the link dangles. @@ -380,7 +380,7 @@ phar_fixture "$WORK/phar-named" named phar_fixture "$WORK/phar-upper" upper phar_fixture "$WORK/phar-split" split for f in info named upper split; do scan "phar-$f" "$WORK/phar-$f" wp /var/www/htdocs 8.4 600; done -R5=1 scan phar-r5call "$WORK/phar-info" wp /var/www/htdocs 8.4 600 +OLD_CALL=1 scan phar-oldcall "$WORK/phar-info" wp /var/www/htdocs 8.4 600 # The syntax lint: PHP 8 parse errors PHPCompatibility misses; above the scanner's PHP, unparseable instead. lint_fixture "$WORK/lint" From dbe6a78bd40b41b5f86d70e499490963a3a927fe Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 07:05:44 +0530 Subject: [PATCH 07/80] fix(compat-scanner): read a double-quoted $wp_version too WordPress writes `$wp_version = '6.x';`, but a hand-edited or repackaged version.php may use double quotes, which gave an unknown version and "can't confirm". A plain version string in either quote style is now read; a double-quoted value with `$` or `{` in it, which PHP would expand, stays unknown. --- compat-scanner/bin/compat-scanner.php | 6 +++--- compat-scanner/tests/assert.php | 4 ++++ compat-scanner/tests/fixture.sh | 13 +++++++++++++ compat-scanner/tests/run.sh | 2 ++ 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 7e3ef98c..42ed6c8b 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -2668,7 +2668,7 @@ function mount_path( string $path, string $what ): string { return $path; } -/** An install's version: exactly one `$wp_version = '…';` line in its version.php, else '' (unknown). */ +/** An install's version: exactly one `$wp_version = '…';` or `"…"` line holding a plain version, else '' (unknown). */ function wp_version( string $dir ): string { $fh = open_regular( $dir . '/wp-includes/version.php' ); if ( null === $fh ) { @@ -2681,10 +2681,10 @@ function wp_version( string $dir ): string { } } fclose( $fh ); - if ( 1 !== count( $lines ) || ! preg_match( '/^\s*\$wp_version\s*=\s*\'(\d+\.\d+[0-9A-Za-z.+-]*)\'\s*;\s*$/', $lines[0], $m ) ) { + if ( 1 !== count( $lines ) || ! preg_match( '/^\s*\$wp_version\s*=\s*([\'"])(\d+\.\d+[0-9A-Za-z.+-]*)\1\s*;\s*$/', $lines[0], $m ) ) { return ''; } - return $m[1]; + return $m[2]; } /** major.minor of a WordPress version, as EE's support table names branches. */ diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 8f53b8af..e1ed1fff 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -858,6 +858,10 @@ function counts( string $name ): array { eq( [ counts( 'phpwpcore-old' ), report( 'phpwpcore-old' )['not_checked'] ?? null ], [ [ 'ok', null, 0, 2, 1 ], [ nc( 'directory', 'htdocs/blog', null, './', 'nested_wordpress' ) ] ], 'phpwpcore-old: without a supported branch, nested_wordpress' ); eq( [ counts( 'oldcall-php' ), array_key_exists( 'phars', report( 'oldcall-php' ) ) ], [ [ 'ok', null, 0, 2, 1 ], false ], 'oldcall-php: a v3.11.1 call on a php site' ); eq( [ counts( 'mountcore' ), installs( 'mountcore' ) ], [ [ 'ok', true, 0, 1, 0 ], [ '/var/www/htdocs 6.1.1 live' ] ], 'mountcore: the version is read where PHP reads it, through a mount over wp-includes' ); +$quote_installs = [ '/var/www/htdocs 6.8.3 live', '/var/www/brace ', '/var/www/dollar ', '/var/www/single 6.9.1' ]; +eq( installs( 'wpquotes' ), $quote_installs, 'wpquotes: either quote style; a value with $ or { unknown' ); +$unknown_cores = [ nc( 'directory', 'brace', null, './', 'nested_wordpress' ), nc( 'directory', 'dollar', null, './', 'nested_wordpress' ) ]; +eq( report( 'wpquotes' )['not_checked'] ?? null, $unknown_cores, 'wpquotes: an unknown version is never a supported branch' ); eq( [ counts( 'wpold-served' ), report( 'wpold-served' )['excluded_old_releases'] ?? null ], [ [ 'ok', true, 0, 1, 0 ], [ '/var/www/htdocs/releases/1', '/var/www/htdocs/releases/2' ] ], 'wpold-served: nginx serves current: the old releases are left out' ); foreach ( [ 'wpold-noserved', 'wpold-above', 'wpold-oldcall' ] as $name ) { diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 8857fecf..e6d4b91d 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -880,6 +880,19 @@ mountcore_fixture() { chmod -R a+rX "$1" "$1-61" } +# wpquotes_fixture : version.php in either quote style; a double-quoted value PHP would expand stays unknown. +wpquotes_fixture() { + local a=$1 + wp_core "$a/htdocs" 6.8.3 + php_file "$a/htdocs/wp-includes/version.php" '$wp_version = "6.8.3";' + wp_core "$a/single" 6.9.1 + wp_core "$a/dollar" 6.8.1 + php_file "$a/dollar/wp-includes/version.php" '$wp_version = "6.8.$x";' + wp_core "$a/brace" 6.8.1 + php_file "$a/brace/wp-includes/version.php" '$wp_version = "6.8.{$x}";' + chmod -R a+rX "$a" +} + # wpold_fixture : a WordPress CI/CD site, htdocs/current -> releases/3, with errors in the old releases. wpold_fixture() { local h="$1/htdocs" diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 7be18a5c..c1752bb6 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -352,6 +352,8 @@ OLD_CALL=1 scan oldcall-php "$WORK/phpwpcore" php /var/www/htdocs 8.4 600 # A mount over the live root's wp-includes: the version PHP runs, not the one left underneath. mountcore_fixture "$WORK/mountcore" scan mountcore "$WORK/mountcore" wp /var/www/htdocs 8.4 600 --mount "type=bind,src=$WORK/mountcore-61,dst=/var/www/htdocs/wp-includes,readonly" +wpquotes_fixture "$WORK/wpquotes" +scan wpquotes "$WORK/wpquotes" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.8,6.9 # Old releases: left out only when what nginx serves (COMPAT_SERVED) passes `current`. wpold_fixture "$WORK/wpold" From e3f911821642b9e4fa3d35883aebc1b10998e8a5 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 07:32:58 +0530 Subject: [PATCH 08/80] fix(compat-scanner): leave the run-again hint of a timeout to EE EE appends its own hint to every timeout detail, so the scanner's copy printed it twice. --- compat-scanner/bin/compat-scanner.php | 3 ++- compat-scanner/tests/assert.php | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 42ed6c8b..5de7f67b 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -1637,7 +1637,8 @@ private function timedOutAt( string $path ): TimedOut { $done = array_sum( array_column( $this->comps, 'files' ) ); $all = $this->listedFiles + $this->dataFiles; $at = clean_text( $this->relMount( $path ) ); - $text = 'timed out after %d s at %s, with %d of %d files checked; run it again with a longer --timeout'; + // No hint to run it again: EE adds its own. + $text = 'timed out after %d s at %s, with %d of %d files checked'; return new TimedOut( sprintf( $text, $this->timeoutLabel, $at, $done, $all ) ); } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index e1ed1fff..c2c18a18 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -263,7 +263,9 @@ static function ( $a, $b ) { eq( rc( 'timeout' ), 1, 'timeout: exit 1' ); eq( array_keys( $t ), [ 'v', 'status', 'site', 'target', 'safe_to_upgrade', 'detail' ], 'timeout: reduced keys only, no counts' ); eq( [ $t['status'] ?? null, field( $t, 'safe_to_upgrade' ) ], [ 'tool_error', null ], 'timeout: tool_error, no verdict' ); -check( (bool) preg_match( '#^timed out after 1 s at htdocs/\S+\.php, with \d+ of \d+ files checked; run it again with a longer --timeout$#', $t['detail'] ?? '' ), 'timeout: detail names the file and how far the scan got (' . ( $t['detail'] ?? '' ) . ')' ); +$detail = $t['detail'] ?? ''; +$where = preg_match( '#^timed out after 1 s at htdocs/\S+\.php, with \d+ of \d+ files checked$#', $detail ); +check( 1 === $where, "timeout: detail names the file and how far the scan got, and leaves the hint to EE ($detail)" ); eq( report( 'timeout' ), $t, 'timeout: report.json equals stdout, no not_checked' ); // ------------------------------------------------------- memory and size bounds From a5fd8e65b0b538167279f4dfbb7cc1f50328027f Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 07:42:09 +0530 Subject: [PATCH 09/80] fix(compat-scanner): read a WordPress version over 64 characters as unknown EE prints the version as the report gives it, and its output is meant to stay bounded; the old scanner refused anything longer too. --- compat-scanner/bin/compat-scanner.php | 7 +++++-- compat-scanner/tests/assert.php | 12 +++++++++--- compat-scanner/tests/fixture.sh | 6 +++++- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 5de7f67b..4715a1cb 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -2669,7 +2669,10 @@ function mount_path( string $path, string $what ): string { return $path; } -/** An install's version: exactly one `$wp_version = '…';` or `"…"` line holding a plain version, else '' (unknown). */ +/** + * An install's version: exactly one `$wp_version = '…';` or `"…"` line holding a plain version of at most 64 characters + * (EE prints it as given), else '' (unknown). + */ function wp_version( string $dir ): string { $fh = open_regular( $dir . '/wp-includes/version.php' ); if ( null === $fh ) { @@ -2685,7 +2688,7 @@ function wp_version( string $dir ): string { if ( 1 !== count( $lines ) || ! preg_match( '/^\s*\$wp_version\s*=\s*([\'"])(\d+\.\d+[0-9A-Za-z.+-]*)\1\s*;\s*$/', $lines[0], $m ) ) { return ''; } - return $m[2]; + return strlen( $m[2] ) > 64 ? '' : $m[2]; } /** major.minor of a WordPress version, as EE's support table names branches. */ diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index c2c18a18..319ccce6 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -860,9 +860,15 @@ function counts( string $name ): array { eq( [ counts( 'phpwpcore-old' ), report( 'phpwpcore-old' )['not_checked'] ?? null ], [ [ 'ok', null, 0, 2, 1 ], [ nc( 'directory', 'htdocs/blog', null, './', 'nested_wordpress' ) ] ], 'phpwpcore-old: without a supported branch, nested_wordpress' ); eq( [ counts( 'oldcall-php' ), array_key_exists( 'phars', report( 'oldcall-php' ) ) ], [ [ 'ok', null, 0, 2, 1 ], false ], 'oldcall-php: a v3.11.1 call on a php site' ); eq( [ counts( 'mountcore' ), installs( 'mountcore' ) ], [ [ 'ok', true, 0, 1, 0 ], [ '/var/www/htdocs 6.1.1 live' ] ], 'mountcore: the version is read where PHP reads it, through a mount over wp-includes' ); -$quote_installs = [ '/var/www/htdocs 6.8.3 live', '/var/www/brace ', '/var/www/dollar ', '/var/www/single 6.9.1' ]; -eq( installs( 'wpquotes' ), $quote_installs, 'wpquotes: either quote style; a value with $ or { unknown' ); -$unknown_cores = [ nc( 'directory', 'brace', null, './', 'nested_wordpress' ), nc( 'directory', 'dollar', null, './', 'nested_wordpress' ) ]; +$max = '6.8.' . str_repeat( 'a', 60 ); +$quote_installs = [ '/var/www/htdocs 6.8.3 live', '/var/www/brace ', '/var/www/dollar ', '/var/www/long ', "/var/www/max $max" ]; +$quote_installs[] = '/var/www/single 6.9.1'; +eq( installs( 'wpquotes' ), $quote_installs, 'wpquotes: either quote style; a value with $ or {, or over 64 characters, unknown' ); +$unknown_cores = [ + nc( 'directory', 'brace', null, './', 'nested_wordpress' ), + nc( 'directory', 'dollar', null, './', 'nested_wordpress' ), + nc( 'directory', 'long', null, './', 'nested_wordpress' ), +]; eq( report( 'wpquotes' )['not_checked'] ?? null, $unknown_cores, 'wpquotes: an unknown version is never a supported branch' ); eq( [ counts( 'wpold-served' ), report( 'wpold-served' )['excluded_old_releases'] ?? null ], [ [ 'ok', true, 0, 1, 0 ], [ '/var/www/htdocs/releases/1', '/var/www/htdocs/releases/2' ] ], 'wpold-served: nginx serves current: the old releases are left out' ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index e6d4b91d..c17feb90 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -880,7 +880,8 @@ mountcore_fixture() { chmod -R a+rX "$1" "$1-61" } -# wpquotes_fixture : version.php in either quote style; a double-quoted value PHP would expand stays unknown. +# wpquotes_fixture : version.php in either quote style; a double-quoted value PHP would expand, or one over 64 +# characters, stays unknown. wpquotes_fixture() { local a=$1 wp_core "$a/htdocs" 6.8.3 @@ -890,6 +891,9 @@ wpquotes_fixture() { php_file "$a/dollar/wp-includes/version.php" '$wp_version = "6.8.$x";' wp_core "$a/brace" 6.8.1 php_file "$a/brace/wp-includes/version.php" '$wp_version = "6.8.{$x}";' + # 64 characters is the longest version kept; one more is unknown. + wp_core "$a/max" "6.8.$(printf 'a%.0s' {1..60})" + wp_core "$a/long" "6.8.$(printf 'a%.0s' {1..61})" chmod -R a+rX "$a" } From ce42b7c4958916bd2f3b5492ffa0514211d5a0a2 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 07:54:54 +0530 Subject: [PATCH 10/80] refactor(compat-scanner): read the contract env in its own function parse_args() had grown past one job; the comment on the never-sniffed extensions also goes back above its constant. --- compat-scanner/bin/compat-scanner.php | 49 +++++++++++++++------------ 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 4715a1cb..7f58a7c7 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -51,11 +51,11 @@ // What sniff() matches in a file's first SNIFF_BYTES, as one regex (no NUL anywhere, then an open tag), for the manifest. const SNIFF_REGEX = '/\\A(?=[^\\x00]*\\z)[\\s\\S]*?<\\?(?:php(?:\\s|\\z)|=)/i'; const PHAR_REGEX = '/\\.phar(?:\\.(?:tar|zip))?(?:\\.(?:gz|bz2))?\\z/i'; -// Never PHP templates, so not sniffed: docs, scripts and styles quote ` Date: Sat, 28 Nov 2026 07:57:18 +0530 Subject: [PATCH 11/80] test(compat-scanner): pin the report key order Every assertion read keys by name, so a reordered report still passed. Also drops a revision label and a time budget that no longer exists from the test comments. --- compat-scanner/tests/assert.php | 6 +++++- compat-scanner/tests/fixture.sh | 2 +- compat-scanner/tests/run.sh | 4 ++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 319ccce6..b22f871c 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -743,7 +743,7 @@ function finding_files( array $report ): array { eq( json_decode( raw( 'bak.manifest.json' ), true )['checked'] ?? null, [ '/var/www/htdocs/wp-config.php', '/var/www/htdocs/wp-content/themes/t/functions.php' ], 'bak: only the code files checked' ); eq( [ out( 'nomanifest' )['status'] ?? null, trim( raw( 'nomanifest.outdir' ) ) ], [ 'ok', './report.json' ], 'nomanifest: without COMPAT_MANIFEST, /out holds only report.json' ); -// r7: a link into an old release or the root's core is an entry by the link's own path (a release pointer beside +// A link into an old release or the root's core is an entry by the link's own path (a release pointer beside // current, and a non-code file link, aren't); php home dot dirs; the per-file cap; the STDIN copy cap. $ol = out( 'oldlink' ); eq( [ $ol['status'] ?? null, field( $ol, 'safe_to_upgrade' ), $ol['files_checked'] ?? null, $ol['files_not_checked'] ?? null ], [ 'ok', null, 1, 5 ], 'oldlink: links into an old release give no verdict' ); @@ -820,6 +820,10 @@ static function ( $f ) { $m = json_decode( raw( 'php-rel.manifest.json' ), true ); eq( [ $m['old_releases'] ?? null, $m['roots'] ?? null ], [ [ '/var/www/htdocs/releases/1/' ], [ '/var/www/' ] ], 'manifest: php old releases and root' ); eq( report( 'php-rel' )['excluded_old_releases'] ?? null, [ '/var/www/htdocs/releases/1' ], 'php-rel: the old release in the report' ); +$keys = [ 'v', 'status', 'site', 'target', 'safe_to_upgrade', 'errors', 'warnings', 'files_checked', 'files_not_checked', 'php_bytes' ]; +$keys = array_merge( $keys, [ 'components_checked', 'components_with_errors', 'duration_s', 'tool', 'components', 'not_checked' ] ); +$keys = array_merge( $keys, [ 'wordpress_installs', 'excluded_old_releases', 'phars', 'phar_named_by' ] ); +eq( array_keys( report( 'php-rel' ) ), $keys, 'php-rel: report key order with COMPAT_SERVED set' ); $m = json_decode( raw( 'full.manifest.json' ), true ); eq( $m['core']['roots'] ?? null, [ '/var/www/htdocs/releases/1/' ], 'manifest: core root is the resolved WordPress root' ); check( ! preg_grep( '#/releases/1/(wp-includes/|wp-settings\.php$)#', $m['checked'] ?? [] ), 'manifest: root core is never checked' ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index c17feb90..b3cc3faf 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -344,7 +344,7 @@ each( \$a );" ln -s ../../vendor/acme/plug-v "$wc/plugins/plug-v" ln -s ../../shared/theme-in "$wc/themes/theme-in" ln -s ../../shared/mu-link.php "$wc/mu-plugins/mu-link.php" - # Links into the root's core are unreadable entries (r7); into another install's core, its nested_wordpress entry. + # Links into the root's core are unreadable entries; into another install's core, its nested_wordpress entry. ln -s ../wp-includes "$wc/inc" ln -s ../wp/wp-load.php "$wc/load.php" ln -s ../wp-includes/version.php "$wc/core-version.php" diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index c1752bb6..601ace96 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -317,8 +317,8 @@ scan untrav "$WORK/untrav" wp /var/www/htdocs 8.4 600 OLD_CALL=1 ENTRY_MEMORY=10M scan pharflood "$WORK/pharflood" wp /var/www/htdocs 8.4 600 ENTRY_MEMORY=10M scan pharflood-info "$WORK/pharflood" wp /var/www/htdocs 8.4 600 -# r7: links into old releases and core are entries; links leaving /var/www by non-asset names; php home dot dirs (dot -# links, dirs uid 33 can't open, links that don't resolve, their own time budget); the per-file cap; the STDIN copy cap. +# Links into old releases and core are entries; links leaving /var/www by non-asset names; php home dot dirs (dot links, +# dirs uid 33 can't open, links that don't resolve); the per-file cap; the STDIN copy cap. oldlink_fixture "$WORK/oldlink" corelink_fixture "$WORK/corelink" phphome_fixture "$WORK/phphome" From 3cecfd8c2b57bb59935329024326d7bfebb2502d Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 08:08:50 +0530 Subject: [PATCH 12/80] fix(compat-scanner): read .user.ini and version.php lines with a length cap One huge line in either file ran the entrypoint out of memory, so the check stopped on a config file's size. Lines are now read at most LINE_MAX at a time: a .user.ini with a longer line is an unreadable entry, as EE treats its own ini files, and such a line in version.php makes the version unknown. A last line that fills the buffer exactly is no longer lost. --- compat-scanner/bin/compat-scanner.php | 48 ++++++++++++++++++++++----- compat-scanner/tests/assert.php | 9 +++++ compat-scanner/tests/fixture.sh | 13 ++++++++ compat-scanner/tests/run.sh | 4 +++ 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 7f58a7c7..1d88b6cb 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -248,18 +248,27 @@ private function checkRequired(): void { } } - /** Collects a .user.ini's auto_prepend_file and auto_append_file values. */ - private function userIni( string $real ): void { + /** + * Collects a .user.ini's auto_prepend_file and auto_append_file values. A line too long to read makes the file itself + * an unreadable entry, as EE does for its ini files. + */ + private function userIni( string $path, string $real ): void { $fh = open_regular( $real ); if ( null === $fh ) { return; } - while ( false !== ( $line = fgets( $fh ) ) ) { - if ( preg_match( '/^\s*auto_(?:prepend|append)_file\s*=(.*)$/i', $line, $m ) && '' !== ini_value( $m[1] ) ) { + $unsure = false; + foreach ( lines( $fh ) as $line ) { + if ( null === $line ) { + $unsure = true; + } elseif ( preg_match( '/^\s*auto_(?:prepend|append)_file\s*=(.*)$/i', $line, $m ) && '' !== ini_value( $m[1] ) ) { $this->required[] = ini_value( $m[1] ); } } fclose( $fh ); + if ( $unsure ) { + $this->notChecked( $this->comp( 'other', '', null, MOUNT_ROOT ), $path, 'unreadable', $real ); + } } /** @@ -787,7 +796,7 @@ private function visit( string $path, string $name, int $comp ): void { return; } if ( '.user.ini' === $name ) { - $this->userIni( $real ); + $this->userIni( $path, $real ); return; } @@ -2679,9 +2688,10 @@ function wp_version( string $dir ): string { return ''; } $lines = []; - while ( false !== ( $line = fgets( $fh ) ) ) { - if ( preg_match( '/\$wp_version\s*=/', $line ) ) { - $lines[] = $line; + foreach ( lines( $fh ) as $line ) { + // A line too long to read may hold it: then the version is unknown. + if ( null === $line || preg_match( '/\$wp_version\s*=/', $line ) ) { + $lines[] = (string) $line; } } fclose( $fh ); @@ -2691,6 +2701,28 @@ function wp_version( string $dir ): string { return strlen( $m[2] ) > 64 ? '' : $m[2]; } +/** + * A file's lines without their `\n`, or null for one longer than LINE_MAX - 2 bytes, so no file size matters. + * + * @param resource $fh + * @return Generator + */ +function lines( $fh ): Generator { + $long = false; + while ( false !== ( $piece = fgets( $fh, LINE_MAX ) ) ) { + if ( "\n" !== substr( $piece, -1 ) && ! feof( $fh ) ) { + $long = true; + continue; + } + yield $long ? null : rtrim( $piece, "\n" ); + $long = false; + } + // A last piece that filled the buffer exactly, with no line break after it. + if ( $long ) { + yield null; + } +} + /** major.minor of a WordPress version, as EE's support table names branches. */ function wp_branch( string $version ): string { return preg_match( '/^\d+\.\d+/', $version, $m ) ? $m[0] : ''; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index b22f871c..d2c40ece 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -896,6 +896,15 @@ function counts( string $name ): array { 'require: outside the site, in core, a phar, not code, relative; from .user.ini files too, also in uploads/ (the scanned wordfence-waf.php and `none` give nothing)' ); +eq( counts( 'longline' ), [ 'ok', null, 0, 1, 3 ], 'longline: a line too long to read is no tool_error' ); +$long_nc = [ + nc( 'other', '', null, '/var/www/htdocs/.user.ini', 'unreadable' ), + nc( 'other', '', null, '/var/www/htdocs/edge/.user.ini', 'unreadable' ), + nc( 'directory', 'htdocs/blog', null, './', 'nested_wordpress' ), +]; +eq( report( 'longline' )['not_checked'] ?? null, $long_nc, 'longline: a .user.ini with such a line is an entry, also one ending at the buffer end' ); +eq( installs( 'longline' ), [ '/var/www/htdocs/blog ' ], 'longline: a version.php line too long to read is an unknown version' ); + foreach ( [ 'phar-info' => null, 'phar-named' => 'boot.php', 'phar-upper' => 'boot.php', 'phar-split' => 'boot.php' ] as $name => $by ) { $r = report( $name ); $phars = [ '/var/www/htdocs/wp-content/plugins/p/lib.phar', '/var/www/htdocs/wp-cli.phar' ]; diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index b3cc3faf..b10251e6 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -968,3 +968,16 @@ lint_fixture() { mkdir -p "$p/views" && printf '

\n\n' > "$p/views/broken.tpl" chmod -R a+rX "$1" } + +# longline_fixture : a php site with a .user.ini and a version.php of one 64 MiB line, and a .user.ini whose +# last line, with no line break, is exactly as long as the scanner's line buffer. +longline_fixture() { + local h="$1/htdocs" + php_file "$h/index.php" 'echo 1;' + mkdir -p "$h/edge" + truncate -s 64M "$h/.user.ini" + head -c 1048575 /dev/zero | tr '\0' ' ' > "$h/edge/.user.ini" + wp_core "$h/blog" 6.8.3 + truncate -s 64M "$h/blog/wp-includes/version.php" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 601ace96..c12b9ae0 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -376,6 +376,10 @@ require_fixture "$WORK/require" scan require "$WORK/require" wp /var/www/htdocs 8.4 600 \ -e COMPAT_REQUIRE=$'/var/www/htdocs/wordfence-waf.php\n/usr/local/etc/php/xhprof.php\n/var/www/htdocs/wp-includes/version.php\n/var/www/htdocs/wp-cli.phar\n/var/www/htdocs/notes.txt\nrel.php\n' +# One huge line in a .user.ini or version.php, read in little entrypoint memory: an entry and an unknown version. +longline_fixture "$WORK/longline" +ENTRY_MEMORY=32M scan longline "$WORK/longline" php /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.8 + # Phars are information unless scanned code names one (in any case, also across a 64 KiB read). phar_fixture "$WORK/phar-info" none phar_fixture "$WORK/phar-named" named From b34b311867f62c3569dc92b898fcadf3ada80fea Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 08:17:03 +0530 Subject: [PATCH 13/80] fix(compat-scanner): read a .user.ini the way PHP does A UTF-8 BOM, lines ending in a bare CR, and `[section] auto_prepend_file=` on one line all hid a prepend or append target that PHP-FPM still runs, so a target the scan never read gave "safe". These are read as PHP's ini scanner reads them, as EE already does for its own ini files. zend.multibyte and zend.script_encoding set in a .user.ini make PHP read the code in another encoding than PHPCS does; the .user.ini is now an unreadable entry then, as EE notes the same settings in the ini files it reads. --- compat-scanner/bin/compat-scanner.php | 25 ++++++++++++++++++++----- compat-scanner/tests/assert.php | 7 +++++++ compat-scanner/tests/fixture.sh | 18 ++++++++++++++++++ compat-scanner/tests/run.sh | 4 ++++ 4 files changed, 49 insertions(+), 5 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 1d88b6cb..a172d3a8 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -249,20 +249,35 @@ private function checkRequired(): void { } /** - * Collects a .user.ini's auto_prepend_file and auto_append_file values. A line too long to read makes the file itself - * an unreadable entry, as EE does for its ini files. + * Collects a .user.ini's auto_prepend_file and auto_append_file values. A line too long to read, or zend.multibyte or + * zend.script_encoding (PHP then reads the code in another encoding than PHPCS), makes the file itself an unreadable + * entry, as EE does for its ini files. */ private function userIni( string $path, string $real ): void { $fh = open_regular( $real ); if ( null === $fh ) { return; } + $keys = '(auto_(?:prepend|append)_file|zend\.multibyte|zend\.script_encoding)'; $unsure = false; - foreach ( lines( $fh ) as $line ) { + foreach ( lines( $fh ) as $n => $line ) { if ( null === $line ) { $unsure = true; - } elseif ( preg_match( '/^\s*auto_(?:prepend|append)_file\s*=(.*)$/i', $line, $m ) && '' !== ini_value( $m[1] ) ) { - $this->required[] = ini_value( $m[1] ); + continue; + } + // As PHP's ini scanner reads it: a BOM first, a bare \r ends a line, `[section] key=` on one line. + $line = 0 === $n ? (string) preg_replace( '/^\xEF\xBB\xBF/', '', $line ) : $line; + foreach ( explode( "\r", $line ) as $part ) { + $value = preg_match( '/^\s*(?:\[[^\]]*\]\s*)*' . $keys . '\s*=(.*)$/i', $part, $m ) ? ini_value( $m[2] ) : ''; + $key = strtolower( $m[1] ?? '' ); + if ( '' === $value || ( 'zend.multibyte' === $key && '0' === $value ) ) { + continue; + } + if ( 0 === strpos( $key, 'auto_' ) ) { + $this->required[] = $value; + } else { + $unsure = true; + } } } fclose( $fh ); diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index d2c40ece..20403d01 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -905,6 +905,13 @@ function counts( string $name ): array { eq( report( 'longline' )['not_checked'] ?? null, $long_nc, 'longline: a .user.ini with such a line is an entry, also one ending at the buffer end' ); eq( installs( 'longline' ), [ '/var/www/htdocs/blog ' ], 'longline: a version.php line too long to read is an unknown version' ); +$styles = [ 'bom', 'cr', 'crlf', 'plain', 'section' ]; +$pre = array_map( static function ( $d ) { return "/var/www/htdocs/$d/pre.txt"; }, $styles ); +eq( counts( 'userini' ), [ 'ok', null, 0, 1, 6 ], 'userini: every prepend target is unread' ); +$ui = report( 'userini' )['not_checked'] ?? []; +eq( $ui[0] ?? null, nc( 'other', '', null, '/var/www/htdocs/sjis/.user.ini', 'unreadable' ), 'userini: a source encoding set is an entry; switched off, none' ); +eq( array_column( array_slice( $ui, 1 ), 'file' ), $pre, 'userini: a BOM, a bare CR, CRLF and `[section] key=` read as by PHP' ); + foreach ( [ 'phar-info' => null, 'phar-named' => 'boot.php', 'phar-upper' => 'boot.php', 'phar-split' => 'boot.php' ] as $name => $by ) { $r = report( $name ); $phars = [ '/var/www/htdocs/wp-content/plugins/p/lib.phar', '/var/www/htdocs/wp-cli.phar' ]; diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index b10251e6..7755cec3 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -981,3 +981,21 @@ longline_fixture() { truncate -s 64M "$h/blog/wp-includes/version.php" chmod -R a+rX "$1" } + +# userini_fixture : a php site with one .user.ini per line style PHP reads (plain, BOM, CR only, CRLF, a +# section on the same line), each prepending a text file the scan doesn't read, and two setting the source encoding. +userini_fixture() { + local h="$1/htdocs" d + php_file "$h/index.php" 'echo 1;' + for d in plain bom cr crlf section; do mkdir -p "$h/$d" && printf 'notes\n' > "$h/$d/pre.txt"; done + printf 'auto_prepend_file = /var/www/htdocs/plain/pre.txt\n' > "$h/plain/.user.ini" + printf '\xEF\xBB\xBFauto_prepend_file = /var/www/htdocs/bom/pre.txt\n' > "$h/bom/.user.ini" + printf '; WAF\rauto_prepend_file = /var/www/htdocs/cr/pre.txt\r' > "$h/cr/.user.ini" + printf '; WAF\r\nauto_prepend_file = /var/www/htdocs/crlf/pre.txt\r\n' > "$h/crlf/.user.ini" + printf '[PHP] auto_prepend_file = /var/www/htdocs/section/pre.txt\n' > "$h/section/.user.ini" + # The source encoding PHP reads with: set in one, switched off in the other. + mkdir -p "$h/sjis" "$h/off" + printf 'zend.multibyte = On\nzend.script_encoding = SJIS\n' > "$h/sjis/.user.ini" + printf 'zend.multibyte = 0\nzend.script_encoding = none\n' > "$h/off/.user.ini" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index c12b9ae0..6f807948 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -380,6 +380,10 @@ scan require "$WORK/require" wp /var/www/htdocs 8.4 600 \ longline_fixture "$WORK/longline" ENTRY_MEMORY=32M scan longline "$WORK/longline" php /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.8 +# Each line style of a .user.ini PHP reads. +userini_fixture "$WORK/userini" +scan userini "$WORK/userini" php /var/www/htdocs 8.4 600 + # Phars are information unless scanned code names one (in any case, also across a 64 KiB read). phar_fixture "$WORK/phar-info" none phar_fixture "$WORK/phar-named" named From fb44320bc167e8e74748a2836a982f37c35af05b Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 08:25:32 +0530 Subject: [PATCH 14/80] fix(compat-scanner): read .user.ini files in core and old releases The walk leaves out the core of every WordPress install and the old releases, so a .user.ini there was never read, though PHP-FPM applies it to the scripts below it (wp-admin/ runs its own scripts). Those directories are now searched for .user.ini by name only, and each .user.ini is read once whichever route reaches it. --- compat-scanner/bin/compat-scanner.php | 43 ++++++++++++++++++++++++++- compat-scanner/tests/assert.php | 7 ++++- compat-scanner/tests/fixture.sh | 15 ++++++++++ compat-scanner/tests/run.sh | 4 +++ 4 files changed, 67 insertions(+), 2 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index a172d3a8..fc788066 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -229,6 +229,10 @@ private function listFiles(): void { foreach ( $this->cfg['extra_roots'] as $root ) { $this->skipped( $root, '.', $this->comp( 'directory', $root, null, $root ) ); } + // PHP reads a .user.ini for the scripts below it in the directories left out too: core and old releases. + foreach ( $this->leftOutDirs() as $dir ) { + $this->iniIn( $dir ); + } $this->checkRequired(); $this->judgeInstalls(); } @@ -248,6 +252,43 @@ private function checkRequired(): void { } } + /** @return string[] Directories the walk leaves out whole: the core dirs of every install met, and the old releases. */ + private function leftOutDirs(): array { + $dirs = $this->oldReleases; + foreach ( array_merge( null === $this->live ? [] : [ $this->live ], array_keys( $this->nested ) ) as $install ) { + foreach ( CORE_DIRS as $core ) { + $dirs[] = $install . '/' . $core; + } + } + return $dirs; + } + + /** Reads every .user.ini under a directory, found by name; links to directories aren't followed. */ + private function iniIn( string $dir ): void { + $stack = [ $dir ]; + while ( $stack ) { + $d = array_pop( $stack ); + foreach ( (array) $this->readDir( $d ) as $name ) { + $path = $d . '/' . $name; + if ( is_dir( $path ) && ! is_link( $path ) ) { + $stack[] = $path; + } elseif ( '.user.ini' === $name ) { + $this->userIniOnce( $path, (string) @realpath( $path ) ); + } + } + } + } + + /** userIni() once per file, whichever route reaches it. */ + private function userIniOnce( string $path, string $real ): void { + $st = @stat( $real ); + if ( false === $st || isset( $this->seenFiles[ $st['dev'] ][ $st['ino'] ] ) ) { + return; + } + $this->seenFiles[ $st['dev'] ][ $st['ino'] ] = 'ini'; + $this->userIni( $path, $real ); + } + /** * Collects a .user.ini's auto_prepend_file and auto_append_file values. A line too long to read, or zend.multibyte or * zend.script_encoding (PHP then reads the code in another encoding than PHPCS), makes the file itself an unreadable @@ -811,7 +852,7 @@ private function visit( string $path, string $name, int $comp ): void { return; } if ( '.user.ini' === $name ) { - $this->userIni( $path, $real ); + $this->userIniOnce( $path, $real ); return; } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 20403d01..64a6757d 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -909,9 +909,14 @@ function counts( string $name ): array { $pre = array_map( static function ( $d ) { return "/var/www/htdocs/$d/pre.txt"; }, $styles ); eq( counts( 'userini' ), [ 'ok', null, 0, 1, 6 ], 'userini: every prepend target is unread' ); $ui = report( 'userini' )['not_checked'] ?? []; -eq( $ui[0] ?? null, nc( 'other', '', null, '/var/www/htdocs/sjis/.user.ini', 'unreadable' ), 'userini: a source encoding set is an entry; switched off, none' ); +$sjis = nc( 'other', '', null, '/var/www/htdocs/sjis/.user.ini', 'unreadable' ); +eq( $ui[0] ?? null, $sjis, 'userini: a source encoding set is an entry; switched off, none' ); eq( array_column( array_slice( $ui, 1 ), 'file' ), $pre, 'userini: a BOM, a bare CR, CRLF and `[section] key=` read as by PHP' ); +$ci = [ '/var/www/htdocs/releases/1/boot.php', '/var/www/htdocs/current/wp-admin/waf.php', '/var/www/htdocs/current/blog/wp-includes/boot.php' ]; +eq( counts( 'coreini' ), [ 'ok', null, 0, 1, 3 ], 'coreini: prepend targets in what the walk leaves out give no verdict' ); +eq( array_column( report( 'coreini' )['not_checked'] ?? [], 'file' ), $ci, 'coreini: .user.ini files in an old release and in core are read' ); + foreach ( [ 'phar-info' => null, 'phar-named' => 'boot.php', 'phar-upper' => 'boot.php', 'phar-split' => 'boot.php' ] as $name => $by ) { $r = report( $name ); $phars = [ '/var/www/htdocs/wp-content/plugins/p/lib.phar', '/var/www/htdocs/wp-cli.phar' ]; diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 7755cec3..bc4ec20c 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -999,3 +999,18 @@ userini_fixture() { printf 'zend.multibyte = 0\nzend.script_encoding = none\n' > "$h/off/.user.ini" chmod -R a+rX "$1" } + +# coreini_fixture : a WordPress CI/CD site, htdocs/current -> releases/2, with a .user.ini in the live core, in +# the core of an install below it and in the old release, each prepending a file there. +coreini_fixture() { + local h="$1/htdocs" r + for r in 1 2; do wp_core "$h/releases/$r" 6.8.3 && php_file "$h/releases/$r/index.php" 'echo 1;'; done + php_file "$h/releases/2/wp-admin/waf.php" 'each( $a );' + printf 'auto_prepend_file = /var/www/htdocs/current/wp-admin/waf.php\n' > "$h/releases/2/wp-admin/.user.ini" + wp_core "$h/releases/2/blog" 6.8.1 + printf 'auto_prepend_file = /var/www/htdocs/current/blog/wp-includes/boot.php\n' > "$h/releases/2/blog/wp-includes/.user.ini" + php_file "$h/releases/1/boot.php" 'each( $a );' + printf 'auto_prepend_file = /var/www/htdocs/releases/1/boot.php\n' > "$h/releases/1/.user.ini" + ln -s releases/2 "$h/current" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 6f807948..4e1d962c 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -384,6 +384,10 @@ ENTRY_MEMORY=32M scan longline "$WORK/longline" php /var/www/htdocs 8.4 600 -e C userini_fixture "$WORK/userini" scan userini "$WORK/userini" php /var/www/htdocs 8.4 600 +# A .user.ini in core or an old release, which the walk leaves out, is still read. +coreini_fixture "$WORK/coreini" +scan coreini "$WORK/coreini" wp /var/www/htdocs/current 8.4 600 -e COMPAT_WP_SUPPORTED=6.8 + # Phars are information unless scanned code names one (in any case, also across a 64 KiB read). phar_fixture "$WORK/phar-info" none phar_fixture "$WORK/phar-named" named From 2084908fc7c5bc279c604a7d0e88e5118fd72337 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 08:28:57 +0530 Subject: [PATCH 15/80] fix(compat-scanner): check a wp-config.php linked into a mount A wp-config.php linked into an extra root was visited by its real path under a component based at /var/www, so its path relative to that base was garbage, the file was counted as deleted and never checked, and the site could scan safe. It is now visited by its link when the target lies outside /var/www, and checked where it is. An extra root that is a file rather than a directory is an unreadable entry, as the contract says, instead of a file that vanished. --- compat-scanner/bin/compat-scanner.php | 12 +++++++++--- compat-scanner/tests/assert.php | 5 +++++ compat-scanner/tests/fixture.sh | 10 ++++++++++ compat-scanner/tests/run.sh | 6 ++++++ 4 files changed, 30 insertions(+), 3 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index fc788066..81840501 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -227,7 +227,12 @@ private function listFiles(): void { // Directories the php container mounts outside /var/www: searched by name, after /var/www so a link into one // keeps its own component. foreach ( $this->cfg['extra_roots'] as $root ) { - $this->skipped( $root, '.', $this->comp( 'directory', $root, null, $root ) ); + $comp = $this->comp( 'directory', $root, null, $root ); + if ( is_dir( $root ) ) { + $this->skipped( $root, '.', $comp ); + } else { + $this->notChecked( $comp, './', 'unreadable' ); + } } // PHP reads a .user.ini for the scripts below it in the directories left out too: core and old releases. foreach ( $this->leftOutDirs() as $dir ) { @@ -368,9 +373,10 @@ private function wpTree( string $wp, array $top ): void { $root = $wp . '/wp-content'; $config = $this->wpConfig( $wp ); if ( null !== $config ) { - // Reported by its real path relative to /var/www (the file to edit), e.g. htdocs/wp-config.php. + // Reported by its real path relative to /var/www (the file to edit), e.g. htdocs/wp-config.php; one linked out of + // /var/www by the link, which visit() follows. $real = @realpath( $config ); - $path = false !== $real && $this->inside( $real ) ? $real : $config; + $path = false !== $real && 0 === strpos( $real, MOUNT_ROOT . '/' ) ? $real : $config; $this->visit( $path, 'wp-config.php', $this->comp( 'other', 'wp-config.php', null, MOUNT_ROOT ) ); } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 64a6757d..55bfa201 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -889,6 +889,11 @@ function counts( string $name ): array { eq( json_decode( raw( 'extraroot.manifest.json' ), true )['roots'] ?? null, [ '/var/www/', '/mnt/media/', '/srv/shared/' ], 'extraroot: manifest roots' ); eq( [ counts( 'extraroot-none' ), report( 'extraroot-none' )['not_checked'] ?? null ], [ [ 'ok', null, 0, 1, 1 ], [ nc( 'other', '', null, 'uploads/', 'unreadable' ) ] ], 'extraroot-none: without the mount the link dangles: unreadable' ); +eq( counts( 'secretroot' ), [ 'ok', false, 1, 1, 1 ], 'secretroot: wp-config.php linked into a mount is checked' ); +eq( finding_files( report( 'secretroot' ) ), [ 'other:wp-config.php::htdocs/wp-config.php' ], 'secretroot: by the link\'s path' ); +$file_root = nc( 'directory', '/srv/one.php', null, './', 'unreadable' ); +eq( report( 'secretroot' )['not_checked'] ?? null, [ $file_root ], 'secretroot: a root that is a file is unreadable' ); + eq( counts( 'require' ), [ 'ok', null, 0, 1, 7 ], 'require: prepend and append targets the scan didn\'t read give no verdict' ); eq( array_column( report( 'require' )['not_checked'] ?? [], 'file' ), diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index bc4ec20c..337474aa 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1014,3 +1014,13 @@ coreini_fixture() { ln -s releases/2 "$h/current" chmod -R a+rX "$1" } + +# secretroot_fixture

: /app's wp-config.php links into /secrets, which run.sh mounts at /mnt/secrets; +# /one.php is mounted as a file where a directory is expected. +secretroot_fixture() { + wp_core "$1/app/htdocs" 6.8.3 + php_file "$1/secrets/wp-config.php" 'each( $a );' + ln -s /mnt/secrets/wp-config.php "$1/app/htdocs/wp-config.php" + php_file "$1/one.php" 'each( $a );' + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 4e1d962c..ce29e6f3 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -371,6 +371,12 @@ scan extraroot "$WORK/extraroot/app" wp /var/www/htdocs 8.4 600 \ -e COMPAT_EXTRA_ROOTS=$'/mnt/media\n/srv/shared' scan extraroot-none "$WORK/extraroot/app" wp /var/www/htdocs 8.4 600 +# wp-config.php linked into a mount is checked there; a file mounted where a directory is expected is unreadable. +secretroot_fixture "$WORK/secretroot" +scan secretroot "$WORK/secretroot/app" wp /var/www/htdocs 8.4 600 \ + --mount "type=bind,src=$WORK/secretroot/secrets,dst=/mnt/secrets,readonly" --mount "type=bind,src=$WORK/secretroot/one.php,dst=/srv/one.php,readonly" \ + -e COMPAT_EXTRA_ROOTS=$'/mnt/secrets\n/srv/one.php' + # Prepend and append targets (COMPAT_REQUIRE, .user.ini): each must be a file the scan read. require_fixture "$WORK/require" scan require "$WORK/require" wp /var/www/htdocs 8.4 600 \ From 49127bed9444375f20b52e5f132fca8554181df3 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 08:32:07 +0530 Subject: [PATCH 16/80] fix(compat-scanner): keep checking a php site whose htdocs is missing or dangling php mode stopped the listing when /var/www/htdocs was missing or a dangling link, so code beside it, the extra roots, the prepend targets and the installs went unread: a missing htdocs said no PHP code was found, and a dangling one hid the errors that would make the site not safe. The bad htdocs keeps its one entry and the rest is checked, as WordPress sites already do. --- compat-scanner/bin/compat-scanner.php | 32 ++++++++++++++------------- compat-scanner/tests/assert.php | 10 +++++++++ compat-scanner/tests/fixture.sh | 9 ++++++++ compat-scanner/tests/run.sh | 7 ++++++ 4 files changed, 43 insertions(+), 15 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 81840501..17f0d5ce 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -203,19 +203,20 @@ private function listFiles(): void { $this->oldReleases = $this->oldReleases( $served ); } if ( 'php' === $this->cfg['site_type'] ) { - $root = MOUNT_ROOT . '/htdocs'; - if ( ! $this->enterRoot( $root ) ) { - return; - } - $this->rootReal = $this->contentReal; - $other = $this->comp( 'other', '', null, $root ); - $entries = $this->readDir( $root ); - if ( null === $entries ) { - $this->notChecked( $other, './', 'unreadable' ); - return; + // A missing or bad htdocs (its own entry) leaves the code beside it, the mounts and the prepend targets to check. + $root = MOUNT_ROOT . '/htdocs'; + $entered = $this->enterRoot( $root ); + if ( $entered ) { + $this->rootReal = $this->contentReal; + $other = $this->comp( 'other', '', null, $root ); + $entries = $this->readDir( $root ); + if ( null === $entries ) { + $this->notChecked( $other, './', 'unreadable' ); + } else { + $this->scanTop( $root, $entries, $other, '' ); + } } - $this->scanTop( $root, $entries, $other, '' ); - $this->scanBeside( $this->comp( 'directory', '..', null, MOUNT_ROOT ), '../' ); + $this->scanBeside( $this->comp( 'directory', '..', null, MOUNT_ROOT ), '../', $entered ? [] : [ 'htdocs' ] ); } else { $top = $this->wpDir( $this->cfg['path'] ); if ( null !== $top ) { @@ -499,9 +500,10 @@ private function enterContent( string $root ): bool { /** * What lies in /var/www beside the root (code above the public dir, a second app, the www-data home), as components - * named $prefix . name. Links come last, so a directory is listed under its own name before a link to it. + * named $prefix . name; $skip: a root already reported. Links come last, so a directory is listed under its own name + * before a link to it. */ - private function scanBeside( int $loose, string $prefix ): void { + private function scanBeside( int $loose, string $prefix, array $skip = [] ): void { $this->markDir( MOUNT_ROOT ); $entries = $this->readDir( MOUNT_ROOT ); if ( null === $entries ) { @@ -509,7 +511,7 @@ private function scanBeside( int $loose, string $prefix ): void { return; } $links = []; - foreach ( $entries as $name ) { + foreach ( array_diff( $entries, $skip ) as $name ) { if ( is_link( MOUNT_ROOT . '/' . $name ) ) { $links[] = $name; } elseif ( in_array( $name, HOME_DIRS, true ) ) { diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 55bfa201..2def1473 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -442,6 +442,16 @@ static function ( $a, $b ) { eq( report( $name )['not_checked'] ?? null, [ [ 'type' => 'other', 'slug' => '', 'branch' => null, 'file' => './', 'reason' => 'unreadable' ] ], "$name: the root is unreadable" ); } +$nh_files = [ 'directory:../lib::old.php', 'directory:/mnt/lib::y.php' ]; +$nh_nc = [ nc( 'other', '', null, '/usr/local/x.php', 'unreadable' ) ]; +$nh_want = [ 'nohtdocs' => [ [ 'ok', false, 2, 2, 1 ], $nh_files, $nh_nc ] ]; +$nh_nc = array_merge( [ nc( 'other', '', null, './', 'unreadable' ) ], $nh_nc ); +$nh_want['badhtdocs'] = [ [ 'ok', false, 2, 2, 2 ], $nh_files, $nh_nc ]; +foreach ( $nh_want as $name => $want ) { + $r = report( $name ); + eq( [ counts( $name ), finding_files( $r ), $r['not_checked'] ?? null ], $want, "$name: without a usable htdocs, the rest is checked" ); +} + $pb = out( 'phpbeside' ); eq( [ $pb['status'] ?? null, field( $pb, 'safe_to_upgrade' ), $pb['errors'] ?? null, $pb['files_checked'] ?? null, $pb['files_not_checked'] ?? null ], [ 'ok', false, 4, 5, 0 ], 'phpbeside: code beside htdocs checked, and the code-named files of the home dirs' ); eq( report( 'phpbeside' )['not_checked'] ?? null, [], 'phpbeside: home dirs holding code are no entries' ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 337474aa..11235959 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1024,3 +1024,12 @@ secretroot_fixture() { php_file "$1/one.php" 'each( $a );' chmod -R a+rX "$1" } + +# nohtdocs_fixture : a php site whose htdocs is missing or a dangling link, with code beside it; +# -mnt is mounted by run.sh. +nohtdocs_fixture() { + php_file "$1/lib/old.php" 'each( $a );' + [ "$2" = dangling ] && ln -s /var/www/nowhere "$1/htdocs" + php_file "$1-mnt/y.php" 'each( $a );' + chmod -R a+rX "$1" "$1-mnt" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index ce29e6f3..59d53626 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -213,6 +213,8 @@ badlink_fixture "$WORK/wplink-dangling" wp /var/www/nowhere badlink_fixture "$WORK/wplink-out" wp /etc badlink_fixture "$WORK/phplink-dangling" php /var/www/nowhere phpbeside_fixture "$WORK/phpbeside" +nohtdocs_fixture "$WORK/nohtdocs" missing +nohtdocs_fixture "$WORK/badhtdocs" dangling bedrock_fixture "$WORK/bedrock" scan wpscope "$WORK/wpscope" wp /var/www/htdocs 8.4 600 estimate est-wpscope "$WORK/wpscope" wp /var/www/htdocs 8.4 @@ -221,6 +223,11 @@ scan wplink-dangling "$WORK/wplink-dangling" wp /var/www/htdocs 8.4 600 scan wplink-out "$WORK/wplink-out" wp /var/www/htdocs 8.4 600 scan phplink-dangling "$WORK/phplink-dangling" php /var/www/htdocs 8.4 600 scan phpbeside "$WORK/phpbeside" php /var/www/htdocs 8.4 600 +# Without a usable htdocs, the code beside it, the mounts and the prepend targets are still checked. +for n in nohtdocs badhtdocs; do + scan "$n" "$WORK/$n" php /var/www/htdocs 8.4 600 --mount "type=bind,src=$WORK/$n-mnt,dst=/mnt/lib,readonly" \ + -e COMPAT_EXTRA_ROOTS=/mnt/lib -e COMPAT_REQUIRE=/usr/local/x.php +done phpdeep_fixture "$WORK/phpdeep" scan phpdeep "$WORK/phpdeep" php /var/www/htdocs 8.4 600 estimate est-phpbeside "$WORK/phpbeside" php /var/www/htdocs 8.4 From 0245d7e3b3bb873535df69d8fd12c6bbee5f0c2a Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 08:35:22 +0530 Subject: [PATCH 17/80] fix(compat-scanner): lint only files that start as PHP A text file quoting `cfg['report_max'] ) ); } - /** A file the lint failed, not run through PHPCS: an ERROR finding, or a not_checked reason (php_tag in a mixed file). */ + /** A file the lint failed, not run through PHPCS: an ERROR finding, or a not_checked reason. */ private function recordLint( array $f ): void { $rel = $this->rel( $f['comp'], $f['path'] ); $reason = $f['lint']; - if ( is_array( $reason ) && $f['mixed'] ) { - $reason = 'php_tag'; - } if ( is_string( $reason ) ) { $this->spoolNotChecked( $f['comp'], $rel, $reason, $f['real'] ); return; @@ -2214,14 +2211,19 @@ private function runTimed( array $cmd, float $cap, array $spec, int $fsize = 0 ) } /** - * `php -l` over a batch, then over each file on its own when the batch fails, since PHPCompatibility misses some parse - * errors (`#[` before PHP 8 code, an unclosed final comment). Targets before 8.0 aren't linted: PHP 8.4 rejects - * syntax they allow. + * `php -l` over a batch, then each file on its own when it fails: PHPCompatibility misses some parse errors (`#[` + * before PHP 8, an unclosed final comment). Not for targets before 8.0, whose syntax PHP 8.4 rejects, nor for files + * with text before their tag (a script or shell history quoting ` By batch key, the files that fail: [ line, message ] or a not_checked reason. */ private function lint( array $batch ): array { - $paths = array_filter( array_column( $batch, 'real' ) ); + $paths = []; + foreach ( $batch as $k => $f ) { + if ( null !== $f['real'] && ! $f['mixed'] ) { + $paths[ $k ] = $f['real']; + } + } if ( ! $paths || version_compare( $this->cfg['version'], '8.0', '<' ) ) { return []; } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 2def1473..4542d62d 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -950,7 +950,12 @@ function counts( string $name ): array { [ 'attr.php:3:CompatScanner.Syntax.ParseError', 'pipe.php:2:CompatScanner.Syntax.ParseError', 'unclosed.php:3:CompatScanner.Syntax.ParseError' ], 'lint: `#[` before code, the pipe operator and an unclosed comment fail on 8.4; an : a WordPress site with text files that quote ` info.php\nexit\n' > "$1/.bash_history" + printf '#!/bin/sh\nset -e\necho " "$1/index.php"\n' > "$1/htdocs/deploy.sh" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 59d53626..3d0903c3 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -411,6 +411,9 @@ OLD_CALL=1 scan phar-oldcall "$WORK/phar-info" wp /var/www/htdocs 8.4 600 # The syntax lint: PHP 8 parse errors PHPCompatibility misses; above the scanner's PHP, unparseable instead. lint_fixture "$WORK/lint" +history_fixture "$WORK/history" +scan history "$WORK/history" wp /var/www/htdocs 8.4 600 +scan history-83 "$WORK/history" wp /var/www/htdocs 8.3 600 scan lint "$WORK/lint" wp /var/www/htdocs 8.4 600 scan lint-85 "$WORK/lint" wp /var/www/htdocs 8.5 600 scan lint-74 "$WORK/lint" wp /var/www/htdocs 7.4 600 From e24f6202a69c5d6b19c66fbef783e7071d62a60a Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 08:38:46 +0530 Subject: [PATCH 18/80] fix(compat-scanner): judge redeclared PHP functions by the target version The lint runs on PHP 8.4, so "Cannot redeclare function array_find()" made an unguarded helper an error for targets that don't have the function yet (8.3 and below), while a helper named after a function PHP 8.5 or 8.6 adds (array_first(), clamp()) passed though it is fatal there. One table, read by both sides, lists the functions PHP added since 8.1 with the version that added them (php-src UPGRADING, matched against the official images; core, standard, json and mbstring). The lint ignores a redeclare of a function the target doesn't have yet, and the file goes on to PHPCS; any other redeclare stays an error, now above 8.4 too instead of unparseable. A new sniff reports a global function declared outside any condition, class, function or namespace whose name is native in the target; a function_exists() guard keeps it quiet. --- compat-scanner/bin/compat-scanner.php | 34 ++++++++++++++--- .../Sniffs/Functions/NativeDeclaredSniff.php | 37 +++++++++++++++++++ compat-scanner/src/CompatScanner/ruleset.xml | 4 ++ compat-scanner/src/native-functions.php | 36 ++++++++++++++++++ compat-scanner/tests/assert.php | 17 +++++++++ compat-scanner/tests/fixture.sh | 25 +++++++++++++ compat-scanner/tests/run.sh | 2 + 7 files changed, 149 insertions(+), 6 deletions(-) create mode 100644 compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php create mode 100644 compat-scanner/src/CompatScanner/ruleset.xml create mode 100644 compat-scanner/src/native-functions.php diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index f2f9b8c0..1b88aef6 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -21,6 +21,8 @@ const PHPCS_BIN = TOOL_DIR . '/vendor/squizlabs/php_codesniffer/bin/phpcs'; const REPORT_CLASS = TOOL_DIR . '/src/LinesReport.php'; const CALIBRATION_DIR = TOOL_DIR . '/calibration'; +// The scanner's own PHPCS checks, added to PHPCompatibility's. +const SNIFFS_DIR = TOOL_DIR . '/src/CompatScanner'; const JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE; // Walked only for code names (see skipped()), and only in the WordPress root's own wp-content for TOP_SKIPS. // upgrade-temp-backup: WordPress' rollback copies of updated plugins and themes (6.3+). @@ -2142,7 +2144,7 @@ private function phpcs( array $paths, string $memory, string $tag, bool $stdin = $cmd = [ PHP_BINARY, '-d', 'memory_limit=' . $memory, '-d', 'display_errors=stderr', '-d', 'log_errors=0', PHPCS_BIN, - '--standard=' . ( 'php' === $this->cfg['site_type'] ? 'PHPCompatibility' : 'PHPCompatibilityWP' ), + '--standard=' . ( 'php' === $this->cfg['site_type'] ? 'PHPCompatibility' : 'PHPCompatibilityWP' ) . ',' . SNIFFS_DIR, '--runtime-set', 'testVersion', $this->cfg['version'], '--extensions=' . implode( ',', CODE_EXTENSIONS ), '--no-cache', '-q', '--no-colors', '--ignore-annotations', '--report=' . REPORT_CLASS, '--report-file=' . $report, @@ -2237,8 +2239,9 @@ private function lint( array $batch ): array { if ( $res['timeout'] ) { throw $this->timedOutAt( $batch[ $k ]['path'] ); } - if ( 0 !== $res['rc'] ) { - $failed[ $k ] = $this->lintResult( $res, $real ); + $result = 0 === $res['rc'] ? null : $this->lintResult( $res, $real ); + if ( null !== $result ) { + $failed[ $k ] = $result; } } return $failed; @@ -2255,7 +2258,10 @@ private function lintRun( array $paths, float $cap ): array { return $res; } - /** @return array{0:int,1:string}|string The finding, or `unparseable` for a target newer than this PHP, which can't parse its syntax. */ + /** + * @return array{0:int,1:string}|string|null The finding, `unparseable` for a target newer than this PHP, which can't + * parse its syntax, or null when only this PHP's own functions clash. + */ private function lintResult( array $res, string $real ) { if ( $res['capped'] ) { return 'timeout'; @@ -2266,10 +2272,19 @@ private function lintResult( array $res, string $real ) { if ( 255 !== $res['rc'] ) { return 'error'; } - if ( version_compare( $this->cfg['version'], PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION, '>' ) ) { + $text = trim( str_replace( ' in ' . $real, '', $res['stderr'] ) ); + // A redeclared function parsed, so it is a finding on any target, unless it clashes only with a function PHP added + // after the target (PHPCS still checks the file then). + if ( preg_match( '/^Fatal error: Cannot redeclare (?:function )?(\w+)\(\)(.*)$/s', $text, $m ) ) { + $native = 0 === strpos( $m[2], ' on line ' ); + $since = $native ? ( native_since()[ strtolower( $m[1] ) ] ?? null ) : null; + if ( null !== $since && version_compare( $this->cfg['version'], $since, '<' ) ) { + return null; + } + } elseif ( version_compare( $this->cfg['version'], PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION, '>' ) ) { return 'unparseable'; } - preg_match( '/^(.*?)(?: on line (\d+))?$/s', trim( str_replace( ' in ' . $real, '', $res['stderr'] ) ), $m ); + preg_match( '/^(.*?)(?: on line (\d+))?$/s', $text, $m ); return [ (int) ( $m[2] ?? 0 ), $m[1] ]; } @@ -2789,6 +2804,13 @@ function lines( $fh ): Generator { } } +/** @return array Functions PHP added since 8.1, by version, as the scanner's PHPCS sniff reads them too. */ +function native_since(): array { + static $since = null; + $since = $since ?? require TOOL_DIR . '/src/native-functions.php'; + return $since; +} + /** major.minor of a WordPress version, as EE's support table names branches. */ function wp_branch( string $version ): string { return preg_match( '/^\d+\.\d+/', $version, $m ) ? $m[0] : ''; diff --git a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php new file mode 100644 index 00000000..5b4db4d8 --- /dev/null +++ b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php @@ -0,0 +1,37 @@ +|null */ + private $since; + + public function register() { + return [ T_FUNCTION ]; + } + + public function process( File $phpcsFile, int $stackPtr ) { + $this->since = $this->since ?? require __DIR__ . '/../../../native-functions.php'; + $name = (string) $phpcsFile->getDeclarationName( $stackPtr ); + $since = $this->since[ strtolower( $name ) ] ?? null; + if ( null === $since || version_compare( (string) Helper::getConfigData( 'testVersion' ), $since, '<' ) ) { + return; + } + // Inside a function_exists() check, a class or a function, or in a namespace, it is another function. + if ( $phpcsFile->getTokens()[ $stackPtr ]['conditions'] || '' !== Namespaces::determineNamespace( $phpcsFile, $stackPtr ) ) { + return; + } + $message = 'Function %s() is native since PHP %s; declaring it without a function_exists() check is fatal there'; + $phpcsFile->addError( $message, $stackPtr, 'Found', [ $name, $since ] ); + } +} diff --git a/compat-scanner/src/CompatScanner/ruleset.xml b/compat-scanner/src/CompatScanner/ruleset.xml new file mode 100644 index 00000000..2cbddd5c --- /dev/null +++ b/compat-scanner/src/CompatScanner/ruleset.xml @@ -0,0 +1,4 @@ + + + Checks of the compat-scanner image that PHPCompatibility doesn't make. + diff --git a/compat-scanner/src/native-functions.php b/compat-scanner/src/native-functions.php new file mode 100644 index 00000000..f4cea98b --- /dev/null +++ b/compat-scanner/src/native-functions.php @@ -0,0 +1,36 @@ + '8.1', + 'enum_exists' => '8.1', + 'fsync' => '8.1', + 'fdatasync' => '8.1', + 'ini_parse_quantity' => '8.2', + 'memory_reset_peak_usage' => '8.2', + 'json_validate' => '8.3', + 'mb_str_pad' => '8.3', + 'str_increment' => '8.3', + 'str_decrement' => '8.3', + 'stream_context_set_options' => '8.3', + 'array_find' => '8.4', + 'array_find_key' => '8.4', + 'array_any' => '8.4', + 'array_all' => '8.4', + 'fpow' => '8.4', + 'http_get_last_response_headers' => '8.4', + 'http_clear_last_response_headers' => '8.4', + 'request_parse_body' => '8.4', + 'mb_trim' => '8.4', + 'mb_ltrim' => '8.4', + 'mb_rtrim' => '8.4', + 'mb_ucfirst' => '8.4', + 'mb_lcfirst' => '8.4', + 'array_first' => '8.5', + 'array_last' => '8.5', + 'get_error_handler' => '8.5', + 'get_exception_handler' => '8.5', + 'clamp' => '8.6', + 'stream_last_errors' => '8.6', + 'stream_clear_errors' => '8.6', +]; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 4542d62d..d2aa5a05 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -952,6 +952,23 @@ function counts( string $name ): array { ); $broken = nc( 'plugin', 'p', null, 'views/broken.tpl', 'unparseable' ); eq( $li['not_checked'] ?? null, [ $broken ], 'lint: text before the tag isn\'t linted; PHPCS can\'t parse it' ); +// A function PHP adds is fatal to declare from that version on: by the lint up to the scanner's PHP, by a sniff above it. +$lint = 'CompatScanner.Syntax.ParseError'; +$sniff = 'CompatScanner.Functions.NativeDeclared.Found'; +$always = [ "strlen.php:$lint", "twice.php:$lint" ]; +$by_ver = [ + '8.3' => $always, + '8.4' => array_merge( [ "find.php:$lint" ], $always ), + '8.5' => array_merge( [ "find.php:$lint", "first.php:$sniff" ], $always ), + '8.6' => array_merge( [ "clamp.php:$sniff", "find.php:$lint", "first.php:$sniff" ], $always ), +]; +foreach ( $by_ver as $v => $want ) { + $r = report( "native-$v" ); + $got = array_map( static function ( $f ) { return $f['file'] . ':' . $f['source']; }, comp_of( $r, 'plugin', 'p' )['findings'] ?? [] ); + sort( $got ); + eq( [ $got, $r['not_checked'] ?? null ], [ $want, [] ], "native-$v: functions native in the target only; guarded, namespaced and methods aren't" ); +} + foreach ( [ 'history', 'history-83' ] as $name ) { $quoted = [ counts( $name ), report( $name )['not_checked'] ?? null ]; eq( $quoted, [ [ 'ok', true, 0, 3, 0 ], [] ], "$name: a shell history and a script quoting "$1/index.php"\n' > "$1/htdocs/deploy.sh" chmod -R a+rX "$1" } + +# native_fixture : global functions named like ones PHP added in 8.4, 8.5 and 8.6, unguarded, guarded, in a +# namespace or as a method; and declarations fatal on every version (a built-in, a function declared twice). +native_fixture() { + local p="$1/htdocs/wp-content/plugins/p" + wp_core "$1/htdocs" 6.8.3 + php_file "$p/p.php" '/* Plugin Name: P */' + php_file "$p/find.php" 'function array_find( $a, $f ) { return null; }' + php_file "$p/first.php" 'if ( function_exists( "array_first" ) ) { return; } +function Array_First( $a ) { return null; }' + php_file "$p/clamp.php" 'function clamp( $v, $min, $max ) { return $v; }' + php_file "$p/guarded.php" 'if ( ! function_exists( "array_last" ) ) { + function array_last( $a ) { return null; } +}' + php_file "$p/alt.php" 'if ( ! function_exists( "array_last" ) ) : + function array_last( $a ) { return null; } +endif;' + php_file "$p/ns.php" 'namespace P; +function array_first( $a ) { return null; }' + php_file "$p/method.php" 'class C { function array_first( $a ) { return null; } }' + php_file "$p/strlen.php" 'function strlen( $s ) { return 0; }' + php_file "$p/twice.php" 'function p_twice() {} +function p_twice() {}' + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 3d0903c3..a3da49e4 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -412,6 +412,8 @@ OLD_CALL=1 scan phar-oldcall "$WORK/phar-info" wp /var/www/htdocs 8.4 600 # The syntax lint: PHP 8 parse errors PHPCompatibility misses; above the scanner's PHP, unparseable instead. lint_fixture "$WORK/lint" history_fixture "$WORK/history" +native_fixture "$WORK/native" +for v in 8.3 8.4 8.5 8.6; do scan "native-$v" "$WORK/native" wp /var/www/htdocs "$v" 600; done scan history "$WORK/history" wp /var/www/htdocs 8.4 600 scan history-83 "$WORK/history" wp /var/www/htdocs 8.3 600 scan lint "$WORK/lint" wp /var/www/htdocs 8.4 600 From 825872280ca0bb138b2f5e5da855b0474f18b69f Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 08:41:06 +0530 Subject: [PATCH 19/80] fix(compat-scanner): leave out only release siblings that look like a release Every directory in releases/ other than the live one was left out as an old release, so a shared/ dir kept there, which the live release requires by a relative path, was never checked. A sibling is now an old release only when it holds what nginx serves from the live one: the served index.php when the live release has one there, else the served directory. Anything else in releases/ is scanned like other code. --- compat-scanner/bin/compat-scanner.php | 14 +++++++++----- compat-scanner/tests/assert.php | 4 ++++ compat-scanner/tests/fixture.sh | 13 +++++++++++++ compat-scanner/tests/run.sh | 2 ++ 4 files changed, 28 insertions(+), 5 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 1b88aef6..649dc1ef 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -570,12 +570,16 @@ private function oldReleases( string $publicDir ): array { if ( is_link( $releases ) || ! is_dir( $releases ) || ! $this->inside( $releases ) || dirname( $live ) !== $releases ) { return []; } - // A release holding the scan path is walked: EE's WordPress hint may name an old one (a stale wp-cli.yml path). - $scan = realpath( $this->cfg['path'] ) . '/'; - $old = []; + // An old release holds what the live one serves (its index.php, else the served dir), so a shared/ dir is walked; + // so is a release holding the scan path, which EE's WordPress hint may name (a stale wp-cli.yml path). + $served = substr( $publicDir, strlen( $path ) ); + $marker = $served . ( is_file( $live . $served . '/index.php' ) ? '/index.php' : '' ); + $scan = realpath( $this->cfg['path'] ) . '/'; + $old = []; foreach ( (array) $this->readDir( $releases ) as $name ) { - $dir = $releases . '/' . $name; - if ( $dir !== $live && ! is_link( $dir ) && is_dir( $dir ) && 0 !== strpos( $scan, $dir . '/' ) ) { + $dir = $releases . '/' . $name; + $release = ! is_link( $dir ) && is_dir( $dir ) && file_exists( $dir . $marker ); + if ( $dir !== $live && $release && 0 !== strpos( $scan, $dir . '/' ) ) { $old[] = $dir; } } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index d2aa5a05..60f98714 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -315,6 +315,10 @@ static function ( $a, $b ) { $e = out( 'est-php-rel' ); eq( [ $e['php_files'] ?? null, $e['php_bytes'] ?? null, $e['components'] ?? null ], [ $pr['files_checked'] + $pr['files_not_checked'], $pr['php_bytes'] ?? null, $pr['components_checked'] ?? null ], 'est-php-rel: counts equal the scan' ); eq( [ out( 'php-rel-link' )['errors'] ?? null ], [ 3 ], 'php-rel-link: symlinked releases/ is not the layout, every release scanned' ); +$rs = report( 'relshared' ); +$rs_want = [ [ 'ok', false, 1, 2, 0 ], [ '/var/www/htdocs/releases/4' ] ]; +eq( [ counts( 'relshared' ), $rs['excluded_old_releases'] ?? null ], $rs_want, 'relshared: only a dir holding the served index.php is old' ); +eq( finding_files( $rs ), [ 'directory:releases::shared/lib.php' ], 'relshared: shared/ in releases/ is scanned' ); // --------------------------------------------------------------- php site diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index c3bafbf1..bd009952 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -262,6 +262,7 @@ php_release_fixture() { [ "$kind" = link ] && store="$h/release-store" php_file "$h/index.php" '// front controller' php_file "$store/1/app.php" 'each( $a );' + php_file "$store/1/public/index.php" 'require "../app.php";' php_file "$store/2/app.php" 'each( $a );' php_file "$store/2/public/index.php" 'require "../app.php";' php_file "$store/hook.php" '// deploy hook' @@ -727,6 +728,7 @@ oldlink_fixture() { php_file "$h/releases/1/vendor/autoload.php" '$f = create_function( "", "" );' php_file "$h/releases/1/h.php" 'each( $a );' php_file "$h/releases/1/lib/l.php" 'each( $a );' + php_file "$h/releases/1/public/index.php" 'require "../vendor/autoload.php";' printf 'notes\n' > "$h/releases/1/notes.txt" php_file "$h/releases/2/public/index.php" 'require "../vendor/autoload.php";' ln -s /var/www/htdocs/releases/1/vendor "$h/releases/2/vendor" @@ -1068,3 +1070,14 @@ function array_first( $a ) { return null; }' function p_twice() {}' chmod -R a+rX "$1" } + +# relshared_fixture : a php CI/CD site, htdocs/current -> releases/5, with a shared/ dir kept in releases/ that +# the live release requires; releases/4 is an old release. +relshared_fixture() { + local r="$1/htdocs/releases" + php_file "$r/5/public/index.php" 'require __DIR__ . "/../../shared/lib.php";' + php_file "$r/4/public/index.php" 'each( $a );' + php_file "$r/shared/lib.php" 'each( $a );' + ln -s releases/5 "$1/htdocs/current" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index a3da49e4..8a0ee0b4 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -170,6 +170,8 @@ scan wpcfg-parent "$WORK/wpcfg-parent" wp /var/www/htdocs 8.4 600 scan php-rel "$WORK/php-rel" php /var/www/htdocs/current/public 8.4 600 estimate est-php-rel "$WORK/php-rel" php /var/www/htdocs/current/public 8.4 scan php-rel-link "$WORK/php-rel-link" php /var/www/htdocs/current/public 8.4 600 +relshared_fixture "$WORK/relshared" +scan relshared "$WORK/relshared" php /var/www/htdocs/current/public 8.4 600 # A deploy re-points current mid-scan: no verdict. A file that grows before its batch: checked as it is now. during switch switch_release "$WORK/switch" From 083658fa0662bcf0ba5263ae79a453141bea2c88 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 08:43:37 +0530 Subject: [PATCH 20/80] fix(compat-scanner): raise the entrypoint memory limit to 2G With no cap on files listed by name, a cache dir of around a million .php files ran the 256M entrypoint out of memory, and a longer --timeout couldn't help. 2G is above the 1g EE gives the container, so the time limit, or the container's own, ends such a scan; it still bounds a run without a container limit. --- compat-scanner/Dockerfile | 3 ++- compat-scanner/tests/assert.php | 3 +++ compat-scanner/tests/run.sh | 2 ++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/compat-scanner/Dockerfile b/compat-scanner/Dockerfile index dbf268a8..fcb6498c 100644 --- a/compat-scanner/Dockerfile +++ b/compat-scanner/Dockerfile @@ -28,4 +28,5 @@ COPY bin/ /opt/compat-scanner/bin/ COPY src/ /opt/compat-scanner/src/ USER 33:33 -ENTRYPOINT ["php", "-d", "memory_limit=256M", "-d", "display_errors=stderr", "/opt/compat-scanner/bin/compat-scanner.php"] +# Above EE's 1g container limit, so the time limit, not PHP's, ends a scan of millions of files; still a bound elsewhere. +ENTRYPOINT ["php", "-d", "memory_limit=2G", "-d", "display_errors=stderr", "/opt/compat-scanner/bin/compat-scanner.php"] diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 60f98714..2451b99b 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -982,6 +982,9 @@ function counts( string $name ): array { $l74sources = array_column( comp_of( $l74, 'plugin', 'p' )['findings'] ?? [], 'source' ); eq( [ in_array( 'CompatScanner.Syntax.ParseError', $l74sources, true ), array_column( $l74['not_checked'] ?? [], 'file' ) ], [ false, [ 'views/broken.tpl' ] ], 'lint-74: targets before 8.0 aren\'t linted (broken.tpl is PHPCS\'s own unparseable)' ); +$entry = json_decode( raw( 'entrypoint' ), true ); +eq( $entry[2] ?? null, 'memory_limit=2G', 'image: the entrypoint\'s memory limit is above EE\'s container limit' ); + tool_error( 'badargs-served', 'bad arguments: COMPAT_SERVED must be', 2, false ); tool_error( 'badargs-supported', 'bad arguments: COMPAT_WP_SUPPORTED must be', 2, false ); tool_error( 'badargs-roots', 'bad arguments: COMPAT_EXTRA_ROOTS must be', 2, false ); diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 8a0ee0b4..b6eaa25e 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -430,6 +430,8 @@ scan badargs-roots "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_EXTRA_ROOTS=/ # An estimate keeps time for calibration: throttled, the listing of 20,000 files can't finish in its share of 1 s. estimate est-listing "$WORK/wide" wp /var/www/htdocs 8.4 -e COMPAT_ESTIMATE_TIMEOUT=1 --cpus 0.05 +docker image inspect -f '{{json .Config.Entrypoint}}' "$IMAGE" > "$RES/entrypoint" + chmod -R a+rX "$RES" docker run --rm --network none --read-only --user 33:33 \ --mount "type=bind,src=$RES,dst=/r,readonly" \ From 242107a962b7a408e389be9ff7bf605dc344b072 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sat, 28 Nov 2026 08:48:39 +0530 Subject: [PATCH 21/80] fix(compat-scanner): lint for fatal errors only PHP 8.4 prints a deprecation while compiling legacy code (an implicitly nullable parameter) before a fatal error, so the redeclare check missed the "Cannot redeclare" line after it, and the deprecation text ended up in the finding. The lint now reports fatal errors only. stream_socket_get_crypto_status(), new in PHP 8.6, joins the table of native functions. --- compat-scanner/bin/compat-scanner.php | 2 ++ compat-scanner/src/native-functions.php | 1 + compat-scanner/tests/assert.php | 6 +++--- compat-scanner/tests/fixture.sh | 3 +++ 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 649dc1ef..819e3c2b 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -2254,6 +2254,8 @@ private function lint( array $batch ): array { private function lintRun( array $paths, float $cap ): array { $err = $this->work . '/lint.err'; $args = [ '-d', 'memory_limit=' . $this->cfg['retry_memory'], '-d', 'display_errors=stderr', '-d', 'log_errors=0' ]; + // Fatal errors only: a deprecation PHP prints while compiling would come before the one line lintResult() reads. + $args = array_merge( $args, [ '-d', 'error_reporting=' . ( E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR ) ] ); // EE's php images turn short tags off; on, PHP would parse a template's `runTimed( $cmd, $cap, [ 0 => [ 'file', '/dev/null', 'r' ], 1 => [ 'file', '/dev/null', 'w' ], 2 => [ 'file', $err, 'w' ] ] ); diff --git a/compat-scanner/src/native-functions.php b/compat-scanner/src/native-functions.php index f4cea98b..373da31c 100644 --- a/compat-scanner/src/native-functions.php +++ b/compat-scanner/src/native-functions.php @@ -33,4 +33,5 @@ 'clamp' => '8.6', 'stream_last_errors' => '8.6', 'stream_clear_errors' => '8.6', + 'stream_socket_get_crypto_status' => '8.6', ]; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 2451b99b..2f3cf35b 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -962,9 +962,9 @@ function counts( string $name ): array { $always = [ "strlen.php:$lint", "twice.php:$lint" ]; $by_ver = [ '8.3' => $always, - '8.4' => array_merge( [ "find.php:$lint" ], $always ), - '8.5' => array_merge( [ "find.php:$lint", "first.php:$sniff" ], $always ), - '8.6' => array_merge( [ "clamp.php:$sniff", "find.php:$lint", "first.php:$sniff" ], $always ), + '8.4' => array_merge( [ "find.php:$lint", "legacy.php:$lint" ], $always ), + '8.5' => array_merge( [ "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always ), + '8.6' => array_merge( [ "clamp.php:$sniff", "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always ), ]; foreach ( $by_ver as $v => $want ) { $r = report( "native-$v" ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index bd009952..dc13f948 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1053,6 +1053,9 @@ native_fixture() { wp_core "$1/htdocs" 6.8.3 php_file "$p/p.php" '/* Plugin Name: P */' php_file "$p/find.php" 'function array_find( $a, $f ) { return null; }' + # PHP 8.4 prints a deprecation for the first function while compiling, before the redeclare. + php_file "$p/legacy.php" 'function p_old( array $x = null ) {} +function array_find( $a, $f ) { return null; }' php_file "$p/first.php" 'if ( function_exists( "array_first" ) ) { return; } function Array_First( $a ) { return null; }' php_file "$p/clamp.php" 'function clamp( $v, $min, $max ) { return $v; }' From 864e0fc2dddeff411a4e6ad87f952bcb92be72f3 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 06:00:26 +0530 Subject: [PATCH 22/80] fix(compat-scanner): leave .user.ini files in old releases unread nginx doesn't serve an old release the scan leaves out, so PHP never applies a .user.ini there; reading it could only turn a prepend target inside that release into "can't confirm". The .user.ini files in the core dirs of the live install and of other installs are still read. --- compat-scanner/bin/compat-scanner.php | 10 +++++----- compat-scanner/tests/assert.php | 6 +++--- compat-scanner/tests/fixture.sh | 2 +- compat-scanner/tests/run.sh | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 819e3c2b..16934cdd 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -237,8 +237,8 @@ private function listFiles(): void { $this->notChecked( $comp, './', 'unreadable' ); } } - // PHP reads a .user.ini for the scripts below it in the directories left out too: core and old releases. - foreach ( $this->leftOutDirs() as $dir ) { + // PHP applies a .user.ini to the core scripts it serves too; old releases aren't served, so theirs never apply. + foreach ( $this->coreDirsMet() as $dir ) { $this->iniIn( $dir ); } $this->checkRequired(); @@ -260,9 +260,9 @@ private function checkRequired(): void { } } - /** @return string[] Directories the walk leaves out whole: the core dirs of every install met, and the old releases. */ - private function leftOutDirs(): array { - $dirs = $this->oldReleases; + /** @return string[] The core dirs of every install met, which the walk leaves out. */ + private function coreDirsMet(): array { + $dirs = []; foreach ( array_merge( null === $this->live ? [] : [ $this->live ], array_keys( $this->nested ) ) as $install ) { foreach ( CORE_DIRS as $core ) { $dirs[] = $install . '/' . $core; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 2f3cf35b..e9521307 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -932,9 +932,9 @@ function counts( string $name ): array { eq( $ui[0] ?? null, $sjis, 'userini: a source encoding set is an entry; switched off, none' ); eq( array_column( array_slice( $ui, 1 ), 'file' ), $pre, 'userini: a BOM, a bare CR, CRLF and `[section] key=` read as by PHP' ); -$ci = [ '/var/www/htdocs/releases/1/boot.php', '/var/www/htdocs/current/wp-admin/waf.php', '/var/www/htdocs/current/blog/wp-includes/boot.php' ]; -eq( counts( 'coreini' ), [ 'ok', null, 0, 1, 3 ], 'coreini: prepend targets in what the walk leaves out give no verdict' ); -eq( array_column( report( 'coreini' )['not_checked'] ?? [], 'file' ), $ci, 'coreini: .user.ini files in an old release and in core are read' ); +$ci = [ '/var/www/htdocs/current/wp-admin/waf.php', '/var/www/htdocs/current/blog/wp-includes/boot.php' ]; +eq( counts( 'coreini' ), [ 'ok', null, 0, 1, 2 ], 'coreini: prepend targets in core give no verdict' ); +eq( array_column( report( 'coreini' )['not_checked'] ?? [], 'file' ), $ci, 'coreini: .user.ini files in core are read, not the old release\'s' ); foreach ( [ 'phar-info' => null, 'phar-named' => 'boot.php', 'phar-upper' => 'boot.php', 'phar-split' => 'boot.php' ] as $name => $by ) { $r = report( $name ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index dc13f948..9edf8c7d 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1003,7 +1003,7 @@ userini_fixture() { } # coreini_fixture : a WordPress CI/CD site, htdocs/current -> releases/2, with a .user.ini in the live core, in -# the core of an install below it and in the old release, each prepending a file there. +# the core of an install below it and in the old release (never served), each prepending a file there. coreini_fixture() { local h="$1/htdocs" r for r in 1 2; do wp_core "$h/releases/$r" 6.8.3 && php_file "$h/releases/$r/index.php" 'echo 1;'; done diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index b6eaa25e..d9fe2db8 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -399,7 +399,7 @@ ENTRY_MEMORY=32M scan longline "$WORK/longline" php /var/www/htdocs 8.4 600 -e C userini_fixture "$WORK/userini" scan userini "$WORK/userini" php /var/www/htdocs 8.4 600 -# A .user.ini in core or an old release, which the walk leaves out, is still read. +# A .user.ini in core, which the walk leaves out, is still read; one in an old release nginx doesn't serve isn't. coreini_fixture "$WORK/coreini" scan coreini "$WORK/coreini" wp /var/www/htdocs/current 8.4 600 -e COMPAT_WP_SUPPORTED=6.8 From e87f7e675648d20ead836ffbd1053571f3177ffc Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 06:16:40 +0530 Subject: [PATCH 23/80] fix(compat-scanner): walk the code beside a wp-content linked out of the WordPress directory When wp-content is a link to a directory outside the WordPress directory (the shared/ dir of a release layout, a directory beside htdocs or inside it, a mount), every directory above its target counted as out of scope, so the other code there (shared/vendor/, a lib/ dir, a bootstrap file) was never listed and gave no entry. Real directories above the content root are now walked like those above the scan root; the content root itself is still walked once, as the content root. --- compat-scanner/bin/compat-scanner.php | 13 ++++----- compat-scanner/tests/assert.php | 11 +++++++ compat-scanner/tests/fixture.sh | 41 +++++++++++++++++++++++++++ compat-scanner/tests/run.sh | 7 +++++ 4 files changed, 64 insertions(+), 8 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 16934cdd..82c2b907 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -807,16 +807,13 @@ private function scanTop( string $root, array $entries, int $loose, string $pref } /** - * outOfScope(), except that a real directory (not reached through a link) above the scan root is walked: - * htdocs may link into the app beside it (`htdocs -> project/app/public`); the root itself stays out. + * outOfScope(), except that a real directory (not reached through a link) above the scan root or the content root is + * walked: htdocs may link into the app beside it (`htdocs -> project/app/public`), wp-content into a shared/ dir + * holding other code; the roots themselves stay out. */ private function inScope( string $path, string $real ): bool { - return ! $this->outOfScope( $real ) || ( $path === $real && $this->holdsRoot( $real ) ); - } - - /** A directory above the scan root other than the mount itself. */ - private function holdsRoot( string $real ): bool { - return MOUNT_ROOT !== $real && null !== $this->rootReal && 0 === strpos( $this->rootReal . '/', $real . '/' ) && $this->rootReal !== $real; + $why = $this->scopeWhy( $real ); + return null === $why || ( 'anchor' === $why && $path === $real && ! in_array( $real, [ MOUNT_ROOT, $this->rootReal, $this->contentReal ], true ) ); } private function walk( string $dir, int $comp ): void { diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index e9521307..9c2b4988 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -908,6 +908,17 @@ function counts( string $name ): array { $file_root = nc( 'directory', '/srv/one.php', null, './', 'unreadable' ); eq( report( 'secretroot' )['not_checked'] ?? null, [ $file_root ], 'secretroot: a root that is a file is unreadable' ); +$content_out = [ + 'shared' => [ 'directory:htdocs::shared/lib.php', 'directory:htdocs::shared/vendor/acme/x.php' ], + 'away' => [ 'directory:content::lib/x.php' ], + 'app' => [ 'directory:htdocs/app::bootstrap.php', 'directory:htdocs/app::vendor/x.php' ], + 'mount' => [ 'directory:/mnt/shared::lib/x.php' ], +]; +foreach ( $content_out as $v => $want ) { + $r = report( "contentout-$v" ); + eq( [ finding_files( $r ), $r['not_checked'] ?? null ], [ $want, [] ], "contentout-$v: code beside a wp-content outside the WordPress directory is checked" ); +} + eq( counts( 'require' ), [ 'ok', null, 0, 1, 7 ], 'require: prepend and append targets the scan didn\'t read give no verdict' ); eq( array_column( report( 'require' )['not_checked'] ?? [], 'file' ), diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 9edf8c7d..d23486f2 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1084,3 +1084,44 @@ relshared_fixture() { ln -s releases/5 "$1/htdocs/current" chmod -R a+rX "$1" } + +# contentout_fixture : wp-content links out of the WordPress directory, with code beside +# its target: a shared/ dir of a release layout, a dir beside htdocs, a dir inside htdocs, or a mount (-mnt, at +# /mnt/shared in run.sh). +contentout_fixture() { + local a=$1 h="$1/htdocs" c + case $2 in + shared) + wp_core "$h/releases/3" 6.8.3 + c="$h/shared" + ln -s ../../shared/wp-content "$h/releases/3/wp-content" + ln -s ../../shared/wp-config.php "$h/releases/3/wp-config.php" + php_file "$c/wp-config.php" "require __DIR__ . '/vendor/acme/x.php';" + php_file "$c/vendor/acme/x.php" 'each( $a );' + php_file "$c/lib.php" 'each( $a );' + ln -s releases/3 "$h/current" + ;; + away) + wp_core "$h" 6.8.3 + c="$a/content" + ln -s /var/www/content/wp-content "$h/wp-content" + php_file "$c/lib/x.php" 'each( $a );' + ;; + app) + wp_core "$h" 6.8.3 + c="$h/app/content" + ln -s app/content/wp-content "$h/wp-content" + php_file "$h/app/vendor/x.php" 'each( $a );' + php_file "$h/app/bootstrap.php" 'each( $a );' + ;; + mount) + wp_core "$h" 6.8.3 + c="$a-mnt" + ln -s /mnt/shared/wp-content "$h/wp-content" + php_file "$c/lib/x.php" 'each( $a );' + chmod -R a+rX "$c" + ;; + esac + php_file "$c/wp-content/plugins/p/p.php" '/* Plugin Name: P */' + chmod -R a+rX "$a" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index d9fe2db8..44350f12 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -386,6 +386,13 @@ scan secretroot "$WORK/secretroot/app" wp /var/www/htdocs 8.4 600 \ --mount "type=bind,src=$WORK/secretroot/secrets,dst=/mnt/secrets,readonly" --mount "type=bind,src=$WORK/secretroot/one.php,dst=/srv/one.php,readonly" \ -e COMPAT_EXTRA_ROOTS=$'/mnt/secrets\n/srv/one.php' +# wp-content linked out of the WordPress directory: the code beside its target is walked too. +for v in shared away app mount; do contentout_fixture "$WORK/contentout-$v" "$v"; done +scan contentout-shared "$WORK/contentout-shared" wp /var/www/htdocs/current 8.4 600 +for v in away app; do scan "contentout-$v" "$WORK/contentout-$v" wp /var/www/htdocs 8.4 600; done +scan contentout-mount "$WORK/contentout-mount" wp /var/www/htdocs 8.4 600 \ + --mount "type=bind,src=$WORK/contentout-mount-mnt,dst=/mnt/shared,readonly" -e COMPAT_EXTRA_ROOTS=/mnt/shared + # Prepend and append targets (COMPAT_REQUIRE, .user.ini): each must be a file the scan read. require_fixture "$WORK/require" scan require "$WORK/require" wp /var/www/htdocs 8.4 600 \ From 1949a88a251a3fcc2a39c5d2a41c66aa071154e4 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 06:33:02 +0530 Subject: [PATCH 24/80] fix(compat-scanner): keep linting past a function PHP adds after the target The lint stops at a file's first fatal error. When that was the declaration of a function PHP added after the target (array_find() checked for 8.3), the file went on to PHPCS alone, so a later unguarded declaration of an older built-in (str_contains()) or a function declared twice, which only the lint catches, was never reported. The lint now runs with the functions PHP added after the target disabled, as they don't exist there: declaring one is no error, and the lint reports the fatal error after it. --- compat-scanner/bin/compat-scanner.php | 30 ++++++++++++++------------- compat-scanner/tests/assert.php | 2 +- compat-scanner/tests/fixture.sh | 8 ++++++- 3 files changed, 24 insertions(+), 16 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 82c2b907..a76d79dd 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -2240,9 +2240,8 @@ private function lint( array $batch ): array { if ( $res['timeout'] ) { throw $this->timedOutAt( $batch[ $k ]['path'] ); } - $result = 0 === $res['rc'] ? null : $this->lintResult( $res, $real ); - if ( null !== $result ) { - $failed[ $k ] = $result; + if ( 0 !== $res['rc'] ) { + $failed[ $k ] = $this->lintResult( $res, $real ); } } return $failed; @@ -2253,6 +2252,15 @@ private function lintRun( array $paths, float $cap ): array { $args = [ '-d', 'memory_limit=' . $this->cfg['retry_memory'], '-d', 'display_errors=stderr', '-d', 'log_errors=0' ]; // Fatal errors only: a deprecation PHP prints while compiling would come before the one line lintResult() reads. $args = array_merge( $args, [ '-d', 'error_reporting=' . ( E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR ) ] ); + // Functions PHP added after the target don't exist there: disabled, declaring one is no error, and the lint goes on + // to whatever comes after it. + $later = array_filter( + native_since(), + function ( $since ) { + return version_compare( $this->cfg['version'], $since, '<' ); + } + ); + $args = array_merge( $args, [ '-d', 'disable_functions=' . implode( ',', array_keys( $later ) ) ] ); // EE's php images turn short tags off; on, PHP would parse a template's `runTimed( $cmd, $cap, [ 0 => [ 'file', '/dev/null', 'r' ], 1 => [ 'file', '/dev/null', 'w' ], 2 => [ 'file', $err, 'w' ] ] ); @@ -2262,8 +2270,8 @@ private function lintRun( array $paths, float $cap ): array { } /** - * @return array{0:int,1:string}|string|null The finding, `unparseable` for a target newer than this PHP, which can't - * parse its syntax, or null when only this PHP's own functions clash. + * @return array{0:int,1:string}|string The finding, or `unparseable` for a target newer than this PHP, which can't parse + * its syntax. */ private function lintResult( array $res, string $real ) { if ( $res['capped'] ) { @@ -2276,15 +2284,9 @@ private function lintResult( array $res, string $real ) { return 'error'; } $text = trim( str_replace( ' in ' . $real, '', $res['stderr'] ) ); - // A redeclared function parsed, so it is a finding on any target, unless it clashes only with a function PHP added - // after the target (PHPCS still checks the file then). - if ( preg_match( '/^Fatal error: Cannot redeclare (?:function )?(\w+)\(\)(.*)$/s', $text, $m ) ) { - $native = 0 === strpos( $m[2], ' on line ' ); - $since = $native ? ( native_since()[ strtolower( $m[1] ) ] ?? null ) : null; - if ( null !== $since && version_compare( $this->cfg['version'], $since, '<' ) ) { - return null; - } - } elseif ( version_compare( $this->cfg['version'], PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION, '>' ) ) { + // A redeclared function parsed, so it is a finding on any target. + $redeclare = (bool) preg_match( '/^Fatal error: Cannot redeclare (?:function )?\w+\(\)/', $text ); + if ( ! $redeclare && version_compare( $this->cfg['version'], PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION, '>' ) ) { return 'unparseable'; } preg_match( '/^(.*?)(?: on line (\d+))?$/s', $text, $m ); diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 9c2b4988..01713f35 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -970,7 +970,7 @@ function counts( string $name ): array { // A function PHP adds is fatal to declare from that version on: by the lint up to the scanner's PHP, by a sniff above it. $lint = 'CompatScanner.Syntax.ParseError'; $sniff = 'CompatScanner.Functions.NativeDeclared.Found'; -$always = [ "strlen.php:$lint", "twice.php:$lint" ]; +$always = [ "poly.php:$lint", "polytwice.php:$lint", "strlen.php:$lint", "twice.php:$lint" ]; $by_ver = [ '8.3' => $always, '8.4' => array_merge( [ "find.php:$lint", "legacy.php:$lint" ], $always ), diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index d23486f2..7241dda0 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1047,7 +1047,8 @@ history_fixture() { } # native_fixture : global functions named like ones PHP added in 8.4, 8.5 and 8.6, unguarded, guarded, in a -# namespace or as a method; and declarations fatal on every version (a built-in, a function declared twice). +# namespace or as a method; and declarations fatal on every version (a built-in, a function declared twice), also after +# one of a function PHP added in 8.4. native_fixture() { local p="$1/htdocs/wp-content/plugins/p" wp_core "$1/htdocs" 6.8.3 @@ -1071,6 +1072,11 @@ function array_first( $a ) { return null; }' php_file "$p/strlen.php" 'function strlen( $s ) { return 0; }' php_file "$p/twice.php" 'function p_twice() {} function p_twice() {}' + php_file "$p/poly.php" 'function array_find( $a, $f ) { return null; } +function str_contains( $h, $n ) { return false; }' + php_file "$p/polytwice.php" 'function array_find( $a, $f ) { return null; } +function p_poly() {} +function p_poly() {}' chmod -R a+rX "$1" } From c30c8bf37f9ab2b293c0b4392bd850c45e50a84a Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 06:39:00 +0530 Subject: [PATCH 25/80] fix(compat-scanner): count only a function_exists() check on the name as a guard The check for a function PHP has natively in the target let any enclosing block count as a guard. A declaration inside a braced global namespace, try, if ( true ), an include guard (! defined( ... )), a function_exists() check on another name or another function's body went unreported, though PHP declares it there unconditionally or once the block runs, which the target's own function makes fatal. Only an if or elseif whose condition calls function_exists() on that same name (any case, either quote style, with or without a leading backslash) keeps it quiet now; methods and functions in a named namespace are still other functions. --- .../Sniffs/Functions/NativeDeclaredSniff.php | 36 ++++++++++++++++--- compat-scanner/tests/assert.php | 8 +++-- compat-scanner/tests/fixture.sh | 31 ++++++++++++++-- 3 files changed, 66 insertions(+), 9 deletions(-) diff --git a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php index 5b4db4d8..348785bb 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php @@ -1,15 +1,19 @@ getTokens()[ $stackPtr ]['conditions'] || '' !== Namespaces::determineNamespace( $phpcsFile, $stackPtr ) ) { + // In a named namespace it is another function. + if ( '' !== Namespaces::determineNamespace( $phpcsFile, $stackPtr ) ) { return; } + foreach ( $phpcsFile->getTokens()[ $stackPtr ]['conditions'] as $ptr => $code ) { + if ( isset( Tokens::OO_SCOPE_TOKENS[ $code ] ) || $this->checksExists( $phpcsFile, $ptr, $name ) ) { + return; + } + } $message = 'Function %s() is native since PHP %s; declaring it without a function_exists() check is fatal there'; $phpcsFile->addError( $message, $stackPtr, 'Found', [ $name, $since ] ); } + + /** Whether the condition is an if or elseif calling function_exists() on this name. */ + private function checksExists( File $phpcsFile, int $ptr, string $name ): bool { + $tokens = $phpcsFile->getTokens(); + if ( ! in_array( $tokens[ $ptr ]['code'], [ T_IF, T_ELSEIF ], true ) || ! isset( $tokens[ $ptr ]['parenthesis_closer'] ) ) { + return false; + } + for ( $i = $tokens[ $ptr ]['parenthesis_opener']; $i < $tokens[ $ptr ]['parenthesis_closer']; $i++ ) { + $call = in_array( $tokens[ $i ]['code'], [ T_STRING, T_NAME_FULLY_QUALIFIED ], true ); + if ( ! $call || 'function_exists' !== strtolower( ltrim( $tokens[ $i ]['content'], '\\' ) ) ) { + continue; + } + $arg = PassedParameters::getParameter( $phpcsFile, $i, 1, 'function' ); + if ( false !== $arg && strtolower( ltrim( TextStrings::stripQuotes( $arg['clean'] ), '\\' ) ) === strtolower( $name ) ) { + return true; + } + } + return false; + } } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 01713f35..04be3a72 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -971,17 +971,19 @@ function counts( string $name ): array { $lint = 'CompatScanner.Syntax.ParseError'; $sniff = 'CompatScanner.Functions.NativeDeclared.Found'; $always = [ "poly.php:$lint", "polytwice.php:$lint", "strlen.php:$lint", "twice.php:$lint" ]; +$no_guard = [ "defined.php:$sniff", "iftrue.php:$sniff", "nested.php:$sniff", "nsbrace.php:$sniff", "other.php:$sniff", "try.php:$sniff" ]; $by_ver = [ '8.3' => $always, '8.4' => array_merge( [ "find.php:$lint", "legacy.php:$lint" ], $always ), - '8.5' => array_merge( [ "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always ), - '8.6' => array_merge( [ "clamp.php:$sniff", "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always ), + '8.5' => array_merge( [ "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always, $no_guard ), + '8.6' => array_merge( [ "clamp.php:$sniff", "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always, $no_guard ), ]; foreach ( $by_ver as $v => $want ) { + sort( $want ); $r = report( "native-$v" ); $got = array_map( static function ( $f ) { return $f['file'] . ':' . $f['source']; }, comp_of( $r, 'plugin', 'p' )['findings'] ?? [] ); sort( $got ); - eq( [ $got, $r['not_checked'] ?? null ], [ $want, [] ], "native-$v: functions native in the target only; guarded, namespaced and methods aren't" ); + eq( [ $got, $r['not_checked'] ?? null ], [ $want, [] ], "native-$v: functions native in the target only; guarded by function_exists() on the name, namespaced and methods aren't" ); } foreach ( [ 'history', 'history-83' ] as $name ) { diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 7241dda0..4c7f9cb6 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1046,8 +1046,9 @@ history_fixture() { chmod -R a+rX "$1" } -# native_fixture : global functions named like ones PHP added in 8.4, 8.5 and 8.6, unguarded, guarded, in a -# namespace or as a method; and declarations fatal on every version (a built-in, a function declared twice), also after +# native_fixture : global functions named like ones PHP added in 8.4, 8.5 and 8.6, unguarded, guarded by +# function_exists() on their name, in a namespace or as a method, or in a block that guards nothing (a braced global +# namespace, try, if ( true ), an include guard, a check on another name, another function's body); and declarations fatal on every version (a built-in, a function declared twice), also after # one of a function PHP added in 8.4. native_fixture() { local p="$1/htdocs/wp-content/plugins/p" @@ -1072,6 +1073,32 @@ function array_first( $a ) { return null; }' php_file "$p/strlen.php" 'function strlen( $s ) { return 0; }' php_file "$p/twice.php" 'function p_twice() {} function p_twice() {}' + php_file "$p/fq.php" "if ( ! \\function_exists( 'Array_Last' ) ) { + function array_last( \$a ) { return null; } +}" + php_file "$p/elseif.php" 'if ( false ) { +} elseif ( ! function_exists( "array_last" ) ) { + function array_last( $a ) { return null; } +}' + php_file "$p/nsbrace.php" 'namespace { + function array_first( $a ) { return null; } +}' + php_file "$p/try.php" 'try { + function array_first( $a ) { return null; } +} catch ( Error $e ) {}' + php_file "$p/iftrue.php" 'if ( true ) { + function array_last( $a ) { return null; } +}' + php_file "$p/defined.php" 'if ( ! defined( "P_HELPERS" ) ) { + define( "P_HELPERS", 1 ); + function array_last( $a ) { return null; } +}' + php_file "$p/nested.php" 'function p_setup() { + function array_first( $a ) { return null; } +}' + php_file "$p/other.php" 'if ( ! function_exists( "array_first" ) ) { + function array_last( $a ) { return null; } +}' php_file "$p/poly.php" 'function array_find( $a, $f ) { return null; } function str_contains( $h, $n ) { return false; }' php_file "$p/polytwice.php" 'function array_find( $a, $f ) { return null; } From 62505426c414af2773cafcccdba1968d3eba7825 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 06:42:10 +0530 Subject: [PATCH 26/80] fix(compat-scanner): leave out an old release only when it holds the served file itself A sibling release was left out when anything sat at the live release's served index.php, a directory too (or, without an index.php, anything at the served path). Such a sibling isn't a copy of the live release, so its code went unchecked. The marker must now be a regular file for index.php, and a directory for the served path. --- compat-scanner/bin/compat-scanner.php | 5 +++-- compat-scanner/tests/assert.php | 7 ++++--- compat-scanner/tests/fixture.sh | 3 ++- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index a76d79dd..374ce0b1 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -573,12 +573,13 @@ private function oldReleases( string $publicDir ): array { // An old release holds what the live one serves (its index.php, else the served dir), so a shared/ dir is walked; // so is a release holding the scan path, which EE's WordPress hint may name (a stale wp-cli.yml path). $served = substr( $publicDir, strlen( $path ) ); - $marker = $served . ( is_file( $live . $served . '/index.php' ) ? '/index.php' : '' ); + $index = is_file( $live . $served . '/index.php' ); + $marker = $served . ( $index ? '/index.php' : '' ); $scan = realpath( $this->cfg['path'] ) . '/'; $old = []; foreach ( (array) $this->readDir( $releases ) as $name ) { $dir = $releases . '/' . $name; - $release = ! is_link( $dir ) && is_dir( $dir ) && file_exists( $dir . $marker ); + $release = ! is_link( $dir ) && is_dir( $dir ) && ( $index ? is_file( $dir . $marker ) : is_dir( $dir . $marker ) ); if ( $dir !== $live && $release && 0 !== strpos( $scan, $dir . '/' ) ) { $old[] = $dir; } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 04be3a72..25ab8dea 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -316,9 +316,10 @@ static function ( $a, $b ) { eq( [ $e['php_files'] ?? null, $e['php_bytes'] ?? null, $e['components'] ?? null ], [ $pr['files_checked'] + $pr['files_not_checked'], $pr['php_bytes'] ?? null, $pr['components_checked'] ?? null ], 'est-php-rel: counts equal the scan' ); eq( [ out( 'php-rel-link' )['errors'] ?? null ], [ 3 ], 'php-rel-link: symlinked releases/ is not the layout, every release scanned' ); $rs = report( 'relshared' ); -$rs_want = [ [ 'ok', false, 1, 2, 0 ], [ '/var/www/htdocs/releases/4' ] ]; -eq( [ counts( 'relshared' ), $rs['excluded_old_releases'] ?? null ], $rs_want, 'relshared: only a dir holding the served index.php is old' ); -eq( finding_files( $rs ), [ 'directory:releases::shared/lib.php' ], 'relshared: shared/ in releases/ is scanned' ); +$rs_want = [ [ 'ok', false, 2, 3, 0 ], [ '/var/www/htdocs/releases/4' ] ]; +eq( [ counts( 'relshared' ), $rs['excluded_old_releases'] ?? null ], $rs_want, 'relshared: only a dir holding the served index.php file is old' ); +$rs_files = [ 'directory:releases::3/lib.php', 'directory:releases::shared/lib.php' ]; +eq( finding_files( $rs ), $rs_files, 'relshared: shared/ and a release without the served file are scanned' ); // --------------------------------------------------------------- php site diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 4c7f9cb6..ba692f8b 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1108,12 +1108,13 @@ function p_poly() {}' } # relshared_fixture : a php CI/CD site, htdocs/current -> releases/5, with a shared/ dir kept in releases/ that -# the live release requires; releases/4 is an old release. +# the live release requires; releases/4 is an old release; releases/3 has a directory where the live one has index.php. relshared_fixture() { local r="$1/htdocs/releases" php_file "$r/5/public/index.php" 'require __DIR__ . "/../../shared/lib.php";' php_file "$r/4/public/index.php" 'each( $a );' php_file "$r/shared/lib.php" 'each( $a );' + mkdir -p "$r/3/public/index.php" && php_file "$r/3/lib.php" 'each( $a );' ln -s releases/5 "$1/htdocs/current" chmod -R a+rX "$1" } From 5f2e9bb0120fc5eb891eb9a6a913c53db4c82cd3 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 06:45:21 +0530 Subject: [PATCH 27/80] fix(compat-scanner): read every .user.ini, and report a core one that can't be followed .user.ini files shared the set of files listed as code, so a code-named hard link to one, listed first, stopped it being read, and its prepend target went unreported. They now have a set of their own. A .user.ini in a WordPress core dir that dangles or resolves outside /var/www and the mounts was skipped silently; it is now the same "unreadable" entry as a .user.ini the scan can't follow elsewhere. --- compat-scanner/bin/compat-scanner.php | 19 +++++++++++++------ compat-scanner/tests/assert.php | 12 ++++++++++-- compat-scanner/tests/fixture.sh | 16 +++++++++++++++- compat-scanner/tests/run.sh | 4 +++- 4 files changed, 41 insertions(+), 10 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 374ce0b1..17fb9bb7 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -114,6 +114,8 @@ final class Scanner { private $seenDirs = []; /** @var array> Listed files by device and inode. */ private $seenFiles = []; + /** @var array> .user.ini files read, by device and inode: another name of one may be code. */ + private $seenInis = []; /** @var array Real paths of the site path and content root when listed. */ private $pins = []; /** @var int */ @@ -281,7 +283,12 @@ private function iniIn( string $dir ): void { if ( is_dir( $path ) && ! is_link( $path ) ) { $stack[] = $path; } elseif ( '.user.ini' === $name ) { - $this->userIniOnce( $path, (string) @realpath( $path ) ); + $real = $this->resolve( $path ); + if ( null === $real ) { + $this->notChecked( $this->comp( 'other', '', null, MOUNT_ROOT ), $path, 'unreadable', $path ); + } else { + $this->userIniOnce( $path, $real ); + } } } } @@ -290,10 +297,10 @@ private function iniIn( string $dir ): void { /** userIni() once per file, whichever route reaches it. */ private function userIniOnce( string $path, string $real ): void { $st = @stat( $real ); - if ( false === $st || isset( $this->seenFiles[ $st['dev'] ][ $st['ino'] ] ) ) { + if ( false === $st || isset( $this->seenInis[ $st['dev'] ][ $st['ino'] ] ) ) { return; } - $this->seenFiles[ $st['dev'] ][ $st['ino'] ] = 'ini'; + $this->seenInis[ $st['dev'] ][ $st['ino'] ] = true; $this->userIni( $path, $real ); } @@ -860,13 +867,13 @@ private function visit( string $path, string $name, int $comp ): void { if ( false === $st || 0100000 !== ( $st['mode'] & 0170000 ) ) { return; } - if ( isset( $this->seenFiles[ $st['dev'] ][ $st['ino'] ] ) ) { - return; - } if ( '.user.ini' === $name ) { $this->userIniOnce( $path, $real ); return; } + if ( isset( $this->seenFiles[ $st['dev'] ][ $st['ino'] ] ) ) { + return; + } // A phar's code is in the archive, which PHPCS can't read (only its `isPharName( $name ) || $this->isPharName( $real ) ) { diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 25ab8dea..7cd7b190 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -944,9 +944,17 @@ function counts( string $name ): array { eq( $ui[0] ?? null, $sjis, 'userini: a source encoding set is an entry; switched off, none' ); eq( array_column( array_slice( $ui, 1 ), 'file' ), $pre, 'userini: a BOM, a bare CR, CRLF and `[section] key=` read as by PHP' ); -$ci = [ '/var/www/htdocs/current/wp-admin/waf.php', '/var/www/htdocs/current/blog/wp-includes/boot.php' ]; -eq( counts( 'coreini' ), [ 'ok', null, 0, 1, 2 ], 'coreini: prepend targets in core give no verdict' ); +$ci = [ + '/var/www/htdocs/releases/2/wp-includes/.user.ini', + '/var/www/htdocs/releases/2/blog/wp-admin/.user.ini', + '/var/www/htdocs/current/wp-admin/waf.php', + '/var/www/htdocs/current/blog/wp-includes/boot.php', +]; +eq( counts( 'coreini' ), [ 'ok', null, 0, 1, 4 ], 'coreini: prepend targets in core, and .user.ini links that can\'t be followed, give no verdict' ); eq( array_column( report( 'coreini' )['not_checked'] ?? [], 'file' ), $ci, 'coreini: .user.ini files in core are read, not the old release\'s' ); +$ia = [ counts( 'inialias' ), array_column( report( 'inialias' )['not_checked'] ?? [], 'file' ) ]; +$ia_want = [ [ 'ok', null, 0, 2, 1 ], [ '/var/www/htdocs/alias/pre.txt' ] ]; +eq( $ia, $ia_want, 'inialias: a .user.ini is read though a code-named link to it was listed first' ); foreach ( [ 'phar-info' => null, 'phar-named' => 'boot.php', 'phar-upper' => 'boot.php', 'phar-split' => 'boot.php' ] as $name => $by ) { $r = report( $name ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index ba692f8b..cd284c83 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1003,7 +1003,8 @@ userini_fixture() { } # coreini_fixture : a WordPress CI/CD site, htdocs/current -> releases/2, with a .user.ini in the live core, in -# the core of an install below it and in the old release (never served), each prepending a file there. +# the core of an install below it and in the old release (never served), each prepending a file there; and a .user.ini +# link in each core that dangles or leaves /var/www. coreini_fixture() { local h="$1/htdocs" r for r in 1 2; do wp_core "$h/releases/$r" 6.8.3 && php_file "$h/releases/$r/index.php" 'echo 1;'; done @@ -1012,6 +1013,8 @@ coreini_fixture() { wp_core "$h/releases/2/blog" 6.8.1 printf 'auto_prepend_file = /var/www/htdocs/current/blog/wp-includes/boot.php\n' > "$h/releases/2/blog/wp-includes/.user.ini" php_file "$h/releases/1/boot.php" 'each( $a );' + ln -s /var/www/nowhere.ini "$h/releases/2/wp-includes/.user.ini" + ln -s /etc/passwd "$h/releases/2/blog/wp-admin/.user.ini" printf 'auto_prepend_file = /var/www/htdocs/releases/1/boot.php\n' > "$h/releases/1/.user.ini" ln -s releases/2 "$h/current" chmod -R a+rX "$1" @@ -1159,3 +1162,14 @@ contentout_fixture() { php_file "$c/wp-content/plugins/p/p.php" '/* Plugin Name: P */' chmod -R a+rX "$a" } + +# inialias_fixture : a php site whose .user.ini, prepending a file the scan doesn't read, has a code-named hard +# link listed before it. +inialias_fixture() { + local h="$1/htdocs" + php_file "$h/index.php" 'echo 1;' + mkdir -p "$h/alias" && printf 'notes\n' > "$h/alias/pre.txt" + printf 'auto_prepend_file = /var/www/htdocs/alias/pre.txt\n' > "$h/alias/.user.ini" + ln "$h/alias/.user.ini" "$h/alias/-.php" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 44350f12..623dd63e 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -402,9 +402,11 @@ scan require "$WORK/require" wp /var/www/htdocs 8.4 600 \ longline_fixture "$WORK/longline" ENTRY_MEMORY=32M scan longline "$WORK/longline" php /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6.8 -# Each line style of a .user.ini PHP reads. +# Each line style of a .user.ini PHP reads; a .user.ini is read though another name of it is listed first. userini_fixture "$WORK/userini" scan userini "$WORK/userini" php /var/www/htdocs 8.4 600 +inialias_fixture "$WORK/inialias" +scan inialias "$WORK/inialias" php /var/www/htdocs 8.4 600 # A .user.ini in core, which the walk leaves out, is still read; one in an old release nginx doesn't serve isn't. coreini_fixture "$WORK/coreini" From 1c8e19dc56971bb170d408c2b5289ec18b3f5041 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 06:47:55 +0530 Subject: [PATCH 28/80] fix(compat-scanner): bound the reads of data-only candidates, the phar search and version.php A data-only candidate (`` in a dir searched by name) was read to its end, so a file of many GiB held the listing far past the deadline; it is read up to 8 MiB again, and a larger one is listed as code. The search for a phar reference now checks the scan deadline on every read, so a huge file ends the scan at the deadline, naming it. Reading version.php stops at the second $wp_version line, which already makes the version unknown, instead of keeping every such line in memory. --- compat-scanner/bin/compat-scanner.php | 19 +++++++++++++++++-- compat-scanner/tests/assert.php | 15 ++++++++++++--- compat-scanner/tests/fixture.sh | 27 +++++++++++++++++++++++++-- compat-scanner/tests/run.sh | 10 ++++++++++ 4 files changed, 64 insertions(+), 7 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 17fb9bb7..5b699ca9 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -48,6 +48,8 @@ // A file PHPCS reads through STDIN is copied to /out first; past this it is refused by size (`memory`), not copied. // Real PHP code of 8 MiB already exceeds 960M, though a mostly-comment file that large could be checked. const STDIN_MAX = 16777216; +// A data-only candidate larger than this isn't read to its end: it is listed as code instead. +const DATA_MAX = 8388608; // Bit of a file list entry's length field: the file has a PHP tag after other text, so its findings can't be trusted. const MIXED_FLAG = 0x80000000; // What sniff() matches in a file's first SNIFF_BYTES, as one regex (no NUL anywhere, then an open tag), for the manifest. @@ -1038,7 +1040,7 @@ private function phar( int $comp, string $rel ): void { } /** Whether a file names `phar://` or `.phar`, in any case. */ - private function namesPhar( string $real ): bool { + private function namesPhar( string $path, string $real ): bool { $fh = open_regular( $real ); if ( null === $fh ) { return false; @@ -1046,6 +1048,10 @@ private function namesPhar( string $real ): bool { $tail = ''; $found = false; while ( ! $found && '' !== ( $chunk = (string) fread( $fh, 65536 ) ) ) { + if ( microtime( true ) >= $this->deadline ) { + fclose( $fh ); + throw $this->timedOutAt( $path ); + } $found = (bool) preg_match( '#phar://|\.phar#i', $tail . $chunk ); $tail = substr( $chunk, -6 ); } @@ -1079,6 +1085,7 @@ private function dataOnly( string $path ): bool { $ok = (bool) preg_match( '/\A(?:\xEF\xBB\xBF)?<\?php\s+(?:exit|die)\s*(?:\(\s*(?:\'[^\'\\\\]*\'|"[^"\\\\$]*"|\d+)?\s*\))?\s*;?\s*(__halt_compiler\s*\(\s*\)\s*;?\s*)?\?>/i', $head, $m ); if ( $ok && empty( $m[1] ) ) { $rest = substr( $head, strlen( $m[0] ) ); + $read = strlen( $head ); while ( true ) { if ( preg_match( '/<\?(?:php(?:\s|\z)|=)/i', $rest ) ) { $ok = false; @@ -1092,6 +1099,11 @@ private function dataOnly( string $path ): bool { if ( '' === $more ) { break; } + $read += strlen( $more ); + if ( $read > DATA_MAX ) { + $ok = false; + break; + } $rest = substr( $rest, -5 ) . $more; // A tag split across reads. } } @@ -1576,7 +1588,7 @@ private function prepare( array $batch ): array { $batch[ $k ]['cap'] = (float) ( $code ? $this->cfg['file_timeout'] : $this->cfg['sniffed_timeout'] ); // Searched only on a site holding a phar, up to the first hit; not in a file refused by size. $search = $this->pharCount > 0 && null === $this->pharNamedBy && ! ( $batch[ $k ]['stdin'] && $st['size'] > STDIN_MAX ); - if ( $search && $this->namesPhar( $real ) ) { + if ( $search && $this->namesPhar( $f['path'], $real ) ) { $this->pharNamedBy = $f['path']; } } @@ -2787,6 +2799,9 @@ function wp_version( string $dir ): string { if ( null === $line || preg_match( '/\$wp_version\s*=/', $line ) ) { $lines[] = (string) $line; } + if ( count( $lines ) > 1 ) { + break; + } } fclose( $fh ); if ( 1 !== count( $lines ) || ! preg_match( '/^\s*\$wp_version\s*=\s*([\'"])(\d+\.\d+[0-9A-Za-z.+-]*)\1\s*;\s*$/', $lines[0], $m ) ) { diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 7cd7b190..aa1f13e8 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -695,7 +695,8 @@ function finding_files( array $report ): array { eq( finding_files( report( $name ) ), [ 'other:::cache/object/tail.php' ], "$name: a data header followed by another open tag is scanned" ); check( ( $ca['duration_s'] ?? 999 ) < 120, "$name: done in " . ( $ca['duration_s'] ?? '?' ) . ' s' ); } -check( 1 === preg_match_all( '/\] batch 3 files rc=/', raw( 'cache.stderr' ) ), 'cache: one PHPCS batch, of p.php, the Docket Cache file and tail.php (data-only files, huge.php too, take no run)' ); +$what = 'cache: one PHPCS batch, of p.php, the Docket Cache file, tail.php and huge.php, too large to read as data (data-only files take no run)'; +check( 1 === preg_match_all( '/\] batch 4 files rc=/', raw( 'cache.stderr' ) ), $what ); $e = out( 'est-cache' ); eq( [ $e['php_files'] ?? null, $e['components'] ?? null ], [ 2506, 2 ], 'est-cache: counts equal the scan' ); @@ -796,6 +797,9 @@ function finding_files( array $report ): array { $e = out( 'est-bigstdin' ); eq( [ $e['php_files'] ?? null, $e['inputs']['stdin_files'] ?? null ], [ 3, 1 ], 'est-bigstdin: the file over the STDIN cap is no PHPCS run' ); +$e = out( 'est-datacap' ); +eq( [ $e['php_files'] ?? null, $e['inputs']['batches'] ?? null ], [ 1, 1 ], 'est-datacap: a data-only candidate over 8 MiB is listed as code' ); + // Every ok scan writes manifest.json; its checked/not_checked match the counts, and every code file of the tree, by the // manifest's own rules, is covered (tests/manifest-check.php ran against the scanned tree). $manifests = 0; @@ -927,14 +931,16 @@ function counts( string $name ): array { 'require: outside the site, in core, a phar, not code, relative; from .user.ini files too, also in uploads/ (the scanned wordfence-waf.php and `none` give nothing)' ); -eq( counts( 'longline' ), [ 'ok', null, 0, 1, 3 ], 'longline: a line too long to read is no tool_error' ); +eq( counts( 'longline' ), [ 'ok', null, 0, 1, 4 ], 'longline: a line too long to read, or many long ones, is no tool_error' ); $long_nc = [ nc( 'other', '', null, '/var/www/htdocs/.user.ini', 'unreadable' ), nc( 'other', '', null, '/var/www/htdocs/edge/.user.ini', 'unreadable' ), nc( 'directory', 'htdocs/blog', null, './', 'nested_wordpress' ), + nc( 'directory', 'htdocs/many', null, './', 'nested_wordpress' ), ]; eq( report( 'longline' )['not_checked'] ?? null, $long_nc, 'longline: a .user.ini with such a line is an entry, also one ending at the buffer end' ); -eq( installs( 'longline' ), [ '/var/www/htdocs/blog ' ], 'longline: a version.php line too long to read is an unknown version' ); +$what = 'longline: a version.php line too long to read, or more than one version line, is an unknown version'; +eq( installs( 'longline' ), [ '/var/www/htdocs/blog ', '/var/www/htdocs/many ' ], $what ); $styles = [ 'bom', 'cr', 'crlf', 'plain', 'section' ]; $pre = array_map( static function ( $d ) { return "/var/www/htdocs/$d/pre.txt"; }, $styles ); @@ -964,6 +970,9 @@ function counts( string $name ): array { eq( [ $r['phars'] ?? null, field( $r, 'phar_named_by' ), $r['not_checked'] ?? null ], [ null === $by ? $phars : [], $named, $nc ], "$name: phars are information unless scanned code names one" ); eq( field( out( $name ), 'safe_to_upgrade' ), null === $by ? true : null, "$name: verdict" ); } +tool_error( 'pharslow', 'timed out after 3 s at htdocs/wp-content/plugins/p/big.php', 1 ); +$secs = trim( raw( 'pharslow.secs' ) ); +check( '' !== $secs && (int) $secs <= 30, "pharslow: the search for a phar reference stops at the deadline ($secs s)" ); $r = report( 'phar-oldcall' ); eq( [ array_key_exists( 'phars', $r ), array_column( $r['not_checked'] ?? [], 'reason' ) ], [ false, [ 'phar', 'phar' ] ], 'phar-oldcall: a v3.11.1 call keeps phar entries' ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index cd284c83..d770c598 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -971,8 +971,8 @@ lint_fixture() { chmod -R a+rX "$1" } -# longline_fixture : a php site with a .user.ini and a version.php of one 64 MiB line, and a .user.ini whose -# last line, with no line break, is exactly as long as the scanner's line buffer. +# longline_fixture : a php site with a .user.ini and a version.php of one 64 MiB line, a .user.ini whose last +# line, with no line break, is exactly as long as the scanner's line buffer, and a version.php of 48 long version lines. longline_fixture() { local h="$1/htdocs" php_file "$h/index.php" 'echo 1;' @@ -981,6 +981,9 @@ longline_fixture() { head -c 1048575 /dev/zero | tr '\0' ' ' > "$h/edge/.user.ini" wp_core "$h/blog" 6.8.3 truncate -s 64M "$h/blog/wp-includes/version.php" + wp_core "$h/many" 6.8.3 + line="\$wp_version = '$(head -c 1000000 /dev/zero | tr '\0' 1)';" + for _ in $(seq 48); do printf '%s\n' "$line"; done > "$h/many/wp-includes/version.php" chmod -R a+rX "$1" } @@ -1173,3 +1176,23 @@ inialias_fixture() { ln "$h/alias/.user.ini" "$h/alias/-.php" chmod -R a+rX "$1" } + +# datacap_fixture : a `` data file over 8 MiB in uploads/cache/. +datacap_fixture() { + local u="$1/htdocs/wp-content/uploads/cache" + wp_core "$1/htdocs" 6.8.3 + mkdir -p "$u" + { printf ''; head -c 9437184 /dev/zero | tr '\0' a; } > "$u/x.php" + chmod -R a+rX "$1" +} + +# pharslow_fixture : a site holding a phar, and a sparse 64 GiB code file read for a phar reference. +pharslow_fixture() { + local p="$1/htdocs/wp-content/plugins/p" + wp_core "$1/htdocs" 6.8.3 + php_file "$p/p.php" '/* Plugin Name: P */' + printf ' "$1/htdocs/wp-cli.phar" + printf ' "$p/big.php" + truncate -s 64G "$p/big.php" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 623dd63e..7e09597f 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -341,6 +341,10 @@ scan slowcode "$WORK/slowcode" wp /var/www/htdocs 7.4 600 -e COMPAT_FILE_TIMEOUT scan bigstdin "$WORK/bigstdin" wp /var/www/htdocs 8.4 600 estimate est-bigstdin "$WORK/bigstdin" wp /var/www/htdocs 8.4 +# A data-only candidate over 8 MiB isn't read to its end: it is listed as code. +datacap_fixture "$WORK/datacap" +estimate est-datacap "$WORK/datacap" wp /var/www/htdocs 8.4 + # Backup copies aren't read; production runs write no manifest. bak_fixture "$WORK/bak" scan bak "$WORK/bak" wp /var/www/htdocs 8.4 600 @@ -418,6 +422,12 @@ phar_fixture "$WORK/phar-named" named phar_fixture "$WORK/phar-upper" upper phar_fixture "$WORK/phar-split" split for f in info named upper split; do scan "phar-$f" "$WORK/phar-$f" wp /var/www/htdocs 8.4 600; done +# The search for a phar reference in a huge file stops at the deadline. +pharslow_fixture "$WORK/pharslow" +start=$SECONDS +scan pharslow "$WORK/pharslow" wp /var/www/htdocs 8.4 3 +echo $(( SECONDS - start )) > "$RES/pharslow.secs" +rm -f "$WORK/pharslow/htdocs/wp-content/plugins/p/big.php" OLD_CALL=1 scan phar-oldcall "$WORK/phar-info" wp /var/www/htdocs 8.4 600 # The syntax lint: PHP 8 parse errors PHPCompatibility misses; above the scanner's PHP, unparseable instead. From 8ae627dae3fb89ae0ffbdc2eeef0eda1192ea642 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 06:50:55 +0530 Subject: [PATCH 29/80] test(compat-scanner): keep the harness exact on odd input installs() reports a missing wordpress_installs key instead of aborting the suite; the manifest check accepts only phars as information entries, so a directory or other code listed there can't hide a file from it; run.sh replays each --mount argument whole, also with a space in TMPDIR; a few long assertion lines are split. --- compat-scanner/tests/assert.php | 12 +++++++++--- compat-scanner/tests/manifest-check.php | 6 ++++++ compat-scanner/tests/run.sh | 4 ++-- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index aa1f13e8..14d8a0fa 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -854,11 +854,15 @@ static function ( $f ) { /** The report's installs as "dir version live". */ function installs( string $name ): array { + $all = report( $name )['wordpress_installs'] ?? null; + if ( ! is_array( $all ) ) { + return [ 'missing' ]; + } return array_map( static function ( $i ) { return $i['dir'] . ' ' . $i['version'] . ( $i['live'] ? ' live' : '' ); }, - report( $name )['wordpress_installs'] ?? [ 'missing' ] + $all ); } @@ -921,7 +925,8 @@ function counts( string $name ): array { ]; foreach ( $content_out as $v => $want ) { $r = report( "contentout-$v" ); - eq( [ finding_files( $r ), $r['not_checked'] ?? null ], [ $want, [] ], "contentout-$v: code beside a wp-content outside the WordPress directory is checked" ); + $what = "contentout-$v: code beside a wp-content outside the WordPress directory is checked"; + eq( [ finding_files( $r ), $r['not_checked'] ?? null ], [ $want, [] ], $what ); } eq( counts( 'require' ), [ 'ok', null, 0, 1, 7 ], 'require: prepend and append targets the scan didn\'t read give no verdict' ); @@ -1001,7 +1006,8 @@ function counts( string $name ): array { $r = report( "native-$v" ); $got = array_map( static function ( $f ) { return $f['file'] . ':' . $f['source']; }, comp_of( $r, 'plugin', 'p' )['findings'] ?? [] ); sort( $got ); - eq( [ $got, $r['not_checked'] ?? null ], [ $want, [] ], "native-$v: functions native in the target only; guarded by function_exists() on the name, namespaced and methods aren't" ); + $what = "native-$v: functions native in the target only; guarded by function_exists() on the name, namespaced and methods aren't"; + eq( [ $got, $r['not_checked'] ?? null ], [ $want, [] ], $what ); } foreach ( [ 'history', 'history-83' ] as $name ) { diff --git a/compat-scanner/tests/manifest-check.php b/compat-scanner/tests/manifest-check.php index 9d28fa63..058f69c2 100644 --- a/compat-scanner/tests/manifest-check.php +++ b/compat-scanner/tests/manifest-check.php @@ -79,6 +79,12 @@ } $inodes[ $st['dev'] . ':' . $st['ino'] ] = true; } +// Only phars are information (by the name walked or the target's), never a directory or other code. +foreach ( $m['information'] as $p ) { + if ( ! is_file( $p ) || ! ( preg_match( $m['phar_regex'], $p ) || preg_match( $m['phar_regex'], (string) realpath( $p ) ) ) ) { + $problems[] = "information entry not a phar: $p"; + } +} $ncDirs = []; $ncFiles = []; foreach ( array_merge( $m['not_checked'], $m['information'] ) as $p ) { diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 7e09597f..4f54d383 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -38,14 +38,14 @@ entry() { v2_env() { [ -n "${OLD_CALL:-}" ] || printf -- '-e COMPAT_SERVED=%s' "$1"; } # The --mount arguments among docker args, for the manifest check to see the same tree. -mounts_of() { while [ $# -gt 0 ]; do [ "$1" = --mount ] && echo --mount "$2"; shift; done; } +mounts_of() { while [ $# -gt 0 ]; do [ "$1" = --mount ] && printf '%s\n' --mount "$2"; shift; done; } # scan [docker args...] scan() { local name=$1 app=$2 type=$3 path=$4 ver=$5 timeout=$6 shift 6 local out rc=0 mounts - mapfile -t mounts < <(mounts_of "$@" | tr ' ' '\n') + mapfile -t mounts < <(mounts_of "$@") out=$(new_out "$name") # OUT_DIR_AT=report.json: a directory already there, so publishing the report fails. if [ -n "${OUT_DIR_AT:-}" ]; then mkdir "$out/$OUT_DIR_AT" && chmod 0777 "$out/$OUT_DIR_AT"; fi From 39606fd7d97af138a99c9e7116b9a3b990df63aa Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 06:57:50 +0530 Subject: [PATCH 30/80] fix(compat-scanner): set the entrypoint memory limit to 1536M EE now runs the scanner with a 2g container limit. A PHP limit above it let the kernel kill a scan that outgrew it, with no JSON document for EE to show; 1536M leaves room for millions of listed files and ends such a scan with PHP's own error, a tool_error, first. Written in M, as PHP reads 1.5G as 1G. --- compat-scanner/Dockerfile | 5 +++-- compat-scanner/tests/assert.php | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/compat-scanner/Dockerfile b/compat-scanner/Dockerfile index fcb6498c..4050a4f9 100644 --- a/compat-scanner/Dockerfile +++ b/compat-scanner/Dockerfile @@ -28,5 +28,6 @@ COPY bin/ /opt/compat-scanner/bin/ COPY src/ /opt/compat-scanner/src/ USER 33:33 -# Above EE's 1g container limit, so the time limit, not PHP's, ends a scan of millions of files; still a bound elsewhere. -ENTRYPOINT ["php", "-d", "memory_limit=2G", "-d", "display_errors=stderr", "/opt/compat-scanner/bin/compat-scanner.php"] +# Room for millions of listed files, yet below EE's 2g container limit, so PHP's own error (a tool_error), not a silent +# OOM kill, ends a scan that outgrows it. 1536M, not 1.5G, which PHP reads as 1G. +ENTRYPOINT ["php", "-d", "memory_limit=1536M", "-d", "display_errors=stderr", "/opt/compat-scanner/bin/compat-scanner.php"] diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 14d8a0fa..5821ce30 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1020,7 +1020,7 @@ function counts( string $name ): array { eq( [ in_array( 'CompatScanner.Syntax.ParseError', $l74sources, true ), array_column( $l74['not_checked'] ?? [], 'file' ) ], [ false, [ 'views/broken.tpl' ] ], 'lint-74: targets before 8.0 aren\'t linted (broken.tpl is PHPCS\'s own unparseable)' ); $entry = json_decode( raw( 'entrypoint' ), true ); -eq( $entry[2] ?? null, 'memory_limit=2G', 'image: the entrypoint\'s memory limit is above EE\'s container limit' ); +eq( $entry[2] ?? null, 'memory_limit=1536M', 'image: the entrypoint\'s memory limit is below EE\'s 2g container limit' ); tool_error( 'badargs-served', 'bad arguments: COMPAT_SERVED must be', 2, false ); tool_error( 'badargs-supported', 'bad arguments: COMPAT_WP_SUPPORTED must be', 2, false ); From 8fee2fda89e1fcac6415e7b4a828f58541d96e2a Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 07:00:47 +0530 Subject: [PATCH 31/80] fix(compat-scanner): lint templates with text before their PHP tag Only files that start as PHP were linted, so an included template with markup before its tag (`
` then a `#[` comment line, or an unclosed final comment) passed although PHP 8 can't parse it, and PHPCompatibility doesn't see it either. Files with text before the tag are linted again when named like a template PHP apps include (.tpl, .tmpl, .html, .htm, .ctp). As such a file may not run as PHP at all, a lint failure there is "can't confirm" (php_tag, or unparseable above the scanner's PHP), not an error. Shell histories, scripts and other names quoting ` By batch key, the files that fail: [ line, message ] or a not_checked reason. */ private function lint( array $batch ): array { $paths = []; foreach ( $batch as $k => $f ) { - if ( null !== $f['real'] && ! $f['mixed'] ) { + if ( null !== $f['real'] && ( ! $f['mixed'] || $this->isTemplateName( basename( $f['path'] ) ) ) ) { $paths[ $k ] = $f['real']; } } @@ -2261,7 +2268,9 @@ private function lint( array $batch ): array { throw $this->timedOutAt( $batch[ $k ]['path'] ); } if ( 0 !== $res['rc'] ) { - $failed[ $k ] = $this->lintResult( $res, $real ); + $result = $this->lintResult( $res, $real ); + // Text before the tag: the file may never run as PHP, so its failure can't prove a break. + $failed[ $k ] = $batch[ $k ]['mixed'] && is_array( $result ) ? 'php_tag' : $result; } } return $failed; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 5821ce30..5a2ea422 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -982,14 +982,18 @@ function counts( string $name ): array { eq( [ array_key_exists( 'phars', $r ), array_column( $r['not_checked'] ?? [], 'reason' ) ], [ false, [ 'phar', 'phar' ] ], 'phar-oldcall: a v3.11.1 call keeps phar entries' ); $li = report( 'lint' ); -eq( counts( 'lint' ), [ 'ok', false, 3, 7, 1 ], 'lint: verdict and counts' ); +eq( counts( 'lint' ), [ 'ok', false, 3, 7, 3 ], 'lint: verdict and counts' ); eq( array_map( static function ( $f ) { return $f['file'] . ':' . $f['line'] . ':' . $f['source']; }, comp_of( $li, 'plugin', 'p' )['findings'] ?? [] ), [ 'attr.php:3:CompatScanner.Syntax.ParseError', 'pipe.php:2:CompatScanner.Syntax.ParseError', 'unclosed.php:3:CompatScanner.Syntax.ParseError' ], 'lint: `#[` before code, the pipe operator and an unclosed comment fail on 8.4; an : files PHP 8.4 can't parse though PHPCompatibility passes them, and files it can. +# lint_fixture : files PHP 8.4 can't parse though PHPCompatibility passes them, also templates with text before +# their tag, and files it can. lint_fixture() { local p="$1/htdocs/wp-content/plugins/p" wp_core "$1/htdocs" 6.8.3 @@ -968,6 +969,8 @@ lint_fixture() { php_file "$p/dup1.php" 'function same() {}' php_file "$p/dup2.php" 'function same() {}' mkdir -p "$p/views" && printf '

\n\n' > "$p/views/broken.tpl" + printf '

\n "$p/views/attr.tpl" + printf '

hi

\n "$p/views/unclosed.tpl" chmod -R a+rX "$1" } From 97fe3224a79eb282923e1f54773282e946f67003 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 07:03:26 +0530 Subject: [PATCH 32/80] feat(compat-scanner): report a class PHP has natively in the target declared without a guard A global class, interface, trait or enum named like one PHP added (Override in 8.3, NoDiscard in 8.5, ...) is fatal on that version ("Cannot declare class ..., because the name is already in use"), but the lint passes it, as PHP binds it at run time, and PHPCompatibility has no rule for it, so the file was judged safe. A new sniff, CompatScanner.Classes.NativeDeclared, reports one declared outside a named namespace without a guard, from a table of the classes, enums and interfaces PHP 8.1 to 8.6 added in Core, standard, json, mbstring, SPL, Reflection and random (the official images' declared classes compared version by version, matched against UPGRADING). A guard is an if or elseif checking that name with the call that sees it (class_exists(), enum_exists() for an enum, interface_exists() for an interface) or testing PHP_VERSION_ID below the version that added it, the way Symfony's polyfill stubs declare these classes. The function sniff now shares its guard check. --- .../Sniffs/Classes/NativeDeclaredSniff.php | 49 +++++++++++++++++++ .../Sniffs/Functions/NativeDeclaredSniff.php | 49 ++++++++++++------- compat-scanner/src/native-classes.php | 34 +++++++++++++ compat-scanner/tests/assert.php | 11 +++-- compat-scanner/tests/fixture.sh | 29 ++++++++++- 5 files changed, 148 insertions(+), 24 deletions(-) create mode 100644 compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php create mode 100644 compat-scanner/src/native-classes.php diff --git a/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php new file mode 100644 index 00000000..1116e318 --- /dev/null +++ b/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php @@ -0,0 +1,49 @@ + [ 'class_exists' ], + 'enum' => [ 'class_exists', 'enum_exists' ], + 'interface' => [ 'interface_exists' ], + ]; + + /** @var string */ + protected $message = 'Class %s is native since PHP %s; declaring it without a class_exists() or interface_exists() check is fatal there'; + + public function register() { + return [ T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM ]; + } + + protected function native( string $lower ): ?array { + $this->table = $this->table ?? require __DIR__ . '/../../../native-classes.php'; + if ( ! isset( $this->table[ $lower ] ) ) { + return null; + } + list( $since, $kind ) = $this->table[ $lower ]; + return [ 'since' => $since, 'checks' => self::CHECKS[ $kind ] ]; + } + + /** Also `PHP_VERSION_ID < N` with N no higher than the native's version, as Symfony's polyfill stubs declare them. */ + protected function guardAt( File $phpcsFile, int $i, string $name, array $native ): bool { + $tokens = $phpcsFile->getTokens(); + if ( 'PHP_VERSION_ID' !== ltrim( $tokens[ $i ]['content'], '\\' ) ) { + return parent::guardAt( $phpcsFile, $i, $name, $native ); + } + list( $major, $minor ) = explode( '.', $native['since'] ); + $op = $phpcsFile->findNext( T_WHITESPACE, $i + 1, null, true ); + $bound = $phpcsFile->findNext( T_WHITESPACE, $op + 1, null, true ); + $below = T_LESS_THAN === $tokens[ $op ]['code'] && T_LNUMBER === $tokens[ $bound ]['code']; + return $below && (int) $tokens[ $bound ]['content'] <= $major * 10000 + $minor * 100; + } +} diff --git a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php index 348785bb..f6c3a3d5 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php @@ -17,49 +17,62 @@ class NativeDeclaredSniff implements Sniff { - /** @var array|null */ - private $since; + /** @var string */ + protected $message = 'Function %s() is native since PHP %s; declaring it without a function_exists() check is fatal there'; + + /** @var array|null The native-name table, by lowercase name. */ + protected $table; public function register() { return [ T_FUNCTION ]; } public function process( File $phpcsFile, int $stackPtr ) { - $this->since = $this->since ?? require __DIR__ . '/../../../native-functions.php'; - $name = (string) $phpcsFile->getDeclarationName( $stackPtr ); - $since = $this->since[ strtolower( $name ) ] ?? null; - if ( null === $since || version_compare( (string) Helper::getConfigData( 'testVersion' ), $since, '<' ) ) { + $name = (string) $phpcsFile->getDeclarationName( $stackPtr ); + $native = $this->native( strtolower( $name ) ); + if ( null === $native || version_compare( (string) Helper::getConfigData( 'testVersion' ), $native['since'], '<' ) ) { return; } - // In a named namespace it is another function. + // In a named namespace it is another one. if ( '' !== Namespaces::determineNamespace( $phpcsFile, $stackPtr ) ) { return; } foreach ( $phpcsFile->getTokens()[ $stackPtr ]['conditions'] as $ptr => $code ) { - if ( isset( Tokens::OO_SCOPE_TOKENS[ $code ] ) || $this->checksExists( $phpcsFile, $ptr, $name ) ) { + if ( isset( Tokens::OO_SCOPE_TOKENS[ $code ] ) || $this->guards( $phpcsFile, $ptr, $name, $native ) ) { return; } } - $message = 'Function %s() is native since PHP %s; declaring it without a function_exists() check is fatal there'; - $phpcsFile->addError( $message, $stackPtr, 'Found', [ $name, $since ] ); + $phpcsFile->addError( $this->message, $stackPtr, 'Found', [ $name, $native['since'] ] ); + } + + /** @return array{since:string,checks:string[]}|null The version that added the name, and the calls that check for it. */ + protected function native( string $lower ): ?array { + $this->table = $this->table ?? require __DIR__ . '/../../../native-functions.php'; + return isset( $this->table[ $lower ] ) ? [ 'since' => $this->table[ $lower ], 'checks' => [ 'function_exists' ] ] : null; } - /** Whether the condition is an if or elseif calling function_exists() on this name. */ - private function checksExists( File $phpcsFile, int $ptr, string $name ): bool { + /** Whether the condition is an if or elseif that checks for the native. */ + protected function guards( File $phpcsFile, int $ptr, string $name, array $native ): bool { $tokens = $phpcsFile->getTokens(); if ( ! in_array( $tokens[ $ptr ]['code'], [ T_IF, T_ELSEIF ], true ) || ! isset( $tokens[ $ptr ]['parenthesis_closer'] ) ) { return false; } for ( $i = $tokens[ $ptr ]['parenthesis_opener']; $i < $tokens[ $ptr ]['parenthesis_closer']; $i++ ) { - $call = in_array( $tokens[ $i ]['code'], [ T_STRING, T_NAME_FULLY_QUALIFIED ], true ); - if ( ! $call || 'function_exists' !== strtolower( ltrim( $tokens[ $i ]['content'], '\\' ) ) ) { - continue; - } - $arg = PassedParameters::getParameter( $phpcsFile, $i, 1, 'function' ); - if ( false !== $arg && strtolower( ltrim( TextStrings::stripQuotes( $arg['clean'] ), '\\' ) ) === strtolower( $name ) ) { + if ( $this->guardAt( $phpcsFile, $i, $name, $native ) ) { return true; } } return false; } + + /** Whether the condition's token at $i is a call of one of the native's checks on this name. */ + protected function guardAt( File $phpcsFile, int $i, string $name, array $native ): bool { + $token = $phpcsFile->getTokens()[ $i ]; + $call = in_array( $token['code'], [ T_STRING, T_NAME_FULLY_QUALIFIED ], true ); + if ( ! $call || ! in_array( strtolower( ltrim( $token['content'], '\\' ) ), $native['checks'], true ) ) { + return false; + } + $arg = PassedParameters::getParameter( $phpcsFile, $i, 1 ); + return false !== $arg && strtolower( ltrim( TextStrings::stripQuotes( $arg['clean'] ), '\\' ) ) === strtolower( $name ); + } } diff --git a/compat-scanner/src/native-classes.php b/compat-scanner/src/native-classes.php new file mode 100644 index 00000000..b0f33276 --- /dev/null +++ b/compat-scanner/src/native-classes.php @@ -0,0 +1,34 @@ + [ '8.1', 'interface' ], + 'fiber' => [ '8.1', 'class' ], + 'fibererror' => [ '8.1', 'class' ], + 'reflectionenum' => [ '8.1', 'class' ], + 'reflectionenumbackedcase' => [ '8.1', 'class' ], + 'reflectionenumunitcase' => [ '8.1', 'class' ], + 'reflectionfiber' => [ '8.1', 'class' ], + 'reflectionintersectiontype' => [ '8.1', 'class' ], + 'returntypewillchange' => [ '8.1', 'class' ], + 'unitenum' => [ '8.1', 'interface' ], + 'allowdynamicproperties' => [ '8.2', 'class' ], + 'sensitiveparameter' => [ '8.2', 'class' ], + 'sensitiveparametervalue' => [ '8.2', 'class' ], + 'override' => [ '8.3', 'class' ], + 'deprecated' => [ '8.4', 'class' ], + 'propertyhooktype' => [ '8.4', 'enum' ], + 'reflectionconstant' => [ '8.4', 'class' ], + 'requestparsebodyexception' => [ '8.4', 'class' ], + 'roundingmode' => [ '8.4', 'enum' ], + 'streambucket' => [ '8.4', 'class' ], + 'delayedtargetvalidation' => [ '8.5', 'class' ], + 'nodiscard' => [ '8.5', 'class' ], + 'sortdirection' => [ '8.6', 'enum' ], + 'streamerror' => [ '8.6', 'class' ], + 'streamerrorcode' => [ '8.6', 'enum' ], + 'streamerrormode' => [ '8.6', 'enum' ], + 'streamerrorstore' => [ '8.6', 'enum' ], + 'streamexception' => [ '8.6', 'class' ], + 'streampollhandle' => [ '8.6', 'class' ], +]; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 5a2ea422..1b70f999 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -998,12 +998,15 @@ function counts( string $name ): array { $lint = 'CompatScanner.Syntax.ParseError'; $sniff = 'CompatScanner.Functions.NativeDeclared.Found'; $always = [ "poly.php:$lint", "polytwice.php:$lint", "strlen.php:$lint", "twice.php:$lint" ]; +$csniff = 'CompatScanner.Classes.NativeDeclared.Found'; +$class83 = [ "override.php:$csniff", "stublate.php:$csniff", "unitenum.php:$csniff" ]; +$class85 = array_merge( $class83, [ "nodiscard.php:$csniff" ] ); $no_guard = [ "defined.php:$sniff", "iftrue.php:$sniff", "nested.php:$sniff", "nsbrace.php:$sniff", "other.php:$sniff", "try.php:$sniff" ]; $by_ver = [ - '8.3' => $always, - '8.4' => array_merge( [ "find.php:$lint", "legacy.php:$lint" ], $always ), - '8.5' => array_merge( [ "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always, $no_guard ), - '8.6' => array_merge( [ "clamp.php:$sniff", "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always, $no_guard ), + '8.3' => array_merge( $always, $class83 ), + '8.4' => array_merge( [ "find.php:$lint", "legacy.php:$lint" ], $always, $class83 ), + '8.5' => array_merge( [ "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always, $no_guard, $class85 ), + '8.6' => array_merge( [ "clamp.php:$sniff", "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always, $no_guard, $class85 ), ]; foreach ( $by_ver as $v => $want ) { sort( $want ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index e8992656..df2dc92e 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1057,8 +1057,10 @@ history_fixture() { # native_fixture : global functions named like ones PHP added in 8.4, 8.5 and 8.6, unguarded, guarded by # function_exists() on their name, in a namespace or as a method, or in a block that guards nothing (a braced global -# namespace, try, if ( true ), an include guard, a check on another name, another function's body); and declarations fatal on every version (a built-in, a function declared twice), also after -# one of a function PHP added in 8.4. +# namespace, try, if ( true ), an include guard, a check on another name, another function's body); classes and +# interfaces named like ones PHP added in 8.1, 8.3 and 8.5, unguarded, guarded by the check that sees them or a +# PHP_VERSION_ID bound below them, by the wrong check or a bound above, or in a namespace; and declarations fatal on +# every version (a built-in, a function declared twice), also after one of a function PHP added in 8.4. native_fixture() { local p="$1/htdocs/wp-content/plugins/p" wp_core "$1/htdocs" 6.8.3 @@ -1108,6 +1110,29 @@ function p_twice() {}' php_file "$p/other.php" 'if ( ! function_exists( "array_first" ) ) { function array_last( $a ) { return null; } }' + php_file "$p/override.php" 'class Override {}' + php_file "$p/overrideguard.php" "if ( ! class_exists( 'Override' ) ) { + final class Override {} +}" + php_file "$p/stub.php" 'if ( \PHP_VERSION_ID < 80300 ) { + final class Override {} +}' + php_file "$p/stublate.php" 'if ( PHP_VERSION_ID < 80400 ) { + final class Override {} +}' + php_file "$p/nodiscard.php" 'final class NoDiscard {}' + php_file "$p/nodiscardguard.php" 'if ( ! class_exists( "NoDiscard", false ) ) { + final class NoDiscard {} +}' + php_file "$p/nsclass.php" 'namespace P; +class Override {} +final class NoDiscard {}' + php_file "$p/unitenum.php" "if ( ! class_exists( 'UnitEnum' ) ) { + interface UnitEnum {} +}" + php_file "$p/backedenum.php" "if ( ! interface_exists( 'BackedEnum' ) ) { + interface BackedEnum {} +}" php_file "$p/poly.php" 'function array_find( $a, $f ) { return null; } function str_contains( $h, $n ) { return false; }' php_file "$p/polytwice.php" 'function array_find( $a, $f ) { return null; } From c7b250ba4bc4b526955d71cb0c0b335606a104a3 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 07:08:49 +0530 Subject: [PATCH 33/80] fix(compat-scanner): count a PHP_VERSION_ID bound as a guard for native functions too A function declared inside `if ( PHP_VERSION_ID < 80500 )` never exists on 8.5, yet the function check reported it, while the class check already accepted that guard. Both now share it: an enclosing if or elseif testing PHP_VERSION_ID below N, with N no higher than the version that added the name, keeps the declaration quiet; a higher bound is still reported. An early `if ( PHP_VERSION_ID >= N ) { return; }` before an unconditional top-level function stays reported, as PHP binds that function when it compiles the file, before the return runs. --- .../Sniffs/Classes/NativeDeclaredSniff.php | 14 ----------- .../Sniffs/Functions/NativeDeclaredSniff.php | 24 +++++++++++++++---- compat-scanner/tests/assert.php | 2 ++ compat-scanner/tests/fixture.sh | 21 ++++++++++++++-- 4 files changed, 41 insertions(+), 20 deletions(-) diff --git a/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php index 1116e318..0cf3ba9e 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php @@ -7,7 +7,6 @@ namespace CompatScanner\Sniffs\Classes; use CompatScanner\Sniffs\Functions\NativeDeclaredSniff as NativeFunctionSniff; -use PHP_CodeSniffer\Files\File; class NativeDeclaredSniff extends NativeFunctionSniff { @@ -33,17 +32,4 @@ protected function native( string $lower ): ?array { list( $since, $kind ) = $this->table[ $lower ]; return [ 'since' => $since, 'checks' => self::CHECKS[ $kind ] ]; } - - /** Also `PHP_VERSION_ID < N` with N no higher than the native's version, as Symfony's polyfill stubs declare them. */ - protected function guardAt( File $phpcsFile, int $i, string $name, array $native ): bool { - $tokens = $phpcsFile->getTokens(); - if ( 'PHP_VERSION_ID' !== ltrim( $tokens[ $i ]['content'], '\\' ) ) { - return parent::guardAt( $phpcsFile, $i, $name, $native ); - } - list( $major, $minor ) = explode( '.', $native['since'] ); - $op = $phpcsFile->findNext( T_WHITESPACE, $i + 1, null, true ); - $bound = $phpcsFile->findNext( T_WHITESPACE, $op + 1, null, true ); - $below = T_LESS_THAN === $tokens[ $op ]['code'] && T_LNUMBER === $tokens[ $bound ]['code']; - return $below && (int) $tokens[ $bound ]['content'] <= $major * 10000 + $minor * 100; - } } diff --git a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php index f6c3a3d5..a6fdc923 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php @@ -1,8 +1,8 @@ getTokens()[ $i ]; + if ( 'PHP_VERSION_ID' === ltrim( $token['content'], '\\' ) ) { + return $this->belowSince( $phpcsFile, $i, $native['since'] ); + } $call = in_array( $token['code'], [ T_STRING, T_NAME_FULLY_QUALIFIED ], true ); if ( ! $call || ! in_array( strtolower( ltrim( $token['content'], '\\' ) ), $native['checks'], true ) ) { return false; @@ -75,4 +81,14 @@ protected function guardAt( File $phpcsFile, int $i, string $name, array $native $arg = PassedParameters::getParameter( $phpcsFile, $i, 1 ); return false !== $arg && strtolower( ltrim( TextStrings::stripQuotes( $arg['clean'] ), '\\' ) ) === strtolower( $name ); } + + /** Whether PHP_VERSION_ID at $i is compared `< N` with N no higher than $since. */ + private function belowSince( File $phpcsFile, int $i, string $since ): bool { + $tokens = $phpcsFile->getTokens(); + list( $major, $minor ) = explode( '.', $since ); + $op = $phpcsFile->findNext( T_WHITESPACE, $i + 1, null, true ); + $bound = $phpcsFile->findNext( T_WHITESPACE, $op + 1, null, true ); + $below = T_LESS_THAN === $tokens[ $op ]['code'] && T_LNUMBER === $tokens[ $bound ]['code']; + return $below && (int) $tokens[ $bound ]['content'] <= $major * 10000 + $minor * 100; + } } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 1b70f999..de453c84 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1002,6 +1002,8 @@ function counts( string $name ): array { $class83 = [ "override.php:$csniff", "stublate.php:$csniff", "unitenum.php:$csniff" ]; $class85 = array_merge( $class83, [ "nodiscard.php:$csniff" ] ); $no_guard = [ "defined.php:$sniff", "iftrue.php:$sniff", "nested.php:$sniff", "nsbrace.php:$sniff", "other.php:$sniff", "try.php:$sniff" ]; +// A top-level function is bound when PHP compiles the file, so an early return on the version comes too late. +$no_guard = array_merge( $no_guard, [ "earlyver.php:$sniff", "verhigh.php:$sniff" ] ); $by_ver = [ '8.3' => array_merge( $always, $class83 ), '8.4' => array_merge( [ "find.php:$lint", "legacy.php:$lint" ], $always, $class83 ), diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index df2dc92e..8177f1f8 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1056,8 +1056,9 @@ history_fixture() { } # native_fixture : global functions named like ones PHP added in 8.4, 8.5 and 8.6, unguarded, guarded by -# function_exists() on their name, in a namespace or as a method, or in a block that guards nothing (a braced global -# namespace, try, if ( true ), an include guard, a check on another name, another function's body); classes and +# function_exists() on their name or a PHP_VERSION_ID bound below them (as in a Symfony polyfill bootstrap), in a +# namespace or as a method, or in a block that guards nothing (a braced global namespace, try, if ( true ), an include +# guard, a check on another name or a bound above, another function's body, an early return on the version); classes and # interfaces named like ones PHP added in 8.1, 8.3 and 8.5, unguarded, guarded by the check that sees them or a # PHP_VERSION_ID bound below them, by the wrong check or a bound above, or in a namespace; and declarations fatal on # every version (a built-in, a function declared twice), also after one of a function PHP added in 8.4. @@ -1110,6 +1111,22 @@ function p_twice() {}' php_file "$p/other.php" 'if ( ! function_exists( "array_first" ) ) { function array_last( $a ) { return null; } }' + php_file "$p/verguard.php" 'if ( \PHP_VERSION_ID < 80500 ) { + function array_first( $a ) { return null; } +}' + php_file "$p/verhigh.php" 'if ( PHP_VERSION_ID < 80600 ) { + function array_last( $a ) { return null; } +}' + php_file "$p/earlyver.php" 'if ( PHP_VERSION_ID >= 80500 ) { + return; +} +function array_first( $a ) { return null; }' + php_file "$p/sfboot.php" "if ( \\PHP_VERSION_ID >= 80500 ) { + return; +} +if ( ! function_exists( 'array_last' ) ) { + function array_last( array \$array ) { return null; } +}" php_file "$p/override.php" 'class Override {}' php_file "$p/overrideguard.php" "if ( ! class_exists( 'Override' ) ) { final class Override {} From bb6273661ca1395a4c701569fe60a8427e4eeeab Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 07:13:36 +0530 Subject: [PATCH 34/80] fix(compat-scanner): keep the scanner and a child below the 2g container limit The entrypoint's memory_limit is now 1G and the PHPCS and lint children get 896M by default, so the scanner and a running child together stay below the --memory 2g EE gives the container. A scan that outgrows that ends with PHP's own error, a tool_error document, instead of an OOM kill that prints nothing. The fixture harness now runs the scanner with EE's --memory 2g. --- compat-scanner/Dockerfile | 5 ++--- compat-scanner/bin/compat-scanner.php | 4 ++-- compat-scanner/tests/assert.php | 2 +- compat-scanner/tests/run.sh | 6 +++--- 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/compat-scanner/Dockerfile b/compat-scanner/Dockerfile index 4050a4f9..1b4db3a2 100644 --- a/compat-scanner/Dockerfile +++ b/compat-scanner/Dockerfile @@ -28,6 +28,5 @@ COPY bin/ /opt/compat-scanner/bin/ COPY src/ /opt/compat-scanner/src/ USER 33:33 -# Room for millions of listed files, yet below EE's 2g container limit, so PHP's own error (a tool_error), not a silent -# OOM kill, ends a scan that outgrows it. 1536M, not 1.5G, which PHP reads as 1G. -ENTRYPOINT ["php", "-d", "memory_limit=1536M", "-d", "display_errors=stderr", "/opt/compat-scanner/bin/compat-scanner.php"] +# 1G plus a PHPCS or lint child's 896M stays below EE's 2g container limit: PHP's own error (a tool_error), not a silent OOM kill, ends a scan that outgrows it. +ENTRYPOINT ["php", "-d", "memory_limit=1G", "-d", "display_errors=stderr", "/opt/compat-scanner/bin/compat-scanner.php"] diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 3ad93610..4e94f3ab 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -46,7 +46,7 @@ // Other files are read this far for a PHP open tag. const SNIFF_BYTES = 8192; // A file PHPCS reads through STDIN is copied to /out first; past this it is refused by size (`memory`), not copied. -// Real PHP code of 8 MiB already exceeds 960M, though a mostly-comment file that large could be checked. +// Real PHP code of 8 MiB already exceeds 896M, though a mostly-comment file that large could be checked. const STDIN_MAX = 16777216; // A data-only candidate larger than this isn't read to its end: it is listed as code instead. const DATA_MAX = 8388608; @@ -2881,7 +2881,7 @@ function parse_args( array $argv, array &$cfg ): void { $cfg['batch_size'] = env_int( 'COMPAT_BATCH_SIZE', 200 ); $cfg['batch_memory'] = env_memory( 'COMPAT_BATCH_MEMORY', '448M' ); $cfg['file_memory'] = env_memory( 'COMPAT_FILE_MEMORY', $cfg['batch_memory'] ); - $cfg['retry_memory'] = env_memory( 'COMPAT_RETRY_MEMORY', '960M' ); + $cfg['retry_memory'] = env_memory( 'COMPAT_RETRY_MEMORY', '896M' ); $cfg['estimate_timeout'] = env_int( 'COMPAT_ESTIMATE_TIMEOUT', 120 ); $cfg['seconds_per_batch'] = env_float( 'COMPAT_SECONDS_PER_BATCH', 0.1 ); $cfg['low_factor'] = env_float( 'COMPAT_LOW_FACTOR', 0.8 ); diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index de453c84..fc315f3c 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1031,7 +1031,7 @@ function counts( string $name ): array { eq( [ in_array( 'CompatScanner.Syntax.ParseError', $l74sources, true ), array_column( $l74['not_checked'] ?? [], 'file' ) ], [ false, [ 'views/broken.tpl' ] ], 'lint-74: targets before 8.0 aren\'t linted (broken.tpl is PHPCS\'s own unparseable)' ); $entry = json_decode( raw( 'entrypoint' ), true ); -eq( $entry[2] ?? null, 'memory_limit=1536M', 'image: the entrypoint\'s memory limit is below EE\'s 2g container limit' ); +eq( $entry[2] ?? null, 'memory_limit=1G', 'image: the entrypoint\'s memory limit plus a child\'s 896M is below EE\'s 2g container limit' ); tool_error( 'badargs-served', 'bad arguments: COMPAT_SERVED must be', 2, false ); tool_error( 'badargs-supported', 'bad arguments: COMPAT_WP_SUPPORTED must be', 2, false ); diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 4f54d383..cba56d5b 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -54,7 +54,7 @@ scan() { timeout 900 docker run --rm --init --name "ee-php-compat-test-$name" \ --network none --read-only --tmpfs /tmp:size=64m \ --cap-drop ALL --security-opt no-new-privileges --pids-limit 64 \ - --memory 1g --memory-swap 1g --cpus 1 --cpu-shares 256 \ + --memory 2g --memory-swap 2g --cpus 1 --cpu-shares 256 \ --user 33:33 \ -e COMPAT_SITE=fixture.test -e COMPAT_IMAGE="$IMAGE" -e COMPAT_MANIFEST="${MANIFEST-1}" $(v2_env "$path") "$@" \ --mount "type=bind,src=$(realpath "$app"),dst=/var/www,readonly" \ @@ -122,7 +122,7 @@ estimate() { docker run --rm --init \ --network none --read-only --tmpfs /tmp:size=64m \ --cap-drop ALL --security-opt no-new-privileges --pids-limit 64 \ - --memory 1g --memory-swap 1g --cpus 1 --cpu-shares 256 \ + --memory 2g --memory-swap 2g --cpus 1 --cpu-shares 256 \ --user 33:33 \ -e COMPAT_SITE=fixture.test $(v2_env "$path") "$@" \ --mount "type=bind,src=$(realpath "$app"),dst=/var/www,readonly" \ @@ -240,7 +240,7 @@ scan bedrock "$WORK/bedrock" wp /var/www/htdocs 8.4 600 rc=0 docker run --rm --init --network none --read-only --tmpfs /tmp:size=64m \ --cap-drop ALL --security-opt no-new-privileges --pids-limit 64 \ - --memory 1g --memory-swap 1g --cpus 1 --user 33:33 \ + --memory 2g --memory-swap 2g --cpus 1 --user 33:33 \ --mount "type=bind,src=$(realpath "$WORK/flood"),dst=/var/www,readonly" \ --mount type=tmpfs,dst=/out,tmpfs-size=262144,tmpfs-mode=1777 \ "$IMAGE" scan wp /var/www/htdocs 8.4 600 > "$RES/fullout.stdout" 2> "$RES/fullout.stderr" || rc=$? From a663f0307d071d0ef9aa9699fc5a3e8a597552d6 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 07:32:37 +0530 Subject: [PATCH 35/80] fix(compat-scanner): time PHPCS and lint runs in the scanner itself Each run went through busybox timeout, whose watcher outlived it by up to a second, so a burst of quick runs (a lint per file after a batch's lint failed) could use up the container's --pids-limit 64. A run that couldn't fork then ended as a not_checked `error` entry at random. Runs are now started directly and killed by the scanner at their cap or at the scan deadline, so a scan holds one child at a time. A lint the scan deadline ends is now the usual timeout ("timed out after N s at "), no longer a `memory` entry in an ok scan, and a lint that never started leaves no warning about a missing lint.err on stderr. Tests: 400 quick lints in a row at --pids-limit 8, and a lint the deadline ends. --- compat-scanner/bin/compat-scanner.php | 45 ++++++++++++++++++--------- compat-scanner/tests/assert.php | 3 ++ compat-scanner/tests/fixture.sh | 18 +++++++++++ compat-scanner/tests/run.sh | 9 +++++- 4 files changed, 59 insertions(+), 16 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 4e94f3ab..613d1486 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -1719,9 +1719,8 @@ private function runSingle( array $f ): void { } } - // busybox `timeout` execs PHP, so a SIGKILL from the kernel's OOM killer - // arrives as 9 rather than 137; the deadline was ruled out above. - $reason = null !== $last && in_array( $last['rc'], [ 9, 137, 255 ], true ) ? 'memory' : 'error'; + // 137 is a SIGKILL from the kernel's OOM killer: the cap and the deadline were ruled out above. + $reason = null !== $last && in_array( $last['rc'], [ 137, 255 ], true ) ? 'memory' : 'error'; $this->spoolNotChecked( $f['comp'], $this->rel( $f['comp'], $f['path'] ), $reason ); } @@ -2150,7 +2149,7 @@ private function copySpool( string $file, callable $write, bool &$first ): void // ------------------------------------------------------------------ phpcs /** - * One PHPCS run under `timeout -s KILL` with the time left. + * One PHPCS run with the time left. * * @return array{ok:bool,timeout:bool,too_large:bool,unreadable:bool,rc:int,seconds:float,report:string} */ @@ -2211,9 +2210,10 @@ private function phpcs( array $paths, string $memory, string $tag, bool $stdin = } /** - * Runs a command under `timeout -s KILL` with the time left, at most $cap seconds when $cap > 0. + * Runs a command with the time left, killed at $cap seconds when $cap > 0 is less. + * Not under busybox `timeout`: its watcher outlives each run, and a burst of quick runs used up the pids limit. * - * @return array{rc:int,seconds:float,capped:bool,timeout:bool} capped: killed by $cap; timeout: no time was left. + * @return array{rc:int,seconds:float,capped:bool,timeout:bool} rc 128 + signal when one ended it; killed at $cap or the deadline. */ private function runTimed( array $cmd, float $cap, array $spec, int $fsize = 0 ): array { $res = [ 'rc' => -1, 'seconds' => 0.0, 'capped' => false, 'timeout' => false ]; @@ -2223,20 +2223,35 @@ private function runTimed( array $cmd, float $cap, array $spec, int $fsize = 0 ) return $res; } $capped = $cap > 0 && $cap < $left; - // The exact time left (busybox takes fractions), so no run finishes past the deadline. - $limit = sprintf( '%.3F', ceil( ( $capped ? $cap : $left ) * 1000 ) / 1000 ); - $t = hrtime( true ); + $end = microtime( true ) + ( $capped ? $cap : $left ); + $t = hrtime( true ); + // The child's end of this pipe closes when it exits, which ends the wait below at once. + $spec[3] = [ 'pipe', 'w' ]; // Set only around the fork, so the entrypoint's own writes aren't bound by it. set_fsize( $fsize > 0 ? $fsize : null ); - $proc = proc_open( array_merge( [ 'timeout', '-s', 'KILL', $limit ], $cmd ), $spec, $pipes ); + $proc = proc_open( $cmd, $spec, $pipes ); set_fsize( null ); if ( ! is_resource( $proc ) ) { throw new ToolError( 'could not start ' . basename( end( $cmd ) ) ); } - $res['rc'] = proc_close( $proc ); + $killed = false; + while ( ( $status = proc_get_status( $proc ) )['running'] ) { + $wait = $end - microtime( true ); + if ( $wait <= 0 && ! $killed ) { + proc_terminate( $proc, 9 ); + $killed = true; + } + $read = [ $pipes[3] ]; + $none = null; + @stream_select( $read, $none, $none, 0, $killed ? 1000 : (int) ceil( min( $wait, 0.1 ) * 1e6 ) ); + } + fclose( $pipes[3] ); + proc_close( $proc ); $res['seconds'] = ( hrtime( true ) - $t ) / 1e9; - // Killed by its own cap, not the scan deadline (busybox timeout reports SIGKILL as 9 or 137). - $res['capped'] = $capped && in_array( $res['rc'], [ 9, 137 ], true ) && $res['seconds'] >= $cap * 0.99; + $res['rc'] = $status['signaled'] ? 128 + $status['termsig'] : $status['exitcode']; + if ( $killed && 137 === $res['rc'] ) { + $res[ $capped ? 'capped' : 'timeout' ] = true; + } return $res; } @@ -2294,7 +2309,7 @@ function ( $since ) { $cmd = array_merge( [ PHP_BINARY, '-d', 'short_open_tag=0' ], $args, [ '-l' ], $paths ); $res = $this->runTimed( $cmd, $cap, [ 0 => [ 'file', '/dev/null', 'r' ], 1 => [ 'file', '/dev/null', 'w' ], 2 => [ 'file', $err, 'w' ] ] ); - $res['stderr'] = (string) file_get_contents( $err, false, null, 0, 65536 ); + $res['stderr'] = $res['timeout'] ? '' : (string) file_get_contents( $err, false, null, 0, 65536 ); return $res; } @@ -2306,7 +2321,7 @@ private function lintResult( array $res, string $real ) { if ( $res['capped'] ) { return 'timeout'; } - if ( in_array( $res['rc'], [ 9, 137 ], true ) || false !== strpos( $res['stderr'], 'Allowed memory size' ) ) { + if ( 137 === $res['rc'] || false !== strpos( $res['stderr'], 'Allowed memory size' ) ) { return 'memory'; } if ( 255 !== $res['rc'] ) { diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index fc315f3c..30a8c6ae 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1030,6 +1030,9 @@ function counts( string $name ): array { $l74sources = array_column( comp_of( $l74, 'plugin', 'p' )['findings'] ?? [], 'source' ); eq( [ in_array( 'CompatScanner.Syntax.ParseError', $l74sources, true ), array_column( $l74['not_checked'] ?? [], 'file' ) ], [ false, [ 'views/broken.tpl' ] ], 'lint-74: targets before 8.0 aren\'t linted (broken.tpl is PHPCS\'s own unparseable)' ); +eq( counts( 'burst' ), [ 'ok', false, 2, 402, 0 ], 'burst: a lint per file, one after another, stays within a pids limit of 8' ); +tool_error( 'slowlint', 'timed out after 2 s at htdocs/big.tpl', 1 ); + $entry = json_decode( raw( 'entrypoint' ), true ); eq( $entry[2] ?? null, 'memory_limit=1G', 'image: the entrypoint\'s memory limit plus a child\'s 896M is below EE\'s 2g container limit' ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 8177f1f8..789d3542 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1241,3 +1241,21 @@ pharslow_fixture() { truncate -s 64G "$p/big.php" chmod -R a+rX "$1" } + +# burst_fixture : a php site with 400 small files and 2 broken ones, so each batch's lint fails and every file +# of it is linted on its own, one quick run after another. +burst_fixture() { + local h="$1/htdocs" i + for i in $(seq -w 400); do php_file "$h/lib/f$i.php" "echo '$i';"; done + printf ' "$h/lib/f100x.php" + printf ' "$h/lib/f300x.php" + chmod -R a+rX "$1" +} + +# slowlint_fixture : a php site whose only code is a template-named file starting with ` "$1/htdocs/big.tpl" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index cba56d5b..b510aaff 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -80,7 +80,7 @@ scan() { echo "scan $name: rc=$rc $(head -c 300 "$RES/$name.stdout")" } -# PID of the container's PHPCS process (not busybox timeout's watcher), if one is running. +# PID of the container's PHPCS process, if one is running. phpcs_pid() { docker top "$1" -o pid,args 2>/dev/null | awk '$2 ~ /\/php$/ && /php_codesniffer\/bin\/phpcs/ { print $1; exit }'; } # during : runs the command while scan (COMPAT_DEBUG=1) is in its first PHPCS run, so @@ -441,6 +441,13 @@ scan lint "$WORK/lint" wp /var/www/htdocs 8.4 600 scan lint-85 "$WORK/lint" wp /var/www/htdocs 8.5 600 scan lint-74 "$WORK/lint" wp /var/www/htdocs 7.4 600 +# Quick runs one after another (a lint per file) stay within a small pids limit; a lint the deadline ends is a timeout. +burst_fixture "$WORK/burst" +scan burst "$WORK/burst" php /var/www/htdocs 8.4 600 --pids-limit 8 +slowlint_fixture "$WORK/slowlint" +scan slowlint "$WORK/slowlint" php /var/www/htdocs 8.4 2 -e COMPAT_FILE_TIMEOUT=1 +rm -f "$WORK/slowlint/htdocs/big.tpl" + # Malformed new env. scan badargs-served "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_SERVED=/etc scan badargs-supported "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6 From 7df0f2d58b64ef8efc110779b3ba167b78b56424 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 07:51:58 +0530 Subject: [PATCH 36/80] fix(compat-scanner): check code that the walk dropped or left out by mistake - wp-config.php of a WordPress whose directory is a mount outside /var/www (htdocs or `current` linking into it) was listed under a name that didn't lead back to it, then dropped as deleted. It is now checked as other/wp-config.php, named in its own directory. A file listed outside its component's base is now a tool_error instead of a silent drop. - A live wp-content linked into an old release (`releases/3/wp-content -> ../2/wp-content`) left its plugins out with no entry. That release is now live code and scanned. - Old releases are left out only when the live release has index.php at the served path, the sibling has the same file, and the sibling is named like a release (a number, a timestamp or a commit hash). Without an index.php at the served path every directory in releases/ counted as an old release, and an index.php stub made a releases/shared/ dir one. The wpold fixture now has an index.php in each release, which the old rule didn't need. - A WordPress core dir linked outside /var/www and the mounts is no longer searched for .user.ini files, which named paths outside the site. - A huge .user.ini, version.php or data-only file is read only until the listing deadline. - `.pharmacy` and the like no longer count as naming a phar. - The nested-install fixture has a plugin in the other install's wp-content, so a walk that skipped it would fail the test. - The comment on why index.php isn't a core file named a check EE no longer makes. --- compat-scanner/bin/compat-scanner.php | 77 +++++++++++++++++++-------- compat-scanner/tests/assert.php | 31 ++++++++--- compat-scanner/tests/fixture.sh | 72 ++++++++++++++++++++++++- compat-scanner/tests/run.sh | 27 +++++++++- 4 files changed, 174 insertions(+), 33 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 613d1486..1cefc15b 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -31,7 +31,7 @@ const STRUCTURAL = [ 'plugins', 'themes', 'mu-plugins' ]; // Core of the WordPress root (wp-settings.php and wp-includes/ in the scanned directory): never scanned. const CORE_DIRS = [ 'wp-admin', 'wp-includes' ]; -// index.php isn't here: it is tiny, and EE validates the root's own loader too. +// index.php isn't here: sites customise it, so it is scanned like any file. const CORE_FILES = [ 'wp-activate.php', 'wp-blog-header.php', 'wp-comments-post.php', 'wp-config-sample.php', 'wp-cron.php', 'wp-links-opml.php', 'wp-load.php', 'wp-login.php', 'wp-mail.php', 'wp-settings.php', 'wp-signup.php', 'wp-trackback.php', 'xmlrpc.php' ]; const TYPE_ORDER = [ 'plugin' => 0, 'theme' => 1, 'mu-plugin' => 2, 'directory' => 3, 'other' => 4 ]; // Same as EE's REPORT_MAX: EE rejects a larger report anyway. @@ -54,6 +54,8 @@ const MIXED_FLAG = 0x80000000; // What sniff() matches in a file's first SNIFF_BYTES, as one regex (no NUL anywhere, then an open tag), for the manifest. const SNIFF_REGEX = '/\\A(?=[^\\x00]*\\z)[\\s\\S]*?<\\?(?:php(?:\\s|\\z)|=)/i'; +// A release dir's name (a number, a timestamp or a commit hash), which a shared/ or current/ dir never has. +const RELEASE_NAME = '/^(?:\\d[\\d._-]*|[0-9a-f]{7,64})\\z/i'; const PHAR_REGEX = '/\\.phar(?:\\.(?:tar|zip))?(?:\\.(?:gz|bz2))?\\z/i'; // Backup copies: never read, so a stale copy can't give "not safe" (a copy code includes is missed, accepted). const BACKUP_EXTENSIONS = [ 'bak', 'orig', 'old', 'save', 'swp', 'log', 'sql', 'dist' ]; @@ -280,6 +282,10 @@ private function coreDirsMet(): array { /** Reads every .user.ini under a directory, found by name; links to directories aren't followed. */ private function iniIn( string $dir ): void { + // A core dir linked out of /var/www and the mounts is the walk's own entry; nothing in it is listed. + if ( null === $this->resolve( $dir ) ) { + return; + } $stack = [ $dir ]; while ( $stack ) { $d = array_pop( $stack ); @@ -321,7 +327,7 @@ private function userIni( string $path, string $real ): void { } $keys = '(auto_(?:prepend|append)_file|zend\.multibyte|zend\.script_encoding)'; $unsure = false; - foreach ( lines( $fh ) as $n => $line ) { + foreach ( lines( $fh, $this->ticker() ) as $n => $line ) { if ( null === $line ) { $unsure = true; continue; @@ -364,12 +370,12 @@ private function servedPath(): string { */ private function judgeInstalls(): void { if ( null !== $this->live ) { - $this->installs[] = [ 'dir' => $this->live, 'version' => wp_version( $this->live ), 'live' => true ]; + $this->installs[] = [ 'dir' => $this->live, 'version' => wp_version( $this->live, $this->ticker() ), 'live' => true ]; } $nested = array_keys( $this->nested ); sort( $nested, SORT_STRING ); foreach ( $nested as $dir ) { - $version = wp_version( $dir ); + $version = wp_version( $dir, $this->ticker() ); $this->installs[] = [ 'dir' => $dir, 'version' => $version, 'live' => false ]; if ( in_array( wp_branch( $version ), $this->cfg['wp_supported'], true ) ) { $this->leftOut[] = $dir; @@ -388,11 +394,12 @@ private function wpTree( string $wp, array $top ): void { $root = $wp . '/wp-content'; $config = $this->wpConfig( $wp ); if ( null !== $config ) { - // Reported by its real path relative to /var/www (the file to edit), e.g. htdocs/wp-config.php; one linked out of - // /var/www by the link, which visit() follows. + // By its real path under /var/www (the file to edit), e.g. htdocs/wp-config.php; one linked out of /var/www by the link. + // In an extra root (WordPress itself there), by its name in its own directory. $real = @realpath( $config ); $path = false !== $real && 0 === strpos( $real, MOUNT_ROOT . '/' ) ? $real : $config; - $this->visit( $path, 'wp-config.php', $this->comp( 'other', 'wp-config.php', null, MOUNT_ROOT ) ); + $base = 0 === strpos( $path, MOUNT_ROOT . '/' ) ? MOUNT_ROOT : dirname( $path ); + $this->visit( $path, 'wp-config.php', $this->comp( 'other', 'wp-config.php', null, $base ) ); } $main = null; @@ -509,6 +516,15 @@ private function enterContent( string $root ): bool { $this->pins[ $root ] = $real; $this->contentReal = $real; $this->markDir( $real ); + // A content root inside an old release (`wp-content -> ../2/wp-content`) makes that release live code. + $this->oldReleases = array_values( + array_filter( + $this->oldReleases, + static function ( $old ) use ( $real ) { + return 0 !== strpos( $real . '/', $old . '/' ); + } + ) + ); return true; } @@ -559,9 +575,8 @@ private function wpConfig( string $wpDir ): ?string { } /** - * CI/CD layout of a php site: the first `current` symlink on the public path, - * pointing at a direct child of a real `releases/` dir next to it (as site-command's - * backup detects it). Returns the other releases, which aren't scanned. + * CI/CD layout: the first `current` symlink on the served path, pointing at a direct child of a real `releases/` dir + * next to it (as site-command's backup detects it). Returns the other releases, which aren't scanned. * * @return string[] */ @@ -582,16 +597,17 @@ private function oldReleases( string $publicDir ): array { if ( is_link( $releases ) || ! is_dir( $releases ) || ! $this->inside( $releases ) || dirname( $live ) !== $releases ) { return []; } - // An old release holds what the live one serves (its index.php, else the served dir), so a shared/ dir is walked; - // so is a release holding the scan path, which EE's WordPress hint may name (a stale wp-cli.yml path). - $served = substr( $publicDir, strlen( $path ) ); - $index = is_file( $live . $served . '/index.php' ); - $marker = $served . ( $index ? '/index.php' : '' ); - $scan = realpath( $this->cfg['path'] ) . '/'; - $old = []; + // An old release is release-named and holds the index.php nginx serves from the live one; without one there, + // nothing tells a release from a shared/ dir. A release holding the scan path (a stale wp-cli.yml path) is scanned. + $marker = substr( $publicDir, strlen( $path ) ) . '/index.php'; + if ( ! is_file( $live . $marker ) ) { + return []; + } + $scan = realpath( $this->cfg['path'] ) . '/'; + $old = []; foreach ( (array) $this->readDir( $releases ) as $name ) { $dir = $releases . '/' . $name; - $release = ! is_link( $dir ) && is_dir( $dir ) && ( $index ? is_file( $dir . $marker ) : is_dir( $dir . $marker ) ); + $release = preg_match( RELEASE_NAME, $name ) && ! is_link( $dir ) && is_file( $dir . $marker ); if ( $dir !== $live && $release && 0 !== strpos( $scan, $dir . '/' ) ) { $old[] = $dir; } @@ -1055,8 +1071,9 @@ private function namesPhar( string $path, string $real ): bool { fclose( $fh ); throw $this->timedOutAt( $path ); } - $found = (bool) preg_match( '#phar://|\.phar#i', $tail . $chunk ); - $tail = substr( $chunk, -6 ); + // Not `.pharmacy`; a `.phar` at a read's end matches, so a cut word errs to "can't confirm". + $found = (bool) preg_match( '#phar://|\.phar(?![a-z0-9_])#i', $tail . $chunk ); + $tail = substr( $chunk, -7 ); } fclose( $fh ); return $found; @@ -1094,6 +1111,7 @@ private function dataOnly( string $path ): bool { $ok = false; break; } + $this->tick(); $more = fread( $fh, 65536 ); if ( false === $more || ( '' === $more && ! feof( $fh ) ) ) { $ok = false; // A failed read: not known to be data. @@ -1350,6 +1368,13 @@ private function hasEntries( $handle ): bool { return false; } + /** tick() for a reader outside the class, per line or chunk read. */ + private function ticker(): Closure { + return function () { + $this->tick(); + }; + } + private function tick(): void { if ( 0 === ( ++$this->ticks % 500 ) && microtime( true ) >= $this->listDeadline ) { if ( ! $this->isScan ) { @@ -1389,6 +1414,10 @@ private function rel( int $comp, string $path ): string { if ( $path === $base ) { return '.'; } + // Listed by a name that doesn't lead back to it, a file would later count as deleted, not as checked. + if ( 0 !== strpos( $path, $base . '/' ) ) { + throw new ToolError( 'internal error: ' . clean_text( $path ) . ' is outside ' . clean_text( $base ) ); + } return substr( $path, strlen( $base ) + 1 ); } @@ -2812,13 +2841,13 @@ function mount_path( string $path, string $what ): string { * An install's version: exactly one `$wp_version = '…';` or `"…"` line holding a plain version of at most 64 characters * (EE prints it as given), else '' (unknown). */ -function wp_version( string $dir ): string { +function wp_version( string $dir, callable $tick ): string { $fh = open_regular( $dir . '/wp-includes/version.php' ); if ( null === $fh ) { return ''; } $lines = []; - foreach ( lines( $fh ) as $line ) { + foreach ( lines( $fh, $tick ) as $line ) { // A line too long to read may hold it: then the version is unknown. if ( null === $line || preg_match( '/\$wp_version\s*=/', $line ) ) { $lines[] = (string) $line; @@ -2836,13 +2865,15 @@ function wp_version( string $dir ): string { /** * A file's lines without their `\n`, or null for one longer than LINE_MAX - 2 bytes, so no file size matters. + * $tick runs per read, so a huge file can't outlast the deadline. * * @param resource $fh * @return Generator */ -function lines( $fh ): Generator { +function lines( $fh, callable $tick ): Generator { $long = false; while ( false !== ( $piece = fgets( $fh, LINE_MAX ) ) ) { + $tick(); if ( "\n" !== substr( $piece, -1 ) && ! feof( $fh ) ) { $long = true; continue; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 30a8c6ae..e143aa06 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -667,8 +667,8 @@ function finding_files( array $report ): array { $ne = out( 'nested' ); $r = report( 'nested' ); -eq( [ $ne['status'] ?? null, field( $ne, 'safe_to_upgrade' ), $ne['errors'] ?? null, $ne['files_checked'] ?? null, $ne['files_not_checked'] ?? null ], [ 'ok', false, 5, 5, 2 ], 'nested: verdict and counts' ); -eq( finding_files( $r ), [ 'directory:htdocs/old::custom.php', 'directory:htdocs/old::index.php', 'directory:htdocs::index.php', 'directory:htdocs::wp-custom.php', 'plugin:fakecore::index.php' ], 'nested: non-core files and every index.php are checked; core (wp-settings.php, wp-includes/) is not' ); +eq( [ $ne['status'] ?? null, field( $ne, 'safe_to_upgrade' ), $ne['errors'] ?? null, $ne['files_checked'] ?? null, $ne['files_not_checked'] ?? null ], [ 'ok', false, 6, 6, 2 ], 'nested: verdict and counts' ); +eq( finding_files( $r ), [ 'directory:htdocs/old::custom.php', 'directory:htdocs/old::index.php', 'directory:htdocs/old::wp-content/plugins/q/q.php', 'directory:htdocs::index.php', 'directory:htdocs::wp-custom.php', 'plugin:fakecore::index.php' ], 'nested: non-core files, also in another install\'s wp-content, and every index.php are checked; core is not' ); eq( $r['not_checked'] ?? null, [ @@ -678,7 +678,7 @@ function finding_files( array $report ): array { 'nested: another install\'s core (also inside a plugin, also behind a link) is reported once per install' ); $e = out( 'est-nested' ); -eq( [ $e['php_files'] ?? null, $e['components'] ?? null ], [ 7, 3 ], 'est-nested: counts equal the scan' ); +eq( [ $e['php_files'] ?? null, $e['components'] ?? null ], [ 8, 3 ], 'est-nested: counts equal the scan' ); $hg = out( 'hang' ); $r = report( 'hang' ); @@ -898,12 +898,12 @@ function counts( string $name ): array { ]; eq( report( 'wpquotes' )['not_checked'] ?? null, $unknown_cores, 'wpquotes: an unknown version is never a supported branch' ); -eq( [ counts( 'wpold-served' ), report( 'wpold-served' )['excluded_old_releases'] ?? null ], [ [ 'ok', true, 0, 1, 0 ], [ '/var/www/htdocs/releases/1', '/var/www/htdocs/releases/2' ] ], 'wpold-served: nginx serves current: the old releases are left out' ); +eq( [ counts( 'wpold-served' ), report( 'wpold-served' )['excluded_old_releases'] ?? null ], [ [ 'ok', true, 0, 2, 0 ], [ '/var/www/htdocs/releases/1', '/var/www/htdocs/releases/2' ] ], 'wpold-served: nginx serves current: the old releases are left out' ); foreach ( [ 'wpold-noserved', 'wpold-above', 'wpold-oldcall' ] as $name ) { - eq( [ counts( $name ), finding_files( report( $name ) ) ], [ [ 'ok', false, 2, 3, 0 ], [ 'directory:htdocs::releases/1/wp-content/plugins/old/old.php', 'directory:htdocs::releases/2/x.php' ] ], "$name: not sure, above current, or a v3.11.1 call: every release scanned" ); + eq( [ counts( $name ), finding_files( report( $name ) ) ], [ [ 'ok', false, 2, 6, 0 ], [ 'directory:htdocs::releases/1/wp-content/plugins/old/old.php', 'directory:htdocs::releases/2/x.php' ] ], "$name: not sure, above current, or a v3.11.1 call: every release scanned" ); } eq( report( 'wpold-noserved' )['excluded_old_releases'] ?? null, [], 'wpold-noserved: none left out' ); -eq( [ counts( 'wpold-hint' ), report( 'wpold-hint' )['excluded_old_releases'] ?? null ], [ [ 'ok', false, 1, 2, 0 ], [ '/var/www/htdocs/releases/2' ] ], 'wpold-hint: a scan path in an old release keeps that release scanned' ); +eq( [ counts( 'wpold-hint' ), report( 'wpold-hint' )['excluded_old_releases'] ?? null ], [ [ 'ok', false, 1, 4, 0 ], [ '/var/www/htdocs/releases/2' ] ], 'wpold-hint: a scan path in an old release keeps that release scanned' ); eq( out( 'phpold-noserved' )['errors'] ?? null, 3, 'phpold-noserved: an empty COMPAT_SERVED leaves no release out on php sites either' ); $er = report( 'extraroot' ); @@ -967,7 +967,7 @@ function counts( string $name ): array { $ia_want = [ [ 'ok', null, 0, 2, 1 ], [ '/var/www/htdocs/alias/pre.txt' ] ]; eq( $ia, $ia_want, 'inialias: a .user.ini is read though a code-named link to it was listed first' ); -foreach ( [ 'phar-info' => null, 'phar-named' => 'boot.php', 'phar-upper' => 'boot.php', 'phar-split' => 'boot.php' ] as $name => $by ) { +foreach ( [ 'phar-info' => null, 'phar-named' => 'boot.php', 'phar-upper' => 'boot.php', 'phar-split' => 'boot.php', 'phar-pharmacy' => null ] as $name => $by ) { $r = report( $name ); $phars = [ '/var/www/htdocs/wp-content/plugins/p/lib.phar', '/var/www/htdocs/wp-cli.phar' ]; $named = null === $by ? null : "/var/www/htdocs/wp-content/plugins/p/$by"; @@ -1033,6 +1033,23 @@ function counts( string $name ): array { eq( counts( 'burst' ), [ 'ok', false, 2, 402, 0 ], 'burst: a lint per file, one after another, stays within a pids limit of 8' ); tool_error( 'slowlint', 'timed out after 2 s at htdocs/big.tpl', 1 ); +foreach ( [ 'wpextra-dir', 'wpextra-parent' ] as $name ) { + $cfg = comp_of( report( $name ), 'other', 'wp-config.php' )['findings'][0] ?? []; + eq( [ counts( $name )[1], $cfg['file'] ?? null ], [ false, 'wp-config.php' ], "$name: wp-config.php of WordPress in an extra root is checked" ); +} +$co = report( 'contentold' ); +eq( [ comp_of( $co, 'plugin', 'p' )['errors'] ?? null, $co['excluded_old_releases'] ?? null ], [ 1, [] ], 'contentold: a release the live wp-content links into is live code' ); +foreach ( [ 'relname-noindex' => [], 'relname-stub' => [ '/var/www/htdocs/releases/1' ] ] as $name => $old ) { + $r = report( $name ); + eq( [ counts( $name )[1], finding_files( $r ), $r['excluded_old_releases'] ?? null ], [ false, [ 'directory:releases::shared/config.php' ], $old ], "$name: shared/ is scanned; only a release-named dir with the served index.php is old" ); +} +eq( report( 'coreout' )['not_checked'] ?? null, [ nc( 'directory', 'htdocs/wp-admin', null, './', 'unreadable' ) ], 'coreout: a core dir linked out of /var/www isn\'t searched for .user.ini files' ); +foreach ( [ 'sparse-ini', 'sparse-version' ] as $name ) { + tool_error( $name, 'timed out after 3 s while listing files', 1 ); + $secs = trim( raw( "$name.secs" ) ); + check( '' !== $secs && (int) $secs <= 10, "$name: a huge file is read only until the deadline ($secs s)" ); +} + $entry = json_decode( raw( 'entrypoint' ), true ); eq( $entry[2] ?? null, 'memory_limit=1G', 'image: the entrypoint\'s memory limit plus a child\'s 896M is below EE\'s 2g container limit' ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 789d3542..7541d5ea 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -601,6 +601,7 @@ nested_fixture() { php_file "$h/old/index.php" 'each( $a );' php_file "$h/old/xmlrpc.php" 'each( $a );' php_file "$h/old/custom.php" 'each( $a );' + php_file "$h/old/wp-content/plugins/q/q.php" 'each( $a );' php_file "$wc/plugins/fakecore/index.php" '/* Plugin Name: Fake Core */ each( $a );' php_file "$wc/plugins/fakecore/wp-settings.php" 'each( $a );' @@ -899,13 +900,15 @@ wpquotes_fixture() { chmod -R a+rX "$a" } -# wpold_fixture : a WordPress CI/CD site, htdocs/current -> releases/3, with errors in the old releases. +# wpold_fixture : a WordPress CI/CD site, htdocs/current -> releases/3, with errors in the old releases; each +# release has the index.php nginx serves. wpold_fixture() { local h="$1/htdocs" wp_core "$h/releases/3" 6.8.3 php_file "$h/releases/3/wp-content/plugins/p/p.php" '/* Plugin Name: P */' php_file "$h/releases/1/wp-content/plugins/old/old.php" 'each( $a );' php_file "$h/releases/2/x.php" 'each( $a );' + for r in 1 2 3; do php_file "$h/releases/$r/index.php" 'echo 1;'; done ln -s releases/3 "$h/current" chmod -R a+rX "$1" } @@ -937,7 +940,7 @@ require_fixture() { chmod -R a+rX "$1" } -# phar_fixture : phars, and a plugin file naming one (or not). +# phar_fixture : phars, and a plugin file naming one (or a word starting `.phar`). phar_fixture() { local p="$1/htdocs/wp-content/plugins/p" pad wp_core "$1/htdocs" 6.8.3 @@ -947,6 +950,7 @@ phar_fixture() { case $2 in named) php_file "$p/boot.php" "include 'phar://' . __DIR__ . '/lib.phar/x.php';" ;; upper) php_file "$p/boot.php" "\$x = 'LIB.PHAR';" ;; + pharmacy) php_file "$p/boot.php" "echo 'https://shop.example.pharmacy/';" ;; split) # `.phar` across the first 64 KiB read: 8 bytes of tag and comment start, then the pad, then `*/ $x = 'l`. pad=$(head -c 65516 /dev/zero | tr '\0' a) @@ -1259,3 +1263,67 @@ slowlint_fixture() { { printf ' "$1/htdocs/big.tpl" chmod -R a+rX "$1" } + +# wpextra_fixture : WordPress in /srv, which run.sh mounts at /srv/wp, and /app/htdocs a +# link to it (dir) or to its public/ (parent, wp-config.php one level up); wp-config.php has an error. +wpextra_fixture() { + local w="$1/srv" + [ "$2" = parent ] && w="$1/srv/public" + wp_core "$w" 6.8.3 + php_file "$w/wp-content/plugins/p/p.php" '/* Plugin Name: P */' + php_file "$1/srv/wp-config.php" 'each( $a );' + mkdir -p "$1/app" + ln -s "/srv/wp${w#"$1/srv"}" "$1/app/htdocs" + chmod -R a+rX "$1" +} + +# contentold_fixture : a WordPress CI/CD site, htdocs/current -> releases/3, whose wp-content links into the +# previous release, where a plugin has an error. +contentold_fixture() { + local h="$1/htdocs" r + for r in 2 3; do wp_core "$h/releases/$r" 6.8.3 && php_file "$h/releases/$r/index.php" 'echo 1;'; done + php_file "$h/releases/2/wp-content/plugins/p/p.php" '/* Plugin Name: P */ +each( $a );' + ln -s ../2/wp-content "$h/releases/3/wp-content" + ln -s releases/3 "$h/current" + chmod -R a+rX "$1" +} + +# relname_fixture : a php CI/CD site, htdocs/current -> releases/2, whose code requires +# releases/shared/config.php (an error); the releases serve index.html (noindex) or index.php, and shared/ holds an +# index.php stub too (stub). +relname_fixture() { + local r="$1/htdocs/releases" n + for n in 1 2; do + php_file "$r/$n/api/ping.php" 'require __DIR__ . "/../../shared/config.php";' + if [ "$2" = noindex ]; then printf '

hi

\n' > "$r/$n/index.html"; else php_file "$r/$n/index.php" 'echo 1;'; fi + done + php_file "$r/shared/config.php" 'each( $a );' + [ "$2" = stub ] && php_file "$r/shared/index.php" '// Silence is golden.' + ln -s releases/2 "$1/htdocs/current" + chmod -R a+rX "$1" +} + +# coreout_fixture : /app's wp-admin links to /srv/core, which run.sh mounts from /core (not an extra root), +# holding a .user.ini. +coreout_fixture() { + wp_core "$1/app/htdocs" 6.8.3 + rm -rf "$1/app/htdocs/wp-admin" + ln -s /srv/core "$1/app/htdocs/wp-admin" + mkdir -p "$1/core/sub" + printf 'auto_prepend_file = /srv/core/x.php\n' > "$1/core/sub/.user.ini" + chmod -R a+rX "$1" +} + +# sparse_fixture : a php site with a 16 GiB sparse .user.ini, or a WordPress install below it +# with a 16 GiB sparse version.php. +sparse_fixture() { + php_file "$1/htdocs/index.php" 'echo 1;' + if [ "$2" = ini ]; then + truncate -s 16G "$1/htdocs/.user.ini" + else + wp_core "$1/htdocs/blog" 6.8.3 + truncate -s 16G "$1/htdocs/blog/wp-includes/version.php" + fi + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index b510aaff..6f72046b 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -421,7 +421,8 @@ phar_fixture "$WORK/phar-info" none phar_fixture "$WORK/phar-named" named phar_fixture "$WORK/phar-upper" upper phar_fixture "$WORK/phar-split" split -for f in info named upper split; do scan "phar-$f" "$WORK/phar-$f" wp /var/www/htdocs 8.4 600; done +phar_fixture "$WORK/phar-pharmacy" pharmacy +for f in info named upper split pharmacy; do scan "phar-$f" "$WORK/phar-$f" wp /var/www/htdocs 8.4 600; done # The search for a phar reference in a huge file stops at the deadline. pharslow_fixture "$WORK/pharslow" start=$SECONDS @@ -448,6 +449,30 @@ slowlint_fixture "$WORK/slowlint" scan slowlint "$WORK/slowlint" php /var/www/htdocs 8.4 2 -e COMPAT_FILE_TIMEOUT=1 rm -f "$WORK/slowlint/htdocs/big.tpl" +# WordPress in a mount outside /var/www, wp-config.php in its dir or the one above. +for v in dir parent; do + wpextra_fixture "$WORK/wpextra-$v" "$v" + scan "wpextra-$v" "$WORK/wpextra-$v/app" wp /var/www/htdocs 8.4 600 \ + --mount "type=bind,src=$WORK/wpextra-$v/srv,dst=/srv/wp,readonly" -e COMPAT_EXTRA_ROOTS=/srv/wp +done +# A live wp-content linked into an old release; old releases told apart by name and the served index.php. +contentold_fixture "$WORK/contentold" +scan contentold "$WORK/contentold" wp /var/www/htdocs/current 8.4 600 +for v in noindex stub; do + relname_fixture "$WORK/relname-$v" "$v" + scan "relname-$v" "$WORK/relname-$v" php /var/www/htdocs/current 8.4 600 +done +# A core dir linked outside /var/www and the mounts isn't searched for .user.ini files. +coreout_fixture "$WORK/coreout" +scan coreout "$WORK/coreout/app" wp /var/www/htdocs 8.4 600 --mount "type=bind,src=$WORK/coreout/core,dst=/srv/core,readonly" +# A huge .user.ini or version.php is read only until the deadline. +for v in ini version; do + sparse_fixture "$WORK/sparse-$v" "$v" + start=$SECONDS + scan "sparse-$v" "$WORK/sparse-$v" php /var/www/htdocs 8.4 3 + echo $(( SECONDS - start )) > "$RES/sparse-$v.secs" +done + # Malformed new env. scan badargs-served "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_SERVED=/etc scan badargs-supported "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6 From 37de1da4cd75ea8f90d8fb8b893ddada40ce1df1 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 07:58:27 +0530 Subject: [PATCH 37/80] fix(compat-scanner): give "can't confirm" for lint failures that may not be PHP's - A file that fails the lint but isn't named as code (Laravel's `*.stub`, PHPUnit's `*.tpl` templates, which start with `:2)`, no longer `(previously declared:2)`. --- compat-scanner/bin/compat-scanner.php | 34 +++++++++++++-------------- compat-scanner/tests/assert.php | 16 +++++++++++++ compat-scanner/tests/fixture.sh | 20 ++++++++++++++++ compat-scanner/tests/run.sh | 4 ++++ 4 files changed, 56 insertions(+), 18 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 1cefc15b..751c8862 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -61,9 +61,10 @@ const BACKUP_EXTENSIONS = [ 'bak', 'orig', 'old', 'save', 'swp', 'log', 'sql', 'dist' ]; // The www-data home in /var/www: searched by name only, like uploads/. const HOME_DIRS = [ '.wp-cli', '.composer', '.cache', '.config', '.local', '.npm', '.ssh' ]; -// Template names PHP apps include (Smarty-style .tpl and .tmpl, plain .html and .htm, CakePHP's .ctp): with text before -// their PHP tag they are still linted, unlike a script or shell history quoting `phpcsTakes( $real ); // Every file's run has a time cap; a sniffed file (not code by name) gets a shorter one. - $code = $this->isPhpName( basename( $f['path'] ) ) || $this->isPhpName( $real ); - $batch[ $k ]['cap'] = (float) ( $code ? $this->cfg['file_timeout'] : $this->cfg['sniffed_timeout'] ); + $batch[ $k ]['code'] = $this->isPhpName( basename( $f['path'] ) ) || $this->isPhpName( $real ); + $batch[ $k ]['cap'] = (float) ( $batch[ $k ]['code'] ? $this->cfg['file_timeout'] : $this->cfg['sniffed_timeout'] ); // Searched only on a site holding a phar, up to the first hit; not in a file refused by size. $search = $this->pharCount > 0 && null === $this->pharNamedBy && ! ( $batch[ $k ]['stdin'] && $st['size'] > STDIN_MAX ); if ( $search && $this->namesPhar( $f['path'], $real ) ) { @@ -2285,9 +2286,8 @@ private function runTimed( array $cmd, float $cap, array $spec, int $fsize = 0 ) } /** - * `php -l` over a batch, then each file on its own when it fails: PHPCompatibility misses some parse errors (`#[` - * before PHP 8, an unclosed final comment). Not for targets before 8.0, whose syntax PHP 8.4 rejects, nor for files - * with text before their tag but no template name (a script or shell history quoting ` By batch key, the files that fail: [ line, message ] or a not_checked reason. */ @@ -2313,8 +2313,8 @@ private function lint( array $batch ): array { } if ( 0 !== $res['rc'] ) { $result = $this->lintResult( $res, $real ); - // Text before the tag: the file may never run as PHP, so its failure can't prove a break. - $failed[ $k ] = $batch[ $k ]['mixed'] && is_array( $result ) ? 'php_tag' : $result; + // Not named as code (a `.stub`, a template): the file may never run as PHP, so its failure can't prove a break. + $failed[ $k ] = ! $batch[ $k ]['code'] && is_array( $result ) ? 'php_tag' : $result; } } return $failed; @@ -2325,8 +2325,7 @@ private function lintRun( array $paths, float $cap ): array { $args = [ '-d', 'memory_limit=' . $this->cfg['retry_memory'], '-d', 'display_errors=stderr', '-d', 'log_errors=0' ]; // Fatal errors only: a deprecation PHP prints while compiling would come before the one line lintResult() reads. $args = array_merge( $args, [ '-d', 'error_reporting=' . ( E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR ) ] ); - // Functions PHP added after the target don't exist there: disabled, declaring one is no error, and the lint goes on - // to whatever comes after it. + // Functions PHP added after the target don't exist there: disabled, declaring one is no error, and the lint goes on. $later = array_filter( native_since(), function ( $since ) { @@ -2342,10 +2341,7 @@ function ( $since ) { return $res; } - /** - * @return array{0:int,1:string}|string The finding, or `unparseable` for a target newer than this PHP, which can't parse - * its syntax. - */ + /** @return array{0:int,1:string}|string The finding, or `unparseable` where this PHP's verdict isn't the target's. */ private function lintResult( array $res, string $real ) { if ( $res['capped'] ) { return 'timeout'; @@ -2356,10 +2352,12 @@ private function lintResult( array $res, string $real ) { if ( 255 !== $res['rc'] ) { return 'error'; } - $text = trim( str_replace( ' in ' . $real, '', $res['stderr'] ) ); + // The path PHP appends to the message, not the one inside `(previously declared in :2)`. + $text = (string) preg_replace( '/ in ' . preg_quote( $real, '/' ) . '(?=(?: on line \d+)?$)/', '', trim( $res['stderr'] ) ); // A redeclared function parsed, so it is a finding on any target. $redeclare = (bool) preg_match( '/^Fatal error: Cannot redeclare (?:function )?\w+\(\)/', $text ); - if ( ! $redeclare && version_compare( $this->cfg['version'], PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION, '>' ) ) { + $newer = ! $redeclare && version_compare( $this->cfg['version'], PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION, '>' ); + if ( $newer || ( '8.0' === $this->cfg['version'] && preg_match( RESERVED_AFTER_80, $text ) ) ) { return 'unparseable'; } preg_match( '/^(.*?)(?: on line (\d+))?$/s', $text, $m ); diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index e143aa06..6253bec6 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1030,6 +1030,22 @@ function counts( string $name ): array { $l74sources = array_column( comp_of( $l74, 'plugin', 'p' )['findings'] ?? [], 'source' ); eq( [ in_array( 'CompatScanner.Syntax.ParseError', $l74sources, true ), array_column( $l74['not_checked'] ?? [], 'file' ) ], [ false, [ 'views/broken.tpl' ] ], 'lint-74: targets before 8.0 aren\'t linted (broken.tpl is PHPCS\'s own unparseable)' ); +// Files not named as code, and templates under any name PHP apps include, can't prove a break; nor names 8.0 still takes. +$ln_tags = [ nc( 'directory', 'vendor', null, 'phpunit/templates/method.tpl', 'php_tag' ), nc( 'directory', 'vendor', null, 'x/stubs/class.stub', 'php_tag' ) ]; +foreach ( [ 'php3', 'php4', 'php6', 'php8', 'phps', 'pht', 'thtml', 'view', 'xhtml' ] as $e ) { + $ln_tags[] = nc( 'directory', 'views', null, "header.$e", 'php_tag' ); +} +$ln_reserved = [ 'other:::nv.php', 'other:::nw.php', 'other:::ro.php' ]; +foreach ( [ 'lintnames' => $ln_reserved, 'lintnames-80' => [] ] as $name => $reserved ) { + $r = report( $name ); + $got = [ finding_files( $r ), array_values( array_filter( $r['not_checked'] ?? [], static function ( $e ) { return 'php_tag' === $e['reason']; } ) ) ]; + eq( $got, [ array_merge( [ 'other:::broken.php' ], $reserved, [ 'other:::tw.php' ] ), $ln_tags ], "$name: lint failures of non-code names are php_tag" ); +} +$ln80 = array_column( array_filter( report( 'lintnames-80' )['not_checked'] ?? [], static function ( $e ) { return 'unparseable' === $e['reason']; } ), 'file' ); +eq( $ln80, [ 'nv.php', 'nw.php', 'ro.php' ], 'lintnames-80: names PHP 8.0 takes but 8.4 reserves can\'t be confirmed' ); +$tw = comp_of( report( 'lintnames' ), 'other', '' )['findings'] ?? []; +eq( end( $tw )['message'] ?? null, 'Fatal error: Cannot redeclare function p_tw() (previously declared in /var/www/htdocs/tw.php:2)', 'lintnames: the lint message keeps the earlier declaration\'s place' ); + eq( counts( 'burst' ), [ 'ok', false, 2, 402, 0 ], 'burst: a lint per file, one after another, stays within a pids limit of 8' ); tool_error( 'slowlint', 'timed out after 2 s at htdocs/big.tpl', 1 ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 7541d5ea..964d0d89 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1327,3 +1327,23 @@ sparse_fixture() { fi chmod -R a+rX "$1" } + +# lintnames_fixture : a php site with files the lint fails: templates and stubs that start with `\n\n' > "$h/views/header.$e" + done + php_file "$h/ro.php" 'class Readonly {}' + php_file "$h/nv.php" 'class Never {}' + php_file "$h/nw.php" '$x = new Readonly();' + php_file "$h/tw.php" 'function p_tw() {} +function p_tw() {}' + printf ' "$h/broken.php" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 6f72046b..5cdb9c12 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -442,6 +442,10 @@ scan lint "$WORK/lint" wp /var/www/htdocs 8.4 600 scan lint-85 "$WORK/lint" wp /var/www/htdocs 8.5 600 scan lint-74 "$WORK/lint" wp /var/www/htdocs 7.4 600 +lintnames_fixture "$WORK/lintnames" +scan lintnames "$WORK/lintnames" php /var/www/htdocs 8.4 600 +scan lintnames-80 "$WORK/lintnames" php /var/www/htdocs 8.0 600 + # Quick runs one after another (a lint per file) stay within a small pids limit; a lint the deadline ends is a timeout. burst_fixture "$WORK/burst" scan burst "$WORK/burst" php /var/www/htdocs 8.4 600 --pids-limit 8 From 43736ba8dc3ebe460f36535541194753a83a8d3f Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 08:01:11 +0530 Subject: [PATCH 38/80] feat(compat-scanner): follow the site's short_open_tag setting EE now tells the scanner whether the site's PHP has short_open_tag on, in the new COMPAT_SHORT_OPEN_TAG env (`1` on; `0`, empty or absent off, as in EE's images; anything else is bad arguments). PHPCS and the syntax lint both run with that value, and with it on a bare `` block PHP prints as text was checked as code (a needless "not safe"), and on a site that turns short tags on a template starting with ` '', 'not_checked' => '', 'information' => '' ]; /** @var string[] Real paths (with `/`) of the directories searched by name only, where nothing is sniffed. */ private $skippedDirs = []; + /** @var string A PHP open tag, as a regex. */ + private $openTag; + /** @var string What sniff() matches in a file's first SNIFF_BYTES, as one regex (no NUL anywhere, then an open tag), for the manifest. */ + private $sniffRegex; /** @var string */ private $work = ''; @@ -170,6 +175,9 @@ public function __construct( array $cfg ) { $this->start = microtime( true ); $limit = $this->isScan ? $cfg['timeout'] : $cfg['estimate_timeout']; + $tag = $cfg['short_tags'] ? OPEN_TAG_SHORT : OPEN_TAG; + $this->openTag = '/' . $tag . '/i'; + $this->sniffRegex = '/\\A(?=[^\\x00]*\\z)[\\s\\S]*?' . $tag . '/i'; $this->timeoutLabel = $limit; $this->deadline = $this->start + $limit; $this->listDeadline = $this->isScan ? $this->deadline : $this->deadline - min( CALIBRATION_RESERVE, $limit / 4 ); @@ -1108,7 +1116,7 @@ private function dataOnly( string $path ): bool { $rest = substr( $head, strlen( $m[0] ) ); $read = strlen( $head ); while ( true ) { - if ( preg_match( '/<\?(?:php(?:\s|\z)|=)/i', $rest ) ) { + if ( preg_match( $this->openTag, $rest ) ) { $ok = false; break; } @@ -1144,8 +1152,8 @@ private function sniff( string $real ): ?string { } $head = fread( $fh, SNIFF_BYTES ); fclose( $fh ); - // SNIFF_REGEX is the rule the manifest publishes; the second match only finds where the tag starts. - if ( false === $head || ! preg_match( SNIFF_REGEX, $head ) || ! preg_match( '/<\?(?:php(?:\s|\z)|=)/i', $head, $m, PREG_OFFSET_CAPTURE ) ) { + // sniffRegex is the rule the manifest publishes; the second match only finds where the tag starts. + if ( false === $head || ! preg_match( $this->sniffRegex, $head ) || ! preg_match( $this->openTag, $head, $m, PREG_OFFSET_CAPTURE ) ) { return null; } return preg_match( '/\A(?:\xEF\xBB\xBF)?(?:#![^\n]*\n)?\s*\z/', substr( $head, 0, $m[0][1] ) ) ? 'code' : 'mixed'; @@ -1943,7 +1951,7 @@ private function writeManifest(): void { 'phar_regex' => PHAR_REGEX, 'sniff' => [ 'bytes' => SNIFF_BYTES, - 'regex' => SNIFF_REGEX, + 'regex' => $this->sniffRegex, 'exclude_extensions' => array_merge( NO_SNIFF_EXTENSIONS, BACKUP_EXTENSIONS ), 'scope' => 'except_skipped_dirs', 'skipped_dirs' => array_values( array_unique( array_map( 'manifest_path', $this->skippedDirs ) ) ), @@ -2200,6 +2208,7 @@ private function phpcs( array $paths, string $memory, string $tag, bool $stdin = $cmd = [ PHP_BINARY, '-d', 'memory_limit=' . $memory, '-d', 'display_errors=stderr', '-d', 'log_errors=0', + '-d', 'short_open_tag=' . (int) $this->cfg['short_tags'], PHPCS_BIN, '--standard=' . ( 'php' === $this->cfg['site_type'] ? 'PHPCompatibility' : 'PHPCompatibilityWP' ) . ',' . SNIFFS_DIR, '--runtime-set', 'testVersion', $this->cfg['version'], @@ -2333,8 +2342,8 @@ function ( $since ) { } ); $args = array_merge( $args, [ '-d', 'disable_functions=' . implode( ',', array_keys( $later ) ) ] ); - // EE's php images turn short tags off; on, PHP would parse a template's `cfg['short_tags'] ], $args, [ '-l' ], $paths ); $res = $this->runTimed( $cmd, $cap, [ 0 => [ 'file', '/dev/null', 'r' ], 1 => [ 'file', '/dev/null', 'w' ], 2 => [ 'file', $err, 'w' ] ] ); $res['stderr'] = $res['timeout'] ? '' : (string) file_get_contents( $err, false, null, 0, 65536 ); @@ -2352,7 +2361,7 @@ private function lintResult( array $res, string $real ) { if ( 255 !== $res['rc'] ) { return 'error'; } - // The path PHP appends to the message, not the one inside `(previously declared in :2)`. + // The path PHP appends to the message, not the one in its note on the earlier declaration. $text = (string) preg_replace( '/ in ' . preg_quote( $real, '/' ) . '(?=(?: on line \d+)?$)/', '', trim( $res['stderr'] ) ); // A redeclared function parsed, so it is a finding on any target. $redeclare = (bool) preg_match( '/^Fatal error: Cannot redeclare (?:function )?\w+\(\)/', $text ); @@ -2939,7 +2948,7 @@ function parse_args( array $argv, array &$cfg ): void { } } -/** COMPAT_SERVED, COMPAT_REQUIRE, COMPAT_EXTRA_ROOTS and COMPAT_WP_SUPPORTED: what EE tells the scanner about the site. */ +/** COMPAT_SERVED, COMPAT_REQUIRE, COMPAT_EXTRA_ROOTS, COMPAT_WP_SUPPORTED and COMPAT_SHORT_OPEN_TAG: what EE tells the scanner about the site. */ function parse_contract_env( array &$cfg ): void { // False when absent: a v3.11.1 call, unlike an empty value. $cfg['served'] = getenv( 'COMPAT_SERVED' ); @@ -2955,6 +2964,11 @@ function parse_contract_env( array &$cfg ): void { } $cfg['extra_roots'][] = $root; } + $short = (string) getenv( 'COMPAT_SHORT_OPEN_TAG' ); + if ( ! in_array( $short, [ '', '0', '1' ], true ) ) { + throw new BadArgs( 'COMPAT_SHORT_OPEN_TAG must be 0 or 1' ); + } + $cfg['short_tags'] = '1' === $short; $supported = (string) getenv( 'COMPAT_WP_SUPPORTED' ); $cfg['wp_supported'] = '' === $supported ? [] : explode( ',', $supported ); foreach ( $cfg['wp_supported'] as $branch ) { diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 6253bec6..1d00fe9d 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1046,6 +1046,9 @@ function counts( string $name ): array { $tw = comp_of( report( 'lintnames' ), 'other', '' )['findings'] ?? []; eq( end( $tw )['message'] ?? null, 'Fatal error: Cannot redeclare function p_tw() (previously declared in /var/www/htdocs/tw.php:2)', 'lintnames: the lint message keeps the earlier declaration\'s place' ); +eq( [ counts( 'shorttag' ), finding_files( report( 'shorttag' ) ) ], [ [ 'ok', true, 0, 2, 0 ], [] ], 'shorttag: with short tags off, ` "$h/broken.php" chmod -R a+rX "$1" } + +# shorttag_fixture : a php site with `\n\n\n' > "$h/short.php" + mkdir -p "$h/views" && printf '\n' > "$h/views/short.tpl" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 5cdb9c12..ba6c7b07 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -446,6 +446,11 @@ lintnames_fixture "$WORK/lintnames" scan lintnames "$WORK/lintnames" php /var/www/htdocs 8.4 600 scan lintnames-80 "$WORK/lintnames" php /var/www/htdocs 8.0 600 +# short_open_tag as EE reads it from the site (default off, as in EE's images). +shorttag_fixture "$WORK/shorttag" +scan shorttag "$WORK/shorttag" php /var/www/htdocs 8.4 600 +scan shorttag-on "$WORK/shorttag" php /var/www/htdocs 8.4 600 -e COMPAT_SHORT_OPEN_TAG=1 + # Quick runs one after another (a lint per file) stay within a small pids limit; a lint the deadline ends is a timeout. burst_fixture "$WORK/burst" scan burst "$WORK/burst" php /var/www/htdocs 8.4 600 --pids-limit 8 @@ -481,6 +486,7 @@ done scan badargs-served "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_SERVED=/etc scan badargs-supported "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6 scan badargs-roots "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_EXTRA_ROOTS=/var/www/x +scan badargs-short "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_SHORT_OPEN_TAG=on # An estimate keeps time for calibration: throttled, the listing of 20,000 files can't finish in its share of 1 s. estimate est-listing "$WORK/wide" wp /var/www/htdocs 8.4 -e COMPAT_ESTIMATE_TIMEOUT=1 --cpus 0.05 From 08f6c145935b178fc6f6fc449de1d0d79be4462f Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 08:06:12 +0530 Subject: [PATCH 39/80] fix(compat-scanner): accept only guards that keep a native's declaration from running The NativeDeclared sniffs took any token of an enclosing if or elseif that named the check or PHP_VERSION_ID as a guard, and read the version bound with (int). Shapes PHP 8.5 dies on were quiet (`! function_exists( 'a' ) || ! function_exists( 'b' )`, a positive function_exists(), `! ( PHP_VERSION_ID < 80500 )`, `PHP_VERSION_ID < 80500 + 100`, `< 90_000`, `< 0x15000`), while shapes it runs were reported. A guard is now the whole condition, or a top-level `&&` operand of it, with the right polarity, testing that exact name: - `! check( 'name' )` (also `false ===` and `=== false`), the name a string or `name::class`, a leading `\` allowed; - `PHP_VERSION_ID < N` with N a plain decimal no higher than the version that added the name, also `N > PHP_VERSION_ID` and `<=` with N one lower; - `version_compare( PHP_VERSION, 'X.Y', '<' )` or `'lt'`, X.Y no higher than that version. The else of an if whose condition, or a top-level `||` operand of it, holds where the native exists is a guard too. For a class, enum or interface, so is a file-scope if with that test and a return in its own block before the declaration; for a function it isn't, since PHP declares a top-level function when it compiles the file. Anything else is reported. A global function declared in a method's or a closure's body is now reported: only a method itself is skipped. A named argument (`function_exists( function: 'x' )`) no longer stops PHPCS on the file. tests/guards.php is the table of shapes: each is a file of the fixture, checked at 8.5, and run.sh runs each on php:8.5.0-cli, so the table's "PHP runs it" column is PHP's own answer. No row PHP can't run is quiet. --- .../Sniffs/Classes/NativeDeclaredSniff.php | 33 +++- .../Sniffs/Functions/NativeDeclaredSniff.php | 171 +++++++++++++++--- compat-scanner/tests/assert.php | 16 ++ compat-scanner/tests/guards.php | 123 +++++++++++++ compat-scanner/tests/run.sh | 10 + 5 files changed, 324 insertions(+), 29 deletions(-) create mode 100644 compat-scanner/tests/guards.php diff --git a/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php index 0cf3ba9e..9e43062d 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php @@ -1,12 +1,13 @@ table[ $lower ]; return [ 'since' => $since, 'checks' => self::CHECKS[ $kind ] ]; } + + /** PHP declares a class when its declaration runs, so a return before it on the native's check is a guard. */ + protected function returnsBefore( File $phpcsFile, int $stackPtr, array $native ): bool { + $tokens = $phpcsFile->getTokens(); + // In a function body it runs whenever the function is called, which other files can do. + if ( array_intersect( $tokens[ $stackPtr ]['conditions'], [ T_FUNCTION, T_CLOSURE, T_FN ] ) ) { + return false; + } + for ( $if = $phpcsFile->findNext( T_IF, 0, $stackPtr ); false !== $if; $if = $phpcsFile->findNext( T_IF, $if + 1, $stackPtr ) ) { + if ( 0 === $tokens[ $if ]['level'] && $this->returns( $tokens, $if ) && $this->holds( $phpcsFile, $if, $native, true ) ) { + return true; + } + } + return false; + } + + /** Whether the if's own block, not one nested in it, holds a return. */ + private function returns( array $tokens, int $if ): bool { + if ( ! isset( $tokens[ $if ]['scope_opener'], $tokens[ $if ]['scope_closer'] ) ) { + return false; + } + for ( $i = $tokens[ $if ]['scope_opener'] + 1; $i < $tokens[ $if ]['scope_closer']; $i++ ) { + if ( T_RETURN === $tokens[ $i ]['code'] && $tokens[ $i ]['level'] === $tokens[ $if ]['level'] + 1 ) { + return true; + } + } + return false; + } } diff --git a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php index a6fdc923..130a68e5 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php @@ -1,8 +1,8 @@ getTokens()[ $stackPtr ]['conditions'] as $ptr => $code ) { - if ( isset( Tokens::OO_SCOPE_TOKENS[ $code ] ) || $this->guards( $phpcsFile, $ptr, $name, $native ) ) { + $conditions = $phpcsFile->getTokens()[ $stackPtr ]['conditions']; + // A method; a function declared in a method's body is global. + if ( $conditions && isset( Tokens::OO_SCOPE_TOKENS[ end( $conditions ) ] ) ) { + return; + } + $native['name'] = strtolower( $name ); + foreach ( array_keys( $conditions ) as $ptr ) { + if ( $this->guards( $phpcsFile, $ptr, $native ) ) { return; } } + if ( $this->returnsBefore( $phpcsFile, $stackPtr, $native ) ) { + return; + } $phpcsFile->addError( $this->message, $stackPtr, 'Found', [ $name, $native['since'] ] ); } @@ -51,14 +59,56 @@ protected function native( string $lower ): ?array { return isset( $this->table[ $lower ] ) ? [ 'since' => $this->table[ $lower ], 'checks' => [ 'function_exists' ] ] : null; } - /** Whether the condition is an if or elseif that checks for the native. */ - protected function guards( File $phpcsFile, int $ptr, string $name, array $native ): bool { + /** An early return doesn't guard a function: PHP declares a top-level one when it compiles the file. */ + protected function returnsBefore( File $phpcsFile, int $stackPtr, array $native ): bool { + return false; + } + + /** Whether the block opened at $ptr runs only where the native is missing. */ + private function guards( File $phpcsFile, int $ptr, array $native ): bool { + $tokens = $phpcsFile->getTokens(); + if ( T_ELSE === $tokens[ $ptr ]['code'] ) { + // The closing brace before `else` belongs to the if or elseif it is the else of. + $prev = $phpcsFile->findPrevious( Tokens::EMPTY_TOKENS, $ptr - 1, null, true ); + $if = T_CLOSE_CURLY_BRACKET === $tokens[ $prev ]['code'] ? ( $tokens[ $prev ]['scope_condition'] ?? null ) : null; + return null !== $if && $this->holds( $phpcsFile, $if, $native, true ); + } + return in_array( $tokens[ $ptr ]['code'], [ T_IF, T_ELSEIF ], true ) && $this->holds( $phpcsFile, $ptr, $native, false ); + } + + /** + * Whether the condition of the if or elseif at $ptr, or a top-level operand of it, tests that the native exists or is missing. + * Operands are joined by `||` for exists, by `&&` for missing; any other top-level logical operator makes it no test. + */ + protected function holds( File $phpcsFile, int $ptr, array $native, bool $exists ): bool { $tokens = $phpcsFile->getTokens(); if ( ! in_array( $tokens[ $ptr ]['code'], [ T_IF, T_ELSEIF ], true ) || ! isset( $tokens[ $ptr ]['parenthesis_closer'] ) ) { return false; } - for ( $i = $tokens[ $ptr ]['parenthesis_opener']; $i < $tokens[ $ptr ]['parenthesis_closer']; $i++ ) { - if ( $this->guardAt( $phpcsFile, $i, $name, $native ) ) { + $open = $tokens[ $ptr ]['parenthesis_opener']; + $depth = count( $tokens[ $open ]['nested_parenthesis'] ?? [] ) + 1; + $join = $exists ? [ T_BOOLEAN_OR, T_LOGICAL_OR ] : [ T_BOOLEAN_AND, T_LOGICAL_AND ]; + $other = $exists ? [ T_BOOLEAN_AND, T_LOGICAL_AND ] : [ T_BOOLEAN_OR, T_LOGICAL_OR ]; + $other = array_merge( $other, [ T_LOGICAL_XOR, T_INLINE_THEN, T_COALESCE ] ); + + $operands = [ [] ]; + for ( $i = $open + 1; $i < $tokens[ $ptr ]['parenthesis_closer']; $i++ ) { + $code = $tokens[ $i ]['code']; + if ( isset( Tokens::EMPTY_TOKENS[ $code ] ) ) { + continue; + } + $top = count( $tokens[ $i ]['nested_parenthesis'] ?? [] ) === $depth; + if ( $top && in_array( $code, $other, true ) ) { + return false; + } + if ( $top && in_array( $code, $join, true ) ) { + $operands[] = []; + continue; + } + $operands[ count( $operands ) - 1 ][] = $i; + } + foreach ( $operands as $operand ) { + if ( $this->tests( $phpcsFile, $this->unwrap( $tokens, $operand ), $native, $exists ) ) { return true; } } @@ -66,29 +116,96 @@ protected function guards( File $phpcsFile, int $ptr, string $name, array $nativ } /** - * Whether the condition's token at $i is a call of one of the native's checks on this name, or `PHP_VERSION_ID < N` - * with N no higher than the version that added it, as Symfony's polyfill stubs declare classes. + * Whether the operand is exactly a check on the name (negated for missing), a PHP_VERSION_ID bound or a version_compare(). + * A bound is never above the version that added the name. */ - protected function guardAt( File $phpcsFile, int $i, string $name, array $native ): bool { - $token = $phpcsFile->getTokens()[ $i ]; - if ( 'PHP_VERSION_ID' === ltrim( $token['content'], '\\' ) ) { - return $this->belowSince( $phpcsFile, $i, $native['since'] ); + private function tests( File $phpcsFile, array $op, array $native, bool $exists ): bool { + $tokens = $phpcsFile->getTokens(); + $n = count( $op ); + if ( $n > 1 && ! $exists && T_BOOLEAN_NOT === $tokens[ $op[0] ]['code'] ) { + return $this->checks( $phpcsFile, $this->unwrap( $tokens, array_slice( $op, 1 ) ), $native ); } - $call = in_array( $token['code'], [ T_STRING, T_NAME_FULLY_QUALIFIED ], true ); - if ( ! $call || ! in_array( strtolower( ltrim( $token['content'], '\\' ) ), $native['checks'], true ) ) { - return false; + if ( $n > 2 && ! $exists && T_IS_IDENTICAL === $tokens[ $op[1] ]['code'] && T_FALSE === $tokens[ $op[0] ]['code'] ) { + return $this->checks( $phpcsFile, array_slice( $op, 2 ), $native ); + } + if ( $n > 2 && ! $exists && T_IS_IDENTICAL === $tokens[ $op[ $n - 2 ] ]['code'] && T_FALSE === $tokens[ $op[ $n - 1 ] ]['code'] ) { + return $this->checks( $phpcsFile, array_slice( $op, 0, $n - 2 ), $native ); + } + if ( $exists && $this->checks( $phpcsFile, $op, $native ) ) { + return true; } - $arg = PassedParameters::getParameter( $phpcsFile, $i, 1 ); - return false !== $arg && strtolower( ltrim( TextStrings::stripQuotes( $arg['clean'] ), '\\' ) ) === strtolower( $name ); + return 3 === $n ? $this->bound( $tokens, $op, $native['since'], $exists ) : $this->compares( $phpcsFile, $op, $native['since'], $exists ); } - /** Whether PHP_VERSION_ID at $i is compared `< N` with N no higher than $since. */ - private function belowSince( File $phpcsFile, int $i, string $since ): bool { + /** Whether the tokens are exactly one call of the native's checks with its name as the first argument. */ + private function checks( File $phpcsFile, array $op, array $native ): bool { $tokens = $phpcsFile->getTokens(); + if ( ! $this->call( $tokens, $op, $native['checks'] ) ) { + return false; + } + $arg = PassedParameters::getParameter( $phpcsFile, $op[0], 1, [ 'function', 'class', 'interface', 'enum' ] ); + // 'name', "name" or name::class, each with an optional leading `\`. + $named = false !== $arg && preg_match( '/^(?:([\'"])\\\\{0,2}(\w+)\1|\\\\?(\w+)::class)$/i', $arg['clean'], $m ); + return $named && strtolower( $m[2] . ( $m[3] ?? '' ) ) === $native['name']; + } + + /** Whether the tokens are exactly a call of one of $names, `\` allowed. */ + private function call( array $tokens, array $op, array $names ): bool { + $fn = in_array( $tokens[ $op[0] ]['code'] ?? null, [ T_STRING, T_NAME_FULLY_QUALIFIED ], true ); + if ( ! $fn || ! in_array( strtolower( ltrim( $tokens[ $op[0] ]['content'], '\\' ) ), $names, true ) || count( $op ) < 3 ) { + return false; + } + return T_OPEN_PARENTHESIS === $tokens[ $op[1] ]['code'] && $tokens[ $op[1] ]['parenthesis_closer'] === end( $op ); + } + + /** `PHP_VERSION_ID < N`, `<= N`, `N > …`, `N >= …` (the reverse for exists), N within the version that added the name. */ + private function bound( array $tokens, array $op, string $since, bool $exists ): bool { + $id = 'PHP_VERSION_ID'; + $ops = [ T_LESS_THAN => '<', T_IS_SMALLER_OR_EQUAL => '<=', T_GREATER_THAN => '>', T_IS_GREATER_OR_EQUAL => '>=' ]; + $op = array_map( + static function ( $ptr ) use ( $tokens, $ops ) { + return $ops[ $tokens[ $ptr ]['code'] ] ?? ltrim( $tokens[ $ptr ]['content'], '\\' ); + }, + $op + ); + // Turned around to `PHP_VERSION_ID N`. + $flip = [ '<' => '>', '<=' => '>=', '>' => '<', '>=' => '<=' ]; + if ( $id === $op[2] && isset( $flip[ $op[1] ] ) ) { + $op = [ $op[2], $flip[ $op[1] ], $op[0] ]; + } + if ( $id !== $op[0] || ! preg_match( '/^[1-9][0-9]*$/', $op[2] ) ) { + return false; + } list( $major, $minor ) = explode( '.', $since ); - $op = $phpcsFile->findNext( T_WHITESPACE, $i + 1, null, true ); - $bound = $phpcsFile->findNext( T_WHITESPACE, $op + 1, null, true ); - $below = T_LESS_THAN === $tokens[ $op ]['code'] && T_LNUMBER === $tokens[ $bound ]['code']; - return $below && (int) $tokens[ $bound ]['content'] <= $major * 10000 + $minor * 100; + $added = $major * 10000 + $minor * 100; + // The lowest version ID the test holds below (missing) or from (exists). + $from = [ '<' => (int) $op[2], '<=' => (int) $op[2] + 1, '>=' => (int) $op[2], '>' => (int) $op[2] + 1 ]; + $kind = $exists ? [ '>=', '>' ] : [ '<', '<=' ]; + return in_array( $op[1], $kind, true ) && $from[ $op[1] ] <= $added; + } + + /** `version_compare( PHP_VERSION, 'X.Y[.Z]', '<' )` or `'lt'` (`'>='` or `'ge'` for exists), X.Y.Z within the version that added the name. */ + private function compares( File $phpcsFile, array $op, string $since, bool $exists ): bool { + if ( ! $this->call( $phpcsFile->getTokens(), $op, [ 'version_compare' ] ) ) { + return false; + } + $args = PassedParameters::getParameters( $phpcsFile, $op[0] ); + if ( 3 !== count( $args ) || ! in_array( ltrim( $args[1]['clean'], '\\' ), [ 'PHP_VERSION' ], true ) ) { + return false; + } + $version = preg_match( '/^([\'"])(\d+(?:\.\d+){0,2})\1$/', $args[2]['clean'], $v ); + $cmp = preg_match( '/^([\'"])(<|lt|>=|ge)\1$/', $args[3]['clean'], $c ); + if ( ! $version || ! $cmp || $exists !== in_array( $c[2], [ '>=', 'ge' ], true ) ) { + return false; + } + return version_compare( $v[2], $since . '.0', '<=' ); + } + + /** The pointers without parentheses around all of them. */ + private function unwrap( array $tokens, array $op ): array { + while ( count( $op ) > 2 && T_OPEN_PARENTHESIS === $tokens[ $op[0] ]['code'] && $tokens[ $op[0] ]['parenthesis_closer'] === end( $op ) ) { + $op = array_slice( $op, 1, -1 ); + } + return $op; } } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 1d00fe9d..83c10b66 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1046,6 +1046,22 @@ function counts( string $name ): array { $tw = comp_of( report( 'lintnames' ), 'other', '' )['findings'] ?? []; eq( end( $tw )['message'] ?? null, 'Fatal error: Cannot redeclare function p_tw() (previously declared in /var/www/htdocs/tw.php:2)', 'lintnames: the lint message keeps the earlier declaration\'s place' ); +// Each guard shape at 8.5: reported exactly as the table says, never quiet where PHP fails, and PHP 8.5.0 agrees. +$reported = []; +foreach ( comp_of( report( 'guards' ), 'directory', 'g' )['findings'] ?? [] as $f ) { + if ( preg_match( '/^CompatScanner\.(?:Functions|Classes)\.NativeDeclared\./', $f['source'] ) ) { + $reported[ basename( $f['file'], '.php' ) ] = true; + } +} +$wrong = []; +foreach ( require '/t/guards.php' as list( $id, $php, $scanner ) ) { + if ( ( 'reported' === $scanner ) !== isset( $reported[ $id ] ) || ( 'fatal' === $php && 'quiet' === $scanner ) ) { + $wrong[] = $id; + } +} +eq( [ $wrong, report( 'guards' )['not_checked'] ?? null ], [ [], [] ], 'guards: each shape reported exactly as tests/guards.php says' ); +eq( trim( raw( 'guards.truth' ) ), 'checked', 'guards: PHP 8.5.0 runs exactly the shapes tests/guards.php says it runs' ); + eq( [ counts( 'shorttag' ), finding_files( report( 'shorttag' ) ) ], [ [ 'ok', true, 0, 2, 0 ], [] ], 'shorttag: with short tags off, ` | php guards.php truth (on php:8.5.0-cli: prints each row PHP disagrees with, then `checked`). + +const F = 'function array_first( $a ) { return null; }'; +const C = 'final class NoDiscard {}'; + +$rows = [ + // Functions, in an if or elseif that holds only where the function is missing. + [ 'f-not', 'ok', 'quiet', "if ( ! function_exists( 'array_first' ) ) { " . F . ' }' ], + [ 'f-not-dq', 'ok', 'quiet', 'if ( ! function_exists( "array_first" ) ) { ' . F . ' }' ], + [ 'f-not-fq', 'ok', 'quiet', "if ( ! \\function_exists( 'Array_First' ) ) { " . F . ' }' ], + [ 'f-not-slash', 'ok', 'quiet', "if ( ! function_exists( '\\\\array_first' ) ) { " . F . ' }' ], + [ 'f-tight', 'ok', 'quiet', "if(!function_exists('array_first')){" . F . '}' ], + [ 'f-parens', 'ok', 'quiet', "if ( ( ! function_exists( 'array_first' ) ) ) { " . F . ' }' ], + [ 'f-not-parens', 'ok', 'quiet', "if ( ! ( function_exists( 'array_first' ) ) ) { " . F . ' }' ], + [ 'f-false-eq', 'ok', 'quiet', "if ( false === function_exists( 'array_first' ) ) { " . F . ' }' ], + [ 'f-eq-false', 'ok', 'quiet', "if ( function_exists( 'array_first' ) === false ) { " . F . ' }' ], + [ 'f-and', 'ok', 'quiet', "if ( ! function_exists( 'array_first' ) && ! defined( 'P_X' ) ) { " . F . ' }' ], + [ 'f-and-word', 'ok', 'quiet', "if ( ! defined( 'P_X' ) and ! function_exists( 'array_first' ) ) { " . F . ' }' ], + [ 'f-comment', 'ok', 'quiet', "if ( ! function_exists( /* polyfill */ 'array_first' ) ) { " . F . ' }' ], + [ 'f-named', 'ok', 'quiet', "if ( ! function_exists( function: 'array_first' ) ) { " . F . ' }' ], + [ 'f-ver', 'ok', 'quiet', 'if ( PHP_VERSION_ID < 80500 ) { ' . F . ' }' ], + [ 'f-ver-fq', 'ok', 'quiet', 'if ( \\PHP_VERSION_ID < 80500 ) { ' . F . ' }' ], + [ 'f-ver-yoda', 'ok', 'quiet', 'if ( 80500 > PHP_VERSION_ID ) { ' . F . ' }' ], + [ 'f-ver-le', 'ok', 'quiet', 'if ( PHP_VERSION_ID <= 80499 ) { ' . F . ' }' ], + [ 'f-ver-yoda-ge', 'ok', 'quiet', 'if ( 80499 >= PHP_VERSION_ID ) { ' . F . ' }' ], + [ 'f-ver-lower', 'ok', 'quiet', 'if ( PHP_VERSION_ID < 80400 ) { ' . F . ' }' ], + [ 'f-ver-comment', 'ok', 'quiet', 'if ( PHP_VERSION_ID /* x */ < 80500 ) { ' . F . ' }' ], + [ 'f-ver-and', 'ok', 'quiet', "if ( \\PHP_VERSION_ID < 80500 && extension_loaded( 'tokenizer' ) ) { " . F . ' }' ], + [ 'f-vc', 'ok', 'quiet', "if ( version_compare( PHP_VERSION, '8.5', '<' ) ) { " . F . ' }' ], + [ 'f-vc-lt', 'ok', 'quiet', "if ( version_compare( \\PHP_VERSION, '8.5.0', 'lt' ) ) { " . F . ' }' ], + [ 'f-elseif', 'ok', 'quiet', "if ( false ) { } elseif ( ! function_exists( 'array_first' ) ) { " . F . ' }' ], + [ 'f-alt', 'ok', 'quiet', "if ( ! function_exists( 'array_first' ) ) : " . F . ' endif;' ], + [ 'f-nested', 'ok', 'quiet', "if ( ! defined( 'P_X' ) ) { if ( ! function_exists( 'array_first' ) ) { " . F . ' } }' ], + [ 'f-else', 'ok', 'quiet', "if ( function_exists( 'array_first' ) ) { } else { " . F . ' }' ], + [ 'f-else-or', 'ok', 'quiet', "if ( function_exists( 'array_first' ) || ! defined( 'P_X' ) ) { } else { " . F . ' }' ], + [ 'f-else-ver', 'ok', 'quiet', 'if ( PHP_VERSION_ID >= 80500 ) { } else { ' . F . ' }' ], + [ 'f-sfboot', 'ok', 'quiet', "if ( \\PHP_VERSION_ID >= 80500 ) { return; }\nif ( ! function_exists( 'array_first' ) ) { " . F . ' }' ], + [ 'f-ns', 'ok', 'quiet', "namespace P;\n" . F ], + [ 'f-method', 'ok', 'quiet', 'class P_M { function array_first( $a ) { return null; } }' ], + [ 'f-anon', 'ok', 'quiet', '$o = new class { function array_first( $a ) { return null; } };' ], + [ 'f-method-guarded', 'ok', 'quiet', "class P_L { static function load() { if ( ! function_exists( 'array_first' ) ) { " . F . " } } }\nP_L::load();" ], + // Functions: shapes that don't guard. + [ 'f-bare', 'fatal', 'reported', F ], + [ 'f-or', 'fatal', 'reported', "if ( ! function_exists( 'array_first' ) || ! function_exists( 'p_x' ) ) { " . F . ' }' ], + [ 'f-positive', 'fatal', 'reported', "if ( function_exists( 'array_first' ) ) { " . F . ' }' ], + [ 'f-other-name', 'fatal', 'reported', "if ( ! function_exists( 'p_helper' ) ) { " . F . ' }' ], + [ 'f-true', 'fatal', 'reported', 'if ( true ) { ' . F . ' }' ], + [ 'f-defined', 'fatal', 'reported', "if ( ! defined( 'P_X' ) ) { " . F . ' }' ], + [ 'f-ver-not', 'fatal', 'reported', 'if ( ! ( PHP_VERSION_ID < 80500 ) ) { ' . F . ' }' ], + [ 'f-ver-or', 'fatal', 'reported', "if ( PHP_VERSION_ID < 80500 || ! defined( 'P_X' ) ) { " . F . ' }' ], + [ 'f-ver-sum', 'fatal', 'reported', 'if ( PHP_VERSION_ID < 80500 + 100 ) { ' . F . ' }' ], + [ 'f-ver-high', 'fatal', 'reported', 'if ( PHP_VERSION_ID < 80600 ) { ' . F . ' }' ], + [ 'f-ver-le-high', 'fatal', 'reported', 'if ( PHP_VERSION_ID <= 80500 ) { ' . F . ' }' ], + [ 'f-ver-yoda-high', 'fatal', 'reported', 'if ( 80500 >= PHP_VERSION_ID ) { ' . F . ' }' ], + [ 'f-ver-sep', 'fatal', 'reported', 'if ( PHP_VERSION_ID < 90_000 ) { ' . F . ' }' ], + [ 'f-ver-hex', 'fatal', 'reported', 'if ( PHP_VERSION_ID < 0x15000 ) { ' . F . ' }' ], + [ 'f-ver-bin', 'fatal', 'reported', 'if ( PHP_VERSION_ID < 0b10100000000000000 ) { ' . F . ' }' ], + [ 'f-ver-oct', 'fatal', 'reported', 'if ( PHP_VERSION_ID < 0o250000 ) { ' . F . ' }' ], + [ 'f-vc-high', 'fatal', 'reported', "if ( version_compare( PHP_VERSION, '8.5.1', '<' ) ) { " . F . ' }' ], + [ 'f-vc-gt', 'fatal', 'reported', "if ( version_compare( PHP_VERSION, '8.5', '>' ) ) { " . F . ' }' ], + [ 'f-else-not', 'fatal', 'reported', "if ( ! function_exists( 'array_first' ) ) { } else { " . F . ' }' ], + [ 'f-else-and', 'fatal', 'reported', "if ( function_exists( 'array_first' ) && defined( 'P_X' ) ) { } else { " . F . ' }' ], + // A top-level function is declared when PHP compiles the file, before an early return runs. + [ 'f-return-ver', 'fatal', 'reported', "if ( PHP_VERSION_ID >= 80500 ) { return; }\n" . F ], + [ 'f-return-exists', 'fatal', 'reported', "if ( function_exists( 'array_first' ) ) { return; }\n" . F ], + [ 'f-in-function', 'fatal', 'reported', 'function p_boot() { ' . F . " }\np_boot();" ], + [ 'f-in-method', 'fatal', 'reported', 'class P_H { static function load() { ' . F . " } }\nP_H::load();" ], + [ 'f-in-closure', 'fatal', 'reported', 'class P_K { static function load() { $f = function () { ' . F . " }; \$f(); } }\nP_K::load();" ], + // Strict: PHP runs these, but they aren't shapes the grammar accepts. + [ 'f-callable', 'ok', 'reported', "if ( ! is_callable( 'array_first' ) ) { " . F . ' }' ], + [ 'f-ver-sep-ok', 'ok', 'reported', 'if ( PHP_VERSION_ID < 80_500 ) { ' . F . ' }' ], + [ 'f-ver-octal', 'ok', 'reported', 'if ( PHP_VERSION_ID < 0235164 ) { ' . F . ' }' ], + // Classes: an enclosing check, the else of the reverse check, or an early return in the file. + [ 'c-not', 'ok', 'quiet', "if ( ! class_exists( 'NoDiscard' ) ) { " . C . ' }' ], + [ 'c-not-noload', 'ok', 'quiet', "if ( ! class_exists( 'NoDiscard', false ) ) { " . C . ' }' ], + [ 'c-class-const', 'ok', 'quiet', 'if ( ! class_exists( NoDiscard::class ) ) { ' . C . ' }' ], + [ 'c-class-const-fq', 'ok', 'quiet', 'if ( ! class_exists( \\NoDiscard::class ) ) { ' . C . ' }' ], + [ 'c-ver', 'ok', 'quiet', 'if ( \\PHP_VERSION_ID < 80500 ) { ' . C . ' }' ], + [ 'c-else', 'ok', 'quiet', "if ( class_exists( 'NoDiscard' ) ) { } else { " . C . ' }' ], + [ 'c-return', 'ok', 'quiet', "if ( class_exists( 'NoDiscard', false ) ) { return; }\n" . C ], + [ 'c-return-ver', 'ok', 'quiet', "if ( \\PHP_VERSION_ID >= 80500 ) { return; }\n" . C ], + [ 'c-return-yoda', 'ok', 'quiet', "if ( 80500 <= PHP_VERSION_ID ) { return; }\n" . C ], + [ 'c-return-gt', 'ok', 'quiet', "if ( PHP_VERSION_ID > 80499 ) { return; }\n" . C ], + [ 'c-return-vc', 'ok', 'quiet', "if ( version_compare( PHP_VERSION, '8.5', '>=' ) ) { return; }\n" . C ], + [ 'c-return-or', 'ok', 'quiet', "if ( class_exists( 'NoDiscard' ) || defined( 'P_X' ) ) { return; }\n" . C ], + [ 'c-return-alt', 'ok', 'quiet', "if ( class_exists( 'NoDiscard' ) ) :\n\treturn;\nendif;\n" . C ], + [ 'c-interface', 'ok', 'quiet', "if ( ! interface_exists( 'UnitEnum' ) ) { interface UnitEnum {} }" ], + [ 'c-ns', 'ok', 'quiet', "namespace P;\n" . C ], + // Classes: shapes that don't guard. + [ 'c-bare', 'fatal', 'reported', C ], + [ 'c-or', 'fatal', 'reported', "if ( ! class_exists( 'NoDiscard' ) || true ) { " . C . ' }' ], + [ 'c-wrong-check', 'fatal', 'reported', "if ( ! interface_exists( 'NoDiscard' ) ) { " . C . ' }' ], + [ 'c-interface-wrong-check', 'fatal', 'reported', "if ( ! class_exists( 'UnitEnum' ) ) { interface UnitEnum {} }" ], + [ 'c-return-and', 'fatal', 'reported', "if ( class_exists( 'NoDiscard' ) && defined( 'P_X' ) ) { return; }\n" . C ], + [ 'c-return-not', 'fatal', 'reported', "if ( ! class_exists( 'NoDiscard' ) ) { return; }\n" . C ], + [ 'c-return-high', 'fatal', 'reported', "if ( PHP_VERSION_ID >= 80600 ) { return; }\n" . C ], + [ 'c-no-return', 'fatal', 'reported', "if ( class_exists( 'NoDiscard' ) ) { \$x = 1; }\n" . C ], + [ 'c-return-nested', 'fatal', 'reported', "if ( class_exists( 'NoDiscard' ) ) { if ( defined( 'P_X' ) ) { return; } }\n" . C ], + [ 'c-return-after', 'fatal', 'reported', C . "\nif ( class_exists( 'NoDiscard' ) ) { return; }" ], + // PHP declares the function at compile time, so other code can still call it and declare the class. + [ 'c-return-in-function', 'ok', 'reported', "if ( class_exists( 'NoDiscard' ) ) { return; }\nfunction p_load() { " . C . ' }' ], +]; + +if ( 'write' === ( $argv[1] ?? '' ) ) { + foreach ( $rows as list( $id, , , $code ) ) { + file_put_contents( "$argv[2]/$id.php", "&1', $out, $rc ); + $got = 0 === $rc ? 'ok' : 'fatal'; + if ( $got !== $php ) { + echo "$id: PHP " . PHP_VERSION . " says $got, the table $php\n"; + } + $out = []; + } + echo "checked\n"; +} +return $rows; diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index ba6c7b07..9d9b2861 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -446,6 +446,15 @@ lintnames_fixture "$WORK/lintnames" scan lintnames "$WORK/lintnames" php /var/www/htdocs 8.4 600 scan lintnames-80 "$WORK/lintnames" php /var/www/htdocs 8.0 600 +# Guard shapes (tests/guards.php), one file each, at 8.5; PHP 8.5.0 itself says which of them run. +mkdir -p "$WORK/guards/htdocs/g" +docker run --rm --network none --user "$(id -u):$(id -g)" --mount "type=bind,src=$WORK/guards/htdocs/g,dst=/g" \ + --mount "type=bind,src=$HERE/guards.php,dst=/t/guards.php,readonly" --entrypoint php "$IMAGE" /t/guards.php write /g +chmod -R a+rX "$WORK/guards" +scan guards "$WORK/guards" php /var/www/htdocs 8.5 600 +docker run --rm --network none --mount "type=bind,src=$HERE/guards.php,dst=/t/guards.php,readonly" \ + php:8.5.0-cli php /t/guards.php truth > "$RES/guards.truth" 2>&1 || true + # short_open_tag as EE reads it from the site (default off, as in EE's images). shorttag_fixture "$WORK/shorttag" scan shorttag "$WORK/shorttag" php /var/www/htdocs 8.4 600 @@ -497,4 +506,5 @@ chmod -R a+rX "$RES" docker run --rm --network none --read-only --user 33:33 \ --mount "type=bind,src=$RES,dst=/r,readonly" \ --mount "type=bind,src=$HERE/assert.php,dst=/t/assert.php,readonly" \ + --mount "type=bind,src=$HERE/guards.php,dst=/t/guards.php,readonly" \ --entrypoint php "$IMAGE" /t/assert.php /r From 2cb69cafcc56763f4386e91ba8dada9e57c24f4f Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 08:08:21 +0530 Subject: [PATCH 40/80] feat(compat-scanner): know the names PHP 8.0 and its date extension added The native tables started at 8.1, so for a move to 8.0 a global class named like one of 8.0's (ValueError, Stringable, WeakMap, ...) or an 8.0 function declared in a block or another function's body (str_contains() in an include guard) gave no finding, though PHP 8.0 dies on it. They also lacked the nine Date* classes PHP 8.3 added to the date extension, which is always compiled in. Added, each checked in php-src and in the get_declared_*() diff of the official php:7.4/8.0 (and 8.2/8.3) CLI images, and confirmed fatal to declare from that version on: - functions (8.0): fdiv, get_debug_type, get_resource_id, preg_last_error_msg, str_contains, str_ends_with, str_starts_with; - classes (8.0): InternalIterator, ReflectionAttribute, ReflectionUnionType, UnhandledMatchError, ValueError, WeakMap, and the interface Stringable; - classes (8.3): DateError, DateException, DateInvalidOperationException, DateInvalidTimeZoneException, DateMalformedIntervalStringException, DateMalformedPeriodStringException, DateMalformedStringException, DateObjectError, DateRangeError. Attribute (8.0) stays out: symfony/polyfill-php80 declares it unguarded in a stub the autoloader loads only where the class is missing, so a row would make every site vendoring it "not safe". --- compat-scanner/src/native-classes.php | 78 +++++++++++++++---------- compat-scanner/src/native-functions.php | 11 +++- compat-scanner/tests/assert.php | 6 ++ compat-scanner/tests/fixture.sh | 17 ++++++ compat-scanner/tests/run.sh | 4 ++ 5 files changed, 83 insertions(+), 33 deletions(-) diff --git a/compat-scanner/src/native-classes.php b/compat-scanner/src/native-classes.php index b0f33276..b1b202c5 100644 --- a/compat-scanner/src/native-classes.php +++ b/compat-scanner/src/native-classes.php @@ -1,34 +1,50 @@ [ '8.1', 'interface' ], - 'fiber' => [ '8.1', 'class' ], - 'fibererror' => [ '8.1', 'class' ], - 'reflectionenum' => [ '8.1', 'class' ], - 'reflectionenumbackedcase' => [ '8.1', 'class' ], - 'reflectionenumunitcase' => [ '8.1', 'class' ], - 'reflectionfiber' => [ '8.1', 'class' ], - 'reflectionintersectiontype' => [ '8.1', 'class' ], - 'returntypewillchange' => [ '8.1', 'class' ], - 'unitenum' => [ '8.1', 'interface' ], - 'allowdynamicproperties' => [ '8.2', 'class' ], - 'sensitiveparameter' => [ '8.2', 'class' ], - 'sensitiveparametervalue' => [ '8.2', 'class' ], - 'override' => [ '8.3', 'class' ], - 'deprecated' => [ '8.4', 'class' ], - 'propertyhooktype' => [ '8.4', 'enum' ], - 'reflectionconstant' => [ '8.4', 'class' ], - 'requestparsebodyexception' => [ '8.4', 'class' ], - 'roundingmode' => [ '8.4', 'enum' ], - 'streambucket' => [ '8.4', 'class' ], - 'delayedtargetvalidation' => [ '8.5', 'class' ], - 'nodiscard' => [ '8.5', 'class' ], - 'sortdirection' => [ '8.6', 'enum' ], - 'streamerror' => [ '8.6', 'class' ], - 'streamerrorcode' => [ '8.6', 'enum' ], - 'streamerrormode' => [ '8.6', 'enum' ], - 'streamerrorstore' => [ '8.6', 'enum' ], - 'streamexception' => [ '8.6', 'class' ], - 'streampollhandle' => [ '8.6', 'class' ], + 'internaliterator' => [ '8.0', 'class' ], + 'reflectionattribute' => [ '8.0', 'class' ], + 'reflectionuniontype' => [ '8.0', 'class' ], + 'stringable' => [ '8.0', 'interface' ], + 'unhandledmatcherror' => [ '8.0', 'class' ], + 'valueerror' => [ '8.0', 'class' ], + 'weakmap' => [ '8.0', 'class' ], + 'backedenum' => [ '8.1', 'interface' ], + 'fiber' => [ '8.1', 'class' ], + 'fibererror' => [ '8.1', 'class' ], + 'reflectionenum' => [ '8.1', 'class' ], + 'reflectionenumbackedcase' => [ '8.1', 'class' ], + 'reflectionenumunitcase' => [ '8.1', 'class' ], + 'reflectionfiber' => [ '8.1', 'class' ], + 'reflectionintersectiontype' => [ '8.1', 'class' ], + 'returntypewillchange' => [ '8.1', 'class' ], + 'unitenum' => [ '8.1', 'interface' ], + 'allowdynamicproperties' => [ '8.2', 'class' ], + 'sensitiveparameter' => [ '8.2', 'class' ], + 'sensitiveparametervalue' => [ '8.2', 'class' ], + 'override' => [ '8.3', 'class' ], + 'dateerror' => [ '8.3', 'class' ], + 'dateexception' => [ '8.3', 'class' ], + 'dateinvalidoperationexception' => [ '8.3', 'class' ], + 'dateinvalidtimezoneexception' => [ '8.3', 'class' ], + 'datemalformedintervalstringexception' => [ '8.3', 'class' ], + 'datemalformedperiodstringexception' => [ '8.3', 'class' ], + 'datemalformedstringexception' => [ '8.3', 'class' ], + 'dateobjecterror' => [ '8.3', 'class' ], + 'daterangeerror' => [ '8.3', 'class' ], + 'deprecated' => [ '8.4', 'class' ], + 'propertyhooktype' => [ '8.4', 'enum' ], + 'reflectionconstant' => [ '8.4', 'class' ], + 'requestparsebodyexception' => [ '8.4', 'class' ], + 'roundingmode' => [ '8.4', 'enum' ], + 'streambucket' => [ '8.4', 'class' ], + 'delayedtargetvalidation' => [ '8.5', 'class' ], + 'nodiscard' => [ '8.5', 'class' ], + 'sortdirection' => [ '8.6', 'enum' ], + 'streamerror' => [ '8.6', 'class' ], + 'streamerrorcode' => [ '8.6', 'enum' ], + 'streamerrormode' => [ '8.6', 'enum' ], + 'streamerrorstore' => [ '8.6', 'enum' ], + 'streamexception' => [ '8.6', 'class' ], + 'streampollhandle' => [ '8.6', 'class' ], ]; diff --git a/compat-scanner/src/native-functions.php b/compat-scanner/src/native-functions.php index 373da31c..08e09e35 100644 --- a/compat-scanner/src/native-functions.php +++ b/compat-scanner/src/native-functions.php @@ -1,7 +1,14 @@ '8.0', + 'get_debug_type' => '8.0', + 'get_resource_id' => '8.0', + 'preg_last_error_msg' => '8.0', + 'str_contains' => '8.0', + 'str_ends_with' => '8.0', + 'str_starts_with' => '8.0', 'array_is_list' => '8.1', 'enum_exists' => '8.1', 'fsync' => '8.1', diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 83c10b66..5cf78601 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1062,6 +1062,12 @@ function counts( string $name ): array { eq( [ $wrong, report( 'guards' )['not_checked'] ?? null ], [ [], [] ], 'guards: each shape reported exactly as tests/guards.php says' ); eq( trim( raw( 'guards.truth' ) ), 'checked', 'guards: PHP 8.5.0 runs exactly the shapes tests/guards.php says it runs' ); +// PHP 8.0's names from 8.0 on, the date extension's 8.3 classes from 8.3; not Attribute, which symfony/polyfill-php80 declares unguarded. +$nt80 = [ 'other:::contains.php', 'other:::starts.php', 'other:::stringable.php', 'other:::valueerror.php' ]; +foreach ( [ '7.4' => [], '8.0' => $nt80, '8.3' => array_merge( [ 'other:::contains.php', 'other:::dateerror.php' ], array_slice( $nt80, 1 ) ) ] as $v => $want ) { + eq( finding_files( report( "nativetables-$v" ) ), $want, "nativetables-$v: names native in the target, declared unguarded" ); +} + eq( [ counts( 'shorttag' ), finding_files( report( 'shorttag' ) ) ], [ [ 'ok', true, 0, 2, 0 ], [] ], 'shorttag: with short tags off, `\n' > "$h/views/short.tpl" chmod -R a+rX "$1" } + +# nativetables_fixture : a php site declaring names PHP added in 8.0 and 8.3 where nothing guards them: classes +# and an interface at the top, functions in an include guard and in another function's body; and a class Attribute. +nativetables_fixture() { + local h="$1/htdocs" + php_file "$h/valueerror.php" 'class ValueError extends Exception {}' + php_file "$h/stringable.php" 'interface Stringable {}' + php_file "$h/dateerror.php" 'class DateError extends Error {}' + php_file "$h/contains.php" 'if ( ! defined( "P_HELPERS" ) ) { + function str_contains( $h, $n ) { return false; } +}' + php_file "$h/starts.php" 'function p_boot() { + function str_starts_with( $h, $n ) { return false; } +}' + php_file "$h/attribute.php" 'class Attribute { public $name; }' + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 9d9b2861..d3d515cd 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -455,6 +455,10 @@ scan guards "$WORK/guards" php /var/www/htdocs 8.5 600 docker run --rm --network none --mount "type=bind,src=$HERE/guards.php,dst=/t/guards.php,readonly" \ php:8.5.0-cli php /t/guards.php truth > "$RES/guards.truth" 2>&1 || true +# Names PHP added in 8.0 and 8.3, declared unguarded. +nativetables_fixture "$WORK/nativetables" +for v in 7.4 8.0 8.3; do scan "nativetables-$v" "$WORK/nativetables" php /var/www/htdocs "$v" 600; done + # short_open_tag as EE reads it from the site (default off, as in EE's images). shorttag_fixture "$WORK/shorttag" scan shorttag "$WORK/shorttag" php /var/www/htdocs 8.4 600 From c4bf1a6daca5c78f500bf93d889445986f4762de Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 08:11:24 +0530 Subject: [PATCH 41/80] fix(compat-scanner): no errors for polyfill files PHP never runs on the target symfony/polyfill made every site that vendors it "not safe": - its php82, php84 and php85 stubs (`namespace Random;`, `Pdo`, `Filter`) drew PHPCompatibility's ReservedNames error from the version that reserved the namespace on, though each declares its class only inside `if ( \PHP_VERSION_ID < 80200 )` and the like, so on those versions it runs nothing (and the classmap autoloader never loads it, as the class exists). The same happens with v3.11.1's scanner; - polyfill-uuid's bootstrap85.php uses PHP 8.5 syntax, so the lint failed it at targets up to 8.4, though bootstrap80.php requires it only inside `if ( \PHP_VERSION_ID >= 80500 )`. This one came with the syntax lint. Now: - a file whose code past its namespace, use and declare statements is only if blocks whose condition (or a top-level `&&` operand of it) holds below the target, by the guard grammar of the NativeDeclared sniffs, runs nothing there: a new sniff marks it and the report drops its findings. Only from target 8.0 on, where the lint checks how PHP parses it; - a file that fails the lint is checked by PHPCS instead when the files beside it name it only in `if ( \PHP_VERSION_ID >= N ) { require __DIR__ . '/name'; }` with N above the target. Look-alikes still give errors: a reserved namespace declaring a name unguarded, a stub gated a version too late, and the same bootstrap85.php required unconditionally or from 8.4. The fixture uses the real polyfill files (symfony/polyfill v1.44.0, MIT, license included). Above the scanner's PHP (8.5, 8.6) bootstrap85.php stays "can't confirm", as any file in syntax PHP 8.4 can't parse. Two native fixture files are now quiet where the target skips their only block (stublate.php from 8.4, verhigh.php at 8.6), which is what PHP does there. --- compat-scanner/bin/compat-scanner.php | 46 ++++++ .../CompatScanner/Sniffs/Files/InertSniff.php | 53 +++++++ compat-scanner/src/LinesReport.php | 7 + compat-scanner/tests/assert.php | 30 +++- compat-scanner/tests/fixture.sh | 21 +++ compat-scanner/tests/run.sh | 4 + compat-scanner/tests/symfony-polyfill/LICENSE | 19 +++ .../Resources/stubs/Random/Engine.php | 19 +++ .../Resources/stubs/Pdo/Mysql.php | 140 ++++++++++++++++++ .../stubs/Filter/FilterException.php | 18 +++ .../polyfill-uuid/bootstrap.php | 109 ++++++++++++++ .../polyfill-uuid/bootstrap80.php | 105 +++++++++++++ .../polyfill-uuid/bootstrap85.php | 16 ++ 13 files changed, 584 insertions(+), 3 deletions(-) create mode 100644 compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php create mode 100644 compat-scanner/tests/symfony-polyfill/LICENSE create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-php82/Resources/stubs/Random/Engine.php create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/Pdo/Mysql.php create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-php85/Resources/stubs/Filter/FilterException.php create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap.php create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap80.php create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap85.php diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 58b4a2e7..f07d2620 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -2322,6 +2322,9 @@ private function lint( array $batch ): array { } if ( 0 !== $res['rc'] ) { $result = $this->lintResult( $res, $real ); + if ( is_array( $result ) && $this->loadedOnlyAbove( $real ) ) { + continue; // PHP never parses it on the target, so PHPCS checks it as usual. + } // Not named as code (a `.stub`, a template): the file may never run as PHP, so its failure can't prove a break. $failed[ $k ] = ! $batch[ $k ]['code'] && is_array( $result ) ? 'php_tag' : $result; } @@ -2329,6 +2332,29 @@ private function lint( array $batch ): array { return $failed; } + /** + * Whether the files beside it load a file only above the target: every string naming it there is in a + * `if ( \PHP_VERSION_ID >= N ) { require __DIR__ . '/name'; }` with N above the target, as Symfony's polyfills load bootstrap85.php. + */ + private function loadedOnlyAbove( string $real ): bool { + list( $major, $minor ) = explode( '.', $this->cfg['version'] ); + $target = $major * 10000 + $minor * 100; + $name = preg_quote( basename( $real ), '/' ); + $load = '(?:return )?(?:require|include)(?:_once)? __DIR__ \. ([\'"])\/' . $name . '\2 ; \}'; + $gated = 0; + foreach ( (array) $this->readDir( dirname( $real ) ) as $sibling ) { + $code = $this->isPhpName( $sibling ) ? code_words( dirname( $real ) . '/' . $sibling ) : ''; + $all = preg_match_all( '/[\'"][^\'"]*\b' . $name . '[\'"]/', $code ); + preg_match_all( '/\bif \( \\\\?PHP_VERSION_ID >= ([1-9][0-9]*) \) \{ ' . $load . '/', $code, $m ); + $above = count( array_filter( $m[1], static function ( $n ) use ( $target ) { return (int) $n > $target; } ) ); + if ( $above !== $all ) { + return false; + } + $gated += $above; + } + return $gated > 0; + } + private function lintRun( array $paths, float $cap ): array { $err = $this->work . '/lint.err'; $args = [ '-d', 'memory_limit=' . $this->cfg['retry_memory'], '-d', 'display_errors=stderr', '-d', 'log_errors=0' ]; @@ -2901,6 +2927,26 @@ function native_since(): array { return $since; } +/** A code file's tokens, without whitespace and comments, joined by single spaces; '' when it can't be read or is over 1 MiB. */ +function code_words( string $path ): string { + $fh = open_regular( $path ); + if ( null === $fh ) { + return ''; + } + $code = (string) fread( $fh, 1048577 ); + fclose( $fh ); + if ( strlen( $code ) > 1048576 ) { + return ''; + } + $words = []; + foreach ( token_get_all( $code ) as $token ) { + if ( ! is_array( $token ) || ! in_array( $token[0], [ T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ], true ) ) { + $words[] = is_array( $token ) ? $token[1] : $token; + } + } + return implode( ' ', $words ); +} + /** major.minor of a WordPress version, as EE's support table names branches. */ function wp_branch( string $version ): string { return preg_match( '/^\d+\.\d+/', $version, $m ) ? $m[0] : ''; diff --git a/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php new file mode 100644 index 00000000..fb53bd25 --- /dev/null +++ b/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php @@ -0,0 +1,53 @@ +numTokens; + } + $tokens = $phpcsFile->getTokens(); + $below = [ 'since' => $target, 'checks' => [], 'name' => '' ]; + $blocks = 0; + for ( $i = $this->next( $phpcsFile, 0 ); false !== $i; $i = $this->next( $phpcsFile, $i ) ) { + $code = $tokens[ $i ]['code']; + if ( in_array( $code, [ T_NAMESPACE, T_USE, T_DECLARE ], true ) && ! isset( $tokens[ $i ]['scope_opener'] ) ) { + $i = $phpcsFile->findNext( T_SEMICOLON, $i + 1 ); + } elseif ( T_IF === $code && isset( $tokens[ $i ]['scope_closer'] ) && $this->holds( $phpcsFile, $i, $below, false ) ) { + $i = $tokens[ $i ]['scope_closer']; + $blocks++; + } elseif ( T_CLOSE_TAG !== $code ) { + return $phpcsFile->numTokens; + } + if ( false === $i ) { + return $phpcsFile->numTokens; + } + } + if ( $blocks > 0 ) { + $phpcsFile->addWarning( 'Runs nothing on PHP %s', 0, 'Found', [ $target ] ); + } + return $phpcsFile->numTokens; + } + + /** @return int|false The next token after $i that isn't whitespace or a comment. */ + private function next( File $phpcsFile, int $i ) { + return $phpcsFile->findNext( Tokens::EMPTY_TOKENS, $i + 1, null, true ); + } +} diff --git a/compat-scanner/src/LinesReport.php b/compat-scanner/src/LinesReport.php index 81e31b6e..556cd481 100644 --- a/compat-scanner/src/LinesReport.php +++ b/compat-scanner/src/LinesReport.php @@ -25,6 +25,7 @@ class LinesReport implements Report { public function generateFileReport( array $report, File $phpcsFile, bool $showSources = false, int $width = 80 ) { $count = 0; $unparseable = 0; + $inert = false; foreach ( $report['messages'] as $columns ) { foreach ( $columns as $list ) { foreach ( $list as $message ) { @@ -32,9 +33,15 @@ public function generateFileReport( array $report, File $phpcsFile, bool $showSo if ( 0 === strpos( $message['source'], 'Internal.Tokenizer.Exception' ) || 0 === strpos( $message['source'], 'Internal.Exception' ) ) { $unparseable = 1; } + $inert = $inert || 0 === strpos( $message['source'], 'CompatScanner.Files.Inert.' ); } } } + // A file that runs nothing on the target (CompatScanner.Files.Inert) breaks nothing there. + if ( $inert && ! $unparseable ) { + $count = 0; + $report['messages'] = []; + } echo json_encode( [ 'f' => base64_encode( $report['filename'] ), 'n' => $count, 'u' => $unparseable ] ), "\n"; foreach ( $report['messages'] as $line => $columns ) { diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 5cf78601..178a87fd 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1000,15 +1000,17 @@ function counts( string $name ): array { $always = [ "poly.php:$lint", "polytwice.php:$lint", "strlen.php:$lint", "twice.php:$lint" ]; $csniff = 'CompatScanner.Classes.NativeDeclared.Found'; $class83 = [ "override.php:$csniff", "stublate.php:$csniff", "unitenum.php:$csniff" ]; -$class85 = array_merge( $class83, [ "nodiscard.php:$csniff" ] ); +// A file whose only code is a block the target skips runs nothing there: stublate.php from 8.4, verhigh.php at 8.6. +$class84 = [ "override.php:$csniff", "unitenum.php:$csniff" ]; +$class85 = array_merge( $class84, [ "nodiscard.php:$csniff" ] ); $no_guard = [ "defined.php:$sniff", "iftrue.php:$sniff", "nested.php:$sniff", "nsbrace.php:$sniff", "other.php:$sniff", "try.php:$sniff" ]; // A top-level function is bound when PHP compiles the file, so an early return on the version comes too late. $no_guard = array_merge( $no_guard, [ "earlyver.php:$sniff", "verhigh.php:$sniff" ] ); $by_ver = [ '8.3' => array_merge( $always, $class83 ), - '8.4' => array_merge( [ "find.php:$lint", "legacy.php:$lint" ], $always, $class83 ), + '8.4' => array_merge( [ "find.php:$lint", "legacy.php:$lint" ], $always, $class84 ), '8.5' => array_merge( [ "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always, $no_guard, $class85 ), - '8.6' => array_merge( [ "clamp.php:$sniff", "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always, $no_guard, $class85 ), + '8.6' => array_merge( [ "clamp.php:$sniff", "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always, array_diff( $no_guard, [ "verhigh.php:$sniff" ] ), $class85 ), ]; foreach ( $by_ver as $v => $want ) { sort( $want ); @@ -1068,6 +1070,28 @@ function counts( string $name ): array { eq( finding_files( report( "nativetables-$v" ) ), $want, "nativetables-$v: names native in the target, declared unguarded" ); } +// symfony/polyfill's stubs and bootstrap85.php, which PHP never runs or loads on the target, give no error there; look-alikes do. +$parse = 'CompatScanner.Syntax.ParseError'; +$names = 'PHPCompatibility.Namespaces.ReservedNames.'; +$pf = [ + '8.2' => [ "acme/always/bootstrap85.php:$parse", "acme/random/Engine.php:{$names}randomFound" ], + '8.4' => [ "acme/always/bootstrap85.php:$parse", "acme/from84/bootstrap85.php:$parse", "acme/pdo/Mysql.php:{$names}pdoFound", "acme/random/Engine.php:{$names}randomFound" ], + '8.5' => [ "acme/random/Engine.php:{$names}randomFound" ], +]; +foreach ( $pf as $v => $want ) { + $got = []; + foreach ( comp_of( report( "polyfill-$v" ), 'directory', 'vendor' )['findings'] ?? [] as $f ) { + if ( 'ERROR' === $f['type'] ) { + $got[] = $f['file'] . ':' . $f['source']; + } + } + sort( $got ); + eq( $got, $want, "polyfill-$v: errors only where PHP would load or run the file" ); +} +// Above the scanner's PHP, 8.5 syntax can't be parsed: the known "can't confirm". +$pf85 = array_column( report( 'polyfill-8.5' )['not_checked'] ?? [], 'file' ); +eq( $pf85, [ 'acme/always/bootstrap85.php', 'acme/from84/bootstrap85.php', 'symfony/polyfill-uuid/bootstrap85.php' ], 'polyfill-8.5: bootstrap85.php is unparseable above the scanner\'s PHP' ); + eq( [ counts( 'shorttag' ), finding_files( report( 'shorttag' ) ) ], [ [ 'ok', true, 0, 2, 0 ], [] ], 'shorttag: with short tags off, `: a php site vendoring real symfony/polyfill files (tests/symfony-polyfill, MIT): stubs that +# declare only below a PHP version, and polyfill-uuid's bootstrap85.php, which only PHP 8.5 loads; and look-alikes PHP +# would load: a reserved namespace declaring a native name, a stub gated a version too late, that bootstrap85.php +# required unconditionally or from 8.4. +polyfill_fixture() { + local v="$1/htdocs/vendor" d + mkdir -p "$v/symfony" && cp -R "$HERE/symfony-polyfill/." "$v/symfony/" + php_file "$v/acme/random/Engine.php" 'namespace Random; +class Engine {}' + php_file "$v/acme/pdo/Mysql.php" 'namespace Pdo; +if ( \PHP_VERSION_ID < 80500 ) { + class Mysql {} +}' + for d in always from84; do mkdir -p "$v/acme/$d" && cp "$HERE/symfony-polyfill/polyfill-uuid/bootstrap85.php" "$v/acme/$d/"; done + php_file "$v/acme/always/bootstrap.php" "require __DIR__ . '/bootstrap85.php';" + php_file "$v/acme/from84/bootstrap.php" "if ( \\PHP_VERSION_ID >= 80400 ) { + require __DIR__ . '/bootstrap85.php'; +}" + chmod -R a+rX "$1" +} diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index d3d515cd..09cc4571 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -459,6 +459,10 @@ docker run --rm --network none --mount "type=bind,src=$HERE/guards.php,dst=/t/gu nativetables_fixture "$WORK/nativetables" for v in 7.4 8.0 8.3; do scan "nativetables-$v" "$WORK/nativetables" php /var/www/htdocs "$v" 600; done +# symfony/polyfill files PHP never loads or runs on the target, and look-alikes it would. +polyfill_fixture "$WORK/polyfill" +for v in 8.2 8.4 8.5; do scan "polyfill-$v" "$WORK/polyfill" php /var/www/htdocs "$v" 600; done + # short_open_tag as EE reads it from the site (default off, as in EE's images). shorttag_fixture "$WORK/shorttag" scan shorttag "$WORK/shorttag" php /var/www/htdocs 8.4 600 diff --git a/compat-scanner/tests/symfony-polyfill/LICENSE b/compat-scanner/tests/symfony-polyfill/LICENSE new file mode 100644 index 00000000..6e3afce6 --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-php82/Resources/stubs/Random/Engine.php b/compat-scanner/tests/symfony-polyfill/polyfill-php82/Resources/stubs/Random/Engine.php new file mode 100644 index 00000000..4fc78c8f --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-php82/Resources/stubs/Random/Engine.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Random; + +if (\PHP_VERSION_ID < 80200) { + interface Engine + { + public function generate(): string; + } +} diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/Pdo/Mysql.php b/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/Pdo/Mysql.php new file mode 100644 index 00000000..74c3abde --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/Pdo/Mysql.php @@ -0,0 +1,140 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Pdo; + +use PDO; + +if (\PHP_VERSION_ID < 80400 && \extension_loaded('pdo_mysql')) { + // Feature detection for non-mysqlnd; see also https://www.php.net/manual/en/class.pdo-mysql.php#pdo-mysql.constants.attr-max-buffer-size + if (\defined('PDO::MYSQL_ATTR_MAX_BUFFER_SIZE') && \defined('PDO::MYSQL_ATTR_READ_DEFAULT_FILE') && \defined('PDO::MYSQL_ATTR_READ_DEFAULT_GROUP')) { + class Mysql extends \PDO + { + public const ATTR_COMPRESS = \PDO::MYSQL_ATTR_COMPRESS; + public const ATTR_DIRECT_QUERY = \PDO::MYSQL_ATTR_DIRECT_QUERY; + public const ATTR_FOUND_ROWS = \PDO::MYSQL_ATTR_FOUND_ROWS; + public const ATTR_IGNORE_SPACE = \PDO::MYSQL_ATTR_IGNORE_SPACE; + public const ATTR_INIT_COMMAND = \PDO::MYSQL_ATTR_INIT_COMMAND; + public const ATTR_LOCAL_INFILE = \PDO::MYSQL_ATTR_LOCAL_INFILE; + public const ATTR_LOCAL_INFILE_DIRECTORY = \PHP_VERSION_ID >= 80100 ? \PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY : 1015; + public const ATTR_MAX_BUFFER_SIZE = \PDO::MYSQL_ATTR_MAX_BUFFER_SIZE; + public const ATTR_MULTI_STATEMENTS = \PDO::MYSQL_ATTR_MULTI_STATEMENTS; + public const ATTR_READ_DEFAULT_FILE = \PDO::MYSQL_ATTR_READ_DEFAULT_FILE; + public const ATTR_READ_DEFAULT_GROUP = \PDO::MYSQL_ATTR_READ_DEFAULT_GROUP; + public const ATTR_SERVER_PUBLIC_KEY = \PDO::MYSQL_ATTR_SERVER_PUBLIC_KEY; + public const ATTR_SSL_CA = \PDO::MYSQL_ATTR_SSL_CA; + public const ATTR_SSL_CAPATH = \PDO::MYSQL_ATTR_SSL_CAPATH; + public const ATTR_SSL_CERT = \PDO::MYSQL_ATTR_SSL_CERT; + public const ATTR_SSL_CIPHER = \PDO::MYSQL_ATTR_SSL_CIPHER; + public const ATTR_SSL_KEY = \PDO::MYSQL_ATTR_SSL_KEY; + public const ATTR_USE_BUFFERED_QUERY = \PDO::MYSQL_ATTR_USE_BUFFERED_QUERY; + + public function __construct(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null) + { + parent::__construct($dsn, $username, $password, $options); + + if ('mysql' !== $driver = $this->getAttribute(\PDO::ATTR_DRIVER_NAME)) { + throw new \PDOException(\sprintf('Pdo\Mysql::__construct() cannot be used for connecting to the "%s" driver', $driver)); + } + } + + public static function connect(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null): self + { + try { + return new self($dsn, $username, $password, $options); + } catch (\PDOException $e) { + throw preg_match('/^Pdo\\\\Mysql::__construct\(\) cannot be used for connecting to the "([a-z]+)" driver/', $e->getMessage(), $matches) ? new \PDOException(\sprintf('Pdo\Mysql::connect() cannot be used for connecting to the "%s" driver', $matches[1])) : $e; + } + } + } + } elseif (\defined('PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT')) { + class Mysql extends \PDO + { + public const ATTR_COMPRESS = \PDO::MYSQL_ATTR_COMPRESS; + public const ATTR_DIRECT_QUERY = \PDO::MYSQL_ATTR_DIRECT_QUERY; + public const ATTR_FOUND_ROWS = \PDO::MYSQL_ATTR_FOUND_ROWS; + public const ATTR_IGNORE_SPACE = \PDO::MYSQL_ATTR_IGNORE_SPACE; + public const ATTR_INIT_COMMAND = \PDO::MYSQL_ATTR_INIT_COMMAND; + public const ATTR_LOCAL_INFILE = \PDO::MYSQL_ATTR_LOCAL_INFILE; + public const ATTR_LOCAL_INFILE_DIRECTORY = \PHP_VERSION_ID >= 80100 ? \PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY : 1015; + // public const ATTR_MAX_BUFFER_SIZE = PDO::MYSQL_ATTR_MAX_BUFFER_SIZE; // disabled for mysqlnd + public const ATTR_MULTI_STATEMENTS = \PDO::MYSQL_ATTR_MULTI_STATEMENTS; + // public const ATTR_READ_DEFAULT_FILE = PDO::MYSQL_ATTR_READ_DEFAULT_FILE; // disabled for mysqlnd + // public const ATTR_READ_DEFAULT_GROUP = PDO::MYSQL_ATTR_READ_DEFAULT_GROUP; // disabled for mysqlnd + public const ATTR_SERVER_PUBLIC_KEY = \PDO::MYSQL_ATTR_SERVER_PUBLIC_KEY; + public const ATTR_SSL_CA = \PDO::MYSQL_ATTR_SSL_CA; + public const ATTR_SSL_CAPATH = \PDO::MYSQL_ATTR_SSL_CAPATH; + public const ATTR_SSL_CERT = \PDO::MYSQL_ATTR_SSL_CERT; + public const ATTR_SSL_CIPHER = \PDO::MYSQL_ATTR_SSL_CIPHER; + public const ATTR_SSL_KEY = \PDO::MYSQL_ATTR_SSL_KEY; + public const ATTR_SSL_VERIFY_SERVER_CERT = \PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT; + public const ATTR_USE_BUFFERED_QUERY = \PDO::MYSQL_ATTR_USE_BUFFERED_QUERY; + + public function __construct(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null) + { + parent::__construct($dsn, $username, $password, $options); + + if ('mysql' !== $driver = $this->getAttribute(\PDO::ATTR_DRIVER_NAME)) { + throw new \PDOException(\sprintf('Pdo\Mysql::__construct() cannot be used for connecting to the "%s" driver', $driver)); + } + } + + public static function connect(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null): self + { + try { + return new self($dsn, $username, $password, $options); + } catch (\PDOException $e) { + throw preg_match('/^Pdo\\\\Mysql::__construct\(\) cannot be used for connecting to the "([a-z]+)" driver/', $e->getMessage(), $matches) ? new \PDOException(\sprintf('Pdo\Mysql::connect() cannot be used for connecting to the "%s" driver', $matches[1])) : $e; + } + } + } + } else { + class Mysql extends \PDO + { + public const ATTR_COMPRESS = \PDO::MYSQL_ATTR_COMPRESS; + public const ATTR_DIRECT_QUERY = \PDO::MYSQL_ATTR_DIRECT_QUERY; + public const ATTR_FOUND_ROWS = \PDO::MYSQL_ATTR_FOUND_ROWS; + public const ATTR_IGNORE_SPACE = \PDO::MYSQL_ATTR_IGNORE_SPACE; + public const ATTR_INIT_COMMAND = \PDO::MYSQL_ATTR_INIT_COMMAND; + public const ATTR_LOCAL_INFILE = \PDO::MYSQL_ATTR_LOCAL_INFILE; + public const ATTR_LOCAL_INFILE_DIRECTORY = \PHP_VERSION_ID >= 80100 ? \PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY : 1015; + // public const ATTR_MAX_BUFFER_SIZE = PDO::MYSQL_ATTR_MAX_BUFFER_SIZE; // disabled for mysqlnd + public const ATTR_MULTI_STATEMENTS = \PDO::MYSQL_ATTR_MULTI_STATEMENTS; + // public const ATTR_READ_DEFAULT_FILE = PDO::MYSQL_ATTR_READ_DEFAULT_FILE; // disabled for mysqlnd + // public const ATTR_READ_DEFAULT_GROUP = PDO::MYSQL_ATTR_READ_DEFAULT_GROUP; // disabled for mysqlnd + public const ATTR_SERVER_PUBLIC_KEY = \PDO::MYSQL_ATTR_SERVER_PUBLIC_KEY; + public const ATTR_SSL_CA = \PDO::MYSQL_ATTR_SSL_CA; + public const ATTR_SSL_CAPATH = \PDO::MYSQL_ATTR_SSL_CAPATH; + public const ATTR_SSL_CERT = \PDO::MYSQL_ATTR_SSL_CERT; + public const ATTR_SSL_CIPHER = \PDO::MYSQL_ATTR_SSL_CIPHER; + public const ATTR_SSL_KEY = \PDO::MYSQL_ATTR_SSL_KEY; + public const ATTR_USE_BUFFERED_QUERY = \PDO::MYSQL_ATTR_USE_BUFFERED_QUERY; + + public function __construct(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null) + { + parent::__construct($dsn, $username, $password, $options); + + if ('mysql' !== $driver = $this->getAttribute(\PDO::ATTR_DRIVER_NAME)) { + throw new \PDOException(\sprintf('Pdo\Mysql::__construct() cannot be used for connecting to the "%s" driver', $driver)); + } + } + + public static function connect(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null): self + { + try { + return new self($dsn, $username, $password, $options); + } catch (\PDOException $e) { + throw preg_match('/^Pdo\\\\Mysql::__construct\(\) cannot be used for connecting to the "([a-z]+)" driver/', $e->getMessage(), $matches) ? new \PDOException(\sprintf('Pdo\Mysql::connect() cannot be used for connecting to the "%s" driver', $matches[1])) : $e; + } + } + } + } +} diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-php85/Resources/stubs/Filter/FilterException.php b/compat-scanner/tests/symfony-polyfill/polyfill-php85/Resources/stubs/Filter/FilterException.php new file mode 100644 index 00000000..e3183ef5 --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-php85/Resources/stubs/Filter/FilterException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Filter; + +if (\PHP_VERSION_ID < 80500) { + class FilterException extends \Exception + { + } +} diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap.php b/compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap.php new file mode 100644 index 00000000..98821c21 --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap.php @@ -0,0 +1,109 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Uuid as p; + +if (extension_loaded('uuid')) { + return; +} + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!defined('UUID_VARIANT_NCS')) { + define('UUID_VARIANT_NCS', 0); +} +if (!defined('UUID_VARIANT_DCE')) { + define('UUID_VARIANT_DCE', 1); +} +if (!defined('UUID_VARIANT_MICROSOFT')) { + define('UUID_VARIANT_MICROSOFT', 2); +} +if (!defined('UUID_VARIANT_OTHER')) { + define('UUID_VARIANT_OTHER', 3); +} +if (!defined('UUID_TYPE_DEFAULT')) { + define('UUID_TYPE_DEFAULT', 0); +} +if (!defined('UUID_TYPE_TIME')) { + define('UUID_TYPE_TIME', 1); +} +if (!defined('UUID_TYPE_SECURITY')) { + define('UUID_TYPE_SECURITY', 2); +} +if (!defined('UUID_TYPE_TIME_V6')) { + define('UUID_TYPE_TIME_V6', 6); +} +if (!defined('UUID_TYPE_TIME_V7')) { + define('UUID_TYPE_TIME_V7', 7); +} +if (!defined('UUID_TYPE_VENDOR')) { + define('UUID_TYPE_VENDOR', 8); +} +if (!defined('UUID_TYPE_MD5')) { + define('UUID_TYPE_MD5', 3); +} +if (!defined('UUID_TYPE_DCE')) { + define('UUID_TYPE_DCE', 4); // Deprecated alias +} +if (!defined('UUID_TYPE_NAME')) { + define('UUID_TYPE_NAME', 1); // Deprecated alias +} +if (!defined('UUID_TYPE_RANDOM')) { + define('UUID_TYPE_RANDOM', 4); +} +if (!defined('UUID_TYPE_SHA1')) { + define('UUID_TYPE_SHA1', 5); +} +if (!defined('UUID_TYPE_NULL')) { + define('UUID_TYPE_NULL', -1); +} +if (!defined('UUID_TYPE_INVALID')) { + define('UUID_TYPE_INVALID', -42); +} + +if (!function_exists('uuid_create')) { + function uuid_create($uuid_type = \UUID_TYPE_DEFAULT) { return p\Uuid::uuid_create($uuid_type); } +} +if (!function_exists('uuid_generate_md5')) { + function uuid_generate_md5($uuid_ns, $name) { return p\Uuid::uuid_generate_md5($uuid_ns, $name); } +} +if (!function_exists('uuid_generate_sha1')) { + function uuid_generate_sha1($uuid_ns, $name) { return p\Uuid::uuid_generate_sha1($uuid_ns, $name); } +} +if (!function_exists('uuid_is_valid')) { + function uuid_is_valid($uuid) { return p\Uuid::uuid_is_valid($uuid); } +} +if (!function_exists('uuid_compare')) { + function uuid_compare($uuid1, $uuid2) { return p\Uuid::uuid_compare($uuid1, $uuid2); } +} +if (!function_exists('uuid_is_null')) { + function uuid_is_null($uuid) { return p\Uuid::uuid_is_null($uuid); } +} +if (!function_exists('uuid_type')) { + function uuid_type($uuid) { return p\Uuid::uuid_type($uuid); } +} +if (!function_exists('uuid_variant')) { + function uuid_variant($uuid) { return p\Uuid::uuid_variant($uuid); } +} +if (!function_exists('uuid_time')) { + function uuid_time($uuid) { return p\Uuid::uuid_time($uuid); } +} +if (!function_exists('uuid_mac')) { + function uuid_mac($uuid) { return p\Uuid::uuid_mac($uuid); } +} +if (!function_exists('uuid_parse')) { + function uuid_parse($uuid) { return p\Uuid::uuid_parse($uuid); } +} +if (!function_exists('uuid_unparse')) { + function uuid_unparse($uuid) { return p\Uuid::uuid_unparse($uuid); } +} diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap80.php b/compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap80.php new file mode 100644 index 00000000..3d05e0ce --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap80.php @@ -0,0 +1,105 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Uuid as p; + +if (\PHP_VERSION_ID >= 80500) { + require __DIR__.'/bootstrap85.php'; +} + +if (!defined('UUID_VARIANT_NCS')) { + define('UUID_VARIANT_NCS', 0); +} +if (!defined('UUID_VARIANT_DCE')) { + define('UUID_VARIANT_DCE', 1); +} +if (!defined('UUID_VARIANT_MICROSOFT')) { + define('UUID_VARIANT_MICROSOFT', 2); +} +if (!defined('UUID_VARIANT_OTHER')) { + define('UUID_VARIANT_OTHER', 3); +} +if (!defined('UUID_TYPE_DEFAULT')) { + define('UUID_TYPE_DEFAULT', 0); +} +if (!defined('UUID_TYPE_TIME')) { + define('UUID_TYPE_TIME', 1); +} +if (!defined('UUID_TYPE_SECURITY')) { + define('UUID_TYPE_SECURITY', 2); +} +if (!defined('UUID_TYPE_TIME_V6')) { + define('UUID_TYPE_TIME_V6', 6); +} +if (!defined('UUID_TYPE_TIME_V7')) { + define('UUID_TYPE_TIME_V7', 7); +} +if (!defined('UUID_TYPE_VENDOR')) { + define('UUID_TYPE_VENDOR', 8); +} +if (!defined('UUID_TYPE_MD5')) { + define('UUID_TYPE_MD5', 3); +} +if (!defined('UUID_TYPE_DCE')) { + define('UUID_TYPE_DCE', 4); // Deprecated alias +} +if (!defined('UUID_TYPE_NAME')) { + define('UUID_TYPE_NAME', 1); // Deprecated alias +} +if (!defined('UUID_TYPE_RANDOM')) { + define('UUID_TYPE_RANDOM', 4); +} +if (!defined('UUID_TYPE_SHA1')) { + define('UUID_TYPE_SHA1', 5); +} +if (!defined('UUID_TYPE_NULL')) { + define('UUID_TYPE_NULL', -1); +} +if (!defined('UUID_TYPE_INVALID')) { + define('UUID_TYPE_INVALID', -42); +} + +if (!function_exists('uuid_create')) { + function uuid_create(?int $uuid_type = \UUID_TYPE_DEFAULT): string { return p\Uuid::uuid_create((int) $uuid_type); } +} +if (!function_exists('uuid_generate_md5')) { + function uuid_generate_md5(?string $uuid_ns, ?string $name): string { return p\Uuid::uuid_generate_md5((string) $uuid_ns, (string) $name); } +} +if (!function_exists('uuid_generate_sha1')) { + function uuid_generate_sha1(?string $uuid_ns, ?string $name): string { return p\Uuid::uuid_generate_sha1((string) $uuid_ns, (string) $name); } +} +if (!function_exists('uuid_is_valid')) { + function uuid_is_valid(?string $uuid): bool { return p\Uuid::uuid_is_valid((string) $uuid); } +} +if (!function_exists('uuid_compare')) { + function uuid_compare(?string $uuid1, ?string $uuid2): int { return p\Uuid::uuid_compare((string) $uuid1, (string) $uuid2); } +} +if (!function_exists('uuid_is_null')) { + function uuid_is_null(?string $uuid): bool { return p\Uuid::uuid_is_null((string) $uuid); } +} +if (!function_exists('uuid_type')) { + function uuid_type(?string $uuid): int { return p\Uuid::uuid_type((string) $uuid); } +} +if (!function_exists('uuid_variant')) { + function uuid_variant(?string $uuid): int { return p\Uuid::uuid_variant((string) $uuid); } +} +if (!function_exists('uuid_time')) { + function uuid_time(?string $uuid): int { return p\Uuid::uuid_time((string) $uuid); } +} +if (!function_exists('uuid_mac')) { + function uuid_mac(?string $uuid): string { return p\Uuid::uuid_mac((string) $uuid); } +} +if (!function_exists('uuid_parse')) { + function uuid_parse(?string $uuid): string { return p\Uuid::uuid_parse((string) $uuid); } +} +if (!function_exists('uuid_unparse')) { + function uuid_unparse(?string $uuid): string { return p\Uuid::uuid_unparse((string) $uuid); } +} diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap85.php b/compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap85.php new file mode 100644 index 00000000..ccde3e0b --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-uuid/bootstrap85.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#[Deprecated(message: 'use UUID_TYPE_RANDOM instead')] +const UUID_TYPE_DCE = 4; + +#[Deprecated(message: 'use UUID_TYPE_TIME instead')] +const UUID_TYPE_NAME = 1; From 29f771b833bbdb26845e12104d98c33b553e3239 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 08:16:47 +0530 Subject: [PATCH 42/80] style(compat-scanner): put each comment on one line Joins the comments that the last two rounds of changes wrapped mid-sentence: the scope and old-release docblocks, the bootstrap check's docblock, and the fixture descriptions in tests/fixture.sh. --- compat-scanner/bin/compat-scanner.php | 17 ++++---- compat-scanner/tests/fixture.sh | 62 ++++++++------------------- 2 files changed, 25 insertions(+), 54 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index f07d2620..c469b156 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -584,8 +584,8 @@ private function wpConfig( string $wpDir ): ?string { } /** - * CI/CD layout: the first `current` symlink on the served path, pointing at a direct child of a real `releases/` dir - * next to it (as site-command's backup detects it). Returns the other releases, which aren't scanned. + * CI/CD layout: the first `current` symlink on the served path, pointing at a direct child of a real `releases/` dir beside it. + * Returns the other releases, which aren't scanned. * * @return string[] */ @@ -606,8 +606,8 @@ private function oldReleases( string $publicDir ): array { if ( is_link( $releases ) || ! is_dir( $releases ) || ! $this->inside( $releases ) || dirname( $live ) !== $releases ) { return []; } - // An old release is release-named and holds the index.php nginx serves from the live one; without one there, - // nothing tells a release from a shared/ dir. A release holding the scan path (a stale wp-cli.yml path) is scanned. + // An old release is release-named and holds the index.php nginx serves from the live one (else nothing tells it from shared/). + // A release holding the scan path (a stale wp-cli.yml path) is scanned. $marker = substr( $publicDir, strlen( $path ) ) . '/index.php'; if ( ! is_file( $live . $marker ) ) { return []; @@ -845,9 +845,8 @@ private function scanTop( string $root, array $entries, int $loose, string $pref } /** - * outOfScope(), except that a real directory (not reached through a link) above the scan root or the content root is - * walked: htdocs may link into the app beside it (`htdocs -> project/app/public`), wp-content into a shared/ dir - * holding other code; the roots themselves stay out. + * outOfScope(), except that a real directory (not reached through a link) above the scan root or the content root is walked. + * htdocs may link into the app beside it (`htdocs -> project/app/public`), wp-content into a shared/ dir holding other code. */ private function inScope( string $path, string $real ): bool { $why = $this->scopeWhy( $real ); @@ -2333,8 +2332,8 @@ private function lint( array $batch ): array { } /** - * Whether the files beside it load a file only above the target: every string naming it there is in a - * `if ( \PHP_VERSION_ID >= N ) { require __DIR__ . '/name'; }` with N above the target, as Symfony's polyfills load bootstrap85.php. + * Whether the code beside a file loads it only above the target, as Symfony's polyfills load bootstrap85.php. + * Every string naming it there must sit in `if ( \PHP_VERSION_ID >= N ) { require __DIR__ . '/name'; }`, N above the target. */ private function loadedOnlyAbove( string $real ): bool { list( $major, $minor ) = explode( '.', $this->cfg['version'] ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 2b687a20..7b2650a4 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -960,8 +960,7 @@ phar_fixture() { chmod -R a+rX "$1" } -# lint_fixture : files PHP 8.4 can't parse though PHPCompatibility passes them, also templates with text before -# their tag, and files it can. +# lint_fixture : files PHP 8.4 can't parse though PHPCompatibility passes them, also templates with text before their tag, and files it can. lint_fixture() { local p="$1/htdocs/wp-content/plugins/p" wp_core "$1/htdocs" 6.8.3 @@ -978,8 +977,7 @@ lint_fixture() { chmod -R a+rX "$1" } -# longline_fixture : a php site with a .user.ini and a version.php of one 64 MiB line, a .user.ini whose last -# line, with no line break, is exactly as long as the scanner's line buffer, and a version.php of 48 long version lines. +# longline_fixture : a php site with a .user.ini and a version.php of one 64 MiB line, a .user.ini whose last line, with no line break, is exactly as long as the scanner's line buffer, and a version.php of 48 long version lines. longline_fixture() { local h="$1/htdocs" php_file "$h/index.php" 'echo 1;' @@ -1012,9 +1010,7 @@ userini_fixture() { chmod -R a+rX "$1" } -# coreini_fixture : a WordPress CI/CD site, htdocs/current -> releases/2, with a .user.ini in the live core, in -# the core of an install below it and in the old release (never served), each prepending a file there; and a .user.ini -# link in each core that dangles or leaves /var/www. +# coreini_fixture : a WordPress CI/CD site, htdocs/current -> releases/2, with a .user.ini in the live core, in the core of an install below it and in the old release (never served), each prepending a file there; and a .user.ini link in each core that dangles or leaves /var/www. coreini_fixture() { local h="$1/htdocs" r for r in 1 2; do wp_core "$h/releases/$r" 6.8.3 && php_file "$h/releases/$r/index.php" 'echo 1;'; done @@ -1059,13 +1055,7 @@ history_fixture() { chmod -R a+rX "$1" } -# native_fixture : global functions named like ones PHP added in 8.4, 8.5 and 8.6, unguarded, guarded by -# function_exists() on their name or a PHP_VERSION_ID bound below them (as in a Symfony polyfill bootstrap), in a -# namespace or as a method, or in a block that guards nothing (a braced global namespace, try, if ( true ), an include -# guard, a check on another name or a bound above, another function's body, an early return on the version); classes and -# interfaces named like ones PHP added in 8.1, 8.3 and 8.5, unguarded, guarded by the check that sees them or a -# PHP_VERSION_ID bound below them, by the wrong check or a bound above, or in a namespace; and declarations fatal on -# every version (a built-in, a function declared twice), also after one of a function PHP added in 8.4. +# native_fixture : global functions named like ones PHP added in 8.4, 8.5 and 8.6, unguarded, guarded by function_exists() on their name or a PHP_VERSION_ID bound below them (as in a Symfony polyfill bootstrap), in a namespace or as a method, or in a block that guards nothing (a braced global namespace, try, if ( true ), an include guard, a check on another name or a bound above, another function's body, an early return on the version); classes and interfaces named like ones PHP added in 8.1, 8.3 and 8.5, unguarded, guarded by the check that sees them or a PHP_VERSION_ID bound below them, by the wrong check or a bound above, or in a namespace; and declarations fatal on every version (a built-in, a function declared twice), also after one of a function PHP added in 8.4. native_fixture() { local p="$1/htdocs/wp-content/plugins/p" wp_core "$1/htdocs" 6.8.3 @@ -1174,9 +1164,7 @@ relshared_fixture() { chmod -R a+rX "$1" } -# contentout_fixture : wp-content links out of the WordPress directory, with code beside -# its target: a shared/ dir of a release layout, a dir beside htdocs, a dir inside htdocs, or a mount (-mnt, at -# /mnt/shared in run.sh). +# contentout_fixture : wp-content links out of the WordPress directory, with code beside its target: a shared/ dir of a release layout, a dir beside htdocs, a dir inside htdocs, or a mount (-mnt, at /mnt/shared in run.sh). contentout_fixture() { local a=$1 h="$1/htdocs" c case $2 in @@ -1215,8 +1203,7 @@ contentout_fixture() { chmod -R a+rX "$a" } -# inialias_fixture : a php site whose .user.ini, prepending a file the scan doesn't read, has a code-named hard -# link listed before it. +# inialias_fixture : a php site whose .user.ini, prepending a file the scan doesn't read, has a code-named hard link listed before it. inialias_fixture() { local h="$1/htdocs" php_file "$h/index.php" 'echo 1;' @@ -1246,8 +1233,7 @@ pharslow_fixture() { chmod -R a+rX "$1" } -# burst_fixture : a php site with 400 small files and 2 broken ones, so each batch's lint fails and every file -# of it is linted on its own, one quick run after another. +# burst_fixture : a php site with 400 small files and 2 broken ones, so each batch's lint fails and every file of it is linted on its own, one quick run after another. burst_fixture() { local h="$1/htdocs" i for i in $(seq -w 400); do php_file "$h/lib/f$i.php" "echo '$i';"; done @@ -1256,16 +1242,14 @@ burst_fixture() { chmod -R a+rX "$1" } -# slowlint_fixture : a php site whose only code is a template-named file starting with `: a php site whose only code is a template-named file starting with ` "$1/htdocs/big.tpl" chmod -R a+rX "$1" } -# wpextra_fixture : WordPress in /srv, which run.sh mounts at /srv/wp, and /app/htdocs a -# link to it (dir) or to its public/ (parent, wp-config.php one level up); wp-config.php has an error. +# wpextra_fixture : WordPress in /srv, which run.sh mounts at /srv/wp, and /app/htdocs a link to it (dir) or to its public/ (parent, wp-config.php one level up); wp-config.php has an error. wpextra_fixture() { local w="$1/srv" [ "$2" = parent ] && w="$1/srv/public" @@ -1277,8 +1261,7 @@ wpextra_fixture() { chmod -R a+rX "$1" } -# contentold_fixture : a WordPress CI/CD site, htdocs/current -> releases/3, whose wp-content links into the -# previous release, where a plugin has an error. +# contentold_fixture : a WordPress CI/CD site, htdocs/current -> releases/3, whose wp-content links into the previous release, where a plugin has an error. contentold_fixture() { local h="$1/htdocs" r for r in 2 3; do wp_core "$h/releases/$r" 6.8.3 && php_file "$h/releases/$r/index.php" 'echo 1;'; done @@ -1289,9 +1272,7 @@ each( $a );' chmod -R a+rX "$1" } -# relname_fixture : a php CI/CD site, htdocs/current -> releases/2, whose code requires -# releases/shared/config.php (an error); the releases serve index.html (noindex) or index.php, and shared/ holds an -# index.php stub too (stub). +# relname_fixture : a php CI/CD site, htdocs/current -> releases/2, whose code requires releases/shared/config.php (an error); the releases serve index.html (noindex) or index.php, and shared/ holds an index.php stub too (stub). relname_fixture() { local r="$1/htdocs/releases" n for n in 1 2; do @@ -1304,8 +1285,7 @@ relname_fixture() { chmod -R a+rX "$1" } -# coreout_fixture : /app's wp-admin links to /srv/core, which run.sh mounts from /core (not an extra root), -# holding a .user.ini. +# coreout_fixture : /app's wp-admin links to /srv/core, which run.sh mounts from /core (not an extra root), holding a .user.ini. coreout_fixture() { wp_core "$1/app/htdocs" 6.8.3 rm -rf "$1/app/htdocs/wp-admin" @@ -1315,8 +1295,7 @@ coreout_fixture() { chmod -R a+rX "$1" } -# sparse_fixture : a php site with a 16 GiB sparse .user.ini, or a WordPress install below it -# with a 16 GiB sparse version.php. +# sparse_fixture : a php site with a 16 GiB sparse .user.ini, or a WordPress install below it with a 16 GiB sparse version.php. sparse_fixture() { php_file "$1/htdocs/index.php" 'echo 1;' if [ "$2" = ini ]; then @@ -1328,9 +1307,7 @@ sparse_fixture() { chmod -R a+rX "$1" } -# lintnames_fixture : a php site with files the lint fails: templates and stubs that start with `: a php site with files the lint fails: templates and stubs that start with `: a php site with `: a php site with `: a php site declaring names PHP added in 8.0 and 8.3 where nothing guards them: classes -# and an interface at the top, functions in an include guard and in another function's body; and a class Attribute. +# nativetables_fixture : a php site declaring names PHP added in 8.0 and 8.3 where nothing guards them: classes and an interface at the top, functions in an include guard and in another function's body; and a class Attribute. nativetables_fixture() { local h="$1/htdocs" php_file "$h/valueerror.php" 'class ValueError extends Exception {}' @@ -1375,10 +1350,7 @@ nativetables_fixture() { chmod -R a+rX "$1" } -# polyfill_fixture : a php site vendoring real symfony/polyfill files (tests/symfony-polyfill, MIT): stubs that -# declare only below a PHP version, and polyfill-uuid's bootstrap85.php, which only PHP 8.5 loads; and look-alikes PHP -# would load: a reserved namespace declaring a native name, a stub gated a version too late, that bootstrap85.php -# required unconditionally or from 8.4. +# polyfill_fixture : a php site vendoring real symfony/polyfill files (tests/symfony-polyfill, MIT): stubs that declare only below a PHP version, and polyfill-uuid's bootstrap85.php, which only PHP 8.5 loads; and look-alikes PHP would load: a reserved namespace declaring a native name, a stub gated a version too late, that bootstrap85.php required unconditionally or from 8.4. polyfill_fixture() { local v="$1/htdocs/vendor" d mkdir -p "$v/symfony" && cp -R "$HERE/symfony-polyfill/." "$v/symfony/" From d2d3bd9fcadaf7eb0836eab182d885fbfb956934 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 08:22:10 +0530 Subject: [PATCH 43/80] test(compat-scanner): pull the PHP 8.5.0 image before the guard table's own run On a runner without the image, docker run's pull progress went into the output the test compares, so the check failed though PHP agreed with every row. --- compat-scanner/tests/run.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 09cc4571..b48dadc7 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -452,6 +452,7 @@ docker run --rm --network none --user "$(id -u):$(id -g)" --mount "type=bind,src --mount "type=bind,src=$HERE/guards.php,dst=/t/guards.php,readonly" --entrypoint php "$IMAGE" /t/guards.php write /g chmod -R a+rX "$WORK/guards" scan guards "$WORK/guards" php /var/www/htdocs 8.5 600 +docker pull -q php:8.5.0-cli > /dev/null docker run --rm --network none --mount "type=bind,src=$HERE/guards.php,dst=/t/guards.php,readonly" \ php:8.5.0-cli php /t/guards.php truth > "$RES/guards.truth" 2>&1 || true From 4364daa18438b928a5841e8071809ffe566f97ad Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 08:25:15 +0530 Subject: [PATCH 44/80] fix(compat-scanner): an XML file isn't PHP code where short tags are on With COMPAT_SHORT_OPEN_TAG=1 a bare `: a php site with `: a php site with `\n\n\n' > "$h/short.php" mkdir -p "$h/views" && printf '\n' > "$h/views/short.tpl" + printf '\n\n' > "$h/views/schema.xsd" chmod -R a+rX "$1" } From bacd6fb6903038d7c164e8d915e050be3cc2ed11 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 08:28:31 +0530 Subject: [PATCH 45/80] perf(compat-scanner): read a directory once for the bootstrap check The check whether the code beside a file loads it only above the target re-read every code file of the directory for each file the lint failed, so a flat legacy directory moving to 8.0 (1,000 files the lint fails) took 49 s instead of 25 s. Each directory's code files are now read once, for the code file names their strings end in and the requires gated above the target. --- compat-scanner/bin/compat-scanner.php | 45 ++++++++++++++++++++------- 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index d8be0a39..32c98d7b 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -156,6 +156,8 @@ final class Scanner { private $skippedDirs = []; /** @var string A PHP open tag, as a regex. */ private $openTag; + /** @var array loadsIn() of each directory read, by path. */ + private $loads = []; /** @var string What sniff() matches in a file's first SNIFF_BYTES, as one regex (no NUL anywhere, then an open tag), for the manifest. */ private $sniffRegex; @@ -2336,22 +2338,41 @@ private function lint( array $batch ): array { * Every string naming it there must sit in `if ( \PHP_VERSION_ID >= N ) { require __DIR__ . '/name'; }`, N above the target. */ private function loadedOnlyAbove( string $real ): bool { + $dir = dirname( $real ); + $name = basename( $real ); + // Read once per directory: a flat legacy dir can have hundreds of files the lint fails. + $this->loads[ $dir ] = $this->loads[ $dir ] ?? $this->loadsIn( $dir ); + $above = 0; + $all = 0; + foreach ( $this->loads[ $dir ] as $file => $names ) { + if ( $file !== $name && isset( $names[ $name ] ) ) { + $above += $names[ $name ][0]; + $all += $names[ $name ][1]; + } + } + return $above > 0 && $above === $all; + } + + /** @return array> Per code file here, the code file names its strings end in: [ required only above the target, all ]. */ + private function loadsIn( string $dir ): array { list( $major, $minor ) = explode( '.', $this->cfg['version'] ); $target = $major * 10000 + $minor * 100; - $name = preg_quote( basename( $real ), '/' ); - $load = '(?:return )?(?:require|include)(?:_once)? __DIR__ \. ([\'"])\/' . $name . '\2 ; \}'; - $gated = 0; - foreach ( (array) $this->readDir( dirname( $real ) ) as $sibling ) { - $code = $this->isPhpName( $sibling ) ? code_words( dirname( $real ) . '/' . $sibling ) : ''; - $all = preg_match_all( '/[\'"][^\'"]*\b' . $name . '[\'"]/', $code ); - preg_match_all( '/\bif \( \\\\?PHP_VERSION_ID >= ([1-9][0-9]*) \) \{ ' . $load . '/', $code, $m ); - $above = count( array_filter( $m[1], static function ( $n ) use ( $target ) { return (int) $n > $target; } ) ); - if ( $above !== $all ) { - return false; + $gate = '/\bif \( \\\\?PHP_VERSION_ID >= ([1-9][0-9]*) \) \{ (?:return )?(?:require|include)(?:_once)? __DIR__ \. ([\'"])\/([^\/\'"]+)\2 ; \}/'; + $loads = []; + foreach ( (array) $this->readDir( $dir ) as $file ) { + $code = $this->isPhpName( $file ) ? code_words( $dir . '/' . $file ) : ''; + preg_match_all( '/[\'"](?:[^\'"]*\/)?([^\/\'"]+)[\'"]/', $code, $strings ); + foreach ( array_filter( $strings[1], [ $this, 'isPhpName' ] ) as $named ) { + $loads[ $file ][ $named ] = [ $loads[ $file ][ $named ][0] ?? 0, ( $loads[ $file ][ $named ][1] ?? 0 ) + 1 ]; + } + preg_match_all( $gate, $code, $gates, PREG_SET_ORDER ); + foreach ( $gates as $m ) { + if ( (int) $m[1] > $target ) { + $loads[ $file ][ $m[3] ][0]++; + } } - $gated += $above; } - return $gated > 0; + return $loads; } private function lintRun( array $paths, float $cap ): array { From 6bf18cbe89707eb1da2d7beb941d950e8fc53903 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 08:30:55 +0530 Subject: [PATCH 46/80] fix(compat-scanner): find every string naming a file in the bootstrap check Since the check read each directory once, it found strings by pairing quotes over the file's tokens joined as text, so a string holding the other quote (`"it's"`) shifted the pairs. An unconditional `require __DIR__ . '/bootstrap85.php'` after such a string went unseen, and the file was trusted as loaded only above the target; the gated require after one was missed the other way. Strings now come from PHP's own string tokens, which also count a name inside a double-quoted string with a variable (`"$dir/bootstrap85.php"`). Tests: both cases beside a copy of polyfill-uuid's bootstrap85.php. --- compat-scanner/bin/compat-scanner.php | 29 +++++++++++++++------------ compat-scanner/tests/assert.php | 12 ++++++++--- compat-scanner/tests/fixture.sh | 11 ++++++++++ 3 files changed, 36 insertions(+), 16 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 32c98d7b..6cb2039a 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -2360,12 +2360,14 @@ private function loadsIn( string $dir ): array { $gate = '/\bif \( \\\\?PHP_VERSION_ID >= ([1-9][0-9]*) \) \{ (?:return )?(?:require|include)(?:_once)? __DIR__ \. ([\'"])\/([^\/\'"]+)\2 ; \}/'; $loads = []; foreach ( (array) $this->readDir( $dir ) as $file ) { - $code = $this->isPhpName( $file ) ? code_words( $dir . '/' . $file ) : ''; - preg_match_all( '/[\'"](?:[^\'"]*\/)?([^\/\'"]+)[\'"]/', $code, $strings ); - foreach ( array_filter( $strings[1], [ $this, 'isPhpName' ] ) as $named ) { - $loads[ $file ][ $named ] = [ $loads[ $file ][ $named ][0] ?? 0, ( $loads[ $file ][ $named ][1] ?? 0 ) + 1 ]; + $tokens = $this->isPhpName( $file ) ? code_tokens( $dir . '/' . $file ) : []; + foreach ( $tokens as list( $id, $text ) ) { + $named = basename( trim( $text, '\'"' ) ); + if ( in_array( $id, [ T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE ], true ) && $this->isPhpName( $named ) ) { + $loads[ $file ][ $named ] = [ $loads[ $file ][ $named ][0] ?? 0, ( $loads[ $file ][ $named ][1] ?? 0 ) + 1 ]; + } } - preg_match_all( $gate, $code, $gates, PREG_SET_ORDER ); + preg_match_all( $gate, implode( ' ', array_column( $tokens, 1 ) ), $gates, PREG_SET_ORDER ); foreach ( $gates as $m ) { if ( (int) $m[1] > $target ) { $loads[ $file ][ $m[3] ][0]++; @@ -2947,24 +2949,25 @@ function native_since(): array { return $since; } -/** A code file's tokens, without whitespace and comments, joined by single spaces; '' when it can't be read or is over 1 MiB. */ -function code_words( string $path ): string { +/** @return array A code file's tokens without whitespace and comments; [] when it can't be read or is over 1 MiB. */ +function code_tokens( string $path ): array { $fh = open_regular( $path ); if ( null === $fh ) { - return ''; + return []; } $code = (string) fread( $fh, 1048577 ); fclose( $fh ); if ( strlen( $code ) > 1048576 ) { - return ''; + return []; } - $words = []; + $tokens = []; foreach ( token_get_all( $code ) as $token ) { - if ( ! is_array( $token ) || ! in_array( $token[0], [ T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ], true ) ) { - $words[] = is_array( $token ) ? $token[1] : $token; + $token = is_array( $token ) ? $token : [ $token, $token ]; + if ( ! in_array( $token[0], [ T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ], true ) ) { + $tokens[] = [ $token[0], $token[1] ]; } } - return implode( ' ', $words ); + return $tokens; } /** major.minor of a WordPress version, as EE's support table names branches. */ diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index a62f03ef..1176225d 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1074,8 +1074,14 @@ function counts( string $name ): array { $parse = 'CompatScanner.Syntax.ParseError'; $names = 'PHPCompatibility.Namespaces.ReservedNames.'; $pf = [ - '8.2' => [ "acme/always/bootstrap85.php:$parse", "acme/random/Engine.php:{$names}randomFound" ], - '8.4' => [ "acme/always/bootstrap85.php:$parse", "acme/from84/bootstrap85.php:$parse", "acme/pdo/Mysql.php:{$names}pdoFound", "acme/random/Engine.php:{$names}randomFound" ], + '8.2' => [ "acme/always/bootstrap85.php:$parse", "acme/quoted/bootstrap85.php:$parse", "acme/random/Engine.php:{$names}randomFound" ], + '8.4' => [ + "acme/always/bootstrap85.php:$parse", + "acme/from84/bootstrap85.php:$parse", + "acme/pdo/Mysql.php:{$names}pdoFound", + "acme/quoted/bootstrap85.php:$parse", + "acme/random/Engine.php:{$names}randomFound", + ], '8.5' => [ "acme/random/Engine.php:{$names}randomFound" ], ]; foreach ( $pf as $v => $want ) { @@ -1090,7 +1096,7 @@ function counts( string $name ): array { } // Above the scanner's PHP, 8.5 syntax can't be parsed: the known "can't confirm". $pf85 = array_column( report( 'polyfill-8.5' )['not_checked'] ?? [], 'file' ); -eq( $pf85, [ 'acme/always/bootstrap85.php', 'acme/from84/bootstrap85.php', 'symfony/polyfill-uuid/bootstrap85.php' ], 'polyfill-8.5: bootstrap85.php is unparseable above the scanner\'s PHP' ); +eq( $pf85, [ 'acme/always/bootstrap85.php', 'acme/from84/bootstrap85.php', 'acme/quoted/bootstrap85.php', 'acme/quotedgate/bootstrap85.php', 'symfony/polyfill-uuid/bootstrap85.php' ], 'polyfill-8.5: bootstrap85.php is unparseable above the scanner\'s PHP' ); eq( [ counts( 'shorttag' ), finding_files( report( 'shorttag' ) ) ], [ [ 'ok', true, 0, 2, 0 ], [] ], 'shorttag: with short tags off, `= 80400 ) { require __DIR__ . '/bootstrap85.php'; +}" + # A string with a quote in it before the gated require, and before an ungated one beside it. + for d in quoted quotedgate; do mkdir -p "$v/acme/$d" && cp "$HERE/symfony-polyfill/polyfill-uuid/bootstrap85.php" "$v/acme/$d/"; done + php_file "$v/acme/quoted/gate.php" "if ( \\PHP_VERSION_ID >= 80500 ) { + require __DIR__ . '/bootstrap85.php'; +}" + php_file "$v/acme/quoted/other.php" "\$n = \"it's\"; +require __DIR__ . '/bootstrap85.php';" + php_file "$v/acme/quotedgate/gate.php" "\$n = \"it's\"; +if ( \\PHP_VERSION_ID >= 80500 ) { + require __DIR__ . '/bootstrap85.php'; }" chmod -R a+rX "$1" } From 28af03c41c4e3b77ea528d9735c27558a3d531cd Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 08:55:01 +0530 Subject: [PATCH 47/80] fix(compat-scanner): lint with each target's PHP and honour guards around flagged code Lint each target with its own PHP. The image now ships the official PHP 8.0, 8.1, 8.2, 8.3, 8.5 and 8.6 CLI binaries (8.0 and 8.1 with their own libraries, found through the binary's RPATH) beside the scanner's 8.4, and `php -l` runs the target's binary with no ini file. This retires the 8.4-lint workarounds: the disable_functions list of later functions, the 8.0 reserved-name mapping and "unparseable above the scanner's PHP". `$GLOBALS = ...` at 8.0, a duplicate static at 8.0-8.2 and `class Readonly` at 8.0 are no longer errors, and polyfill-uuid's bootstrap85.php parses at 8.5 and 8.6. Before 8.3 `php -l` reads only its first file, so 8.0-8.2 lint one file per run. A target from 8.0 up with no binary in the image is a tool error. One guard grammar (CompatScanner\Guard) now serves the NativeDeclared sniffs, the Inert sniff, the report and the bootstrap gate. Version tests are read in one place, as a PHP_VERSION_ID range. version_compare() with named arguments is no test instead of an internal exception. - PHPCompatibility's new/removed function, extension, class and interface findings are dropped inside a block that runs only where that name exists (function_exists(), class_exists(), interface_exists() on it), or only on versions that exclude the target. The else of the reverse test counts too. tests/use-guards.php holds each shape with PHP's own answer. - New class and interface findings are dropped when a scanned file declares that class where the declaration runs on the target (symfony/polyfill-php83's Date* stubs at 8.0-8.2). - The class early-return guard must be a statement of its own whose block is a single return ending before the declaration, with no goto in the file. A conditional return, a guard nested in a braceless if or foreach, `else if`, and a declaration inside the guard block are reported again. - Inert files: the version test must be the condition's first `&&` operand, since operands to its left run. A use/namespace/declare statement ends at a close tag, so code after it is checked. - The bootstrap gate applies only to files in a Composer package (vendor/// of a vendor dir with composer/installed.json or autoload.php), so app code keeps its lint error. Its test must hold only from the next minor on: `>= 80401` loads the file on 8.4. A sibling that is unreadable or over 1 MiB keeps the error. Siblings are read under the scan deadline, and a gate naming a non-code file no longer prints warnings. - Files under symfony/polyfill-*/Resources/stubs/ get no NativeDeclared error: only a classmap loads them, where the native is missing. Attribute is back in the class table, so an app's own unguarded Attribute is reported. - .stub and .tpl files under stubs/ or templates/ in a Composer package are not checked. These are the Laravel and PHPUnit code generator templates, which are filled in and written out, never run. - short_open_tag set in a .user.ini applies to the files in its directory and below, as PHP-FPM reads it. The doc root's value applies to code beside the doc root. The new COMPAT_SHORT_OPEN_TAG_LOCKED=1 says the pool sets it with php_admin_value, and then every .user.ini is ignored. Unless it is locked, files without a code name are sniffed with a bare `//php. +const PHP_DIR = '/opt/php'; // Never PHP templates, so not sniffed: docs, scripts and styles quote ` short_open_tag of the .user.ini files that set it, by their directory as walked. */ + private $shortIni = []; + /** @var bool short_open_tag of the files PHPCS and the lint check now. */ + private $short = false; + /** @var array Lowercase global classes the scanned files declare where that runs on the target. */ + private $declared = []; /** @var array loadsIn() of each directory read, by path. */ private $loads = []; /** @var string What sniff() matches in a file's first SNIFF_BYTES, as one regex (no NUL anywhere, then an open tag), for the manifest. */ @@ -177,7 +188,8 @@ public function __construct( array $cfg ) { $this->start = microtime( true ); $limit = $this->isScan ? $cfg['timeout'] : $cfg['estimate_timeout']; - $tag = $cfg['short_tags'] ? OPEN_TAG_SHORT : OPEN_TAG; + // A .user.ini can turn short tags on for its directory unless the pool locks the setting. + $tag = $cfg['short_tags'] || ! $cfg['short_locked'] ? OPEN_TAG_SHORT : OPEN_TAG; $this->openTag = '/' . $tag . '/i'; $this->sniffRegex = '/\\A(?=[^\\x00]*\\z)[\\s\\S]*?' . $tag . '/i'; $this->timeoutLabel = $limit; @@ -336,7 +348,7 @@ private function userIni( string $path, string $real ): void { if ( null === $fh ) { return; } - $keys = '(auto_(?:prepend|append)_file|zend\.multibyte|zend\.script_encoding)'; + $keys = '(auto_(?:prepend|append)_file|zend\.multibyte|zend\.script_encoding|short_open_tag)'; $unsure = false; foreach ( lines( $fh, $this->ticker() ) as $n => $line ) { if ( null === $line ) { @@ -348,6 +360,11 @@ private function userIni( string $path, string $real ): void { foreach ( explode( "\r", $line ) as $part ) { $value = preg_match( '/^\s*(?:\[[^\]]*\]\s*)*' . $keys . '\s*=(.*)$/i', $part, $m ) ? ini_value( $m[2] ) : ''; $key = strtolower( $m[1] ?? '' ); + if ( 'short_open_tag' === $key ) { + // PHP's boolean: on, yes or true, else the number (an unquoted Off reads as ''). + $this->shortIni[ dirname( $path ) ] = in_array( strtolower( $value ), [ 'on', 'yes', 'true' ], true ) || 0 !== (int) $value; + continue; + } if ( '' === $value || ( 'zend.multibyte' === $key && '0' === $value ) ) { continue; } @@ -381,12 +398,12 @@ private function servedPath(): string { */ private function judgeInstalls(): void { if ( null !== $this->live ) { - $this->installs[] = [ 'dir' => $this->live, 'version' => wp_version( $this->live, $this->ticker() ), 'live' => true ]; + $this->installs[] = [ 'dir' => $this->live, 'version' => wp_version( $this->resolve( $this->live . '/wp-includes/version.php' ), $this->ticker() ), 'live' => true ]; } $nested = array_keys( $this->nested ); sort( $nested, SORT_STRING ); foreach ( $nested as $dir ) { - $version = wp_version( $dir, $this->ticker() ); + $version = wp_version( $this->resolve( $dir . '/wp-includes/version.php' ), $this->ticker() ); $this->installs[] = [ 'dir' => $dir, 'version' => $version, 'live' => false ]; if ( in_array( wp_branch( $version ), $this->cfg['wp_supported'], true ) ) { $this->leftOut[] = $dir; @@ -919,6 +936,12 @@ private function visit( string $path, string $name, int $comp ): void { if ( in_array( $ext, NO_SNIFF_EXTENSIONS, true ) || in_array( $ext, BACKUP_EXTENSIONS, true ) ) { return; } + if ( $this->packageTemplate( $path ) ) { + if ( $this->cfg['manifest'] ) { + $this->manifestAdd( 'information', $real ); + } + return; + } $tag = $this->sniff( $real ); if ( null === $tag ) { return; @@ -1296,6 +1319,26 @@ private function isTemplateName( string $name ): bool { } /** `.phar` and the archive forms PHP's phar extension also opens (`.phar.tar`, `.phar.tar.gz`, `.phar.zip`, ...). */ + /** + * A `.stub` or `.tpl` under a `stubs/` or `templates/` dir of a Composer package, as Laravel's and PHPUnit's code + * generators ship them: filled in and written out, never run. + */ + private function packageTemplate( string $path ): bool { + return preg_match( '#/vendor/[^/]+/[^/]+/(?:[^/]+/)*(?:stubs|templates)/(?:[^/]+/)*[^/]+\.(?:stub|tpl)\z#i', $path ) && $this->inPackage( $path ); + } + + /** Whether the path lies in vendor/// of a Composer vendor dir (one holding composer/installed.json or autoload.php). */ + private function inPackage( string $path ): bool { + preg_match_all( '#/vendor/[^/]+/[^/]+/#', $path, $m, PREG_OFFSET_CAPTURE ); + foreach ( $m[0] as list( , $at ) ) { + $vendor = substr( $path, 0, $at ) . '/vendor'; + if ( is_file( $vendor . '/composer/installed.json' ) || is_file( $vendor . '/autoload.php' ) ) { + return true; + } + } + return false; + } + private function isPharName( string $name ): bool { return (bool) preg_match( PHAR_REGEX, $name ); } @@ -1571,6 +1614,12 @@ private function scan(): array { $read = 0; while ( null !== ( $rec = $this->nextFile() ) ) { $read++; + $rec['short'] = $this->shortFor( $rec['path'] ); + // One short_open_tag per run. + if ( $batch && $batch[0]['short'] !== $rec['short'] ) { + $this->runBatch( $batch ); + $batch = []; + } $batch[] = $rec; if ( count( $batch ) >= $this->cfg['batch_size'] ) { $this->runBatch( $batch ); @@ -1647,6 +1696,7 @@ private function prepare( array $batch ): array { */ private function runBatch( array $batch ): void { $this->checkPins(); + $this->short = $batch[0]['short']; $batch = $this->prepare( $batch ); foreach ( $this->lint( $batch ) as $k => $result ) { $batch[ $k ]['lint'] = $result; @@ -1713,6 +1763,28 @@ private function runBatch( array $batch ): void { } } + /** + * short_open_tag for a file, as PHP-FPM applies .user.ini files: the deepest one that sets it from the doc root down to + * the file's directory; for a file outside the doc root, the doc root's, where the requests that load it start. + */ + private function shortFor( string $path ): bool { + $short = $this->cfg['short_tags']; + if ( $this->cfg['short_locked'] || ! $this->shortIni ) { + return $short; + } + $root = is_string( $this->cfg['served'] ) && '' !== $this->cfg['served'] ? $this->cfg['served'] : $this->cfg['path']; + $dir = dirname( $path ); + if ( $dir !== $root && 0 !== strpos( $dir, $root . '/' ) ) { + return $this->shortIni[ $root ] ?? $short; + } + for ( $at = $root; ; $at .= '/' . strtok( substr( $dir, strlen( $at ) + 1 ), '/' ) ) { + $short = $this->shortIni[ $at ] ?? $short; + if ( $at === $dir ) { + return $short; + } + } + } + /** Steps 2 to 4 for one file. */ private function runSingle( array $f ): void { if ( $f['stdin'] && $f['size'] > STDIN_MAX ) { @@ -1861,8 +1933,11 @@ private function record( array $f, ReportReader $reader ): void { } } + foreach ( $block['d'] as $class ) { + $this->declared[ $class ] = true; + } $errors = $warnings = $i = 0; - $buf = [ 'e' => '', 'w' => '' ]; + $buf = [ 'e' => '', 'w' => '', 'p' => '' ]; while ( null !== ( $m = null !== $messages ? ( $messages[ $i++ ] ?? null ) : $reader->message() ) ) { list( $line, , $type, $source, $text ) = $m; if ( 0 === strpos( $source, 'Internal.' ) ) { @@ -1873,7 +1948,11 @@ private function record( array $f, ReportReader $reader ): void { JSON_FLAGS ); $this->addReportBytes( strlen( $entry ) ); - if ( 'ERROR' === $type ) { + if ( isset( $m[5] ) ) { + // A new class the site may declare itself: settled when every file has been read. + $key = 'p'; + $entry = json_encode( [ $m[5], $type, $entry ], JSON_FLAGS ) . "\n"; + } elseif ( 'ERROR' === $type ) { $errors++; $key = 'e'; } else { @@ -2007,6 +2086,9 @@ private function addReportBytes( int $n ): void { private function finish(): array { $this->settlePhars(); $listed = $this->listedComponents(); + foreach ( $listed as $idx ) { + $this->settleClasses( $idx ); + } $errors = $warnings = $checked = $bytes = $withErrors = 0; foreach ( $listed as $idx ) { @@ -2125,6 +2207,33 @@ private function writeReport( array $summary, array $order ): void { } } + /** Keeps a component's new-class findings whose class no scanned file declares where that runs on the target. */ + private function settleClasses( int $idx ): void { + $file = $this->work . "/c$idx.p"; + $in = is_file( $file ) ? fopen( $file, 'rb' ) : null; + if ( false === $in ) { + throw new ToolError( 'could not read the spool' ); + } + $buf = [ 'e' => '', 'w' => '' ]; + while ( null !== $in && false !== ( $line = fgets( $in ) ) ) { + list( $class, $type, $entry ) = json_decode( $line, true ); + if ( ! isset( $this->declared[ $class ] ) ) { + $key = 'ERROR' === $type ? 'e' : 'w'; + $buf[ $key ] .= $entry; + $this->comps[ $idx ][ 'e' === $key ? 'errors' : 'warnings' ]++; + } + } + if ( null !== $in ) { + fclose( $in ); + @unlink( $file ); + } + foreach ( $buf as $key => $data ) { + if ( '' !== $data ) { + $this->append( $this->work . "/c$idx.$key", $data ); + } + } + } + /** Report keys after not_checked: the WordPress installs and, for a caller that sets COMPAT_SERVED, the old releases left out. */ private function reportTail(): array { $tail = [ 'wordpress_installs' => [] ]; @@ -2209,7 +2318,7 @@ private function phpcs( array $paths, string $memory, string $tag, bool $stdin = $cmd = [ PHP_BINARY, '-d', 'memory_limit=' . $memory, '-d', 'display_errors=stderr', '-d', 'log_errors=0', - '-d', 'short_open_tag=' . (int) $this->cfg['short_tags'], + '-d', 'short_open_tag=' . (int) $this->short, PHPCS_BIN, '--standard=' . ( 'php' === $this->cfg['site_type'] ? 'PHPCompatibility' : 'PHPCompatibilityWP' ) . ',' . SNIFFS_DIR, '--runtime-set', 'testVersion', $this->cfg['version'], @@ -2296,8 +2405,9 @@ private function runTimed( array $cmd, float $cap, array $spec, int $fsize = 0 ) } /** - * `php -l` over a batch, then each failing file alone: PHPCompatibility misses some parse errors (`#[` before PHP 8, an unclosed comment). - * Not for targets before 8.0 (PHP 8.4 rejects their syntax), nor for files with text before the tag and no template name. + * `php -l` with the target's PHP over a batch, then each failing file alone: PHPCompatibility misses some parse errors (`#[` + * before PHP 8, an unclosed comment). Not for targets before 8.0 (none in the image), nor files with text before the tag and + * no template name. * * @return array By batch key, the files that fail: [ line, message ] or a not_checked reason. */ @@ -2311,8 +2421,12 @@ private function lint( array $batch ): array { if ( ! $paths || version_compare( $this->cfg['version'], '8.0', '<' ) ) { return []; } - $res = $this->lintRun( array_values( $paths ), (float) $this->cfg['file_timeout'] ); - if ( 0 === $res['rc'] ) { + if ( ! is_file( $this->lintPhp() ) ) { + throw new ToolError( 'no PHP ' . $this->cfg['version'] . ' in the image to lint with' ); + } + // Before 8.3 `php -l` reads only its first file, so each file is linted alone. + $batched = version_compare( $this->cfg['version'], '8.3', '>=' ); + if ( $batched && 0 === $this->lintRun( array_values( $paths ), (float) $this->cfg['file_timeout'] )['rc'] ) { return []; } $failed = []; @@ -2323,7 +2437,7 @@ private function lint( array $batch ): array { } if ( 0 !== $res['rc'] ) { $result = $this->lintResult( $res, $real ); - if ( is_array( $result ) && $this->loadedOnlyAbove( $real ) ) { + if ( is_array( $result ) && $this->loadedOnlyAbove( $real, $batch[ $k ]['path'] ) ) { continue; // PHP never parses it on the target, so PHPCS checks it as usual. } // Not named as code (a `.stub`, a template): the file may never run as PHP, so its failure can't prove a break. @@ -2334,71 +2448,98 @@ private function lint( array $batch ): array { } /** - * Whether the code beside a file loads it only above the target, as Symfony's polyfills load bootstrap85.php. - * Every string naming it there must sit in `if ( \PHP_VERSION_ID >= N ) { require __DIR__ . '/name'; }`, N above the target. + * Whether the code beside a file in a Composer package loads it only above the target, as Symfony's polyfills load bootstrap85.php. + * Every string naming it there must sit in `if ( ) { [return] require __DIR__ . '/name'; }`, the test + * holding only above the target; a code file beside it that can't be read may name it too. */ - private function loadedOnlyAbove( string $real ): bool { + private function loadedOnlyAbove( string $real, string $path ): bool { + // App code may load it from anywhere; a package is loaded through its own files. + if ( ! $this->inPackage( $path ) ) { + return false; + } $dir = dirname( $real ); $name = basename( $real ); // Read once per directory: a flat legacy dir can have hundreds of files the lint fails. - $this->loads[ $dir ] = $this->loads[ $dir ] ?? $this->loadsIn( $dir ); + if ( ! array_key_exists( $dir, $this->loads ) ) { + $this->loads[ $dir ] = $this->loadsIn( $dir, $path ); + } $above = 0; $all = 0; - foreach ( $this->loads[ $dir ] as $file => $names ) { + foreach ( (array) $this->loads[ $dir ] as $file => $names ) { if ( $file !== $name && isset( $names[ $name ] ) ) { $above += $names[ $name ][0]; $all += $names[ $name ][1]; } } - return $above > 0 && $above === $all; + return null !== $this->loads[ $dir ] && $above > 0 && $above === $all; } - /** @return array> Per code file here, the code file names its strings end in: [ required only above the target, all ]. */ - private function loadsIn( string $dir ): array { - list( $major, $minor ) = explode( '.', $this->cfg['version'] ); - $target = $major * 10000 + $minor * 100; - $gate = '/\bif \( \\\\?PHP_VERSION_ID >= ([1-9][0-9]*) \) \{ (?:return )?(?:require|include)(?:_once)? __DIR__ \. ([\'"])\/([^\/\'"]+)\2 ; \}/'; - $loads = []; + /** @return array>|null Per code file here, the code file names its strings end in: [ loaded only above the target, all ]. */ + private function loadsIn( string $dir, string $path ): ?array { + $above = Guard::target( $this->cfg['version'] )[1]; + $loads = []; foreach ( (array) $this->readDir( $dir ) as $file ) { - $tokens = $this->isPhpName( $file ) ? code_tokens( $dir . '/' . $file ) : []; - foreach ( $tokens as list( $id, $text ) ) { + if ( ! $this->isPhpName( $file ) ) { + continue; + } + if ( microtime( true ) >= $this->deadline ) { + throw $this->timedOutAt( $path ); + } + $tokens = code_tokens( $dir . '/' . $file ); + if ( null === $tokens ) { + return null; + } + foreach ( $tokens as $i => list( $id, $text ) ) { $named = basename( trim( $text, '\'"' ) ); if ( in_array( $id, [ T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE ], true ) && $this->isPhpName( $named ) ) { - $loads[ $file ][ $named ] = [ $loads[ $file ][ $named ][0] ?? 0, ( $loads[ $file ][ $named ][1] ?? 0 ) + 1 ]; - } - } - preg_match_all( $gate, implode( ' ', array_column( $tokens, 1 ) ), $gates, PREG_SET_ORDER ); - foreach ( $gates as $m ) { - if ( (int) $m[1] > $target ) { - $loads[ $file ][ $m[3] ][0]++; + $count = $loads[ $file ][ $named ] ?? [ 0, 0 ]; + + $loads[ $file ][ $named ] = [ $count[0] + (int) $this->gatedAbove( $tokens, $i, $above ), $count[1] + 1 ]; } } } return $loads; } + /** Whether the string at $i is the `'/name'` of `if ( ) { [return] require|include[_once] __DIR__ . '/name'; }`, the test holding only from $above on. */ + private function gatedAbove( array $tokens, int $i, int $above ): bool { + $text = static function ( $at ) use ( $tokens ) { + return $tokens[ $at ][1] ?? ''; + }; + $load = in_array( $tokens[ $i - 3 ][0] ?? null, [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ); + if ( ! $load || ! preg_match( '#^([\'"])/[^/\'"]+\1$#', $text( $i ) ) || [ '.', ';', '}' ] !== [ $text( $i - 1 ), $text( $i + 1 ), $text( $i + 2 ) ] ) { + return false; + } + $j = T_RETURN === ( $tokens[ $i - 4 ][0] ?? null ) ? $i - 5 : $i - 4; + if ( T_DIR !== ( $tokens[ $i - 2 ][0] ?? null ) || [ '{', ')' ] !== [ $text( $j ), $text( $j - 1 ) ] ) { + return false; + } + // Back to the condition's opening parenthesis. + for ( $k = $j - 2, $depth = 0; $k >= 0 && ( '(' !== $text( $k ) || $depth > 0 ); $k-- ) { + $depth += ( ')' === $text( $k ) ) - ( '(' === $text( $k ) ); + } + $range = $k > 0 && T_IF === $tokens[ $k - 1 ][0] ? Guard::range( array_column( array_slice( $tokens, $k + 1, $j - $k - 2 ), 1 ) ) : null; + return null !== $range && $range[0] >= $above; + } + + private function lintPhp(): string { + return PHP_DIR . '/' . $this->cfg['version'] . '/php'; + } + private function lintRun( array $paths, float $cap ): array { $err = $this->work . '/lint.err'; - $args = [ '-d', 'memory_limit=' . $this->cfg['retry_memory'], '-d', 'display_errors=stderr', '-d', 'log_errors=0' ]; + $args = [ '-n', '-d', 'memory_limit=' . $this->cfg['retry_memory'], '-d', 'display_errors=stderr', '-d', 'log_errors=0' ]; // Fatal errors only: a deprecation PHP prints while compiling would come before the one line lintResult() reads. $args = array_merge( $args, [ '-d', 'error_reporting=' . ( E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR ) ] ); - // Functions PHP added after the target don't exist there: disabled, declaring one is no error, and the lint goes on. - $later = array_filter( - native_since(), - function ( $since ) { - return version_compare( $this->cfg['version'], $since, '<' ); - } - ); - $args = array_merge( $args, [ '-d', 'disable_functions=' . implode( ',', array_keys( $later ) ) ] ); - // The site's setting (EE's images turn it off): on, PHP parses a template's `cfg['short_tags'] ], $args, [ '-l' ], $paths ); + // The files' setting (EE's images turn it off): on, PHP parses a template's `lintPhp(), '-d', 'short_open_tag=' . (int) $this->short ], $args, [ '-l' ], $paths ); $res = $this->runTimed( $cmd, $cap, [ 0 => [ 'file', '/dev/null', 'r' ], 1 => [ 'file', '/dev/null', 'w' ], 2 => [ 'file', $err, 'w' ] ] ); $res['stderr'] = $res['timeout'] ? '' : (string) file_get_contents( $err, false, null, 0, 65536 ); return $res; } - /** @return array{0:int,1:string}|string The finding, or `unparseable` where this PHP's verdict isn't the target's. */ + /** @return array{0:int,1:string}|string The finding, or why the file isn't checked. */ private function lintResult( array $res, string $real ) { if ( $res['capped'] ) { return 'timeout'; @@ -2411,12 +2552,6 @@ private function lintResult( array $res, string $real ) { } // The path PHP appends to the message, not the one in its note on the earlier declaration. $text = (string) preg_replace( '/ in ' . preg_quote( $real, '/' ) . '(?=(?: on line \d+)?$)/', '', trim( $res['stderr'] ) ); - // A redeclared function parsed, so it is a finding on any target. - $redeclare = (bool) preg_match( '/^Fatal error: Cannot redeclare (?:function )?\w+\(\)/', $text ); - $newer = ! $redeclare && version_compare( $this->cfg['version'], PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION, '>' ); - if ( $newer || ( '8.0' === $this->cfg['version'] && preg_match( RESERVED_AFTER_80, $text ) ) ) { - return 'unparseable'; - } preg_match( '/^(.*?)(?: on line (\d+))?$/s', $text, $m ); return [ (int) ( $m[2] ?? 0 ), $m[1] ]; } @@ -2577,7 +2712,7 @@ public function peek(): ?string { return null === $this->next ? null : $this->next['f']; } - /** @return array{f:string,n:int,u:int} */ + /** @return array{f:string,n:int,u:int,d:string[]} */ public function take(): array { $this->skipMessages(); $block = $this->next; @@ -2662,7 +2797,11 @@ private function parseHeader( string $line ): ?array { if ( false === $name ) { return null; } - return [ 'f' => $name, 'n' => $h['n'], 'u' => $h['u'] ? 1 : 0 ]; + $declared = $h['d'] ?? []; + if ( ! is_array( $declared ) || array_filter( $declared, 'is_string' ) !== $declared ) { + return null; + } + return [ 'f' => $name, 'n' => $h['n'], 'u' => $h['u'] ? 1 : 0, 'd' => $declared ]; } private function decode( ?string $line ): ?array { @@ -2670,7 +2809,8 @@ private function decode( ?string $line ): ?array { return null; } $m = json_decode( $line, true, 4, JSON_INVALID_UTF8_SUBSTITUTE ); - if ( ! is_array( $m ) || 5 !== count( $m ) || ! is_int( $m[0] ) || ! is_string( $m[2] ) || ! is_string( $m[3] ) || ! is_string( $m[4] ) ) { + // A sixth item is the class a new-class finding names. + if ( ! is_array( $m ) || ! in_array( count( $m ), [ 5, 6 ], true ) || ! is_int( $m[0] ) || ! is_string( $m[2] ) || ! is_string( $m[3] ) || ! is_string( $m[4] ) || ! is_string( $m[5] ?? '' ) ) { return null; } return $m; @@ -2894,10 +3034,10 @@ function mount_path( string $path, string $what ): string { /** * An install's version: exactly one `$wp_version = '…';` or `"…"` line holding a plain version of at most 64 characters - * (EE prints it as given), else '' (unknown). + * (EE prints it as given), else '' (unknown), as when version.php resolves outside the roots (null). */ -function wp_version( string $dir, callable $tick ): string { - $fh = open_regular( $dir . '/wp-includes/version.php' ); +function wp_version( ?string $file, callable $tick ): string { + $fh = null === $file ? null : open_regular( $file ); if ( null === $fh ) { return ''; } @@ -2942,23 +3082,16 @@ function lines( $fh, callable $tick ): Generator { } } -/** @return array Functions PHP added since 8.1, by version, as the scanner's PHPCS sniff reads them too. */ -function native_since(): array { - static $since = null; - $since = $since ?? require TOOL_DIR . '/src/native-functions.php'; - return $since; -} - -/** @return array A code file's tokens without whitespace and comments; [] when it can't be read or is over 1 MiB. */ -function code_tokens( string $path ): array { +/** @return array|null A code file's tokens without whitespace and comments; null when it can't be read or is over 1 MiB. */ +function code_tokens( string $path ): ?array { $fh = open_regular( $path ); if ( null === $fh ) { - return []; + return null; } - $code = (string) fread( $fh, 1048577 ); + $code = fread( $fh, 1048577 ); fclose( $fh ); - if ( strlen( $code ) > 1048576 ) { - return []; + if ( false === $code || strlen( $code ) > 1048576 ) { + return null; } $tokens = []; foreach ( token_get_all( $code ) as $token ) { @@ -3017,7 +3150,7 @@ function parse_args( array $argv, array &$cfg ): void { } } -/** COMPAT_SERVED, COMPAT_REQUIRE, COMPAT_EXTRA_ROOTS, COMPAT_WP_SUPPORTED and COMPAT_SHORT_OPEN_TAG: what EE tells the scanner about the site. */ +/** COMPAT_SERVED, COMPAT_REQUIRE, COMPAT_EXTRA_ROOTS, COMPAT_WP_SUPPORTED and COMPAT_SHORT_OPEN_TAG(_LOCKED): what EE tells the scanner about the site. */ function parse_contract_env( array &$cfg ): void { // False when absent: a v3.11.1 call, unlike an empty value. $cfg['served'] = getenv( 'COMPAT_SERVED' ); @@ -3038,6 +3171,11 @@ function parse_contract_env( array &$cfg ): void { throw new BadArgs( 'COMPAT_SHORT_OPEN_TAG must be 0 or 1' ); } $cfg['short_tags'] = '1' === $short; + $locked = (string) getenv( 'COMPAT_SHORT_OPEN_TAG_LOCKED' ); + if ( ! in_array( $locked, [ '', '0', '1' ], true ) ) { + throw new BadArgs( 'COMPAT_SHORT_OPEN_TAG_LOCKED must be 0 or 1' ); + } + $cfg['short_locked'] = '1' === $locked; $supported = (string) getenv( 'COMPAT_WP_SUPPORTED' ); $cfg['wp_supported'] = '' === $supported ? [] : explode( ',', $supported ); foreach ( $cfg['wp_supported'] as $branch ) { diff --git a/compat-scanner/src/CompatScanner/Guard.php b/compat-scanner/src/CompatScanner/Guard.php new file mode 100644 index 00000000..28db75a6 --- /dev/null +++ b/compat-scanner/src/CompatScanner/Guard.php @@ -0,0 +1,186 @@ + N` either way round with N a plain decimal, or `version_compare( PHP_VERSION, 'X.Y[.Z]', '<' | 'lt' | '>=' | 'ge' )`. + * + * @return int[]|null + */ + public static function range( array $words ): ?array { + $w = array_map( 'ltrim', $words, array_fill( 0, count( $words ), '\\' ) ); + $flip = [ '<' => '>', '<=' => '>=', '>' => '<', '>=' => '<=' ]; + if ( 3 === count( $w ) && 'PHP_VERSION_ID' === $w[2] && isset( $flip[ $w[1] ] ) ) { + $w = [ $w[2], $flip[ $w[1] ], $w[0] ]; + } + if ( 3 === count( $w ) && 'PHP_VERSION_ID' === $w[0] && isset( $flip[ $w[1] ] ) && preg_match( '/^[1-9][0-9]*$/', $w[2] ) ) { + $n = (int) $w[2]; + return [ '<' => [ 0, $n ], '<=' => [ 0, $n + 1 ], '>' => [ $n + 1, self::TOP ], '>=' => [ $n, self::TOP ] ][ $w[1] ]; + } + // Positional arguments only: a named one can reorder them. + if ( 8 !== count( $w ) || 'version_compare' !== strtolower( $w[0] ) || [ '(', 'PHP_VERSION', ',', ',', ')' ] !== [ $w[1], $w[2], $w[3], $w[5], $w[7] ] ) { + return null; + } + if ( ! preg_match( '/^([\'"])(\d+)(?:\.(\d+))?(?:\.(\d+))?\1$/', $w[4], $v ) || ! preg_match( '/^([\'"])(<|lt|>=|ge)\1$/', $w[6], $c ) ) { + return null; + } + $id = $v[2] * 10000 + (int) ( $v[3] ?? 0 ) * 100 + (int) ( $v[4] ?? 0 ); + return in_array( $c[2], [ '<', 'lt' ], true ) ? [ 0, $id ] : [ $id, self::TOP ]; + } + + /** The PHP_VERSION_ID range of a target `X.Y`: every X.Y.Z. */ + public static function target( string $version ): array { + list( $major, $minor ) = explode( '.', $version ); + $id = $major * 10000 + $minor * 100; + return [ $id, $id + 100 ]; + } + + /** + * Whether a block enclosing $ptr runs only where $inIf accepts an `&&` operand of its if or elseif, or is the else + * of an if with a `||` operand $inElse accepts. + */ + public static function encloses( File $file, int $ptr, callable $inIf, callable $inElse ): bool { + $tokens = $file->getTokens(); + foreach ( array_keys( $tokens[ $ptr ]['conditions'] ) as $block ) { + if ( T_ELSE === $tokens[ $block ]['code'] ) { + // The closing brace before `else` belongs to the if or elseif it is the else of. + $prev = $file->findPrevious( Tokens::EMPTY_TOKENS, $block - 1, null, true ); + $if = T_CLOSE_CURLY_BRACKET === $tokens[ $prev ]['code'] ? ( $tokens[ $prev ]['scope_condition'] ?? null ) : null; + if ( null !== $if && self::any( $file, $if, true, $inElse ) ) { + return true; + } + } elseif ( self::any( $file, $block, false, $inIf ) ) { + return true; + } + } + return false; + } + + /** Whether $test accepts an operand of the condition of the if or elseif at $ptr, split at its top-level `||` ($or) or `&&`. */ + public static function any( File $file, int $ptr, bool $or, callable $test ): bool { + foreach ( (array) self::operands( $file, $ptr, $or ) as $op ) { + if ( $test( $op ) ) { + return true; + } + } + return false; + } + + /** + * The top-level operands of the condition of the if or elseif at $ptr, each without parentheses around it; null when + * it isn't one or another top-level logical operator joins them. + * + * @return array|null + */ + public static function operands( File $file, int $ptr, bool $or ): ?array { + $tokens = $file->getTokens(); + if ( ! in_array( $tokens[ $ptr ]['code'], [ T_IF, T_ELSEIF ], true ) || ! isset( $tokens[ $ptr ]['parenthesis_closer'] ) ) { + return null; + } + $open = $tokens[ $ptr ]['parenthesis_opener']; + $depth = count( $tokens[ $open ]['nested_parenthesis'] ?? [] ) + 1; + $join = $or ? [ T_BOOLEAN_OR, T_LOGICAL_OR ] : [ T_BOOLEAN_AND, T_LOGICAL_AND ]; + $other = $or ? [ T_BOOLEAN_AND, T_LOGICAL_AND ] : [ T_BOOLEAN_OR, T_LOGICAL_OR ]; + $other = array_merge( $other, [ T_LOGICAL_XOR, T_INLINE_THEN, T_COALESCE ] ); + + $operands = [ [] ]; + for ( $i = $open + 1; $i < $tokens[ $ptr ]['parenthesis_closer']; $i++ ) { + $code = $tokens[ $i ]['code']; + if ( isset( Tokens::EMPTY_TOKENS[ $code ] ) ) { + continue; + } + $top = count( $tokens[ $i ]['nested_parenthesis'] ?? [] ) === $depth; + if ( $top && in_array( $code, $other, true ) ) { + return null; + } + if ( $top && in_array( $code, $join, true ) ) { + $operands[] = []; + continue; + } + $operands[ count( $operands ) - 1 ][] = $i; + } + return array_map( + static function ( $op ) use ( $tokens ) { + return self::unwrap( $tokens, $op ); + }, + $operands + ); + } + + /** The version range an operand tests, or null when it is no version test. */ + public static function versions( File $file, array $op ): ?array { + $tokens = $file->getTokens(); + return self::range( + array_map( + static function ( $ptr ) use ( $tokens ) { + return $tokens[ $ptr ]['content']; + }, + $op + ) + ); + } + + /** + * Whether an operand checks for the name with one of $checks: true for exactly `check( 'name' )`, false for its + * negation (`! check()`, `false === check()`, `check() === false`), null otherwise. + */ + public static function checks( File $file, array $op, array $checks, string $name ): ?bool { + $tokens = $file->getTokens(); + $n = count( $op ); + $inner = null; + if ( $n > 1 && T_BOOLEAN_NOT === $tokens[ $op[0] ]['code'] ) { + $inner = self::unwrap( $tokens, array_slice( $op, 1 ) ); + } elseif ( $n > 2 && T_IS_IDENTICAL === $tokens[ $op[1] ]['code'] && T_FALSE === $tokens[ $op[0] ]['code'] ) { + $inner = array_slice( $op, 2 ); + } elseif ( $n > 2 && T_IS_IDENTICAL === $tokens[ $op[ $n - 2 ] ]['code'] && T_FALSE === $tokens[ $op[ $n - 1 ] ]['code'] ) { + $inner = array_slice( $op, 0, $n - 2 ); + } + if ( null !== $inner ) { + return self::named( $file, $inner, $checks, $name ) ? false : null; + } + return self::named( $file, $op, $checks, $name ) ? true : null; + } + + /** Whether the tokens are exactly one call of $checks with the name as its first argument. */ + private static function named( File $file, array $op, array $checks, string $name ): bool { + $tokens = $file->getTokens(); + if ( ! self::call( $tokens, $op, $checks ) ) { + return false; + } + $arg = PassedParameters::getParameter( $file, $op[0], 1, [ 'function', 'class', 'interface', 'enum' ] ); + // 'name', "name" or name::class, each with an optional leading `\`. + $is = false !== $arg && preg_match( '/^(?:([\'"])\\\\{0,2}(\w+)\1|\\\\?(\w+)::class)$/i', $arg['clean'], $m ); + return $is && strtolower( $m[2] . ( $m[3] ?? '' ) ) === strtolower( $name ); + } + + /** Whether the tokens are exactly a call of one of $names, `\` allowed. */ + private static function call( array $tokens, array $op, array $names ): bool { + $fn = in_array( $tokens[ $op[0] ]['code'] ?? null, [ T_STRING, T_NAME_FULLY_QUALIFIED ], true ); + if ( ! $fn || ! in_array( strtolower( ltrim( $tokens[ $op[0] ]['content'], '\\' ) ), $names, true ) || count( $op ) < 3 ) { + return false; + } + return T_OPEN_PARENTHESIS === $tokens[ $op[1] ]['code'] && $tokens[ $op[1] ]['parenthesis_closer'] === end( $op ); + } + + /** The pointers without parentheses around all of them. */ + private static function unwrap( array $tokens, array $op ): array { + while ( count( $op ) > 2 && T_OPEN_PARENTHESIS === $tokens[ $op[0] ]['code'] && $tokens[ $op[0] ]['parenthesis_closer'] === end( $op ) ) { + $op = array_slice( $op, 1, -1 ); + } + return $op; + } +} diff --git a/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php index 9e43062d..79ac6c1b 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php @@ -7,7 +7,9 @@ namespace CompatScanner\Sniffs\Classes; use CompatScanner\Sniffs\Functions\NativeDeclaredSniff as NativeFunctionSniff; +use CompatScanner\Guard; use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; class NativeDeclaredSniff extends NativeFunctionSniff { @@ -34,31 +36,40 @@ protected function native( string $lower ): ?array { return [ 'since' => $since, 'checks' => self::CHECKS[ $kind ] ]; } - /** PHP declares a class when its declaration runs, so a return before it on the native's check is a guard. */ + /** + * PHP declares a class when its declaration runs, so a file-scope statement `if ( ) { return; }` before it is a + * guard: the if a statement of its own, its block nothing but the return, and no goto in the file to jump past it. + */ protected function returnsBefore( File $phpcsFile, int $stackPtr, array $native ): bool { $tokens = $phpcsFile->getTokens(); // In a function body it runs whenever the function is called, which other files can do. - if ( array_intersect( $tokens[ $stackPtr ]['conditions'], [ T_FUNCTION, T_CLOSURE, T_FN ] ) ) { + if ( array_intersect( $tokens[ $stackPtr ]['conditions'], [ T_FUNCTION, T_CLOSURE, T_FN ] ) || false !== $phpcsFile->findNext( T_GOTO, 0 ) ) { return false; } + $exists = function ( $op ) use ( $phpcsFile, $native ) { + return $this->exists( $phpcsFile, $op, $native ); + }; for ( $if = $phpcsFile->findNext( T_IF, 0, $stackPtr ); false !== $if; $if = $phpcsFile->findNext( T_IF, $if + 1, $stackPtr ) ) { - if ( 0 === $tokens[ $if ]['level'] && $this->returns( $tokens, $if ) && $this->holds( $phpcsFile, $if, $native, true ) ) { + if ( $this->onlyReturns( $phpcsFile, $if ) && $tokens[ $if ]['scope_closer'] < $stackPtr && Guard::any( $phpcsFile, $if, true, $exists ) ) { return true; } } return false; } - /** Whether the if's own block, not one nested in it, holds a return. */ - private function returns( array $tokens, int $if ): bool { - if ( ! isset( $tokens[ $if ]['scope_opener'], $tokens[ $if ]['scope_closer'] ) ) { + /** Whether the if is a file-scope statement (not an else's, nor the body of a braceless one) whose block is one return. */ + private function onlyReturns( File $phpcsFile, int $if ): bool { + $tokens = $phpcsFile->getTokens(); + $prev = $phpcsFile->findPrevious( Tokens::EMPTY_TOKENS, $if - 1, null, true ); + $after = in_array( $tokens[ $prev ]['code'], [ T_OPEN_TAG, T_SEMICOLON, T_CLOSE_CURLY_BRACKET ], true ); + if ( 0 !== $tokens[ $if ]['level'] || ! $after || ! isset( $tokens[ $if ]['scope_opener'], $tokens[ $if ]['scope_closer'] ) ) { return false; } - for ( $i = $tokens[ $if ]['scope_opener'] + 1; $i < $tokens[ $if ]['scope_closer']; $i++ ) { - if ( T_RETURN === $tokens[ $i ]['code'] && $tokens[ $i ]['level'] === $tokens[ $if ]['level'] + 1 ) { - return true; - } + $return = $phpcsFile->findNext( Tokens::EMPTY_TOKENS, $tokens[ $if ]['scope_opener'] + 1, null, true ); + if ( T_RETURN !== $tokens[ $return ]['code'] ) { + return false; } - return false; + $end = $phpcsFile->findEndOfStatement( $return ); + return $phpcsFile->findNext( Tokens::EMPTY_TOKENS, $end + 1, null, true ) === $tokens[ $if ]['scope_closer']; } } diff --git a/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php index fb53bd25..3f1c18fd 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php @@ -1,17 +1,19 @@ numTokens; } $tokens = $phpcsFile->getTokens(); - $below = [ 'since' => $target, 'checks' => [], 'name' => '' ]; $blocks = 0; for ( $i = $this->next( $phpcsFile, 0 ); false !== $i; $i = $this->next( $phpcsFile, $i ) ) { $code = $tokens[ $i ]['code']; if ( in_array( $code, [ T_NAMESPACE, T_USE, T_DECLARE ], true ) && ! isset( $tokens[ $i ]['scope_opener'] ) ) { - $i = $phpcsFile->findNext( T_SEMICOLON, $i + 1 ); - } elseif ( T_IF === $code && isset( $tokens[ $i ]['scope_closer'] ) && $this->holds( $phpcsFile, $i, $below, false ) ) { + // A close tag ends the statement too; what follows it is checked as usual. + $i = $phpcsFile->findNext( [ T_SEMICOLON, T_CLOSE_TAG ], $i + 1 ); + } elseif ( T_IF === $code && isset( $tokens[ $i ]['scope_closer'] ) && $this->below( $phpcsFile, $i, $target ) ) { $i = $tokens[ $i ]['scope_closer']; $blocks++; } elseif ( T_CLOSE_TAG !== $code ) { @@ -46,6 +48,13 @@ public function process( File $phpcsFile, int $stackPtr ) { return $phpcsFile->numTokens; } + /** Whether the if's first `&&` operand holds only below the target: operands after it never run there, those before it do. */ + private function below( File $phpcsFile, int $if, string $target ): bool { + $ops = Guard::operands( $phpcsFile, $if, false ); + $range = null === $ops ? null : Guard::versions( $phpcsFile, $ops[0] ); + return null !== $range && $range[1] <= Guard::target( $target )[0]; + } + /** @return int|false The next token after $i that isn't whitespace or a comment. */ private function next( File $phpcsFile, int $i ) { return $phpcsFile->findNext( Tokens::EMPTY_TOKENS, $i + 1, null, true ); diff --git a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php index 130a68e5..400277a5 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php @@ -7,12 +7,12 @@ namespace CompatScanner\Sniffs\Functions; +use CompatScanner\Guard; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Util\Tokens; use PHPCSUtils\BackCompat\Helper; use PHPCSUtils\Utils\Namespaces; -use PHPCSUtils\Utils\PassedParameters; class NativeDeclaredSniff implements Sniff { @@ -41,13 +41,19 @@ public function process( File $phpcsFile, int $stackPtr ) { if ( $conditions && isset( Tokens::OO_SCOPE_TOKENS[ end( $conditions ) ] ) ) { return; } - $native['name'] = strtolower( $name ); - foreach ( array_keys( $conditions ) as $ptr ) { - if ( $this->guards( $phpcsFile, $ptr, $native ) ) { - return; - } + // Symfony's old polyfills ship unguarded stubs that only a classmap autoloader loads, where the native is missing. + if ( preg_match( '#/symfony/polyfill-[^/]+/Resources/stubs/#', $phpcsFile->getFilename() ) ) { + return; } - if ( $this->returnsBefore( $phpcsFile, $stackPtr, $native ) ) { + $native['name'] = $name; + $native['added'] = Guard::target( $native['since'] )[0]; + $missing = function ( $op ) use ( $phpcsFile, $native ) { + return $this->missing( $phpcsFile, $op, $native ); + }; + $exists = function ( $op ) use ( $phpcsFile, $native ) { + return $this->exists( $phpcsFile, $op, $native ); + }; + if ( Guard::encloses( $phpcsFile, $stackPtr, $missing, $exists ) || $this->returnsBefore( $phpcsFile, $stackPtr, $native ) ) { return; } $phpcsFile->addError( $this->message, $stackPtr, 'Found', [ $name, $native['since'] ] ); @@ -64,148 +70,15 @@ protected function returnsBefore( File $phpcsFile, int $stackPtr, array $native return false; } - /** Whether the block opened at $ptr runs only where the native is missing. */ - private function guards( File $phpcsFile, int $ptr, array $native ): bool { - $tokens = $phpcsFile->getTokens(); - if ( T_ELSE === $tokens[ $ptr ]['code'] ) { - // The closing brace before `else` belongs to the if or elseif it is the else of. - $prev = $phpcsFile->findPrevious( Tokens::EMPTY_TOKENS, $ptr - 1, null, true ); - $if = T_CLOSE_CURLY_BRACKET === $tokens[ $prev ]['code'] ? ( $tokens[ $prev ]['scope_condition'] ?? null ) : null; - return null !== $if && $this->holds( $phpcsFile, $if, $native, true ); - } - return in_array( $tokens[ $ptr ]['code'], [ T_IF, T_ELSEIF ], true ) && $this->holds( $phpcsFile, $ptr, $native, false ); - } - - /** - * Whether the condition of the if or elseif at $ptr, or a top-level operand of it, tests that the native exists or is missing. - * Operands are joined by `||` for exists, by `&&` for missing; any other top-level logical operator makes it no test. - */ - protected function holds( File $phpcsFile, int $ptr, array $native, bool $exists ): bool { - $tokens = $phpcsFile->getTokens(); - if ( ! in_array( $tokens[ $ptr ]['code'], [ T_IF, T_ELSEIF ], true ) || ! isset( $tokens[ $ptr ]['parenthesis_closer'] ) ) { - return false; - } - $open = $tokens[ $ptr ]['parenthesis_opener']; - $depth = count( $tokens[ $open ]['nested_parenthesis'] ?? [] ) + 1; - $join = $exists ? [ T_BOOLEAN_OR, T_LOGICAL_OR ] : [ T_BOOLEAN_AND, T_LOGICAL_AND ]; - $other = $exists ? [ T_BOOLEAN_AND, T_LOGICAL_AND ] : [ T_BOOLEAN_OR, T_LOGICAL_OR ]; - $other = array_merge( $other, [ T_LOGICAL_XOR, T_INLINE_THEN, T_COALESCE ] ); - - $operands = [ [] ]; - for ( $i = $open + 1; $i < $tokens[ $ptr ]['parenthesis_closer']; $i++ ) { - $code = $tokens[ $i ]['code']; - if ( isset( Tokens::EMPTY_TOKENS[ $code ] ) ) { - continue; - } - $top = count( $tokens[ $i ]['nested_parenthesis'] ?? [] ) === $depth; - if ( $top && in_array( $code, $other, true ) ) { - return false; - } - if ( $top && in_array( $code, $join, true ) ) { - $operands[] = []; - continue; - } - $operands[ count( $operands ) - 1 ][] = $i; - } - foreach ( $operands as $operand ) { - if ( $this->tests( $phpcsFile, $this->unwrap( $tokens, $operand ), $native, $exists ) ) { - return true; - } - } - return false; - } - - /** - * Whether the operand is exactly a check on the name (negated for missing), a PHP_VERSION_ID bound or a version_compare(). - * A bound is never above the version that added the name. - */ - private function tests( File $phpcsFile, array $op, array $native, bool $exists ): bool { - $tokens = $phpcsFile->getTokens(); - $n = count( $op ); - if ( $n > 1 && ! $exists && T_BOOLEAN_NOT === $tokens[ $op[0] ]['code'] ) { - return $this->checks( $phpcsFile, $this->unwrap( $tokens, array_slice( $op, 1 ) ), $native ); - } - if ( $n > 2 && ! $exists && T_IS_IDENTICAL === $tokens[ $op[1] ]['code'] && T_FALSE === $tokens[ $op[0] ]['code'] ) { - return $this->checks( $phpcsFile, array_slice( $op, 2 ), $native ); - } - if ( $n > 2 && ! $exists && T_IS_IDENTICAL === $tokens[ $op[ $n - 2 ] ]['code'] && T_FALSE === $tokens[ $op[ $n - 1 ] ]['code'] ) { - return $this->checks( $phpcsFile, array_slice( $op, 0, $n - 2 ), $native ); - } - if ( $exists && $this->checks( $phpcsFile, $op, $native ) ) { - return true; - } - return 3 === $n ? $this->bound( $tokens, $op, $native['since'], $exists ) : $this->compares( $phpcsFile, $op, $native['since'], $exists ); + /** Whether the operand holds only where the native is missing: `! check( 'name' )`, or a version test below the version that added it. */ + private function missing( File $phpcsFile, array $op, array $native ): bool { + $range = Guard::versions( $phpcsFile, $op ); + return false === Guard::checks( $phpcsFile, $op, $native['checks'], $native['name'] ) || ( null !== $range && $range[1] <= $native['added'] ); } - /** Whether the tokens are exactly one call of the native's checks with its name as the first argument. */ - private function checks( File $phpcsFile, array $op, array $native ): bool { - $tokens = $phpcsFile->getTokens(); - if ( ! $this->call( $tokens, $op, $native['checks'] ) ) { - return false; - } - $arg = PassedParameters::getParameter( $phpcsFile, $op[0], 1, [ 'function', 'class', 'interface', 'enum' ] ); - // 'name', "name" or name::class, each with an optional leading `\`. - $named = false !== $arg && preg_match( '/^(?:([\'"])\\\\{0,2}(\w+)\1|\\\\?(\w+)::class)$/i', $arg['clean'], $m ); - return $named && strtolower( $m[2] . ( $m[3] ?? '' ) ) === $native['name']; - } - - /** Whether the tokens are exactly a call of one of $names, `\` allowed. */ - private function call( array $tokens, array $op, array $names ): bool { - $fn = in_array( $tokens[ $op[0] ]['code'] ?? null, [ T_STRING, T_NAME_FULLY_QUALIFIED ], true ); - if ( ! $fn || ! in_array( strtolower( ltrim( $tokens[ $op[0] ]['content'], '\\' ) ), $names, true ) || count( $op ) < 3 ) { - return false; - } - return T_OPEN_PARENTHESIS === $tokens[ $op[1] ]['code'] && $tokens[ $op[1] ]['parenthesis_closer'] === end( $op ); - } - - /** `PHP_VERSION_ID < N`, `<= N`, `N > …`, `N >= …` (the reverse for exists), N within the version that added the name. */ - private function bound( array $tokens, array $op, string $since, bool $exists ): bool { - $id = 'PHP_VERSION_ID'; - $ops = [ T_LESS_THAN => '<', T_IS_SMALLER_OR_EQUAL => '<=', T_GREATER_THAN => '>', T_IS_GREATER_OR_EQUAL => '>=' ]; - $op = array_map( - static function ( $ptr ) use ( $tokens, $ops ) { - return $ops[ $tokens[ $ptr ]['code'] ] ?? ltrim( $tokens[ $ptr ]['content'], '\\' ); - }, - $op - ); - // Turned around to `PHP_VERSION_ID N`. - $flip = [ '<' => '>', '<=' => '>=', '>' => '<', '>=' => '<=' ]; - if ( $id === $op[2] && isset( $flip[ $op[1] ] ) ) { - $op = [ $op[2], $flip[ $op[1] ], $op[0] ]; - } - if ( $id !== $op[0] || ! preg_match( '/^[1-9][0-9]*$/', $op[2] ) ) { - return false; - } - list( $major, $minor ) = explode( '.', $since ); - $added = $major * 10000 + $minor * 100; - // The lowest version ID the test holds below (missing) or from (exists). - $from = [ '<' => (int) $op[2], '<=' => (int) $op[2] + 1, '>=' => (int) $op[2], '>' => (int) $op[2] + 1 ]; - $kind = $exists ? [ '>=', '>' ] : [ '<', '<=' ]; - return in_array( $op[1], $kind, true ) && $from[ $op[1] ] <= $added; - } - - /** `version_compare( PHP_VERSION, 'X.Y[.Z]', '<' )` or `'lt'` (`'>='` or `'ge'` for exists), X.Y.Z within the version that added the name. */ - private function compares( File $phpcsFile, array $op, string $since, bool $exists ): bool { - if ( ! $this->call( $phpcsFile->getTokens(), $op, [ 'version_compare' ] ) ) { - return false; - } - $args = PassedParameters::getParameters( $phpcsFile, $op[0] ); - if ( 3 !== count( $args ) || ! in_array( ltrim( $args[1]['clean'], '\\' ), [ 'PHP_VERSION' ], true ) ) { - return false; - } - $version = preg_match( '/^([\'"])(\d+(?:\.\d+){0,2})\1$/', $args[2]['clean'], $v ); - $cmp = preg_match( '/^([\'"])(<|lt|>=|ge)\1$/', $args[3]['clean'], $c ); - if ( ! $version || ! $cmp || $exists !== in_array( $c[2], [ '>=', 'ge' ], true ) ) { - return false; - } - return version_compare( $v[2], $since . '.0', '<=' ); - } - - /** The pointers without parentheses around all of them. */ - private function unwrap( array $tokens, array $op ): array { - while ( count( $op ) > 2 && T_OPEN_PARENTHESIS === $tokens[ $op[0] ]['code'] && $tokens[ $op[0] ]['parenthesis_closer'] === end( $op ) ) { - $op = array_slice( $op, 1, -1 ); - } - return $op; + /** Whether the operand holds wherever the native exists: `check( 'name' )`, or a version test from the version that added it on. */ + protected function exists( File $phpcsFile, array $op, array $native ): bool { + $range = Guard::versions( $phpcsFile, $op ); + return true === Guard::checks( $phpcsFile, $op, $native['checks'], $native['name'] ) || ( null !== $range && $range[0] <= $native['added'] && Guard::TOP === $range[1] ); } } diff --git a/compat-scanner/src/LinesReport.php b/compat-scanner/src/LinesReport.php index 556cd481..9ac421c2 100644 --- a/compat-scanner/src/LinesReport.php +++ b/compat-scanner/src/LinesReport.php @@ -1,18 +1,17 @@ ","n":,"u":0|1}; "u" is 1 when - * PHPCS couldn't tokenize or process the file. Each message line is - * [line, column, type, source, message]. One line per message lets the - * entrypoint stream a report without holding a file's findings in memory. - * Clean files get a header too, so the caller knows which files PHPCS finished. + * PHPCS report: per file a header {"f":,"n":,"u":<1 when PHPCS couldn't process it>,"d":[]}, + * then one line per message, [line, column, type, source, message(, lowercase class of a new class or interface)], so the + * entrypoint streams it without holding a file's findings. Clean files get a header too, so it knows which files PHPCS finished. */ namespace EasyEngine\CompatScanner; +use CompatScanner\Guard; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Reports\Report; +use PHPCSUtils\BackCompat\Helper; +use PHPCSUtils\Utils\Namespaces; class LinesReport implements Report { @@ -22,38 +21,69 @@ class LinesReport implements Report { // and 64 KiB stays below that even when every byte is escaped as \u00XX. const MESSAGE_MAX = 65536; + /** PHPCompatibility findings on a name, by source prefix: dropped in a block that runs only where the name exists or not on the target. */ + const GUARDED = [ + 'PHPCompatibility.FunctionUse.NewFunctions.' => 'function_exists', + 'PHPCompatibility.FunctionUse.RemovedFunctions.' => 'function_exists', + 'PHPCompatibility.Extensions.RemovedExtensions.' => 'function_exists', + 'PHPCompatibility.Classes.NewClasses.' => 'class_exists', + 'PHPCompatibility.Classes.RemovedClasses.' => 'class_exists', + 'PHPCompatibility.Interfaces.NewInterfaces.' => 'interface_exists', + ]; + + /** @var int[] The target's PHP_VERSION_ID range. */ + private $target; + public function generateFileReport( array $report, File $phpcsFile, bool $showSources = false, int $width = 80 ) { - $count = 0; - $unparseable = 0; - $inert = false; - foreach ( $report['messages'] as $columns ) { - foreach ( $columns as $list ) { + $this->target = Guard::target( (string) Helper::getConfigData( 'testVersion' ) ); + $at = null; + $count = 0; + $unparseable = 0; + $inert = false; + $kept = []; + foreach ( $report['messages'] as $line => $columns ) { + foreach ( $columns as $column => $list ) { foreach ( $list as $message ) { - $count++; if ( 0 === strpos( $message['source'], 'Internal.Tokenizer.Exception' ) || 0 === strpos( $message['source'], 'Internal.Exception' ) ) { $unparseable = 1; } $inert = $inert || 0 === strpos( $message['source'], 'CompatScanner.Files.Inert.' ); + list( $check, $name ) = $this->named( $message['source'] ); + if ( null !== $check ) { + $at = $at ?? $this->positions( $phpcsFile ); + $ptr = $at[ "$line:$column" ] ?? null; + // An extension's finding names its prefix; the function is the token it is on. + $name = $name ?? ( null === $ptr ? '' : ltrim( $phpcsFile->getTokens()[ $ptr ]['content'], '\\' ) ); + if ( null !== $ptr && $this->guarded( $phpcsFile, $ptr, $check, $name ) ) { + continue; + } + if ( preg_match( '/\.New(?:Classes|Interfaces)\./', $message['source'] ) ) { + $message['class'] = $name; + } + } + $count++; + $kept[] = [ (int) $line, (int) $column, $message ]; } } } // A file that runs nothing on the target (CompatScanner.Files.Inert) breaks nothing there. if ( $inert && ! $unparseable ) { - $count = 0; - $report['messages'] = []; + $count = 0; + $kept = []; } - echo json_encode( [ 'f' => base64_encode( $report['filename'] ), 'n' => $count, 'u' => $unparseable ] ), "\n"; - foreach ( $report['messages'] as $line => $columns ) { - foreach ( $columns as $column => $list ) { - foreach ( $list as $message ) { - $text = $message['message']; - if ( strlen( $text ) > self::MESSAGE_MAX ) { - $text = substr( $text, 0, self::MESSAGE_MAX ) . '…'; - } - echo json_encode( [ (int) $line, (int) $column, $message['type'], $message['source'], $text ], self::FLAGS ), "\n"; - } + $declared = $unparseable ? [] : $this->declared( $phpcsFile ); + echo json_encode( [ 'f' => base64_encode( $report['filename'] ), 'n' => $count, 'u' => $unparseable, 'd' => $declared ], self::FLAGS ), "\n"; + foreach ( $kept as list( $line, $column, $message ) ) { + $text = $message['message']; + if ( strlen( $text ) > self::MESSAGE_MAX ) { + $text = substr( $text, 0, self::MESSAGE_MAX ) . '…'; } + $row = [ $line, $column, $message['type'], $message['source'], $text ]; + if ( isset( $message['class'] ) ) { + $row[] = $message['class']; + } + echo json_encode( $row, self::FLAGS ), "\n"; } return true; @@ -62,4 +92,80 @@ public function generateFileReport( array $report, File $phpcsFile, bool $showSo public function generate( string $cachedData, int $totalFiles, int $totalErrors, int $totalWarnings, int $totalFixable, bool $showSources = false, int $width = 80, bool $interactive = false, bool $toScreen = true ) { echo $cachedData; } + + /** + * The check that sees the name a finding of this source is about, and the name from the source (lowercase; null for an + * extension); [ null, null ] when it isn't one GUARDED names. + */ + private function named( string $source ): array { + foreach ( self::GUARDED as $prefix => $check ) { + if ( 0 === strpos( $source, $prefix ) ) { + $name = (string) preg_replace( '/(?:Found|Deprecated|Removed)+\z/', '', substr( $source, strlen( $prefix ) ) ); + return [ $check, false !== strpos( $prefix, '.Extensions.' ) ? null : $name ]; + } + } + return [ null, null ]; + } + + /** @return array Token pointers by "line:column", where PHPCS anchors a finding. */ + private function positions( File $phpcsFile ): array { + $at = []; + foreach ( $phpcsFile->getTokens() as $ptr => $token ) { + $at[ $token['line'] . ':' . $token['column'] ] = $at[ $token['line'] . ':' . $token['column'] ] ?? $ptr; + } + return $at; + } + + /** Whether the name at $ptr is used only in a block that runs where it exists, or not on the target. */ + private function guarded( File $phpcsFile, int $ptr, string $check, string $name ): bool { + $target = $this->target; + $inIf = static function ( $op ) use ( $phpcsFile, $check, $name, $target ) { + $range = Guard::versions( $phpcsFile, $op ); + return true === Guard::checks( $phpcsFile, $op, [ $check ], $name ) || ( null !== $range && ( $range[1] <= $target[0] || $range[0] >= $target[1] ) ); + }; + $inElse = static function ( $op ) use ( $phpcsFile, $check, $name, $target ) { + $range = Guard::versions( $phpcsFile, $op ); + return false === Guard::checks( $phpcsFile, $op, [ $check ], $name ) || ( null !== $range && $range[0] <= $target[0] && $range[1] >= $target[1] ); + }; + return Guard::encloses( $phpcsFile, $ptr, $inIf, $inElse ); + } + + /** + * Lowercase names of the global classes, interfaces, traits and enums the file declares where the declaration runs on + * the target: at file scope, or only in if blocks each of whose `&&` operands holds there (a version test, or a + * negated class_exists() or interface_exists() on that name). + * + * @return string[] + */ + private function declared( File $phpcsFile ): array { + $tokens = $phpcsFile->getTokens(); + $names = []; + foreach ( $tokens as $ptr => $token ) { + if ( ! in_array( $token['code'], [ T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM ], true ) || '' !== Namespaces::determineNamespace( $phpcsFile, $ptr ) ) { + continue; + } + $name = (string) $phpcsFile->getDeclarationName( $ptr ); + $runs = '' !== $name; + foreach ( array_keys( $token['conditions'] ) as $block ) { + $runs = $runs && ( T_NAMESPACE === $tokens[ $block ]['code'] || $this->holds( $phpcsFile, $block, $name ) ); + } + if ( $runs ) { + $names[] = strtolower( $name ); + } + } + return $names; + } + + /** Whether the if at $ptr holds on the target, by every `&&` operand of its condition. */ + private function holds( File $phpcsFile, int $ptr, string $name ): bool { + $ops = T_IF === $phpcsFile->getTokens()[ $ptr ]['code'] ? Guard::operands( $phpcsFile, $ptr, false ) : null; + foreach ( (array) $ops as $op ) { + $range = Guard::versions( $phpcsFile, $op ); + $covers = null !== $range && $range[0] <= $this->target[0] && $range[1] >= $this->target[1]; + if ( ! $covers && false !== Guard::checks( $phpcsFile, $op, [ 'class_exists', 'interface_exists' ], $name ) ) { + return false; + } + } + return null !== $ops; + } } diff --git a/compat-scanner/src/native-classes.php b/compat-scanner/src/native-classes.php index b1b202c5..da3db9b5 100644 --- a/compat-scanner/src/native-classes.php +++ b/compat-scanner/src/native-classes.php @@ -1,7 +1,7 @@ [ '8.0', 'class' ], 'internaliterator' => [ '8.0', 'class' ], 'reflectionattribute' => [ '8.0', 'class' ], 'reflectionuniontype' => [ '8.0', 'class' ], diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 1176225d..48768952 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -994,7 +994,7 @@ function counts( string $name ): array { nc( 'plugin', 'p', null, 'views/unclosed.tpl', 'php_tag' ), ]; eq( $li['not_checked'] ?? null, $templates, 'lint: a template with text before its tag that fails the lint can\'t be confirmed' ); -// A function PHP adds is fatal to declare from that version on: by the lint up to the scanner's PHP, by a sniff above it. +// A function PHP adds is fatal to declare from that version on: the target's own lint says so where PHP binds it at compile time, the sniff elsewhere. $lint = 'CompatScanner.Syntax.ParseError'; $sniff = 'CompatScanner.Functions.NativeDeclared.Found'; $always = [ "poly.php:$lint", "polytwice.php:$lint", "strlen.php:$lint", "twice.php:$lint" ]; @@ -1003,14 +1003,14 @@ function counts( string $name ): array { // A file whose only code is a block the target skips runs nothing there: stublate.php from 8.4, verhigh.php at 8.6. $class84 = [ "override.php:$csniff", "unitenum.php:$csniff" ]; $class85 = array_merge( $class84, [ "nodiscard.php:$csniff" ] ); -$no_guard = [ "defined.php:$sniff", "iftrue.php:$sniff", "nested.php:$sniff", "nsbrace.php:$sniff", "other.php:$sniff", "try.php:$sniff" ]; +$no_guard = [ "defined.php:$sniff", "iftrue.php:$sniff", "nested.php:$sniff", "nsbrace.php:$lint", "other.php:$sniff", "try.php:$sniff" ]; // A top-level function is bound when PHP compiles the file, so an early return on the version comes too late. -$no_guard = array_merge( $no_guard, [ "earlyver.php:$sniff", "verhigh.php:$sniff" ] ); +$no_guard = array_merge( $no_guard, [ "earlyver.php:$lint", "verhigh.php:$sniff" ] ); $by_ver = [ '8.3' => array_merge( $always, $class83 ), '8.4' => array_merge( [ "find.php:$lint", "legacy.php:$lint" ], $always, $class84 ), - '8.5' => array_merge( [ "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always, $no_guard, $class85 ), - '8.6' => array_merge( [ "clamp.php:$sniff", "find.php:$lint", "first.php:$sniff", "legacy.php:$lint" ], $always, array_diff( $no_guard, [ "verhigh.php:$sniff" ] ), $class85 ), + '8.5' => array_merge( [ "find.php:$lint", "first.php:$lint", "legacy.php:$lint" ], $always, $no_guard, $class85 ), + '8.6' => array_merge( [ "clamp.php:$lint", "find.php:$lint", "first.php:$lint", "legacy.php:$lint" ], $always, array_diff( $no_guard, [ "verhigh.php:$sniff" ] ), $class85 ), ]; foreach ( $by_ver as $v => $want ) { sort( $want ); @@ -1025,9 +1025,10 @@ function counts( string $name ): array { $quoted = [ counts( $name ), report( $name )['not_checked'] ?? null ]; eq( $quoted, [ [ 'ok', true, 0, 3, 0 ], [] ], "$name: a shell history and a script quoting $ln_reserved, 'lintnames-80' => [] ] as $name => $reserved ) { $r = report( $name ); $got = [ finding_files( $r ), array_values( array_filter( $r['not_checked'] ?? [], static function ( $e ) { return 'php_tag' === $e['reason']; } ) ) ]; eq( $got, [ array_merge( [ 'other:::broken.php' ], $reserved, [ 'other:::tw.php' ] ), $ln_tags ], "$name: lint failures of non-code names are php_tag" ); } -$ln80 = array_column( array_filter( report( 'lintnames-80' )['not_checked'] ?? [], static function ( $e ) { return 'unparseable' === $e['reason']; } ), 'file' ); -eq( $ln80, [ 'nv.php', 'nw.php', 'ro.php' ], 'lintnames-80: names PHP 8.0 takes but 8.4 reserves can\'t be confirmed' ); $tw = comp_of( report( 'lintnames' ), 'other', '' )['findings'] ?? []; eq( end( $tw )['message'] ?? null, 'Fatal error: Cannot redeclare function p_tw() (previously declared in /var/www/htdocs/tw.php:2)', 'lintnames: the lint message keeps the earlier declaration\'s place' ); // Each guard shape at 8.5: reported exactly as the table says, never quiet where PHP fails, and PHP 8.5.0 agrees. $reported = []; foreach ( comp_of( report( 'guards' ), 'directory', 'g' )['findings'] ?? [] as $f ) { - if ( preg_match( '/^CompatScanner\.(?:Functions|Classes)\.NativeDeclared\./', $f['source'] ) ) { + if ( preg_match( '/^CompatScanner\.(?:(?:Functions|Classes)\.NativeDeclared\.|Syntax\.ParseError\z)/', $f['source'] ) ) { $reported[ basename( $f['file'], '.php' ) ] = true; } } @@ -1064,9 +1064,9 @@ function counts( string $name ): array { eq( [ $wrong, report( 'guards' )['not_checked'] ?? null ], [ [], [] ], 'guards: each shape reported exactly as tests/guards.php says' ); eq( trim( raw( 'guards.truth' ) ), 'checked', 'guards: PHP 8.5.0 runs exactly the shapes tests/guards.php says it runs' ); -// PHP 8.0's names from 8.0 on, the date extension's 8.3 classes from 8.3; not Attribute, which symfony/polyfill-php80 declares unguarded. -$nt80 = [ 'other:::contains.php', 'other:::starts.php', 'other:::stringable.php', 'other:::valueerror.php' ]; -foreach ( [ '7.4' => [], '8.0' => $nt80, '8.3' => array_merge( [ 'other:::contains.php', 'other:::dateerror.php' ], array_slice( $nt80, 1 ) ) ] as $v => $want ) { +// PHP 8.0's names from 8.0 on, the date extension's 8.3 classes from 8.3. +$nt80 = [ 'other:::attribute.php', 'other:::contains.php', 'other:::starts.php', 'other:::stringable.php', 'other:::valueerror.php' ]; +foreach ( [ '7.4' => [], '8.0' => $nt80, '8.3' => array_merge( [ 'other:::attribute.php', 'other:::contains.php', 'other:::dateerror.php' ], array_slice( $nt80, 2 ) ) ] as $v => $want ) { eq( finding_files( report( "nativetables-$v" ) ), $want, "nativetables-$v: names native in the target, declared unguarded" ); } @@ -1074,13 +1074,25 @@ function counts( string $name ): array { $parse = 'CompatScanner.Syntax.ParseError'; $names = 'PHPCompatibility.Namespaces.ReservedNames.'; $pf = [ - '8.2' => [ "acme/always/bootstrap85.php:$parse", "acme/quoted/bootstrap85.php:$parse", "acme/random/Engine.php:{$names}randomFound" ], + // A gate 8.4.1 passes loads it on 8.4; a sibling too big or unreadable to check may load it too. + '8.2' => [ + "acme/always/bootstrap85.php:$parse", + "acme/bigsib/bootstrap85.php:$parse", + "acme/gatetxt/broken.php:$parse", + "acme/quoted/bootstrap85.php:$parse", + "acme/random/Engine.php:{$names}randomFound", + "acme/unreadsib/bootstrap85.php:$parse", + ], '8.4' => [ "acme/always/bootstrap85.php:$parse", + "acme/bigsib/bootstrap85.php:$parse", "acme/from84/bootstrap85.php:$parse", + "acme/gate841/bootstrap85.php:$parse", + "acme/gatetxt/broken.php:$parse", "acme/pdo/Mysql.php:{$names}pdoFound", "acme/quoted/bootstrap85.php:$parse", "acme/random/Engine.php:{$names}randomFound", + "acme/unreadsib/bootstrap85.php:$parse", ], '8.5' => [ "acme/random/Engine.php:{$names}randomFound" ], ]; @@ -1094,12 +1106,61 @@ function counts( string $name ): array { sort( $got ); eq( $got, $want, "polyfill-$v: errors only where PHP would load or run the file" ); } -// Above the scanner's PHP, 8.5 syntax can't be parsed: the known "can't confirm". -$pf85 = array_column( report( 'polyfill-8.5' )['not_checked'] ?? [], 'file' ); -eq( $pf85, [ 'acme/always/bootstrap85.php', 'acme/from84/bootstrap85.php', 'acme/quoted/bootstrap85.php', 'acme/quotedgate/bootstrap85.php', 'symfony/polyfill-uuid/bootstrap85.php' ], 'polyfill-8.5: bootstrap85.php is unparseable above the scanner\'s PHP' ); +// PHP 8.5 parses bootstrap85.php: only the unreadable sibling is an entry. +foreach ( [ '8.2', '8.4', '8.5' ] as $v ) { + $pf = report( "polyfill-$v" ); + $got = [ array_column( $pf['not_checked'] ?? [], 'file' ), raw( "polyfill-$v.stderr" ) ]; + eq( $got, [ [ 'acme/unreadsib/load.php' ], '' ], "polyfill-$v: no other entry, nothing on stderr" ); +} +tool_error( 'slowsib', 'timed out after 3 s at htdocs/vendor/acme/slow/a.php', 1 ); +$secs = trim( raw( 'slowsib.secs' ) ); +check( '' !== $secs && (int) $secs <= 9, "slowsib: the files beside a failing one are read only until the deadline ($secs s)" ); +eq( finding_files( report( 'appgate' ) ), [ 'directory:lib::bootstrap85.php' ], 'appgate: app code outside a Composer package keeps its lint error, whatever its siblings gate' ); + +// Uses of a name in a block that runs only where it exists, or not on the target, give no finding; PHP agrees on each row. +foreach ( [ '7.4', '8.0' ] as $v ) { + $reported = []; + foreach ( comp_of( report( "useguards-$v" ), 'directory', 'u' )['findings'] ?? [] as $f ) { + $reported[ basename( $f['file'], '.php' ) ] = true; + } + $wrong = []; + foreach ( require '/t/use-guards.php' as list( $id, $target, $php, $scanner ) ) { + $bad = ( 'reported' === $scanner ) !== isset( $reported[ $id ] ) || ( 'fatal' === $php && 'quiet' === $scanner ); + if ( $target === $v && $bad ) { + $wrong[] = $id; + } + } + eq( [ $wrong, report( "useguards-$v" )['not_checked'] ?? null ], [ [], [] ], "useguards-$v: each use reported exactly as tests/use-guards.php says" ); + eq( trim( raw( "useguards-$v.truth" ) ), 'checked', "useguards-$v: PHP $v runs exactly the uses tests/use-guards.php says it runs" ); +} -eq( [ counts( 'shorttag' ), finding_files( report( 'shorttag' ) ) ], [ [ 'ok', true, 0, 2, 0 ], [] ], 'shorttag: with short tags off, ` [], + '8.1' => [ 'other:::globals.php', 'other:::inert.php', 'other:::readonly.php' ], + '8.2' => [ 'other:::globals.php', 'other:::inert.php', 'other:::newro.php', 'other:::readonly.php' ], + '8.3' => [ 'other:::globals.php', 'other:::inert.php', 'other:::newro.php', 'other:::readonly.php', 'other:::statics.php' ], +]; +foreach ( $tl as $v => $want ) { + eq( finding_files( report( "targetlint-$v" ) ), $want, "targetlint-$v: the lint fails exactly where PHP $v does" ); +} +$pt = [ nc( 'directory', 'lib', null, 'stubs/model.stub', 'php_tag' ), nc( 'directory', 'vendor', null, 'acme/x/views/page.tpl', 'php_tag' ) ]; +eq( [ counts( 'pkgtpl' ), report( 'pkgtpl' )['not_checked'] ?? null ], [ [ 'ok', null, 0, 1, 2 ], $pt ], 'pkgtpl: generator templates in a package\'s stubs/ or templates/ aren\'t checked; the same names elsewhere are' ); + +// A .user.ini may turn short tags on, so files with a bare ` '/var/www/htdocs', 'version' => '', 'live' => true ] ], 'wpverout: a version.php outside the roots gives no version' ); echo "\n", $count - $fails, '/', $count, " checks passed\n"; exit( $fails ? 1 : 0 ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 5f0bd0fb..72b4c37d 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1332,6 +1332,8 @@ shorttag_fixture() { printf '\n\n\n' > "$h/short.php" mkdir -p "$h/views" && printf '\n' > "$h/views/short.tpl" printf '\n\n' > "$h/views/schema.xsd" + # Short tags on, only an XML declaration (`\n' > "$h/views/xmlcall.tpl" chmod -R a+rX "$1" } @@ -1354,7 +1356,8 @@ nativetables_fixture() { # polyfill_fixture : a php site vendoring real symfony/polyfill files (tests/symfony-polyfill, MIT): stubs that declare only below a PHP version, and polyfill-uuid's bootstrap85.php, which only PHP 8.5 loads; and look-alikes PHP would load: a reserved namespace declaring a native name, a stub gated a version too late, that bootstrap85.php required unconditionally or from 8.4. polyfill_fixture() { local v="$1/htdocs/vendor" d - mkdir -p "$v/symfony" && cp -R "$HERE/symfony-polyfill/." "$v/symfony/" + mkdir -p "$v/symfony" "$v/composer" && cp -R "$HERE/symfony-polyfill/." "$v/symfony/" + echo '{"packages":[]}' > "$v/composer/installed.json" php_file "$v/acme/random/Engine.php" 'namespace Random; class Engine {}' php_file "$v/acme/pdo/Mysql.php" 'namespace Pdo; @@ -1377,5 +1380,141 @@ require __DIR__ . '/bootstrap85.php';" if ( \\PHP_VERSION_ID >= 80500 ) { require __DIR__ . '/bootstrap85.php'; }" + # A gate that 8.4.1 passes, a version_compare() gate, and siblings the gate check can't read. + for d in gate841 gatevc bigsib unreadsib; do mkdir -p "$v/acme/$d" && cp "$HERE/symfony-polyfill/polyfill-uuid/bootstrap85.php" "$v/acme/$d/"; done + php_file "$v/acme/gate841/bootstrap.php" "if ( \\PHP_VERSION_ID >= 80401 ) { + require __DIR__ . '/bootstrap85.php'; +}" + php_file "$v/acme/gatevc/bootstrap.php" "if ( version_compare( PHP_VERSION, '8.5', '>=' ) ) { + require __DIR__ . '/bootstrap85.php'; +}" + for d in bigsib unreadsib; do + php_file "$v/acme/$d/bootstrap.php" "if ( \\PHP_VERSION_ID >= 80500 ) { + require __DIR__ . '/bootstrap85.php'; +}" + done + { printf ' "$v/acme/bigsib/load.php" + php_file "$v/acme/unreadsib/load.php" "require __DIR__ . '/bootstrap85.php';" + # A gate naming a file that isn't code. + php_file "$v/acme/gatetxt/bootstrap.php" "if ( \\PHP_VERSION_ID >= 80500 ) { + require __DIR__ . '/notes.txt'; +}" + printf ' strlen(...);\n' > "$v/acme/gatetxt/broken.php" + chmod -R a+rX "$1" + chmod 0 "$v/acme/unreadsib/load.php" +} +# Syntax only some targets reject, also inside a file whose code runs only below the target. +targetlint_fixture() { + local h="$1/htdocs" + php_file "$h/globals.php" 'function p_g() { $GLOBALS = []; }' + php_file "$h/statics.php" 'function p_s() { static $a; static $a; }' + php_file "$h/readonly.php" 'class Readonly {}' + php_file "$h/newro.php" '$x = new Readonly();' + php_file "$h/inert.php" 'if ( \PHP_VERSION_ID < 80000 ) { + function p_i() { $GLOBALS = []; } +}' + chmod -R a+rX "$1" +} +# Code generator templates in Composer packages, and the same names outside a Composer vendor dir. +pkgtpl_fixture() { + local h="$1/htdocs" + mkdir -p "$h/vendor/composer" && echo '{"packages":[]}' > "$h/vendor/composer/installed.json" + php_file "$h/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/model.stub" 'namespace {{ namespace }}; + +class {{ class }} extends Model {}' + php_file "$h/vendor/phpunit/phpunit/src/Framework/MockObject/Generator/templates/proxied_method.tpl" '{modifier} function {reference}{method_name}({arguments_decl}){return_declaration} {}' + php_file "$h/lib/stubs/model.stub" 'namespace {{ namespace }};' + php_file "$h/vendor/acme/x/views/page.tpl" 'echo 1 |> strlen(...);' + php_file "$h/index.php" 'echo 1;' + chmod -R a+rX "$1" +} +# symfony/polyfill's old unguarded stubs, its current guarded Attribute, and a site's own Attribute. +oldstubs_fixture() { + local v="$1/htdocs/vendor/symfony" + php_file "$v/polyfill-php80/Resources/stubs/ValueError.php" 'class ValueError extends Error {}' + php_file "$v/polyfill-php80/Resources/stubs/Attribute.php" '#[Attribute(Attribute::TARGET_CLASS)] +final class Attribute {}' + php_file "$v/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php" '#[Attribute(Attribute::TARGET_METHOD)] +final class ReturnTypeWillChange {}' + php_file "$1/htdocs/vendor/acme/attr/Attribute.php" 'if ( \PHP_VERSION_ID < 80000 ) { + final class Attribute {} +}' + php_file "$1/htdocs/app/Attribute.php" 'final class Attribute {}' + chmod -R a+rX "$1" +} +# Classes PHP added later that the site declares itself where that runs on the target, and ones it doesn't. +declared_fixture() { + local h="$1/htdocs" + php_file "$h/vendor/symfony/polyfill-php83/Resources/stubs/DateError.php" 'if ( \PHP_VERSION_ID < 80300 ) { + class DateError extends Error {} +}' + php_file "$h/vendor/symfony/polyfill-php83/Resources/stubs/DateRangeError.php" 'if ( \PHP_VERSION_ID < 80300 ) { + class DateRangeError extends DateError {} +}' + php_file "$h/app/use.php" '$e = new DateRangeError();' + php_file "$h/app/fiber.php" '$f = new Fiber( function () {} );' + php_file "$h/app/late.php" 'if ( \PHP_VERSION_ID >= 80100 ) { + class Fiber {} +}' + php_file "$h/app/inner.php" 'function p_d() { + class Fiber {} +}' + chmod -R a+rX "$1" +} +# Code a file runs before or around the version test the rest of it is wrapped in. +inertedge_fixture() { + local h="$1/htdocs" + php_file "$h/left.php" 'if ( each( $a ) && \PHP_VERSION_ID < 80000 ) { +}' + printf '\n "$h/closetag.php" + php_file "$h/right.php" 'if ( \PHP_VERSION_ID < 80000 && each( $a ) ) { +}' + chmod -R a+rX "$1" +} +# short_open_tag set by .user.ini files: the doc root's applies below it and to code beside it, a deeper one below itself. +shortini_fixture() { + local h="$1/htdocs" + mkdir -p "$h" && printf 'short_open_tag = On\n' > "$h/.user.ini" + printf '\n\n' > "$h/on.php" + mkdir -p "$h/off" && printf 'short_open_tag = Off\n' > "$h/off/.user.ini" + printf '\n\n' > "$h/off/quiet.php" + mkdir -p "$1/lib" && printf '\n\n' > "$1/lib/beside.php" + chmod -R a+rX "$1" +} +# wp-includes/version.php linked to a file outside /var/www and the extra roots. +wpverout_fixture() { + local h="$1/app/htdocs" + wp_core "$h" 6.8.3 + php_file "$1/outside/version.php" "\$wp_version = '6.9.1';" + rm -f "$h/wp-includes/version.php" && ln -s /srv/outside/version.php "$h/wp-includes/version.php" + chmod -R a+rX "$1" +} +# App code (no Composer package) that a sibling loads behind a version gate and public/index.php loads always. +appgate_fixture() { + local h="$1/htdocs" + mkdir -p "$h/lib" && cp "$HERE/symfony-polyfill/polyfill-uuid/bootstrap85.php" "$h/lib/" + php_file "$h/lib/bootstrap.php" "if ( \\PHP_VERSION_ID >= 80500 ) { + require __DIR__ . '/bootstrap85.php'; +}" + php_file "$h/public/index.php" "require __DIR__ . '/../lib/bootstrap85.php';" + chmod -R a+rX "$1" +} +# A file that fails the lint, with many big code files beside it for the bootstrap check to read. +slowsib_fixture() { + local v="$1/htdocs/vendor" i + mkdir -p "$v/composer" "$v/acme/slow" && echo '{"packages":[]}' > "$v/composer/installed.json" + cp "$HERE/symfony-polyfill/polyfill-uuid/bootstrap85.php" "$v/acme/slow/a.php" + { printf ' "$v/acme/slow/s01.php" + for i in $(seq 2 40); do ln "$v/acme/slow/s01.php" "$v/acme/slow/s$(printf %02d "$i").php"; done + chmod -R a+rX "$1" +} +# shortiniwp_fixture : WordPress whose .user.ini turns short tags on, in htdocs or a release behind `current`. +shortiniwp_fixture() { + local h="$1/htdocs" + if [ "$2" = release ]; then mkdir -p "$h/releases/1" && ln -s releases/1 "$h/current" && h="$h/releases/1"; fi + wp_core "$h" 6.8.3 + printf 'short_open_tag = On\n' > "$h/.user.ini" + php_file "$h/wp-content/plugins/p/p.php" '/* Plugin Name: P */' + printf '\n\n' > "$h/wp-content/plugins/p/view.php" chmod -R a+rX "$1" } diff --git a/compat-scanner/tests/guards.php b/compat-scanner/tests/guards.php index bd6fe993..ada2f74d 100644 --- a/compat-scanner/tests/guards.php +++ b/compat-scanner/tests/guards.php @@ -99,6 +99,17 @@ [ 'c-no-return', 'fatal', 'reported', "if ( class_exists( 'NoDiscard' ) ) { \$x = 1; }\n" . C ], [ 'c-return-nested', 'fatal', 'reported', "if ( class_exists( 'NoDiscard' ) ) { if ( defined( 'P_X' ) ) { return; } }\n" . C ], [ 'c-return-after', 'fatal', 'reported', C . "\nif ( class_exists( 'NoDiscard' ) ) { return; }" ], + // The return must be the guard block's only statement, the guard a statement of its own, and no goto may jump past it. + [ 'c-return-braceless', 'fatal', 'reported', "if ( class_exists( 'NoDiscard' ) ) { if ( defined( 'P_X' ) ) return; }\n" . C ], + [ 'c-return-foreach-in', 'fatal', 'reported', "if ( class_exists( 'NoDiscard' ) ) { foreach ( [] as \$p ) return; }\n" . C ], + [ 'c-return-goto', 'fatal', 'reported', "if ( class_exists( 'NoDiscard' ) ) { goto p_l; return; }\np_l:\n" . C ], + [ 'c-return-goto-before', 'fatal', 'reported', "goto p_l;\nif ( class_exists( 'NoDiscard' ) ) { return; }\np_l:\n" . C ], + [ 'c-return-in-braceless-if', 'fatal', 'reported', "if ( false ) if ( class_exists( 'NoDiscard' ) ) { return; }\n" . C ], + [ 'c-return-in-foreach', 'fatal', 'reported', "foreach ( [] as \$p ) if ( class_exists( 'NoDiscard' ) ) { return; }\n" . C ], + [ 'c-return-else-if', 'fatal', 'reported', "if ( true ) { } else if ( class_exists( 'NoDiscard' ) ) { return; }\n" . C ], + [ 'c-return-decl-first', 'fatal', 'reported', "if ( class_exists( 'NoDiscard' ) ) { " . C . ' return; }' ], + [ 'c-return-value', 'ok', 'quiet', "if ( class_exists( 'NoDiscard' ) ) { return 1; }\n" . C ], + [ 'c-return-two', 'ok', 'reported', "if ( class_exists( 'NoDiscard' ) ) { \$x = 1; return; }\n" . C ], // PHP declares the function at compile time, so other code can still call it and declare the class. [ 'c-return-in-function', 'ok', 'reported', "if ( class_exists( 'NoDiscard' ) ) { return; }\nfunction p_load() { " . C . ' }' ], ]; @@ -108,7 +119,7 @@ file_put_contents( "$argv[2]/$id.php", "&1', $out, $rc ); @@ -118,6 +129,7 @@ } $out = []; } + unlink( $tmp ); echo "checked\n"; } return $rows; diff --git a/compat-scanner/tests/manifest-check.php b/compat-scanner/tests/manifest-check.php index 058f69c2..093eb7f7 100644 --- a/compat-scanner/tests/manifest-check.php +++ b/compat-scanner/tests/manifest-check.php @@ -79,10 +79,14 @@ } $inodes[ $st['dev'] . ':' . $st['ino'] ] = true; } -// Only phars are information (by the name walked or the target's), never a directory or other code. +// Only phars (by the name walked or the target's) and generator templates in Composer packages are information. +$template = static function ( string $p ): bool { + $vendor = preg_match( '#^(.*)/vendor/[^/]+/[^/]+/(?:[^/]+/)*(?:stubs|templates)/(?:[^/]+/)*[^/]+\.(?:stub|tpl)\z#i', $p, $v ) ? $v[1] . '/vendor' : null; + return null !== $vendor && ( is_file( "$vendor/composer/installed.json" ) || is_file( "$vendor/autoload.php" ) ); +}; foreach ( $m['information'] as $p ) { - if ( ! is_file( $p ) || ! ( preg_match( $m['phar_regex'], $p ) || preg_match( $m['phar_regex'], (string) realpath( $p ) ) ) ) { - $problems[] = "information entry not a phar: $p"; + if ( ! is_file( $p ) || ! ( preg_match( $m['phar_regex'], $p ) || preg_match( $m['phar_regex'], (string) realpath( $p ) ) || $template( $p ) ) ) { + $problems[] = "information entry not a phar or package template: $p"; } } $ncDirs = []; diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index b48dadc7..37b66419 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -456,6 +456,18 @@ docker pull -q php:8.5.0-cli > /dev/null docker run --rm --network none --mount "type=bind,src=$HERE/guards.php,dst=/t/guards.php,readonly" \ php:8.5.0-cli php /t/guards.php truth > "$RES/guards.truth" 2>&1 || true +# Uses of names PHPCompatibility flags, guarded or not (tests/use-guards.php); PHP itself says which of them run. +for v in 7.4 8.0; do + mkdir -p "$WORK/useguards-$v/htdocs/u" + docker run --rm --network none --user "$(id -u):$(id -g)" --mount "type=bind,src=$WORK/useguards-$v/htdocs/u,dst=/u" \ + --mount "type=bind,src=$HERE/use-guards.php,dst=/t/use-guards.php,readonly" --entrypoint php "$IMAGE" /t/use-guards.php write /u "$v" + chmod -R a+rX "$WORK/useguards-$v" + scan "useguards-$v" "$WORK/useguards-$v" php /var/www/htdocs "$v" 600 + docker pull -q "php:$v-cli" > /dev/null + docker run --rm --network none --mount "type=bind,src=$HERE/use-guards.php,dst=/t/use-guards.php,readonly" \ + "php:$v-cli" php /t/use-guards.php truth "$v" > "$RES/useguards-$v.truth" 2>&1 || true +done + # Names PHP added in 8.0 and 8.3, declared unguarded. nativetables_fixture "$WORK/nativetables" for v in 7.4 8.0 8.3; do scan "nativetables-$v" "$WORK/nativetables" php /var/www/htdocs "$v" 600; done @@ -463,11 +475,38 @@ for v in 7.4 8.0 8.3; do scan "nativetables-$v" "$WORK/nativetables" php /var/ww # symfony/polyfill files PHP never loads or runs on the target, and look-alikes it would. polyfill_fixture "$WORK/polyfill" for v in 8.2 8.4 8.5; do scan "polyfill-$v" "$WORK/polyfill" php /var/www/htdocs "$v" 600; done +appgate_fixture "$WORK/appgate" +scan appgate "$WORK/appgate" php /var/www/htdocs 8.4 600 +# The bootstrap check reads the files beside a failing one only until the deadline. +slowsib_fixture "$WORK/slowsib" +start=$SECONDS +scan slowsib "$WORK/slowsib" php /var/www/htdocs 8.4 3 -e COMPAT_BATCH_SIZE=1 +echo $(( SECONDS - start )) > "$RES/slowsib.secs" +rm -rf "$WORK/slowsib" +oldstubs_fixture "$WORK/oldstubs" +for v in 8.0 8.1; do scan "oldstubs-$v" "$WORK/oldstubs" php /var/www/htdocs "$v" 600; done +declared_fixture "$WORK/declared" +scan declared "$WORK/declared" php /var/www/htdocs 8.0 600 +inertedge_fixture "$WORK/inertedge" +scan inertedge "$WORK/inertedge" php /var/www/htdocs 8.2 600 + +# The lint runs each target's own PHP. +targetlint_fixture "$WORK/targetlint" +for v in 8.0 8.1 8.2 8.3; do scan "targetlint-$v" "$WORK/targetlint" php /var/www/htdocs "$v" 600; done +pkgtpl_fixture "$WORK/pkgtpl" +scan pkgtpl "$WORK/pkgtpl" php /var/www/htdocs 8.4 600 # short_open_tag as EE reads it from the site (default off, as in EE's images). shorttag_fixture "$WORK/shorttag" scan shorttag "$WORK/shorttag" php /var/www/htdocs 8.4 600 scan shorttag-on "$WORK/shorttag" php /var/www/htdocs 8.4 600 -e COMPAT_SHORT_OPEN_TAG=1 +# ... and as .user.ini files set it, unless the pool locks it. +shortini_fixture "$WORK/shortini" +scan shortini "$WORK/shortini" php /var/www/htdocs 8.0 600 +scan shortini-locked "$WORK/shortini" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG_LOCKED=1 +for v in flat release; do shortiniwp_fixture "$WORK/shortiniwp-$v" "$v"; done +scan shortiniwp-flat "$WORK/shortiniwp-flat" wp /var/www/htdocs 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 +scan shortiniwp-release "$WORK/shortiniwp-release" wp /var/www/htdocs/current 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 # Quick runs one after another (a lint per file) stay within a small pids limit; a lint the deadline ends is a timeout. burst_fixture "$WORK/burst" @@ -505,6 +544,11 @@ scan badargs-served "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_SERVED=/etc scan badargs-supported "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_WP_SUPPORTED=6 scan badargs-roots "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_EXTRA_ROOTS=/var/www/x scan badargs-short "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_SHORT_OPEN_TAG=on +scan badargs-locked "$WORK/wp" wp /var/www/htdocs 8.4 600 -e COMPAT_SHORT_OPEN_TAG_LOCKED=yes + +# A version.php that resolves outside the roots gives no version. +wpverout_fixture "$WORK/wpverout" +scan wpverout "$WORK/wpverout/app" wp /var/www/htdocs 8.4 600 --mount "type=bind,src=$WORK/wpverout/outside,dst=/srv/outside,readonly" # An estimate keeps time for calibration: throttled, the listing of 20,000 files can't finish in its share of 1 s. estimate est-listing "$WORK/wide" wp /var/www/htdocs 8.4 -e COMPAT_ESTIMATE_TIMEOUT=1 --cpus 0.05 @@ -516,4 +560,5 @@ docker run --rm --network none --read-only --user 33:33 \ --mount "type=bind,src=$RES,dst=/r,readonly" \ --mount "type=bind,src=$HERE/assert.php,dst=/t/assert.php,readonly" \ --mount "type=bind,src=$HERE/guards.php,dst=/t/guards.php,readonly" \ + --mount "type=bind,src=$HERE/use-guards.php,dst=/t/use-guards.php,readonly" \ --entrypoint php "$IMAGE" /t/assert.php /r diff --git a/compat-scanner/tests/use-guards.php b/compat-scanner/tests/use-guards.php new file mode 100644 index 00000000..9bbfc19d --- /dev/null +++ b/compat-scanner/tests/use-guards.php @@ -0,0 +1,75 @@ + runs it, the scanner reports it, code ]. +// Usage: php use-guards.php write | php use-guards.php truth (on php:-cli: prints each row PHP disagrees with, then `checked`). + +const E = 'each( $a );'; +const L = 'array_is_list( [] );'; +const N = 'new Fiber( function () {} );'; + +$rows = [ + // each() is gone from 8.0: a use that runs only where it exists, or only below 8.0. + [ 'e-bare', '8.0', 'fatal', 'reported', E ], + [ 'e-exists', '8.0', 'ok', 'quiet', "if ( function_exists( 'each' ) ) { " . E . ' }' ], + [ 'e-exists-fq', '8.0', 'ok', 'quiet', "if ( \\function_exists( 'EACH' ) ) { " . E . ' }' ], + [ 'e-exists-and', '8.0', 'ok', 'quiet', "if ( defined( 'PHP_EOL' ) && function_exists( 'each' ) ) { " . E . ' }' ], + [ 'e-nested', '8.0', 'ok', 'quiet', "if ( function_exists( 'each' ) ) { if ( true ) { " . E . ' } }' ], + [ 'e-in-function', '8.0', 'ok', 'quiet', "if ( function_exists( 'each' ) ) { function p_e( \$a ) { return each( \$a ); } }" ], + [ 'e-else', '8.0', 'ok', 'quiet', "if ( ! function_exists( 'each' ) ) { } else { " . E . ' }' ], + [ 'e-else-or', '8.0', 'ok', 'quiet', "if ( ! function_exists( 'each' ) || false ) { } else { " . E . ' }' ], + [ 'e-ver', '8.0', 'ok', 'quiet', 'if ( PHP_VERSION_ID < 80000 ) { ' . E . ' }' ], + [ 'e-ver-yoda', '8.0', 'ok', 'quiet', 'if ( 80000 > \\PHP_VERSION_ID ) { ' . E . ' }' ], + [ 'e-vc', '8.0', 'ok', 'quiet', "if ( version_compare( PHP_VERSION, '8.0', '<' ) ) { " . E . ' }' ], + [ 'e-else-ver', '8.0', 'ok', 'quiet', 'if ( PHP_VERSION_ID >= 80000 ) { } else { ' . E . ' }' ], + [ 'e-mysql', '8.0', 'ok', 'quiet', "if ( function_exists( 'mysql_query' ) ) { mysql_query( 'SELECT 1' ); }" ], + // Shapes that don't guard it. + [ 'e-or', '8.0', 'fatal', 'reported', "if ( function_exists( 'each' ) || true ) { " . E . ' }' ], + [ 'e-missing', '8.0', 'fatal', 'reported', "if ( ! function_exists( 'each' ) ) { " . E . ' }' ], + [ 'e-other-name', '8.0', 'fatal', 'reported', "if ( function_exists( 'strlen' ) ) { " . E . ' }' ], + [ 'e-ver-high', '8.0', 'fatal', 'reported', 'if ( PHP_VERSION_ID < 80100 ) { ' . E . ' }' ], + [ 'e-else-exists', '8.0', 'fatal', 'reported', "if ( function_exists( 'each' ) ) { } else { " . E . ' }' ], + [ 'e-after', '8.0', 'fatal', 'reported', "if ( function_exists( 'each' ) ) { }\n" . E ], + // Strict: PHP runs these, but they aren't shapes the grammar accepts. + [ 'e-in-condition', '8.0', 'ok', 'reported', "if ( function_exists( 'each' ) && each( \$a ) ) { }" ], + [ 'e-ternary', '8.0', 'ok', 'reported', "\$x = function_exists( 'each' ) ? each( \$a ) : null;" ], + [ 'e-vc-named', '8.0', 'ok', 'reported', "if ( version_compare( PHP_VERSION, '8.0', operator: '<' ) ) { " . E . ' }' ], + // Not in PHP 8.0: array_is_list() and Fiber. + [ 'l-bare', '8.0', 'fatal', 'reported', L ], + [ 'l-exists', '8.0', 'ok', 'quiet', "if ( function_exists( 'array_is_list' ) ) { " . L . ' }' ], + [ 'l-ver', '8.0', 'ok', 'quiet', 'if ( PHP_VERSION_ID >= 80100 ) { ' . L . ' }' ], + [ 'l-ver-low', '8.0', 'fatal', 'reported', 'if ( PHP_VERSION_ID >= 80000 ) { ' . L . ' }' ], + [ 'n-bare', '8.0', 'fatal', 'reported', N ], + [ 'n-exists', '8.0', 'ok', 'quiet', "if ( class_exists( 'Fiber' ) ) { " . N . ' }' ], + [ 'n-ver', '8.0', 'ok', 'quiet', 'if ( \\PHP_VERSION_ID >= 80100 ) { new \\Fiber( function () {} ); }' ], + [ 'n-wrong-check', '8.0', 'ok', 'reported', "if ( function_exists( 'Fiber' ) ) { " . N . ' }' ], + // PHPCompatibility flags `Fiber::class` in the condition itself, outside the block. + [ 'n-exists-class', '8.0', 'ok', 'reported', 'if ( class_exists( \\Fiber::class ) ) { ' . N . ' }' ], + [ 'n-declared-here', '8.0', 'fatal', 'reported', 'function p_f() { class Fiber {} }' . "\n" . N ], + // Not in PHP 7.4: Stringable. + [ 's-bare', '7.4', 'fatal', 'reported', "class P_S implements Stringable { public function __toString() { return ''; } }" ], + [ 's-exists', '7.4', 'ok', 'quiet', "if ( interface_exists( 'Stringable' ) ) { class P_T implements Stringable { public function __toString() { return ''; } } }" ], +]; + +if ( 'write' === ( $argv[1] ?? '' ) ) { + foreach ( $rows as list( $id, $target, , , $code ) ) { + if ( $target === $argv[3] ) { + file_put_contents( "$argv[2]/$id.php", "&1', $out, $rc ); + $got = 0 === $rc ? 'ok' : 'fatal'; + if ( $got !== $php ) { + echo "$id: PHP " . PHP_VERSION . " says $got, the table $php\n"; + } + $out = []; + } + unlink( $tmp ); + echo "checked\n"; +} +return $rows; From 69a1e04e7f7b5fca6584f28203c1d6ffc66819ec Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 09:10:46 +0530 Subject: [PATCH 48/80] fix(compat-scanner): a sniffed file with no PHP code isn't a php_tag entry Files without a code name are now sniffed with a bare ``: symfony/translation ships one in every Laravel app. Where short tags are off, PHPCS finds no code in such a file and says so with an Internal.NoCodeFound warning. The rule for files with text before their tag took that warning as trouble, so the file became "can't confirm". A file with no code runs nothing, so it is now counted as checked. --- compat-scanner/bin/compat-scanner.php | 3 ++- compat-scanner/tests/assert.php | 4 ++-- compat-scanner/tests/fixture.sh | 2 ++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 9347d160..ccc1e3b1 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -1924,7 +1924,8 @@ private function record( array $f, ReportReader $reader ): void { if ( $f['mixed'] ) { $messages = []; while ( null !== ( $m = $reader->message() ) ) { - if ( 'ERROR' === $m[2] || 0 === strpos( $m[3], 'Internal.' ) ) { + // No code at all (a bare `skipMessages(); $this->spoolNotChecked( $comp, $raw, 'php_tag', $f['real'] ); return; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 48768952..fd999dab 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1153,8 +1153,8 @@ function counts( string $name ): array { eq( [ counts( 'pkgtpl' ), report( 'pkgtpl' )['not_checked'] ?? null ], [ [ 'ok', null, 0, 1, 2 ], $pt ], 'pkgtpl: generator templates in a package\'s stubs/ or templates/ aren\'t checked; the same names elsewhere are' ); // A .user.ini may turn short tags on, so files with a bare `\n\n' > "$h/views/schema.xsd" # Short tags on, only an XML declaration (`\n' > "$h/views/xmlcall.tpl" + # An XML processing instruction: with short tags off, a file with no code that is checked and gives nothing. + printf '\n\n\n' > "$h/views/style.xsd" chmod -R a+rX "$1" } From 29e1aa48b2986e362d50b54c5a62d883d233d6e1 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 09:14:13 +0530 Subject: [PATCH 49/80] fix(compat-scanner): count a lint run per file in the estimate below PHP 8.3 Before 8.3, `php -l` reads only its first file, so targets 8.0 to 8.2 lint each file in a run of its own. Each run costs the target PHP's start-up time. The estimate now times one such run on the calibration's empty file, adds it once per listed file, and reports the time as inputs.lint_seconds. Without it, an 8.0 to 8.2 estimate fell short of the scan's real time, and so did the timeout EE derives from it. --- compat-scanner/bin/compat-scanner.php | 14 ++++++++++---- compat-scanner/tests/assert.php | 2 ++ compat-scanner/tests/run.sh | 1 + 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index ccc1e3b1..a4578f17 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -1555,6 +1555,8 @@ private function estimate(): array { $calBytes += filesize( $p ); } $sample = $this->timed( $list ); + // A lint run per file costs at least its start-up. + $lint = $this->lintsEach() ? $this->lintRun( [ CALIBRATION_DIR . '/empty.php' ], 0.0 )['seconds'] : 0.0; } finally { $this->removeWork(); } @@ -1564,7 +1566,7 @@ private function estimate(): array { $batches = $files > 0 ? (int) ceil( $files / $this->cfg['batch_size'] ) : 0; $perBatch = $this->cfg['seconds_per_batch']; // Every STDIN file is a PHPCS run of its own, which costs at least its start-up. - $raw = $bytes / $bps + $batches * $perBatch + $this->stdinFiles * $empty; + $raw = $bytes / $bps + $batches * $perBatch + $this->stdinFiles * $empty + $files * $lint; $est = max( 1, (int) round( $raw ) ); $doc = $this->head( 'ok' ); @@ -1583,6 +1585,7 @@ private function estimate(): array { 'batches' => $batches, 'seconds_per_batch' => $perBatch, 'stdin_files' => $this->stdinFiles, + 'lint_seconds' => round( $lint, 3 ), 'cpus' => cpu_count(), 'load_average_1m' => load_average(), 'low_factor' => $this->cfg['low_factor'], @@ -2425,9 +2428,7 @@ private function lint( array $batch ): array { if ( ! is_file( $this->lintPhp() ) ) { throw new ToolError( 'no PHP ' . $this->cfg['version'] . ' in the image to lint with' ); } - // Before 8.3 `php -l` reads only its first file, so each file is linted alone. - $batched = version_compare( $this->cfg['version'], '8.3', '>=' ); - if ( $batched && 0 === $this->lintRun( array_values( $paths ), (float) $this->cfg['file_timeout'] )['rc'] ) { + if ( ! $this->lintsEach() && 0 === $this->lintRun( array_values( $paths ), (float) $this->cfg['file_timeout'] )['rc'] ) { return []; } $failed = []; @@ -2523,6 +2524,11 @@ private function gatedAbove( array $tokens, int $i, int $above ): bool { return null !== $range && $range[0] >= $above; } + /** Before 8.3 `php -l` reads only its first file, so each file is linted alone. */ + private function lintsEach(): bool { + return version_compare( $this->cfg['version'], '8.0', '>=' ) && version_compare( $this->cfg['version'], '8.3', '<' ); + } + private function lintPhp(): string { return PHP_DIR . '/' . $this->cfg['version'] . '/php'; } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index fd999dab..f1c52b39 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -369,6 +369,8 @@ static function ( $a, $b ) { $in = $e['inputs'] ?? []; check( ( $in['calibration_bytes'] ?? 0 ) > 500000 && ( $in['bytes_per_second'] ?? 0 ) > 0 && ( $in['cpus'] ?? 0 ) == 1 && isset( $in['load_average_1m'], $in['batches'], $in['seconds_per_batch'], $in['low_factor'], $in['high_factor'] ), "$name: inputs" ); } +$lint80 = out( 'est-80' )['inputs']['lint_seconds'] ?? 0; +eq( [ $lint80 > 0, out( 'est' )['inputs']['lint_seconds'] ?? null ], [ true, 0.0 ], 'est-80: below 8.3 each file\'s own lint run is counted; from 8.3 the lint is one run a batch' ); tool_error( 'est-timeout', 'timed out after 1 s', 1, false ); tool_error( 'badver', 'bad arguments: version must look like 8.4', 2, false ); eq( out( 'est-nocode' ), [ 'v' => 1, 'status' => 'no_code_found', 'estimate' => true, 'site' => 'fixture.test', 'target' => '8.4', 'safe_to_upgrade' => null ], 'est-nocode: no_code_found' ); diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 37b66419..d81ed2ed 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -161,6 +161,7 @@ scan nocode "$WORK/empty" wp /var/www/htdocs 8.4 600 scan badargs "$WORK/wp" wp /etc 8.4 600 estimate est "$WORK/wp" wp /var/www/htdocs/current 8.4 estimate est-php "$WORK/php" php /var/www/htdocs/public 8.4 +estimate est-80 "$WORK/wp" wp /var/www/htdocs/current 8.0 estimate est-nocode "$WORK/empty" wp /var/www/htdocs 8.4 # wp-config.php: the one WordPress loads, as component other/wp-config.php. From a458768a5c43ea2453e750b9cbf6d54bee4968e5 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 09:27:16 +0530 Subject: [PATCH 50/80] test(compat-scanner): compare the estimate's lint time as a number JSON gives 0 for a zero lint time, which PHP decodes as an integer. --- compat-scanner/tests/assert.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index f1c52b39..be94953a 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -370,7 +370,7 @@ static function ( $a, $b ) { check( ( $in['calibration_bytes'] ?? 0 ) > 500000 && ( $in['bytes_per_second'] ?? 0 ) > 0 && ( $in['cpus'] ?? 0 ) == 1 && isset( $in['load_average_1m'], $in['batches'], $in['seconds_per_batch'], $in['low_factor'], $in['high_factor'] ), "$name: inputs" ); } $lint80 = out( 'est-80' )['inputs']['lint_seconds'] ?? 0; -eq( [ $lint80 > 0, out( 'est' )['inputs']['lint_seconds'] ?? null ], [ true, 0.0 ], 'est-80: below 8.3 each file\'s own lint run is counted; from 8.3 the lint is one run a batch' ); +eq( [ $lint80 > 0, (float) ( out( 'est' )['inputs']['lint_seconds'] ?? -1 ) ], [ true, 0.0 ], 'est-80: below 8.3 each file\'s own lint run is counted; from 8.3 the lint is one run a batch' ); tool_error( 'est-timeout', 'timed out after 1 s', 1, false ); tool_error( 'badver', 'bad arguments: version must look like 8.4', 2, false ); eq( out( 'est-nocode' ), [ 'v' => 1, 'status' => 'no_code_found', 'estimate' => true, 'site' => 'fixture.test', 'target' => '8.4', 'safe_to_upgrade' => null ], 'est-nocode: no_code_found' ); From 6caebdee486b2dc0de1ae0139bcf7780c67e1557 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 09:34:26 +0530 Subject: [PATCH 51/80] fix(compat-scanner): match namespaced new classes the site declares itself A new class or interface finding was dropped only for a global class the site declares. The polyfills also declare namespaced ones, such as symfony/polyfill-php82's Random\RandomError and Random\CryptoSafeEngine and polyfill-php85's Filter\FilterException, so their own stubs and every use of them stayed an error at 8.0 to 8.4. Declarations are now matched by their full name, which is taken from PHPCompatibility's message, since its error code mangles the `\`. --- compat-scanner/src/LinesReport.php | 10 ++++++---- compat-scanner/tests/assert.php | 2 +- compat-scanner/tests/fixture.sh | 9 +++++++++ 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/compat-scanner/src/LinesReport.php b/compat-scanner/src/LinesReport.php index 9ac421c2..a68cf37a 100644 --- a/compat-scanner/src/LinesReport.php +++ b/compat-scanner/src/LinesReport.php @@ -57,8 +57,9 @@ public function generateFileReport( array $report, File $phpcsFile, bool $showSo if ( null !== $ptr && $this->guarded( $phpcsFile, $ptr, $check, $name ) ) { continue; } + // The message names a namespaced class in full; the source mangles its `\`. if ( preg_match( '/\.New(?:Classes|Interfaces)\./', $message['source'] ) ) { - $message['class'] = $name; + $message['class'] = preg_match( '/^The built-in (?:class|interface) \\\\?(\S+) is /', $message['message'], $c ) ? strtolower( $c[1] ) : $name; } } $count++; @@ -131,7 +132,7 @@ private function guarded( File $phpcsFile, int $ptr, string $check, string $name } /** - * Lowercase names of the global classes, interfaces, traits and enums the file declares where the declaration runs on + * Lowercase full names of the classes, interfaces, traits and enums the file declares where the declaration runs on * the target: at file scope, or only in if blocks each of whose `&&` operands holds there (a version test, or a * negated class_exists() or interface_exists() on that name). * @@ -141,16 +142,17 @@ private function declared( File $phpcsFile ): array { $tokens = $phpcsFile->getTokens(); $names = []; foreach ( $tokens as $ptr => $token ) { - if ( ! in_array( $token['code'], [ T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM ], true ) || '' !== Namespaces::determineNamespace( $phpcsFile, $ptr ) ) { + if ( ! in_array( $token['code'], [ T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM ], true ) ) { continue; } $name = (string) $phpcsFile->getDeclarationName( $ptr ); + $ns = Namespaces::determineNamespace( $phpcsFile, $ptr ); $runs = '' !== $name; foreach ( array_keys( $token['conditions'] ) as $block ) { $runs = $runs && ( T_NAMESPACE === $tokens[ $block ]['code'] || $this->holds( $phpcsFile, $block, $name ) ); } if ( $runs ) { - $names[] = strtolower( $name ); + $names[] = strtolower( '' === $ns ? $name : "$ns\\$name" ); } } return $names; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index be94953a..53135411 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1140,7 +1140,7 @@ function counts( string $name ): array { foreach ( [ '8.0', '8.1' ] as $v ) { eq( finding_files( report( "oldstubs-$v" ) ), [ 'directory:app::Attribute.php' ], "oldstubs-$v: only the unguarded Attribute outside the polyfill's stubs" ); } -eq( finding_files( report( 'declared' ) ), [ 'directory:app::fiber.php' ], 'declared: a new class the site declares where that runs on the target is no finding' ); +eq( finding_files( report( 'declared' ) ), [ 'directory:app::fiber.php', 'directory:app::random.php' ], 'declared: a new class the site declares where that runs on the target is no finding' ); eq( finding_files( report( 'inertedge' ) ), [ 'other:::closetag.php', 'other:::left.php' ], 'inertedge: code before the version test, or past a close tag, still runs' ); $tl = [ '8.0' => [], diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index e98804a3..16737015 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1453,6 +1453,15 @@ declared_fixture() { php_file "$h/vendor/symfony/polyfill-php83/Resources/stubs/DateRangeError.php" 'if ( \PHP_VERSION_ID < 80300 ) { class DateRangeError extends DateError {} }' + php_file "$h/vendor/symfony/polyfill-php82/Resources/stubs/Random/RandomError.php" 'namespace Random; +if ( \PHP_VERSION_ID < 80200 ) { + class RandomError extends \Error {} +}' + php_file "$h/vendor/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php" 'namespace Random; +if ( \PHP_VERSION_ID < 80200 ) { + class BrokenRandomEngineError extends RandomError {} +}' + php_file "$h/app/random.php" '$r = new \Random\Randomizer();' php_file "$h/app/use.php" '$e = new DateRangeError();' php_file "$h/app/fiber.php" '$f = new Fiber( function () {} );' php_file "$h/app/late.php" 'if ( \PHP_VERSION_ID >= 80100 ) { From abab5dfd57dc405383d3bc197e71a28f09a55181 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 09:40:21 +0530 Subject: [PATCH 52/80] test(compat-scanner): cover a version_compare() guard with named arguments A guard with version_compare( PHP_VERSION, '8.5', operator: '<' ) used to end the run in an internal exception, which made the file unparseable. It is now read as no version test, so the declaration it wraps is reported. The guard table gets that row. Docblocks added in this round are unwrapped to one line per paragraph. --- compat-scanner/bin/compat-scanner.php | 17 +++++------------ compat-scanner/src/CompatScanner/Guard.php | 15 +++++---------- .../Sniffs/Classes/NativeDeclaredSniff.php | 3 +-- .../CompatScanner/Sniffs/Files/InertSniff.php | 4 +--- compat-scanner/src/LinesReport.php | 11 +++-------- compat-scanner/tests/guards.php | 1 + 6 files changed, 16 insertions(+), 35 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index a4578f17..7e2219cd 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -1320,8 +1320,7 @@ private function isTemplateName( string $name ): bool { /** `.phar` and the archive forms PHP's phar extension also opens (`.phar.tar`, `.phar.tar.gz`, `.phar.zip`, ...). */ /** - * A `.stub` or `.tpl` under a `stubs/` or `templates/` dir of a Composer package, as Laravel's and PHPUnit's code - * generators ship them: filled in and written out, never run. + * A `.stub` or `.tpl` under a `stubs/` or `templates/` dir of a Composer package, as Laravel's and PHPUnit's code generators ship them: filled in and written out, never run. */ private function packageTemplate( string $path ): bool { return preg_match( '#/vendor/[^/]+/[^/]+/(?:[^/]+/)*(?:stubs|templates)/(?:[^/]+/)*[^/]+\.(?:stub|tpl)\z#i', $path ) && $this->inPackage( $path ); @@ -1767,8 +1766,7 @@ private function runBatch( array $batch ): void { } /** - * short_open_tag for a file, as PHP-FPM applies .user.ini files: the deepest one that sets it from the doc root down to - * the file's directory; for a file outside the doc root, the doc root's, where the requests that load it start. + * short_open_tag for a file, as PHP-FPM applies .user.ini files: the deepest one that sets it from the doc root down to the file's directory; for a file outside the doc root, the doc root's, where the requests that load it start. */ private function shortFor( string $path ): bool { $short = $this->cfg['short_tags']; @@ -2409,9 +2407,7 @@ private function runTimed( array $cmd, float $cap, array $spec, int $fsize = 0 ) } /** - * `php -l` with the target's PHP over a batch, then each failing file alone: PHPCompatibility misses some parse errors (`#[` - * before PHP 8, an unclosed comment). Not for targets before 8.0 (none in the image), nor files with text before the tag and - * no template name. + * `php -l` with the target's PHP over a batch, then each failing file alone: PHPCompatibility misses some parse errors (`#[` before PHP 8, an unclosed comment). Not for targets before 8.0 (none in the image), nor files with text before the tag and no template name. * * @return array By batch key, the files that fail: [ line, message ] or a not_checked reason. */ @@ -2450,9 +2446,7 @@ private function lint( array $batch ): array { } /** - * Whether the code beside a file in a Composer package loads it only above the target, as Symfony's polyfills load bootstrap85.php. - * Every string naming it there must sit in `if ( ) { [return] require __DIR__ . '/name'; }`, the test - * holding only above the target; a code file beside it that can't be read may name it too. + * Whether the code beside a file in a Composer package loads it only above the target, as Symfony's polyfills load bootstrap85.php. Every string naming it there must sit in `if ( ) { [return] require __DIR__ . '/name'; }`, the test holding only above the target; a code file beside it that can't be read may name it too. */ private function loadedOnlyAbove( string $real, string $path ): bool { // App code may load it from anywhere; a package is loaded through its own files. @@ -3040,8 +3034,7 @@ function mount_path( string $path, string $what ): string { } /** - * An install's version: exactly one `$wp_version = '…';` or `"…"` line holding a plain version of at most 64 characters - * (EE prints it as given), else '' (unknown), as when version.php resolves outside the roots (null). + * An install's version: exactly one `$wp_version = '…';` or `"…"` line holding a plain version of at most 64 characters (EE prints it as given), else '' (unknown), as when version.php resolves outside the roots (null). */ function wp_version( ?string $file, callable $tick ): string { $fh = null === $file ? null : open_regular( $file ); diff --git a/compat-scanner/src/CompatScanner/Guard.php b/compat-scanner/src/CompatScanner/Guard.php index 28db75a6..9cfe7a29 100644 --- a/compat-scanner/src/CompatScanner/Guard.php +++ b/compat-scanner/src/CompatScanner/Guard.php @@ -1,7 +1,6 @@ N` either way round with N a plain decimal, or `version_compare( PHP_VERSION, 'X.Y[.Z]', '<' | 'lt' | '>=' | 'ge' )`. + * The PHP_VERSION_ID range [from, to) where a version test holds, from the text of its tokens (no whitespace or comments): `PHP_VERSION_ID N` either way round with N a plain decimal, or `version_compare( PHP_VERSION, 'X.Y[.Z]', '<' | 'lt' | '>=' | 'ge' )`. * * @return int[]|null */ @@ -50,8 +48,7 @@ public static function target( string $version ): array { } /** - * Whether a block enclosing $ptr runs only where $inIf accepts an `&&` operand of its if or elseif, or is the else - * of an if with a `||` operand $inElse accepts. + * Whether a block enclosing $ptr runs only where $inIf accepts an `&&` operand of its if or elseif, or is the else of an if with a `||` operand $inElse accepts. */ public static function encloses( File $file, int $ptr, callable $inIf, callable $inElse ): bool { $tokens = $file->getTokens(); @@ -81,8 +78,7 @@ public static function any( File $file, int $ptr, bool $or, callable $test ): bo } /** - * The top-level operands of the condition of the if or elseif at $ptr, each without parentheses around it; null when - * it isn't one or another top-level logical operator joins them. + * The top-level operands of the condition of the if or elseif at $ptr, each without parentheses around it; null when it isn't one or another top-level logical operator joins them. * * @return array|null */ @@ -135,8 +131,7 @@ static function ( $ptr ) use ( $tokens ) { } /** - * Whether an operand checks for the name with one of $checks: true for exactly `check( 'name' )`, false for its - * negation (`! check()`, `false === check()`, `check() === false`), null otherwise. + * Whether an operand checks for the name with one of $checks: true for exactly `check( 'name' )`, false for its negation (`! check()`, `false === check()`, `check() === false`), null otherwise. */ public static function checks( File $file, array $op, array $checks, string $name ): ?bool { $tokens = $file->getTokens(); diff --git a/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php index 79ac6c1b..a384ac4e 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php @@ -37,8 +37,7 @@ protected function native( string $lower ): ?array { } /** - * PHP declares a class when its declaration runs, so a file-scope statement `if ( ) { return; }` before it is a - * guard: the if a statement of its own, its block nothing but the return, and no goto in the file to jump past it. + * PHP declares a class when its declaration runs, so a file-scope statement `if ( ) { return; }` before it is a guard: the if a statement of its own, its block nothing but the return, and no goto in the file to jump past it. */ protected function returnsBefore( File $phpcsFile, int $stackPtr, array $native ): bool { $tokens = $phpcsFile->getTokens(); diff --git a/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php index 3f1c18fd..17032b70 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php @@ -1,8 +1,6 @@ ,"n":,"u":<1 when PHPCS couldn't process it>,"d":[]}, - * then one line per message, [line, column, type, source, message(, lowercase class of a new class or interface)], so the - * entrypoint streams it without holding a file's findings. Clean files get a header too, so it knows which files PHPCS finished. + * PHPCS report: per file a header {"f":,"n":,"u":<1 when PHPCS couldn't process it>,"d":[]}, then one line per message, [line, column, type, source, message(, lowercase class of a new class or interface)], so the entrypoint streams it without holding a file's findings. Clean files get a header too, so it knows which files PHPCS finished. */ namespace EasyEngine\CompatScanner; @@ -95,8 +93,7 @@ public function generate( string $cachedData, int $totalFiles, int $totalErrors, } /** - * The check that sees the name a finding of this source is about, and the name from the source (lowercase; null for an - * extension); [ null, null ] when it isn't one GUARDED names. + * The check that sees the name a finding of this source is about, and the name from the source (lowercase; null for an extension); [ null, null ] when it isn't one GUARDED names. */ private function named( string $source ): array { foreach ( self::GUARDED as $prefix => $check ) { @@ -132,9 +129,7 @@ private function guarded( File $phpcsFile, int $ptr, string $check, string $name } /** - * Lowercase full names of the classes, interfaces, traits and enums the file declares where the declaration runs on - * the target: at file scope, or only in if blocks each of whose `&&` operands holds there (a version test, or a - * negated class_exists() or interface_exists() on that name). + * Lowercase full names of the classes, interfaces, traits and enums the file declares where the declaration runs on the target: at file scope, or only in if blocks each of whose `&&` operands holds there (a version test, or a negated class_exists() or interface_exists() on that name). * * @return string[] */ diff --git a/compat-scanner/tests/guards.php b/compat-scanner/tests/guards.php index ada2f74d..d74478f6 100644 --- a/compat-scanner/tests/guards.php +++ b/compat-scanner/tests/guards.php @@ -72,6 +72,7 @@ [ 'f-callable', 'ok', 'reported', "if ( ! is_callable( 'array_first' ) ) { " . F . ' }' ], [ 'f-ver-sep-ok', 'ok', 'reported', 'if ( PHP_VERSION_ID < 80_500 ) { ' . F . ' }' ], [ 'f-ver-octal', 'ok', 'reported', 'if ( PHP_VERSION_ID < 0235164 ) { ' . F . ' }' ], + [ 'f-vc-named', 'ok', 'reported', "if ( version_compare( PHP_VERSION, '8.5', operator: '<' ) ) { " . F . ' }' ], // Classes: an enclosing check, the else of the reverse check, or an early return in the file. [ 'c-not', 'ok', 'quiet', "if ( ! class_exists( 'NoDiscard' ) ) { " . C . ' }' ], [ 'c-not-noload', 'ok', 'quiet', "if ( ! class_exists( 'NoDiscard', false ) ) { " . C . ' }' ], From 57f272f15450cdf216f66aa3ec8438ee1561945f Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 09:53:47 +0530 Subject: [PATCH 53/80] refactor(compat-scanner): share the guard operand test The use filter, the site-declared class check and the NativeDeclared sniffs each tested an operand the same way: the exists-check with a given polarity, or a version test whose range fits. That test now lives in Guard::tests(), and Guard::checks() is private to the grammar. No behaviour change. --- compat-scanner/src/CompatScanner/Guard.php | 8 +++++++- .../Sniffs/Functions/NativeDeclaredSniff.php | 6 ++---- compat-scanner/src/LinesReport.php | 14 ++++++-------- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/compat-scanner/src/CompatScanner/Guard.php b/compat-scanner/src/CompatScanner/Guard.php index 9cfe7a29..1cd02d47 100644 --- a/compat-scanner/src/CompatScanner/Guard.php +++ b/compat-scanner/src/CompatScanner/Guard.php @@ -67,6 +67,12 @@ public static function encloses( File $file, int $ptr, callable $inIf, callable return false; } + /** Whether the operand is `check( 'name' )` with that polarity (false: negated), or a version test whose range $fits accepts. */ + public static function tests( File $file, array $op, array $checks, string $name, bool $polarity, callable $fits ): bool { + $range = self::versions( $file, $op ); + return $polarity === self::checks( $file, $op, $checks, $name ) || ( null !== $range && $fits( $range ) ); + } + /** Whether $test accepts an operand of the condition of the if or elseif at $ptr, split at its top-level `||` ($or) or `&&`. */ public static function any( File $file, int $ptr, bool $or, callable $test ): bool { foreach ( (array) self::operands( $file, $ptr, $or ) as $op ) { @@ -133,7 +139,7 @@ static function ( $ptr ) use ( $tokens ) { /** * Whether an operand checks for the name with one of $checks: true for exactly `check( 'name' )`, false for its negation (`! check()`, `false === check()`, `check() === false`), null otherwise. */ - public static function checks( File $file, array $op, array $checks, string $name ): ?bool { + private static function checks( File $file, array $op, array $checks, string $name ): ?bool { $tokens = $file->getTokens(); $n = count( $op ); $inner = null; diff --git a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php index 400277a5..ab8f4b49 100644 --- a/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php +++ b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php @@ -72,13 +72,11 @@ protected function returnsBefore( File $phpcsFile, int $stackPtr, array $native /** Whether the operand holds only where the native is missing: `! check( 'name' )`, or a version test below the version that added it. */ private function missing( File $phpcsFile, array $op, array $native ): bool { - $range = Guard::versions( $phpcsFile, $op ); - return false === Guard::checks( $phpcsFile, $op, $native['checks'], $native['name'] ) || ( null !== $range && $range[1] <= $native['added'] ); + return Guard::tests( $phpcsFile, $op, $native['checks'], $native['name'], false, static fn ( $r ) => $r[1] <= $native['added'] ); } /** Whether the operand holds wherever the native exists: `check( 'name' )`, or a version test from the version that added it on. */ protected function exists( File $phpcsFile, array $op, array $native ): bool { - $range = Guard::versions( $phpcsFile, $op ); - return true === Guard::checks( $phpcsFile, $op, $native['checks'], $native['name'] ) || ( null !== $range && $range[0] <= $native['added'] && Guard::TOP === $range[1] ); + return Guard::tests( $phpcsFile, $op, $native['checks'], $native['name'], true, static fn ( $r ) => $r[0] <= $native['added'] && Guard::TOP === $r[1] ); } } diff --git a/compat-scanner/src/LinesReport.php b/compat-scanner/src/LinesReport.php index 678e31f2..259a5d72 100644 --- a/compat-scanner/src/LinesReport.php +++ b/compat-scanner/src/LinesReport.php @@ -118,12 +118,10 @@ private function positions( File $phpcsFile ): array { private function guarded( File $phpcsFile, int $ptr, string $check, string $name ): bool { $target = $this->target; $inIf = static function ( $op ) use ( $phpcsFile, $check, $name, $target ) { - $range = Guard::versions( $phpcsFile, $op ); - return true === Guard::checks( $phpcsFile, $op, [ $check ], $name ) || ( null !== $range && ( $range[1] <= $target[0] || $range[0] >= $target[1] ) ); + return Guard::tests( $phpcsFile, $op, [ $check ], $name, true, static fn ( $r ) => $r[1] <= $target[0] || $r[0] >= $target[1] ); }; $inElse = static function ( $op ) use ( $phpcsFile, $check, $name, $target ) { - $range = Guard::versions( $phpcsFile, $op ); - return false === Guard::checks( $phpcsFile, $op, [ $check ], $name ) || ( null !== $range && $range[0] <= $target[0] && $range[1] >= $target[1] ); + return Guard::tests( $phpcsFile, $op, [ $check ], $name, false, static fn ( $r ) => $r[0] <= $target[0] && $r[1] >= $target[1] ); }; return Guard::encloses( $phpcsFile, $ptr, $inIf, $inElse ); } @@ -155,11 +153,11 @@ private function declared( File $phpcsFile ): array { /** Whether the if at $ptr holds on the target, by every `&&` operand of its condition. */ private function holds( File $phpcsFile, int $ptr, string $name ): bool { - $ops = T_IF === $phpcsFile->getTokens()[ $ptr ]['code'] ? Guard::operands( $phpcsFile, $ptr, false ) : null; + $ops = T_IF === $phpcsFile->getTokens()[ $ptr ]['code'] ? Guard::operands( $phpcsFile, $ptr, false ) : null; + $target = $this->target; + $covers = static fn ( $r ) => $r[0] <= $target[0] && $r[1] >= $target[1]; foreach ( (array) $ops as $op ) { - $range = Guard::versions( $phpcsFile, $op ); - $covers = null !== $range && $range[0] <= $this->target[0] && $range[1] >= $this->target[1]; - if ( ! $covers && false !== Guard::checks( $phpcsFile, $op, [ 'class_exists', 'interface_exists' ], $name ) ) { + if ( ! Guard::tests( $phpcsFile, $op, [ 'class_exists', 'interface_exists' ], $name, false, $covers ) ) { return false; } } From a817b578070d736ae125965d7ca471d6975abf6a Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 09:57:03 +0530 Subject: [PATCH 54/80] fix(compat-scanner): count a guard only inside the code's own function or class A guard around a function, method, closure or class decided whether the code inside it runs, but it only decides whether the function or class is declared; code outside the guard can still call it. So `if ( function_exists( 'each' ) ) { function w() { each(); } } w();` was safe at 8.0 while PHP 8.0 fails, and a native function declared inside a guarded loader function was quiet at 8.5. Guards now count only within the innermost function, closure, arrow function or class around the code. A goto label inside a guard's block also voids the guard, since a goto can enter the block past its condition, for uses and declarations alike. The use-guard and declaration-guard tables get wrapper, closure, arrow function and goto rows; the never-called guarded function row is now reported (strict). --- compat-scanner/src/CompatScanner/Guard.php | 35 +++++++++++++++++++++- compat-scanner/tests/guards.php | 5 ++++ compat-scanner/tests/use-guards.php | 12 +++++++- 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/compat-scanner/src/CompatScanner/Guard.php b/compat-scanner/src/CompatScanner/Guard.php index 1cd02d47..60cfccf0 100644 --- a/compat-scanner/src/CompatScanner/Guard.php +++ b/compat-scanner/src/CompatScanner/Guard.php @@ -48,11 +48,19 @@ public static function target( string $version ): array { } /** - * Whether a block enclosing $ptr runs only where $inIf accepts an `&&` operand of its if or elseif, or is the else of an if with a `||` operand $inElse accepts. + * Whether a block enclosing $ptr, within its innermost function or class and with no goto label in it, runs only where $inIf accepts an `&&` operand of its if or elseif, or is the else of an if with a `||` operand $inElse accepts. */ public static function encloses( File $file, int $ptr, callable $inIf, callable $inElse ): bool { $tokens = $file->getTokens(); + if ( ! $tokens[ $ptr ]['conditions'] ) { + return false; + } + $scope = self::scope( $file, $ptr ); foreach ( array_keys( $tokens[ $ptr ]['conditions'] ) as $block ) { + // A guard around a function or class decides only whether it is declared; code outside the guard can call it. + if ( $block < $scope || self::jumpedInto( $file, $block ) ) { + continue; + } if ( T_ELSE === $tokens[ $block ]['code'] ) { // The closing brace before `else` belongs to the if or elseif it is the else of. $prev = $file->findPrevious( Tokens::EMPTY_TOKENS, $block - 1, null, true ); @@ -67,6 +75,31 @@ public static function encloses( File $file, int $ptr, callable $inIf, callable return false; } + /** The innermost function, closure, arrow function or class around $ptr, or -1. */ + private static function scope( File $file, int $ptr ): int { + $tokens = $file->getTokens(); + $scope = -1; + foreach ( $tokens[ $ptr ]['conditions'] as $block => $code ) { + if ( T_FUNCTION === $code || T_CLOSURE === $code || isset( Tokens::OO_SCOPE_TOKENS[ $code ] ) ) { + $scope = $block; + } + } + // Arrow functions aren't conditions; only one inside the outermost block matters. + $from = max( $scope, array_key_first( $tokens[ $ptr ]['conditions'] ) ); + for ( $fn = $ptr; false !== ( $fn = $file->findPrevious( T_FN, $fn - 1, $from + 1 ) ); ) { + if ( ( $tokens[ $fn ]['scope_closer'] ?? -1 ) >= $ptr ) { + return $fn; + } + } + return $scope; + } + + /** Whether a goto can enter the block: a label inside it. */ + private static function jumpedInto( File $file, int $block ): bool { + $tokens = $file->getTokens(); + return isset( $tokens[ $block ]['scope_closer'] ) && false !== $file->findNext( T_GOTO_LABEL, $block, $tokens[ $block ]['scope_closer'] ); + } + /** Whether the operand is `check( 'name' )` with that polarity (false: negated), or a version test whose range $fits accepts. */ public static function tests( File $file, array $op, array $checks, string $name, bool $polarity, callable $fits ): bool { $range = self::versions( $file, $op ); diff --git a/compat-scanner/tests/guards.php b/compat-scanner/tests/guards.php index d74478f6..36a916eb 100644 --- a/compat-scanner/tests/guards.php +++ b/compat-scanner/tests/guards.php @@ -68,6 +68,11 @@ [ 'f-in-function', 'fatal', 'reported', 'function p_boot() { ' . F . " }\np_boot();" ], [ 'f-in-method', 'fatal', 'reported', 'class P_H { static function load() { ' . F . " } }\nP_H::load();" ], [ 'f-in-closure', 'fatal', 'reported', 'class P_K { static function load() { $f = function () { ' . F . " }; \$f(); } }\nP_K::load();" ], + // A guard around the function that declares it decides only whether that function exists. + [ 'f-in-guarded-function', 'fatal', 'reported', "if ( ! function_exists( 'array_first' ) ) { function p_decl() { " . F . " } }\np_decl();" ], + // goto can enter the guard's block. + [ 'f-goto-into', 'fatal', 'reported', "goto p_g;\nif ( ! function_exists( 'array_first' ) ) {\np_g:\n" . F . "\n}" ], + [ 'f-goto-before', 'ok', 'quiet', "goto p_g;\np_g:\nif ( ! function_exists( 'array_first' ) ) { " . F . ' }' ], // Strict: PHP runs these, but they aren't shapes the grammar accepts. [ 'f-callable', 'ok', 'reported', "if ( ! is_callable( 'array_first' ) ) { " . F . ' }' ], [ 'f-ver-sep-ok', 'ok', 'reported', 'if ( PHP_VERSION_ID < 80_500 ) { ' . F . ' }' ], diff --git a/compat-scanner/tests/use-guards.php b/compat-scanner/tests/use-guards.php index 9bbfc19d..9ac70417 100644 --- a/compat-scanner/tests/use-guards.php +++ b/compat-scanner/tests/use-guards.php @@ -13,7 +13,6 @@ [ 'e-exists-fq', '8.0', 'ok', 'quiet', "if ( \\function_exists( 'EACH' ) ) { " . E . ' }' ], [ 'e-exists-and', '8.0', 'ok', 'quiet', "if ( defined( 'PHP_EOL' ) && function_exists( 'each' ) ) { " . E . ' }' ], [ 'e-nested', '8.0', 'ok', 'quiet', "if ( function_exists( 'each' ) ) { if ( true ) { " . E . ' } }' ], - [ 'e-in-function', '8.0', 'ok', 'quiet', "if ( function_exists( 'each' ) ) { function p_e( \$a ) { return each( \$a ); } }" ], [ 'e-else', '8.0', 'ok', 'quiet', "if ( ! function_exists( 'each' ) ) { } else { " . E . ' }' ], [ 'e-else-or', '8.0', 'ok', 'quiet', "if ( ! function_exists( 'each' ) || false ) { } else { " . E . ' }' ], [ 'e-ver', '8.0', 'ok', 'quiet', 'if ( PHP_VERSION_ID < 80000 ) { ' . E . ' }' ], @@ -21,6 +20,8 @@ [ 'e-vc', '8.0', 'ok', 'quiet', "if ( version_compare( PHP_VERSION, '8.0', '<' ) ) { " . E . ' }' ], [ 'e-else-ver', '8.0', 'ok', 'quiet', 'if ( PHP_VERSION_ID >= 80000 ) { } else { ' . E . ' }' ], [ 'e-mysql', '8.0', 'ok', 'quiet', "if ( function_exists( 'mysql_query' ) ) { mysql_query( 'SELECT 1' ); }" ], + [ 'e-in-guarded-function', '8.0', 'ok', 'quiet', "function p_g( \$a ) { if ( function_exists( 'each' ) ) { " . E . " } }\np_g( \$a );" ], + [ 'e-goto-before', '8.0', 'ok', 'quiet', "goto g;\ng:\nif ( function_exists( 'each' ) ) { " . E . ' }' ], // Shapes that don't guard it. [ 'e-or', '8.0', 'fatal', 'reported', "if ( function_exists( 'each' ) || true ) { " . E . ' }' ], [ 'e-missing', '8.0', 'fatal', 'reported', "if ( ! function_exists( 'each' ) ) { " . E . ' }' ], @@ -28,10 +29,19 @@ [ 'e-ver-high', '8.0', 'fatal', 'reported', 'if ( PHP_VERSION_ID < 80100 ) { ' . E . ' }' ], [ 'e-else-exists', '8.0', 'fatal', 'reported', "if ( function_exists( 'each' ) ) { } else { " . E . ' }' ], [ 'e-after', '8.0', 'fatal', 'reported', "if ( function_exists( 'each' ) ) { }\n" . E ], + // A guard around a function, class or closure decides only whether it exists; the call outside runs it. + [ 'e-wrapper', '8.0', 'fatal', 'reported', "if ( function_exists( 'each' ) ) { function p_w( \$a ) { " . E . " } }\np_w( \$a );" ], + [ 'e-wrapper-class', '8.0', 'fatal', 'reported', "if ( function_exists( 'each' ) ) { class P_W { static function m( \$a ) { " . E . " } } }\nP_W::m( \$a );" ], + [ 'e-wrapper-ver', '8.0', 'fatal', 'reported', "if ( PHP_VERSION_ID < 80000 ) { function p_v( \$a ) { " . E . " } }\np_v( \$a );" ], + [ 'e-wrapper-closure', '8.0', 'fatal', 'reported', "\$f = null;\nif ( function_exists( 'each' ) ) { \$f = function ( \$a ) { " . E . " }; }\n\$f( \$a );" ], + [ 'e-wrapper-arrow', '8.0', 'fatal', 'reported', "\$f = null;\nif ( function_exists( 'each' ) ) { \$f = fn( \$a ) => each( \$a ); }\n\$f( \$a );" ], + // goto can enter the block past its guard. + [ 'e-goto-into', '8.0', 'fatal', 'reported', "goto g;\nif ( function_exists( 'each' ) ) {\ng:\n" . E . "\n}" ], // Strict: PHP runs these, but they aren't shapes the grammar accepts. [ 'e-in-condition', '8.0', 'ok', 'reported', "if ( function_exists( 'each' ) && each( \$a ) ) { }" ], [ 'e-ternary', '8.0', 'ok', 'reported', "\$x = function_exists( 'each' ) ? each( \$a ) : null;" ], [ 'e-vc-named', '8.0', 'ok', 'reported', "if ( version_compare( PHP_VERSION, '8.0', operator: '<' ) ) { " . E . ' }' ], + [ 'e-in-function', '8.0', 'ok', 'reported', "if ( function_exists( 'each' ) ) { function p_e( \$a ) { " . E . " } }" ], // Not in PHP 8.0: array_is_list() and Fiber. [ 'l-bare', '8.0', 'fatal', 'reported', L ], [ 'l-exists', '8.0', 'ok', 'quiet', "if ( function_exists( 'array_is_list' ) ) { " . L . ' }' ], From 577a96e383bd4732f7c834a954d039639d0071ca Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 09:59:58 +0530 Subject: [PATCH 55/80] fix(compat-scanner): keep deprecation warnings under an exists-check function_exists() and its kin dropped findings on deprecated names too, such as utf8_encode() at 8.2 or get_magic_quotes_gpc() at 7.4. Those names still exist on the target, so the guarded call runs and PHP emits the deprecation. A finding whose source ends in Deprecated is now dropped only by a version test that excludes the target. The use-guard table's truth run tells deprecations apart from clean runs. --- compat-scanner/src/LinesReport.php | 16 +++++++++------- compat-scanner/tests/assert.php | 2 +- compat-scanner/tests/use-guards.php | 10 +++++++--- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/compat-scanner/src/LinesReport.php b/compat-scanner/src/LinesReport.php index 259a5d72..7736ce6d 100644 --- a/compat-scanner/src/LinesReport.php +++ b/compat-scanner/src/LinesReport.php @@ -52,7 +52,9 @@ public function generateFileReport( array $report, File $phpcsFile, bool $showSo $ptr = $at[ "$line:$column" ] ?? null; // An extension's finding names its prefix; the function is the token it is on. $name = $name ?? ( null === $ptr ? '' : ltrim( $phpcsFile->getTokens()[ $ptr ]['content'], '\\' ) ); - if ( null !== $ptr && $this->guarded( $phpcsFile, $ptr, $check, $name ) ) { + // A deprecated name still exists on the target, so only a version test keeps its warning from firing. + $checks = preg_match( '/Deprecated\z/', $message['source'] ) ? [] : [ $check ]; + if ( null !== $ptr && $this->guarded( $phpcsFile, $ptr, $checks, $name ) ) { continue; } // The message names a namespaced class in full; the source mangles its `\`. @@ -114,14 +116,14 @@ private function positions( File $phpcsFile ): array { return $at; } - /** Whether the name at $ptr is used only in a block that runs where it exists, or not on the target. */ - private function guarded( File $phpcsFile, int $ptr, string $check, string $name ): bool { + /** Whether the name at $ptr is used only in a block that runs where one of $checks finds it, or not on the target. */ + private function guarded( File $phpcsFile, int $ptr, array $checks, string $name ): bool { $target = $this->target; - $inIf = static function ( $op ) use ( $phpcsFile, $check, $name, $target ) { - return Guard::tests( $phpcsFile, $op, [ $check ], $name, true, static fn ( $r ) => $r[1] <= $target[0] || $r[0] >= $target[1] ); + $inIf = static function ( $op ) use ( $phpcsFile, $checks, $name, $target ) { + return Guard::tests( $phpcsFile, $op, $checks, $name, true, static fn ( $r ) => $r[1] <= $target[0] || $r[0] >= $target[1] ); }; - $inElse = static function ( $op ) use ( $phpcsFile, $check, $name, $target ) { - return Guard::tests( $phpcsFile, $op, [ $check ], $name, false, static fn ( $r ) => $r[0] <= $target[0] && $r[1] >= $target[1] ); + $inElse = static function ( $op ) use ( $phpcsFile, $checks, $name, $target ) { + return Guard::tests( $phpcsFile, $op, $checks, $name, false, static fn ( $r ) => $r[0] <= $target[0] && $r[1] >= $target[1] ); }; return Guard::encloses( $phpcsFile, $ptr, $inIf, $inElse ); } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 53135411..d97f8bf5 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1059,7 +1059,7 @@ function counts( string $name ): array { } $wrong = []; foreach ( require '/t/guards.php' as list( $id, $php, $scanner ) ) { - if ( ( 'reported' === $scanner ) !== isset( $reported[ $id ] ) || ( 'fatal' === $php && 'quiet' === $scanner ) ) { + if ( ( 'reported' === $scanner ) !== isset( $reported[ $id ] ) || ( 'ok' !== $php && 'quiet' === $scanner ) ) { $wrong[] = $id; } } diff --git a/compat-scanner/tests/use-guards.php b/compat-scanner/tests/use-guards.php index 9ac70417..138675db 100644 --- a/compat-scanner/tests/use-guards.php +++ b/compat-scanner/tests/use-guards.php @@ -1,5 +1,5 @@ runs it, the scanner reports it, code ]. +// Guard shapes around a use of a name PHPCompatibility flags, one file each: [ id, target, PHP runs it (ok, deprecated or fatal), the scanner reports it, code ]. // Usage: php use-guards.php write | php use-guards.php truth (on php:-cli: prints each row PHP disagrees with, then `checked`). const E = 'each( $a );'; @@ -57,6 +57,9 @@ // Not in PHP 7.4: Stringable. [ 's-bare', '7.4', 'fatal', 'reported', "class P_S implements Stringable { public function __toString() { return ''; } }" ], [ 's-exists', '7.4', 'ok', 'quiet', "if ( interface_exists( 'Stringable' ) ) { class P_T implements Stringable { public function __toString() { return ''; } } }" ], + // get_magic_quotes_gpc() is deprecated in 7.4: it exists, so only a version test keeps the deprecation away. + [ 'q-exists', '7.4', 'deprecated', 'reported', "if ( function_exists( 'get_magic_quotes_gpc' ) ) { get_magic_quotes_gpc(); }" ], + [ 'q-ver', '7.4', 'ok', 'quiet', 'if ( PHP_VERSION_ID < 70400 ) { get_magic_quotes_gpc(); }' ], ]; if ( 'write' === ( $argv[1] ?? '' ) ) { @@ -72,8 +75,9 @@ continue; } file_put_contents( $tmp, "&1', $out, $rc ); - $got = 0 === $rc ? 'ok' : 'fatal'; + exec( 'php -d error_reporting=-1 -d display_errors=1 ' . escapeshellarg( $tmp ) . ' 2>&1', $out, $rc ); + $got = preg_grep( '/^(PHP )?Deprecated: /', $out ) ? 'deprecated' : 'ok'; + $got = 0 === $rc ? $got : 'fatal'; if ( $got !== $php ) { echo "$id: PHP " . PHP_VERSION . " says $got, the table $php\n"; } From 0af602ad6a9a5224caf500ce206c712b0a2ab9ac Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:03:05 +0530 Subject: [PATCH 56/80] fix(compat-scanner): match a new class's guard on its full name The guard name for a new class came from PHPCompatibility's error code, which mangles the namespace separator: `class_exists( 'Random_Randomizer' )`, a different class, guarded `new \Random\Randomizer()`, while `class_exists( 'Random\Randomizer' )` never matched. The name now comes from the finding's message, a string guard may name a namespaced class, and `X::class` resolves in the file's namespace, so `WeakMap::class` in `namespace P` no longer guards `\WeakMap`. A class_exists() guard around a site's own namespaced class declaration is matched on its full name as well. --- compat-scanner/src/CompatScanner/Guard.php | 24 +++++++++++++++++++--- compat-scanner/src/LinesReport.php | 12 +++++++---- compat-scanner/tests/use-guards.php | 16 +++++++++++++-- 3 files changed, 43 insertions(+), 9 deletions(-) diff --git a/compat-scanner/src/CompatScanner/Guard.php b/compat-scanner/src/CompatScanner/Guard.php index 60cfccf0..35b3d9df 100644 --- a/compat-scanner/src/CompatScanner/Guard.php +++ b/compat-scanner/src/CompatScanner/Guard.php @@ -7,6 +7,7 @@ use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Util\Tokens; +use PHPCSUtils\Utils\Namespaces; use PHPCSUtils\Utils\PassedParameters; final class Guard { @@ -196,9 +197,26 @@ private static function named( File $file, array $op, array $checks, string $nam return false; } $arg = PassedParameters::getParameter( $file, $op[0], 1, [ 'function', 'class', 'interface', 'enum' ] ); - // 'name', "name" or name::class, each with an optional leading `\`. - $is = false !== $arg && preg_match( '/^(?:([\'"])\\\\{0,2}(\w+)\1|\\\\?(\w+)::class)$/i', $arg['clean'], $m ); - return $is && strtolower( $m[2] . ( $m[3] ?? '' ) ) === strtolower( $name ); + return false !== $arg && strtolower( (string) self::nameOf( $file, $arg['start'], $arg['clean'] ) ) === strtolower( $name ); + } + + /** + * The full name an argument gives: 'name' or "name" (parts joined by `\` or `\\`, an optional leading one), or name::class resolved in its namespace (PHPCompatibility reports no new class whose short name a `use` statement imports); null for anything else. + */ + private static function nameOf( File $file, int $ptr, string $arg ): ?string { + if ( preg_match( '/^([\'"])(\\\\{0,2}(?:\w+\\\\{1,2})*\w+)\1$/', $arg, $m ) ) { + // In double quotes `\n`, `\r` and the like are escapes, not separators. + $escape = '"' === $m[1] && preg_match( '/\\\\[nrtvef0-7xu]/', str_replace( '\\\\', '', $m[2] ) ); + return $escape ? null : ltrim( str_replace( '\\\\', '\\', $m[2] ), '\\' ); + } + if ( ! preg_match( '/^(\\\\?)((?:\w+\\\\)*\w+)::class$/i', $arg, $m ) ) { + return null; + } + if ( '' !== $m[1] ) { + return $m[2]; + } + $ns = Namespaces::determineNamespace( $file, $ptr ); + return '' === $ns ? $m[2] : "$ns\\$m[2]"; } /** Whether the tokens are exactly a call of one of $names, `\` allowed. */ diff --git a/compat-scanner/src/LinesReport.php b/compat-scanner/src/LinesReport.php index 7736ce6d..a6265273 100644 --- a/compat-scanner/src/LinesReport.php +++ b/compat-scanner/src/LinesReport.php @@ -50,6 +50,10 @@ public function generateFileReport( array $report, File $phpcsFile, bool $showSo if ( null !== $check ) { $at = $at ?? $this->positions( $phpcsFile ); $ptr = $at[ "$line:$column" ] ?? null; + // The message names a namespaced class in full; the source mangles its `\`. + if ( preg_match( '/\.New(?:Classes|Interfaces)\./', $message['source'] ) && preg_match( '/^The built-in (?:class|interface) \\\\?(\S+) is /', $message['message'], $c ) ) { + $name = strtolower( $c[1] ); + } // An extension's finding names its prefix; the function is the token it is on. $name = $name ?? ( null === $ptr ? '' : ltrim( $phpcsFile->getTokens()[ $ptr ]['content'], '\\' ) ); // A deprecated name still exists on the target, so only a version test keeps its warning from firing. @@ -57,9 +61,8 @@ public function generateFileReport( array $report, File $phpcsFile, bool $showSo if ( null !== $ptr && $this->guarded( $phpcsFile, $ptr, $checks, $name ) ) { continue; } - // The message names a namespaced class in full; the source mangles its `\`. if ( preg_match( '/\.New(?:Classes|Interfaces)\./', $message['source'] ) ) { - $message['class'] = preg_match( '/^The built-in (?:class|interface) \\\\?(\S+) is /', $message['message'], $c ) ? strtolower( $c[1] ) : $name; + $message['class'] = $name; } } $count++; @@ -142,12 +145,13 @@ private function declared( File $phpcsFile ): array { } $name = (string) $phpcsFile->getDeclarationName( $ptr ); $ns = Namespaces::determineNamespace( $phpcsFile, $ptr ); + $full = '' === $ns ? $name : "$ns\\$name"; $runs = '' !== $name; foreach ( array_keys( $token['conditions'] ) as $block ) { - $runs = $runs && ( T_NAMESPACE === $tokens[ $block ]['code'] || $this->holds( $phpcsFile, $block, $name ) ); + $runs = $runs && ( T_NAMESPACE === $tokens[ $block ]['code'] || $this->holds( $phpcsFile, $block, $full ) ); } if ( $runs ) { - $names[] = strtolower( '' === $ns ? $name : "$ns\\$name" ); + $names[] = strtolower( $full ); } } return $names; diff --git a/compat-scanner/tests/use-guards.php b/compat-scanner/tests/use-guards.php index 138675db..57e19aee 100644 --- a/compat-scanner/tests/use-guards.php +++ b/compat-scanner/tests/use-guards.php @@ -54,18 +54,30 @@ // PHPCompatibility flags `Fiber::class` in the condition itself, outside the block. [ 'n-exists-class', '8.0', 'ok', 'reported', 'if ( class_exists( \\Fiber::class ) ) { ' . N . ' }' ], [ 'n-declared-here', '8.0', 'fatal', 'reported', 'function p_f() { class Fiber {} }' . "\n" . N ], + // Random\Randomizer is new in 8.2: the guard names it in full. + [ 'r-exists', '8.0', 'ok', 'quiet', "if ( class_exists( 'Random\\Randomizer' ) ) { new \\Random\\Randomizer(); }" ], + [ 'r-exists-dq', '8.0', 'ok', 'quiet', 'if ( class_exists( "\\\\Random\\\\Randomizer" ) ) { new \\Random\\Randomizer(); }' ], + // PHPCompatibility flags Randomizer::class in the condition itself; the use in the block is dropped. + [ 'r-ns', '8.0', 'ok', 'reported', "namespace Random;\nif ( class_exists( Randomizer::class ) ) { new Randomizer(); }" ], + [ 'r-mangled', '8.0', 'fatal', 'reported', "class Random_Randomizer {}\nif ( class_exists( 'Random_Randomizer' ) ) { new \\Random\\Randomizer(); }" ], // Not in PHP 7.4: Stringable. [ 's-bare', '7.4', 'fatal', 'reported', "class P_S implements Stringable { public function __toString() { return ''; } }" ], [ 's-exists', '7.4', 'ok', 'quiet', "if ( interface_exists( 'Stringable' ) ) { class P_T implements Stringable { public function __toString() { return ''; } } }" ], + // WeakMap is new in 8.0; X::class names the class of its namespace. + [ 'w-ns', '7.4', 'fatal', 'reported', "namespace P;\nclass WeakMap {}\nif ( class_exists( WeakMap::class ) ) { new \\WeakMap(); }" ], // get_magic_quotes_gpc() is deprecated in 7.4: it exists, so only a version test keeps the deprecation away. [ 'q-exists', '7.4', 'deprecated', 'reported', "if ( function_exists( 'get_magic_quotes_gpc' ) ) { get_magic_quotes_gpc(); }" ], [ 'q-ver', '7.4', 'ok', 'quiet', 'if ( PHP_VERSION_ID < 70400 ) { get_magic_quotes_gpc(); }' ], ]; +// A namespace declaration stays first. +$source = static function ( $code ) { + return "&1', $out, $rc ); $got = preg_grep( '/^(PHP )?Deprecated: /', $out ) ? 'deprecated' : 'ok'; $got = 0 === $rc ? $got : 'fatal'; From ce9f838e6294331d91608ff5a2ec67efb148215f Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:05:35 +0530 Subject: [PATCH 57/80] fix(compat-scanner): a site's trait or interface doesn't stand in for a new class A new class finding was dropped when the site declared anything of that name, a trait or an interface included, though `new` on either is fatal. Declarations are now kept by kind: a class or enum matches a new class finding, an interface a new interface finding, and a trait nothing. --- compat-scanner/bin/compat-scanner.php | 2 +- compat-scanner/src/LinesReport.php | 19 ++++++++++--------- compat-scanner/tests/use-guards.php | 3 +++ 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 7e2219cd..62c5d7ed 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -165,7 +165,7 @@ final class Scanner { private $shortIni = []; /** @var bool short_open_tag of the files PHPCS and the lint check now. */ private $short = false; - /** @var array Lowercase global classes the scanned files declare where that runs on the target. */ + /** @var array The classes and interfaces the scanned files declare where that runs on the target, keyed as the PHPCS report names them. */ private $declared = []; /** @var array loadsIn() of each directory read, by path. */ private $loads = []; diff --git a/compat-scanner/src/LinesReport.php b/compat-scanner/src/LinesReport.php index a6265273..2af5bb35 100644 --- a/compat-scanner/src/LinesReport.php +++ b/compat-scanner/src/LinesReport.php @@ -1,6 +1,6 @@ ,"n":,"u":<1 when PHPCS couldn't process it>,"d":[]}, then one line per message, [line, column, type, source, message(, lowercase class of a new class or interface)], so the entrypoint streams it without holding a file's findings. Clean files get a header too, so it knows which files PHPCS finished. + * PHPCS report: per file a header {"f":,"n":,"u":<1 when PHPCS couldn't process it>,"d":[<"class " or "interface " it declares on the target>]}, then one line per message, [line, column, type, source, message(, "class " or "interface " of a new one)], so the entrypoint streams it without holding a file's findings. Clean files get a header too, so it knows which files PHPCS finished. */ namespace EasyEngine\CompatScanner; @@ -51,8 +51,11 @@ public function generateFileReport( array $report, File $phpcsFile, bool $showSo $at = $at ?? $this->positions( $phpcsFile ); $ptr = $at[ "$line:$column" ] ?? null; // The message names a namespaced class in full; the source mangles its `\`. - if ( preg_match( '/\.New(?:Classes|Interfaces)\./', $message['source'] ) && preg_match( '/^The built-in (?:class|interface) \\\\?(\S+) is /', $message['message'], $c ) ) { - $name = strtolower( $c[1] ); + if ( preg_match( '/\.New(Class|Interface)es\./', $message['source'], $kind ) ) { + if ( preg_match( '/^The built-in (?:class|interface) \\\\?(\S+) is /', $message['message'], $c ) ) { + $name = strtolower( $c[1] ); + } + $message['class'] = strtolower( $kind[1] ) . " $name"; } // An extension's finding names its prefix; the function is the token it is on. $name = $name ?? ( null === $ptr ? '' : ltrim( $phpcsFile->getTokens()[ $ptr ]['content'], '\\' ) ); @@ -61,9 +64,6 @@ public function generateFileReport( array $report, File $phpcsFile, bool $showSo if ( null !== $ptr && $this->guarded( $phpcsFile, $ptr, $checks, $name ) ) { continue; } - if ( preg_match( '/\.New(?:Classes|Interfaces)\./', $message['source'] ) ) { - $message['class'] = $name; - } } $count++; $kept[] = [ (int) $line, (int) $column, $message ]; @@ -132,7 +132,7 @@ private function guarded( File $phpcsFile, int $ptr, array $checks, string $name } /** - * Lowercase full names of the classes, interfaces, traits and enums the file declares where the declaration runs on the target: at file scope, or only in if blocks each of whose `&&` operands holds there (a version test, or a negated class_exists() or interface_exists() on that name). + * The classes (enums too) and interfaces the file declares where the declaration runs on the target, as "class " or "interface <…>": at file scope, or only in if blocks each of whose `&&` operands holds there (a version test, or a negated class_exists() or interface_exists() on that name). * * @return string[] */ @@ -140,7 +140,8 @@ private function declared( File $phpcsFile ): array { $tokens = $phpcsFile->getTokens(); $names = []; foreach ( $tokens as $ptr => $token ) { - if ( ! in_array( $token['code'], [ T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM ], true ) ) { + // A trait can't stand in for a new class: `new` or `extends` on it is fatal. + if ( ! in_array( $token['code'], [ T_CLASS, T_INTERFACE, T_ENUM ], true ) ) { continue; } $name = (string) $phpcsFile->getDeclarationName( $ptr ); @@ -151,7 +152,7 @@ private function declared( File $phpcsFile ): array { $runs = $runs && ( T_NAMESPACE === $tokens[ $block ]['code'] || $this->holds( $phpcsFile, $block, $full ) ); } if ( $runs ) { - $names[] = strtolower( $full ); + $names[] = ( T_INTERFACE === $token['code'] ? 'interface ' : 'class ' ) . strtolower( $full ); } } return $names; diff --git a/compat-scanner/tests/use-guards.php b/compat-scanner/tests/use-guards.php index 57e19aee..2b2dc672 100644 --- a/compat-scanner/tests/use-guards.php +++ b/compat-scanner/tests/use-guards.php @@ -65,6 +65,9 @@ [ 's-exists', '7.4', 'ok', 'quiet', "if ( interface_exists( 'Stringable' ) ) { class P_T implements Stringable { public function __toString() { return ''; } } }" ], // WeakMap is new in 8.0; X::class names the class of its namespace. [ 'w-ns', '7.4', 'fatal', 'reported', "namespace P;\nclass WeakMap {}\nif ( class_exists( WeakMap::class ) ) { new \\WeakMap(); }" ], + // A site's trait or interface of a new class's name doesn't stand in for it. + [ 'v-trait', '7.4', 'fatal', 'reported', "trait ValueError {}\nthrow new ValueError();" ], + [ 'v-interface', '7.4', 'fatal', 'reported', "interface UnhandledMatchError {}\nthrow new UnhandledMatchError();" ], // get_magic_quotes_gpc() is deprecated in 7.4: it exists, so only a version test keeps the deprecation away. [ 'q-exists', '7.4', 'deprecated', 'reported', "if ( function_exists( 'get_magic_quotes_gpc' ) ) { get_magic_quotes_gpc(); }" ], [ 'q-ver', '7.4', 'ok', 'quiet', 'if ( PHP_VERSION_ID < 70400 ) { get_magic_quotes_gpc(); }' ], From 3a546a92fe9e12c661739dc971db847da18bc682 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:08:33 +0530 Subject: [PATCH 58/80] fix(compat-scanner): check short tags on where any .user.ini down to the file turns them on The deepest .user.ini from the doc root down to a file's directory decided its short_open_tag. PHP-FPM applies the entry script's chain instead, so with short tags on in the doc root and off in a plugin's directory, the plugin's `cfg['short_tags']; - if ( $this->cfg['short_locked'] || ! $this->shortIni ) { - return $short; + if ( $this->cfg['short_tags'] || $this->cfg['short_locked'] || ! $this->shortIni ) { + return $this->cfg['short_tags']; } $root = is_string( $this->cfg['served'] ) && '' !== $this->cfg['served'] ? $this->cfg['served'] : $this->cfg['path']; $dir = dirname( $path ); if ( $dir !== $root && 0 !== strpos( $dir, $root . '/' ) ) { - return $this->shortIni[ $root ] ?? $short; + return $this->shortIni[ $root ] ?? false; } for ( $at = $root; ; $at .= '/' . strtok( substr( $dir, strlen( $at ) + 1 ), '/' ) ) { - $short = $this->shortIni[ $at ] ?? $short; + if ( $this->shortIni[ $at ] ?? false ) { + return true; + } if ( $at === $dir ) { - return $short; + return false; } } } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index d97f8bf5..3440c2c9 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1158,7 +1158,10 @@ function counts( string $name ): array { eq( [ counts( 'shorttag' ), finding_files( report( 'shorttag' ) ) ], [ [ 'ok', true, 0, 5, 0 ], [] ], 'shorttag: with short tags off, `\n\n' > "$1/lib/beside.php" chmod -R a+rX "$1" } +# short_open_tag off by default, on in sub/ and off again below it: PHP-FPM applies the entry script's chain, so sub/off/ may run with it on. +shortdeep_fixture() { + local h="$1/htdocs" f + mkdir -p "$h/sub/off" && printf 'short_open_tag = On\n' > "$h/sub/.user.ini" && printf 'short_open_tag = Off\n' > "$h/sub/off/.user.ini" + printf ' "$h/sub/index.php" + for f in top.php sub/on.php sub/off/below.php; do printf '\n\n' > "$h/$f"; done + chmod -R a+rX "$1" +} # wp-includes/version.php linked to a file outside /var/www and the extra roots. wpverout_fixture() { local h="$1/app/htdocs" diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index d81ed2ed..37215fdb 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -505,6 +505,8 @@ scan shorttag-on "$WORK/shorttag" php /var/www/htdocs 8.4 600 -e COMPAT_SHORT_OP shortini_fixture "$WORK/shortini" scan shortini "$WORK/shortini" php /var/www/htdocs 8.0 600 scan shortini-locked "$WORK/shortini" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG_LOCKED=1 +shortdeep_fixture "$WORK/shortdeep" +scan shortdeep "$WORK/shortdeep" php /var/www/htdocs 8.0 600 for v in flat release; do shortiniwp_fixture "$WORK/shortiniwp-$v" "$v"; done scan shortiniwp-flat "$WORK/shortiniwp-flat" wp /var/www/htdocs 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 scan shortiniwp-release "$WORK/shortiniwp-release" wp /var/www/htdocs/current 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 From b75cb47149d256352ffc0d5504519656c8144a95 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:10:42 +0530 Subject: [PATCH 59/80] style(compat-scanner): put the phar-name docblock back on its function --- compat-scanner/bin/compat-scanner.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index dd66235c..678c7ec9 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -1318,7 +1318,6 @@ private function isTemplateName( string $name ): bool { return (bool) preg_match( '/\.(?:' . implode( '|', TEMPLATE_EXTENSIONS ) . ')\z/i', $name ); } - /** `.phar` and the archive forms PHP's phar extension also opens (`.phar.tar`, `.phar.tar.gz`, `.phar.zip`, ...). */ /** * A `.stub` or `.tpl` under a `stubs/` or `templates/` dir of a Composer package, as Laravel's and PHPUnit's code generators ship them: filled in and written out, never run. */ @@ -1338,6 +1337,7 @@ private function inPackage( string $path ): bool { return false; } + /** `.phar` and the archive forms PHP's phar extension also opens (`.phar.tar`, `.phar.tar.gz`, `.phar.zip`, ...). */ private function isPharName( string $name ): bool { return (bool) preg_match( PHAR_REGEX, $name ); } From 3dc4ad03638ed4509e40cab414e819910306070a Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:14:00 +0530 Subject: [PATCH 60/80] test(compat-scanner): read the use-guard table once The assertions required tests/use-guards.php once per target, which redefined its constants and printed warnings. --- compat-scanner/tests/assert.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 3440c2c9..4e757c5c 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1059,7 +1059,7 @@ function counts( string $name ): array { } $wrong = []; foreach ( require '/t/guards.php' as list( $id, $php, $scanner ) ) { - if ( ( 'reported' === $scanner ) !== isset( $reported[ $id ] ) || ( 'ok' !== $php && 'quiet' === $scanner ) ) { + if ( ( 'reported' === $scanner ) !== isset( $reported[ $id ] ) || ( 'fatal' === $php && 'quiet' === $scanner ) ) { $wrong[] = $id; } } @@ -1120,14 +1120,15 @@ function counts( string $name ): array { eq( finding_files( report( 'appgate' ) ), [ 'directory:lib::bootstrap85.php' ], 'appgate: app code outside a Composer package keeps its lint error, whatever its siblings gate' ); // Uses of a name in a block that runs only where it exists, or not on the target, give no finding; PHP agrees on each row. +$useGuards = require '/t/use-guards.php'; foreach ( [ '7.4', '8.0' ] as $v ) { $reported = []; foreach ( comp_of( report( "useguards-$v" ), 'directory', 'u' )['findings'] ?? [] as $f ) { $reported[ basename( $f['file'], '.php' ) ] = true; } $wrong = []; - foreach ( require '/t/use-guards.php' as list( $id, $target, $php, $scanner ) ) { - $bad = ( 'reported' === $scanner ) !== isset( $reported[ $id ] ) || ( 'fatal' === $php && 'quiet' === $scanner ); + foreach ( $useGuards as list( $id, $target, $php, $scanner ) ) { + $bad = ( 'reported' === $scanner ) !== isset( $reported[ $id ] ) || ( 'ok' !== $php && 'quiet' === $scanner ); if ( $target === $v && $bad ) { $wrong[] = $id; } From 24d4105ce21ffc6125026ec91e622004611bab8e Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:19:56 +0530 Subject: [PATCH 61/80] test(compat-scanner): pin the shapes that aren't guards extension_loaded(), defined() around a function, an alternative-syntax else and a while condition are no guards by design: the use-guard table gets a row for each, and the declaration table one for `! extension_loaded( 'mbstring' )` around mb_str_pad(). PHP runs them all; the scanner reports them. --- compat-scanner/tests/guards.php | 1 + compat-scanner/tests/use-guards.php | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/compat-scanner/tests/guards.php b/compat-scanner/tests/guards.php index 36a916eb..56c38012 100644 --- a/compat-scanner/tests/guards.php +++ b/compat-scanner/tests/guards.php @@ -74,6 +74,7 @@ [ 'f-goto-into', 'fatal', 'reported', "goto p_g;\nif ( ! function_exists( 'array_first' ) ) {\np_g:\n" . F . "\n}" ], [ 'f-goto-before', 'ok', 'quiet', "goto p_g;\np_g:\nif ( ! function_exists( 'array_first' ) ) { " . F . ' }' ], // Strict: PHP runs these, but they aren't shapes the grammar accepts. + [ 'f-ext', 'ok', 'reported', "if ( ! extension_loaded( 'mbstring' ) ) { function mb_str_pad() {} }" ], [ 'f-callable', 'ok', 'reported', "if ( ! is_callable( 'array_first' ) ) { " . F . ' }' ], [ 'f-ver-sep-ok', 'ok', 'reported', 'if ( PHP_VERSION_ID < 80_500 ) { ' . F . ' }' ], [ 'f-ver-octal', 'ok', 'reported', 'if ( PHP_VERSION_ID < 0235164 ) { ' . F . ' }' ], diff --git a/compat-scanner/tests/use-guards.php b/compat-scanner/tests/use-guards.php index 2b2dc672..9b0a88da 100644 --- a/compat-scanner/tests/use-guards.php +++ b/compat-scanner/tests/use-guards.php @@ -37,6 +37,11 @@ [ 'e-wrapper-arrow', '8.0', 'fatal', 'reported', "\$f = null;\nif ( function_exists( 'each' ) ) { \$f = fn( \$a ) => each( \$a ); }\n\$f( \$a );" ], // goto can enter the block past its guard. [ 'e-goto-into', '8.0', 'fatal', 'reported', "goto g;\nif ( function_exists( 'each' ) ) {\ng:\n" . E . "\n}" ], + // Not guards by design: extension_loaded(), defined() for a function, alternative-syntax else, while. + [ 'e-ext', '8.0', 'ok', 'reported', "if ( extension_loaded( 'mcrypt' ) ) { mcrypt_create_iv( 16 ); }" ], + [ 'e-defined-fn', '8.0', 'ok', 'reported', "if ( defined( 'MCRYPT_DEV_URANDOM' ) ) { mcrypt_create_iv( 16 ); }" ], + [ 'e-alt-else', '8.0', 'ok', 'reported', "if ( ! function_exists( 'each' ) ) : else : " . E . ' endif;' ], + [ 'e-while', '8.0', 'ok', 'reported', "while ( function_exists( 'each' ) ) { " . E . ' break; }' ], // Strict: PHP runs these, but they aren't shapes the grammar accepts. [ 'e-in-condition', '8.0', 'ok', 'reported', "if ( function_exists( 'each' ) && each( \$a ) ) { }" ], [ 'e-ternary', '8.0', 'ok', 'reported', "\$x = function_exists( 'each' ) ? each( \$a ) : null;" ], From ae61abaa2d8a35bca21a49eeef2db8734c55c36b Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:22:17 +0530 Subject: [PATCH 62/80] fix(compat-scanner): let defined() guard the constant it names New and removed constant findings now follow the guard rules of functions and classes: a version test that excludes the target drops them, and so does `defined( 'X' )` for exactly the constant X, matched case-sensitively, as the whole condition or a top-level `&&` operand, or as the else of `! defined( 'X' )`. A constant only deprecated on the target still exists, so defined() keeps its warning. PHPMailer's `if ( defined( 'INTL_IDNA_VARIANT_2003' ) )` branch was an error at every target from 8.0. A function's parameter list now belongs to that function, so a guard around the declaration doesn't cover a default in its signature. --- compat-scanner/src/CompatScanner/Guard.php | 19 +++++++++++++++++-- compat-scanner/src/LinesReport.php | 8 +++++--- compat-scanner/tests/use-guards.php | 22 ++++++++++++++++++++++ 3 files changed, 44 insertions(+), 5 deletions(-) diff --git a/compat-scanner/src/CompatScanner/Guard.php b/compat-scanner/src/CompatScanner/Guard.php index 35b3d9df..752cf179 100644 --- a/compat-scanner/src/CompatScanner/Guard.php +++ b/compat-scanner/src/CompatScanner/Guard.php @@ -85,6 +85,13 @@ private static function scope( File $file, int $ptr ): int { $scope = $block; } } + // A parameter list belongs to its function, though it isn't one of the function's conditions. + foreach ( $tokens[ $ptr ]['nested_parenthesis'] ?? [] as $open => $close ) { + $owner = $tokens[ $open ]['parenthesis_owner'] ?? -1; + if ( $owner > $scope && in_array( $tokens[ $owner ]['code'] ?? null, [ T_FUNCTION, T_CLOSURE, T_FN ], true ) ) { + $scope = $owner; + } + } // Arrow functions aren't conditions; only one inside the outermost block matters. $from = max( $scope, array_key_first( $tokens[ $ptr ]['conditions'] ) ); for ( $fn = $ptr; false !== ( $fn = $file->findPrevious( T_FN, $fn - 1, $from + 1 ) ); ) { @@ -196,8 +203,16 @@ private static function named( File $file, array $op, array $checks, string $nam if ( ! self::call( $tokens, $op, $checks ) ) { return false; } - $arg = PassedParameters::getParameter( $file, $op[0], 1, [ 'function', 'class', 'interface', 'enum' ] ); - return false !== $arg && strtolower( (string) self::nameOf( $file, $arg['start'], $arg['clean'] ) ) === strtolower( $name ); + $arg = PassedParameters::getParameter( $file, $op[0], 1, [ 'function', 'class', 'interface', 'enum', 'constant_name' ] ); + if ( false === $arg ) { + return false; + } + $given = self::nameOf( $file, $arg['start'], $arg['clean'] ); + // A constant's name is case-sensitive, and defined() takes no X::class. + if ( [ 'defined' ] === $checks ) { + return preg_match( '/^[\'"]/', $arg['clean'] ) && $given === ltrim( $name, '\\' ); + } + return strtolower( (string) $given ) === strtolower( $name ); } /** diff --git a/compat-scanner/src/LinesReport.php b/compat-scanner/src/LinesReport.php index 2af5bb35..571cc8d6 100644 --- a/compat-scanner/src/LinesReport.php +++ b/compat-scanner/src/LinesReport.php @@ -27,6 +27,8 @@ class LinesReport implements Report { 'PHPCompatibility.Classes.NewClasses.' => 'class_exists', 'PHPCompatibility.Classes.RemovedClasses.' => 'class_exists', 'PHPCompatibility.Interfaces.NewInterfaces.' => 'interface_exists', + 'PHPCompatibility.Constants.NewConstants.' => 'defined', + 'PHPCompatibility.Constants.RemovedConstants.' => 'defined', ]; /** @var int[] The target's PHP_VERSION_ID range. */ @@ -57,7 +59,7 @@ public function generateFileReport( array $report, File $phpcsFile, bool $showSo } $message['class'] = strtolower( $kind[1] ) . " $name"; } - // An extension's finding names its prefix; the function is the token it is on. + // An extension's finding names its prefix; the function or constant is the token it is on. $name = $name ?? ( null === $ptr ? '' : ltrim( $phpcsFile->getTokens()[ $ptr ]['content'], '\\' ) ); // A deprecated name still exists on the target, so only a version test keeps its warning from firing. $checks = preg_match( '/Deprecated\z/', $message['source'] ) ? [] : [ $check ]; @@ -98,13 +100,13 @@ public function generate( string $cachedData, int $totalFiles, int $totalErrors, } /** - * The check that sees the name a finding of this source is about, and the name from the source (lowercase; null for an extension); [ null, null ] when it isn't one GUARDED names. + * The check that sees the name a finding of this source is about, and the name from the source (lowercase; null for an extension or a constant, whose case counts); [ null, null ] when it isn't one GUARDED names. */ private function named( string $source ): array { foreach ( self::GUARDED as $prefix => $check ) { if ( 0 === strpos( $source, $prefix ) ) { $name = (string) preg_replace( '/(?:Found|Deprecated|Removed)+\z/', '', substr( $source, strlen( $prefix ) ) ); - return [ $check, false !== strpos( $prefix, '.Extensions.' ) ? null : $name ]; + return [ $check, false !== strpos( $prefix, '.Extensions.' ) || 'defined' === $check ? null : $name ]; } } return [ null, null ]; diff --git a/compat-scanner/tests/use-guards.php b/compat-scanner/tests/use-guards.php index 9b0a88da..862a2dae 100644 --- a/compat-scanner/tests/use-guards.php +++ b/compat-scanner/tests/use-guards.php @@ -5,6 +5,7 @@ const E = 'each( $a );'; const L = 'array_is_list( [] );'; const N = 'new Fiber( function () {} );'; +const I = 'INTL_IDNA_VARIANT_2003'; $rows = [ // each() is gone from 8.0: a use that runs only where it exists, or only below 8.0. @@ -73,6 +74,27 @@ // A site's trait or interface of a new class's name doesn't stand in for it. [ 'v-trait', '7.4', 'fatal', 'reported', "trait ValueError {}\nthrow new ValueError();" ], [ 'v-interface', '7.4', 'fatal', 'reported', "interface UnhandledMatchError {}\nthrow new UnhandledMatchError();" ], + // INTL_IDNA_VARIANT_2003 is gone from 8.0: defined() on exactly that name guards it, as a version test does. + [ 'k-defined', '8.0', 'ok', 'quiet', "if ( defined( '" . I . "' ) ) { \$v = " . I . '; }' ], + [ 'k-defined-elseif', '8.0', 'ok', 'quiet', "if ( false ) { } elseif ( defined( '" . I . "' ) ) { \$v = " . I . '; }' ], + [ 'k-defined-else', '8.0', 'ok', 'quiet', "if ( ! defined( '" . I . "' ) ) { } else { \$v = " . I . '; }' ], + [ 'k-defined-and', '8.0', 'ok', 'quiet', "if ( defined( '" . I . "' ) && \$a ) { \$v = " . I . '; }' ], + [ 'k-defined-fq', '8.0', 'ok', 'quiet', "if ( \\defined( '\\" . I . "' ) ) { \$v = \\" . I . '; }' ], + [ 'k-ver', '8.0', 'ok', 'quiet', 'if ( PHP_VERSION_ID < 80000 ) { $v = ' . I . '; }' ], + [ 'k-new', '8.0', 'ok', 'quiet', "if ( defined( 'FILTER_FLAG_GLOBAL_RANGE' ) ) { \$v = FILTER_FLAG_GLOBAL_RANGE; }" ], + [ 'k-other', '8.0', 'fatal', 'reported', "define( 'P_K', 1 );\nif ( defined( 'P_K' ) ) { \$v = " . I . '; }' ], + [ 'k-case', '8.0', 'fatal', 'reported', "define( '" . strtolower( I ) . "', 1 );\nif ( defined( '" . strtolower( I ) . "' ) ) { \$v = " . I . '; }' ], + [ 'k-or', '8.0', 'fatal', 'reported', "if ( defined( '" . I . "' ) || true ) { \$v = " . I . '; }' ], + [ 'k-else-defined', '8.0', 'fatal', 'reported', "if ( defined( '" . I . "' ) ) { } else { \$v = " . I . '; }' ], + [ 'k-ver-high', '8.0', 'fatal', 'reported', 'if ( PHP_VERSION_ID < 80100 ) { $v = ' . I . '; }' ], + [ 'k-goto', '8.0', 'fatal', 'reported', "goto g;\nif ( defined( '" . I . "' ) ) {\ng:\n\$v = " . I . ";\n}" ], + [ 'k-exists', '8.0', 'ok', 'reported', "if ( function_exists( 'mcrypt_create_iv' ) ) { \$v = MCRYPT_DEV_URANDOM; }" ], + [ 'k-fn-body', '8.0', 'fatal', 'reported', "if ( defined( '" . I . "' ) ) { function p_kb() { return " . I . "; } }\np_kb();" ], + [ 'k-fn-default', '8.0', 'fatal', 'reported', "if ( defined( '" . I . "' ) ) { function p_kd( \$v = " . I . " ) { return \$v; } }\np_kd();" ], + // mcrypt_create_iv() stays reported; only the constant defined() names is guarded. + [ 'k-mcrypt', '8.0', 'ok', 'reported', "if ( defined( 'MCRYPT_DEV_URANDOM' ) ) { mcrypt_create_iv( 16, MCRYPT_DEV_URANDOM ); }" ], + // Only deprecated in 7.4: it exists, so defined() doesn't keep its warning away. + [ 'k-deprecated', '7.4', 'ok', 'reported', "if ( defined( '" . I . "' ) ) { \$v = " . I . '; }' ], // get_magic_quotes_gpc() is deprecated in 7.4: it exists, so only a version test keeps the deprecation away. [ 'q-exists', '7.4', 'deprecated', 'reported', "if ( function_exists( 'get_magic_quotes_gpc' ) ) { get_magic_quotes_gpc(); }" ], [ 'q-ver', '7.4', 'ok', 'quiet', 'if ( PHP_VERSION_ID < 70400 ) { get_magic_quotes_gpc(); }' ], From 33bfa7ceb6d911abd274ae379919bf3c7247f30f Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:25:07 +0530 Subject: [PATCH 63/80] fix(compat-scanner): skip a constant default of a function declared only below the target symfony/polyfill-intl-idn's bootstrap.php declares idn_to_ascii() and idn_to_utf8() only below PHP 7.4, with INTL_IDNA_VARIANT_2003 as a parameter default, which made every site using guzzle 7 or symfony/mailer not safe at any target from 8.0. A default runs only in a call, and on the target the function is never declared. A new or removed constant in a parameter default of a named function is now dropped when a version test around the declaration excludes the target; defined() there doesn't count, and methods, closures and the function body keep the finding. --- compat-scanner/src/LinesReport.php | 18 ++++++++++++++++++ compat-scanner/tests/use-guards.php | 6 ++++++ 2 files changed, 24 insertions(+) diff --git a/compat-scanner/src/LinesReport.php b/compat-scanner/src/LinesReport.php index 571cc8d6..7b2154c0 100644 --- a/compat-scanner/src/LinesReport.php +++ b/compat-scanner/src/LinesReport.php @@ -8,6 +8,7 @@ use CompatScanner\Guard; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Reports\Report; +use PHP_CodeSniffer\Util\Tokens; use PHPCSUtils\BackCompat\Helper; use PHPCSUtils\Utils\Namespaces; @@ -63,6 +64,11 @@ public function generateFileReport( array $report, File $phpcsFile, bool $showSo $name = $name ?? ( null === $ptr ? '' : ltrim( $phpcsFile->getTokens()[ $ptr ]['content'], '\\' ) ); // A deprecated name still exists on the target, so only a version test keeps its warning from firing. $checks = preg_match( '/Deprecated\z/', $message['source'] ) ? [] : [ $check ]; + $decl = 'defined' === $check && null !== $ptr ? $this->declaredWith( $phpcsFile, $ptr ) : null; + // A parameter default runs only in calls, and the function exists only where its version test holds. + if ( null !== $decl && $this->guarded( $phpcsFile, $decl, [], $name ) ) { + continue; + } if ( null !== $ptr && $this->guarded( $phpcsFile, $ptr, $checks, $name ) ) { continue; } @@ -133,6 +139,18 @@ private function guarded( File $phpcsFile, int $ptr, array $checks, string $name return Guard::encloses( $phpcsFile, $ptr, $inIf, $inElse ); } + /** The named function (no method, closure or arrow function) whose parameter list holds $ptr, or null. */ + private function declaredWith( File $phpcsFile, int $ptr ): ?int { + $tokens = $phpcsFile->getTokens(); + foreach ( $tokens[ $ptr ]['nested_parenthesis'] ?? [] as $open => $close ) { + $fn = $tokens[ $open ]['parenthesis_owner'] ?? null; + if ( null !== $fn && T_FUNCTION === $tokens[ $fn ]['code'] && ! isset( Tokens::OO_SCOPE_TOKENS[ end( $tokens[ $fn ]['conditions'] ) ] ) ) { + return $fn; + } + } + return null; + } + /** * The classes (enums too) and interfaces the file declares where the declaration runs on the target, as "class " or "interface <…>": at file scope, or only in if blocks each of whose `&&` operands holds there (a version test, or a negated class_exists() or interface_exists() on that name). * diff --git a/compat-scanner/tests/use-guards.php b/compat-scanner/tests/use-guards.php index 862a2dae..dd4d5445 100644 --- a/compat-scanner/tests/use-guards.php +++ b/compat-scanner/tests/use-guards.php @@ -91,6 +91,12 @@ [ 'k-exists', '8.0', 'ok', 'reported', "if ( function_exists( 'mcrypt_create_iv' ) ) { \$v = MCRYPT_DEV_URANDOM; }" ], [ 'k-fn-body', '8.0', 'fatal', 'reported', "if ( defined( '" . I . "' ) ) { function p_kb() { return " . I . "; } }\np_kb();" ], [ 'k-fn-default', '8.0', 'fatal', 'reported', "if ( defined( '" . I . "' ) ) { function p_kd( \$v = " . I . " ) { return \$v; } }\np_kd();" ], + // A default of a function declared only below the target runs only in a call that can't happen there. + [ 'k-default-ver', '8.0', 'ok', 'quiet', "if ( PHP_VERSION_ID < 70400 ) { function p_ka( \$v = " . I . ' ) { return $v; } }' ], + [ 'k-default-ver-high', '8.0', 'fatal', 'reported', "if ( PHP_VERSION_ID < 80100 ) { function p_kh( \$v = " . I . " ) { return \$v; } }\np_kh();" ], + [ 'k-body-ver', '8.0', 'ok', 'reported', 'if ( PHP_VERSION_ID < 70400 ) { function p_kc() { return ' . I . '; } }' ], + [ 'k-default-method', '8.0', 'ok', 'reported', "if ( PHP_VERSION_ID < 70400 ) { class P_KM { function m( \$v = " . I . ' ) {} } }' ], + [ 'k-default-closure', '8.0', 'ok', 'reported', "if ( PHP_VERSION_ID < 70400 ) { \$f = function ( \$v = " . I . ' ) {}; }' ], // mcrypt_create_iv() stays reported; only the constant defined() names is guarded. [ 'k-mcrypt', '8.0', 'ok', 'reported', "if ( defined( 'MCRYPT_DEV_URANDOM' ) ) { mcrypt_create_iv( 16, MCRYPT_DEV_URANDOM ); }" ], // Only deprecated in 7.4: it exists, so defined() doesn't keep its warning away. From acb699ae8c6689c1a9a4b93533f9f588539b53d9 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:28:32 +0530 Subject: [PATCH 64/80] fix(compat-scanner): leave out package files their package loads only above the target symfony/polyfill-php84 loads Resources/Deprecated.php and Resources/RoundingMode.php from stubs/ in the elseif of an if that runs below 8.1, and polyfill-php83 loads bootstrap81.php only from 8.1 on, so PHP 8.0 never reads them; they still gave ParseErrors and LDAP\Connection errors at 8.0. A file in a Composer package that its package loads only above the target is now out of the verdict: no lint error, and nothing PHPCS reports on it counts, the classes it declares included. It is still counted as checked. A gated load is `[return] require|include[_once] . '/name';` alone in the block of an if or elseif whose version test holds only from the next minor on, where is `__DIR__` beside the file or exactly `dirname( __DIR__ )` in a direct subdirectory. An elseif also needs each earlier "below n" branch to have failed; `else if` reads as a plain if, and an else is no gated load. Every string naming the file in the code of its directory and direct subdirectories must be such a load, and each of those files must be readable. Only the file itself is skipped, by path. The check runs for a package file with a lint failure or a PHPCS error. Tests: the real polyfill-php84, polyfill-php83 and polyfill-intl-idn files at 8.0 and 8.1, and a table of chains and loads that do or don't gate. --- compat-scanner/bin/compat-scanner.php | 126 +++++++++++---- compat-scanner/tests/assert.php | 35 ++++- compat-scanner/tests/fixture.sh | 33 ++++ compat-scanner/tests/run.sh | 4 +- .../polyfill-intl-idn/bootstrap.php | 145 ++++++++++++++++++ .../polyfill-php83/bootstrap.php | 54 +++++++ .../polyfill-php83/bootstrap81.php | 40 +++++ .../polyfill-php84/Resources/Deprecated.php | 25 +++ .../polyfill-php84/Resources/RoundingMode.php | 24 +++ .../Resources/stubs/Deprecated.php | 34 ++++ .../Resources/stubs/RoundingMode.php | 44 ++++++ 11 files changed, 528 insertions(+), 36 deletions(-) create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-intl-idn/bootstrap.php create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-php83/bootstrap.php create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-php83/bootstrap81.php create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/Deprecated.php create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/RoundingMode.php create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/Deprecated.php create mode 100644 compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/RoundingMode.php diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 678c7ec9..39d381e9 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -1879,6 +1879,10 @@ private function tooLarge(): ToolError { private function recordLint( array $f ): void { $rel = $this->rel( $f['comp'], $f['path'] ); $reason = $f['lint']; + if ( true === $reason ) { + $this->counted( $f, 0, 0 ); + return; + } if ( is_string( $reason ) ) { $this->spoolNotChecked( $f['comp'], $rel, $reason, $f['real'] ); return; @@ -1921,13 +1925,13 @@ private function record( array $f, ReportReader $reader ): void { $this->spoolNotChecked( $comp, $raw, 'unparseable', $f['real'] ); return; } - // Text before the tag (a script with `inPackage( $f['path'] ) ) { $messages = []; while ( null !== ( $m = $reader->message() ) ) { // No code at all (a bare `skipMessages(); $this->spoolNotChecked( $comp, $raw, 'php_tag', $f['real'] ); return; @@ -1935,6 +1939,11 @@ private function record( array $f, ReportReader $reader ): void { $messages[] = $m; } } + // PHP never reads it on the target, so nothing PHPCS says about it counts, its classes included. + if ( null !== $messages && in_array( 'ERROR', array_column( $messages, 2 ), true ) && $this->loadedOnlyAbove( $f['real'], $f['path'] ) ) { + $this->counted( $f, 0, 0 ); + return; + } foreach ( $block['d'] as $class ) { $this->declared[ $class ] = true; @@ -2410,7 +2419,7 @@ private function runTimed( array $cmd, float $cap, array $spec, int $fsize = 0 ) /** * `php -l` with the target's PHP over a batch, then each failing file alone: PHPCompatibility misses some parse errors (`#[` before PHP 8, an unclosed comment). Not for targets before 8.0 (none in the image), nor files with text before the tag and no template name. * - * @return array By batch key, the files that fail: [ line, message ] or a not_checked reason. + * @return array By batch key, the files that fail: [ line, message ], a not_checked reason, or true when its package loads it only above the target. */ private function lint( array $batch ): array { $paths = []; @@ -2436,8 +2445,10 @@ private function lint( array $batch ): array { } if ( 0 !== $res['rc'] ) { $result = $this->lintResult( $res, $real ); + // PHP never reads it on the target: no verdict on it, from the lint or PHPCS. if ( is_array( $result ) && $this->loadedOnlyAbove( $real, $batch[ $k ]['path'] ) ) { - continue; // PHP never parses it on the target, so PHPCS checks it as usual. + $failed[ $k ] = true; + continue; } // Not named as code (a `.stub`, a template): the file may never run as PHP, so its failure can't prove a break. $failed[ $k ] = ! $batch[ $k ]['code'] && is_array( $result ) ? 'php_tag' : $result; @@ -2447,42 +2458,58 @@ private function lint( array $batch ): array { } /** - * Whether the code beside a file in a Composer package loads it only above the target, as Symfony's polyfills load bootstrap85.php. Every string naming it there must sit in `if ( ) { [return] require __DIR__ . '/name'; }`, the test holding only above the target; a code file beside it that can't be read may name it too. + * Whether its Composer package loads a file only above the target, as Symfony's polyfills load bootstrap85.php or Resources/Deprecated.php: every string naming it in the code files of its directory and their direct subdirectories is a gated load (gatedLoad()), and there is one. */ private function loadedOnlyAbove( string $real, string $path ): bool { // App code may load it from anywhere; a package is loaded through its own files. if ( ! $this->inPackage( $path ) ) { return false; } - $dir = dirname( $real ); - $name = basename( $real ); - // Read once per directory: a flat legacy dir can have hundreds of files the lint fails. + $dir = dirname( $real ); + // Read once per directory: a flat legacy dir can have hundreds of files with errors. if ( ! array_key_exists( $dir, $this->loads ) ) { $this->loads[ $dir ] = $this->loadsIn( $dir, $path ); } - $above = 0; + $name = basename( $real ); + $gated = 0; $all = 0; foreach ( (array) $this->loads[ $dir ] as $file => $names ) { + // Only the file itself is skipped: a namesake in a subdirectory may be its loader. if ( $file !== $name && isset( $names[ $name ] ) ) { - $above += $names[ $name ][0]; + $gated += $names[ $name ][0]; $all += $names[ $name ][1]; } } - return null !== $this->loads[ $dir ] && $above > 0 && $above === $all; + return null !== $this->loads[ $dir ] && $gated > 0 && $gated === $all; } - /** @return array>|null Per code file here, the code file names its strings end in: [ loaded only above the target, all ]. */ + /** + * Per code file in the directory or a direct subdirectory (by relative path), the code file names its strings end in: [ gated loads, all ]; null when one of them can't be read. + * + * @return array>|null + */ private function loadsIn( string $dir, string $path ): ?array { $above = Guard::target( $this->cfg['version'] )[1]; + $files = []; + foreach ( (array) $this->readDir( $dir ) as $entry ) { + $sub = is_dir( "$dir/$entry" ) ? $this->readDir( "$dir/$entry" ) : []; + if ( null === $sub ) { + return null; + } + $files[ $entry ] = false; + foreach ( $sub as $file ) { + $files[ "$entry/$file" ] = true; + } + } $loads = []; - foreach ( (array) $this->readDir( $dir ) as $file ) { + foreach ( $files as $file => $child ) { if ( ! $this->isPhpName( $file ) ) { continue; } if ( microtime( true ) >= $this->deadline ) { throw $this->timedOutAt( $path ); } - $tokens = code_tokens( $dir . '/' . $file ); + $tokens = code_tokens( "$dir/$file" ); if ( null === $tokens ) { return null; } @@ -2491,32 +2518,57 @@ private function loadsIn( string $dir, string $path ): ?array { if ( in_array( $id, [ T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE ], true ) && $this->isPhpName( $named ) ) { $count = $loads[ $file ][ $named ] ?? [ 0, 0 ]; - $loads[ $file ][ $named ] = [ $count[0] + (int) $this->gatedAbove( $tokens, $i, $above ), $count[1] + 1 ]; + $loads[ $file ][ $named ] = [ $count[0] + (int) $this->gatedLoad( $tokens, $i, $child, $above ), $count[1] + 1 ]; } } } return $loads; } - /** Whether the string at $i is the `'/name'` of `if ( ) { [return] require|include[_once] __DIR__ . '/name'; }`, the test holding only from $above on. */ - private function gatedAbove( array $tokens, int $i, int $above ): bool { - $text = static function ( $at ) use ( $tokens ) { - return $tokens[ $at ][1] ?? ''; - }; - $load = in_array( $tokens[ $i - 3 ][0] ?? null, [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ); - if ( ! $load || ! preg_match( '#^([\'"])/[^/\'"]+\1$#', $text( $i ) ) || [ '.', ';', '}' ] !== [ $text( $i - 1 ), $text( $i + 1 ), $text( $i + 2 ) ] ) { + /** + * Whether the string at $i is the `'/name'` of `[return] require|include[_once] . '/name';` alone in the block of an if or elseif that runs only from $above on. is `__DIR__`, or `dirname( __DIR__ )` in a subdirectory ($child). An elseif runs only where each earlier branch's "below n" test failed. + */ + private function gatedLoad( array $tokens, int $i, bool $child, int $above ): bool { + $text = static fn ( $at ) => $tokens[ $at ][1] ?? ''; + if ( ! preg_match( '#^([\'"])/[^/\'"]+\1$#', $text( $i ) ) || [ '.', ';', '}' ] !== [ $text( $i - 1 ), $text( $i + 1 ), $text( $i + 2 ) ] ) { return false; } - $j = T_RETURN === ( $tokens[ $i - 4 ][0] ?? null ) ? $i - 5 : $i - 4; - if ( T_DIR !== ( $tokens[ $i - 2 ][0] ?? null ) || [ '{', ')' ] !== [ $text( $j ), $text( $j - 1 ) ] ) { + $dirname = 'dirname' === strtolower( ltrim( $text( $i - 5 ), '\\' ) ) && [ '(', ')' ] === [ $text( $i - 4 ), $text( $i - 2 ) ]; + $at = $child ? $i - 3 : $i - 2; + $load = $child ? $i - 6 : $i - 3; + if ( T_DIR !== ( $tokens[ $at ][0] ?? null ) || ( $child && ! $dirname ) ) { return false; } - // Back to the condition's opening parenthesis. - for ( $k = $j - 2, $depth = 0; $k >= 0 && ( '(' !== $text( $k ) || $depth > 0 ); $k-- ) { - $depth += ( ')' === $text( $k ) ) - ( '(' === $text( $k ) ); + $open = T_RETURN === ( $tokens[ $load - 1 ][0] ?? null ) ? $load - 2 : $load - 1; + $kind = $tokens[ $load ][0] ?? null; + if ( ! in_array( $kind, [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ) || [ '{', ')' ] !== [ $text( $open ), $text( $open - 1 ) ] ) { + return false; + } + $branch = $this->branch( $tokens, $open - 1 ); + if ( null === $branch || null === $branch[1] ) { + return false; + } + $lo = $branch[1][0]; + while ( T_ELSEIF === $tokens[ $branch[0] ][0] && '}' === $text( $branch[0] - 1 ) ) { + $brace = opening( $tokens, $branch[0] - 1 ); + $branch = null !== $brace && ')' === $text( $brace - 1 ) ? $this->branch( $tokens, $brace - 1 ) : null; + if ( null === $branch ) { + break; + } + if ( null !== $branch[1] && 0 === $branch[1][0] ) { + $lo = max( $lo, $branch[1][1] ); + } } - $range = $k > 0 && T_IF === $tokens[ $k - 1 ][0] ? Guard::range( array_column( array_slice( $tokens, $k + 1, $j - $k - 2 ), 1 ) ) : null; - return null !== $range && $range[0] >= $above; + return $lo >= $above; + } + + /** The if or elseif whose condition ends at $close: [ its index, the version range its whole condition tests, or null ]; null when it is no such condition. */ + private function branch( array $tokens, int $close ): ?array { + $open = opening( $tokens, $close ); + if ( null === $open || ! in_array( $tokens[ $open - 1 ][0] ?? null, [ T_IF, T_ELSEIF ], true ) ) { + return null; + } + return [ $open - 1, Guard::range( array_column( array_slice( $tokens, $open + 1, $close - $open - 1 ), 1 ) ) ]; } /** Before 8.3 `php -l` reads only its first file, so each file is linted alone. */ @@ -3104,6 +3156,20 @@ function code_tokens( string $path ): ?array { return $tokens; } +/** The index of the `(` or `{` (also `${`) that the `)` or `}` at $close closes, among code_tokens(); null when there is none. */ +function opening( array $tokens, int $close ): ?int { + $open = ')' === $tokens[ $close ][1] ? [ '(' ] : [ '{', '${' ]; + $depth = 0; + for ( $k = $close - 1; $k >= 0; $k-- ) { + if ( $tokens[ $k ][1] === $tokens[ $close ][1] ) { + $depth++; + } elseif ( in_array( $tokens[ $k ][1], $open, true ) && 0 === $depth-- ) { + return $k; + } + } + return null; +} + /** major.minor of a WordPress version, as EE's support table names branches. */ function wp_branch( string $version ): string { return preg_match( '/^\d+\.\d+/', $version, $m ) ? $m[0] : ''; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 4e757c5c..c484decc 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1072,10 +1072,19 @@ function counts( string $name ): array { eq( finding_files( report( "nativetables-$v" ) ), $want, "nativetables-$v: names native in the target, declared unguarded" ); } -// symfony/polyfill's stubs and bootstrap85.php, which PHP never runs or loads on the target, give no error there; look-alikes do. -$parse = 'CompatScanner.Syntax.ParseError'; -$names = 'PHPCompatibility.Namespaces.ReservedNames.'; -$pf = [ +// symfony/polyfill's stubs, bootstrap85.php, polyfill-php84's Resources/*.php and polyfill-php83's bootstrap81.php, which PHP never runs or loads on the target, give no error there; look-alikes do. +$parse = 'CompatScanner.Syntax.ParseError'; +$names = 'PHPCompatibility.Namespaces.ReservedNames.'; +$always = [ + "acme/always/bootstrap85.php:$parse", + "acme/bigsib/bootstrap85.php:$parse", + "acme/gatetxt/broken.php:$parse", + "acme/quoted/bootstrap85.php:$parse", + "acme/unreadsib/bootstrap85.php:$parse", +]; +$pf = [ + '8.0' => $always, + '8.1' => $always, // A gate 8.4.1 passes loads it on 8.4; a sibling too big or unreadable to check may load it too. '8.2' => [ "acme/always/bootstrap85.php:$parse", @@ -1109,11 +1118,27 @@ function counts( string $name ): array { eq( $got, $want, "polyfill-$v: errors only where PHP would load or run the file" ); } // PHP 8.5 parses bootstrap85.php: only the unreadable sibling is an entry. -foreach ( [ '8.2', '8.4', '8.5' ] as $v ) { +foreach ( [ '8.0', '8.1', '8.2', '8.4', '8.5' ] as $v ) { $pf = report( "polyfill-$v" ); $got = [ array_column( $pf['not_checked'] ?? [], 'file' ), raw( "polyfill-$v.stderr" ) ]; eq( $got, [ [ 'acme/unreadsib/load.php' ], '' ], "polyfill-$v: no other entry, nothing on stderr" ); } +// A package file loaded only from the next minors on, through an if/elseif chain, is out of the verdict, PHPCS findings and classes included; other loads keep it in. +$kept = []; +foreach ( [ 'array', 'arraysub', 'deep', 'dir2', 'dirdir', 'dotdot', 'elseonly', 'low', 'nonver', 'unread', 'unreadsub' ] as $d ) { + $kept[] = "directory:vendor::acme/$d/x.php"; +} +$at81 = [ 'directory:vendor::acme/b81/b81.php', 'directory:vendor::acme/decl/fiber.php', 'directory:vendor::acme/own/x.php', 'directory:vendor::acme/php84/x.php' ]; +$gc = [ + '8.0' => array_merge( [ 'directory:app::x.php' ], $kept, [ 'other:::fiber.php' ] ), + '8.1' => array_merge( [ 'directory:app::x.php' ], $kept, $at81 ), + '8.2' => array_merge( [ 'directory:app::x.php' ], $kept, array_slice( $at81, 1 ) ), + '8.3' => array_merge( [ 'directory:app::x.php' ], $kept, array_slice( $at81, 1 ) ), +]; +foreach ( $gc as $v => $want ) { + sort( $want ); + eq( array_values( array_unique( finding_files( report( "gatechain-$v" ) ) ) ), $want, "gatechain-$v: a package file is left out only where its package loads it above the target alone" ); +} tool_error( 'slowsib', 'timed out after 3 s at htdocs/vendor/acme/slow/a.php', 1 ); $secs = trim( raw( 'slowsib.secs' ) ); check( '' !== $secs && (int) $secs <= 9, "slowsib: the files beside a failing one are read only until the deadline ($secs s)" ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 3a043dda..18d333a6 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1405,6 +1405,39 @@ if ( \\PHP_VERSION_ID >= 80500 ) { chmod -R a+rX "$1" chmod 0 "$v/acme/unreadsib/load.php" } +# gatechain_fixture : package files loaded only from the next minors on through if/elseif chains (PHP 8.4 syntax in x.php, a PHP 8.2 class in b81.php), and loads that don't gate them. +gatechain_fixture() { + local v="$1/htdocs/vendor" d + local hooks='class P_H { public int $x { get => 1; } }' + mkdir -p "$v/composer" && echo '{"packages":[]}' > "$v/composer/installed.json" + for d in own php84 low nonver elseonly dir2 dirdir dotdot deep array arraysub unread unreadsub; do php_file "$v/acme/$d/x.php" "$hooks"; done + php_file "$v/acme/own/load.php" "if ( \\PHP_VERSION_ID >= 80400 ) { } elseif ( \\PHP_VERSION_ID >= 80100 ) { require __DIR__ . '/x.php'; }" + php_file "$v/acme/php84/stubs/x.php" "if ( \\PHP_VERSION_ID < 80100 ) { } elseif ( \\PHP_VERSION_ID < 80400 ) { require dirname( __DIR__ ) . '/x.php'; }" + php_file "$v/acme/low/load.php" "if ( \\PHP_VERSION_ID < 80000 ) { } elseif ( \\PHP_VERSION_ID < 80400 ) { require __DIR__ . '/x.php'; }" + php_file "$v/acme/nonver/load.php" "if ( function_exists( 'p_x' ) ) { } elseif ( \\PHP_VERSION_ID < 80400 ) { require __DIR__ . '/x.php'; }" + php_file "$v/acme/elseonly/load.php" "if ( \\PHP_VERSION_ID < 80100 ) { } else { require __DIR__ . '/x.php'; }" + php_file "$v/acme/dir2/sub/load.php" "if ( \\PHP_VERSION_ID >= 80100 ) { require dirname( __DIR__, 2 ) . '/x.php'; }" + php_file "$v/acme/dirdir/sub/load.php" "if ( \\PHP_VERSION_ID >= 80100 ) { require dirname( dirname( __DIR__ ) ) . '/x.php'; }" + php_file "$v/acme/dotdot/sub/load.php" "if ( \\PHP_VERSION_ID >= 80100 ) { require __DIR__ . '/../x.php'; }" + php_file "$v/acme/deep/a/b/load.php" "if ( \\PHP_VERSION_ID >= 80100 ) { require dirname( dirname( __DIR__ ) ) . '/x.php'; }" + for d in array arraysub unread unreadsub; do php_file "$v/acme/$d/load.php" "if ( \\PHP_VERSION_ID >= 80100 ) { require __DIR__ . '/x.php'; }"; done + php_file "$v/acme/array/list.php" "\$files = [ 'x.php' ];" + php_file "$v/acme/arraysub/sub/list.php" "\$files = [ 'x.php' ];" + php_file "$v/acme/unread/other.php" '$a = 1;' + php_file "$v/acme/unreadsub/sub/other.php" '$a = 1;' + php_file "$v/acme/b81/bootstrap.php" "if ( \\PHP_VERSION_ID >= 80100 ) { return require __DIR__ . '/b81.php'; }" + php_file "$v/acme/b81/b81.php" '$r = new \Random\Randomizer();' + # A gated file's classes go with its findings: the site's own new Fiber stays reported. + php_file "$v/acme/decl/load.php" "if ( \\PHP_VERSION_ID >= 80100 ) { require __DIR__ . '/fiber.php'; }" + php_file "$v/acme/decl/fiber.php" 'class Fiber {} +$r = new \Random\Randomizer();' + php_file "$1/htdocs/fiber.php" '$f = new Fiber( function () {} );' + # The php84 shape in app code. + php_file "$1/htdocs/app/x.php" "$hooks" + php_file "$1/htdocs/app/stubs/x.php" "if ( \\PHP_VERSION_ID < 80100 ) { } elseif ( \\PHP_VERSION_ID < 80400 ) { require dirname( __DIR__ ) . '/x.php'; }" + chmod -R a+rX "$1" + chmod 0 "$v/acme/unread/other.php" "$v/acme/unreadsub/sub/other.php" +} # Syntax only some targets reject, also inside a file whose code runs only below the target. targetlint_fixture() { local h="$1/htdocs" diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 37215fdb..84ff91ff 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -475,7 +475,9 @@ for v in 7.4 8.0 8.3; do scan "nativetables-$v" "$WORK/nativetables" php /var/ww # symfony/polyfill files PHP never loads or runs on the target, and look-alikes it would. polyfill_fixture "$WORK/polyfill" -for v in 8.2 8.4 8.5; do scan "polyfill-$v" "$WORK/polyfill" php /var/www/htdocs "$v" 600; done +for v in 8.0 8.1 8.2 8.4 8.5; do scan "polyfill-$v" "$WORK/polyfill" php /var/www/htdocs "$v" 600; done +gatechain_fixture "$WORK/gatechain" +for v in 8.0 8.1 8.2 8.3; do scan "gatechain-$v" "$WORK/gatechain" php /var/www/htdocs "$v" 600; done appgate_fixture "$WORK/appgate" scan appgate "$WORK/appgate" php /var/www/htdocs 8.4 600 # The bootstrap check reads the files beside a failing one only until the deadline. diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-intl-idn/bootstrap.php b/compat-scanner/tests/symfony-polyfill/polyfill-intl-idn/bootstrap.php new file mode 100644 index 00000000..57c78356 --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-intl-idn/bootstrap.php @@ -0,0 +1,145 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Intl\Idn as p; + +if (extension_loaded('intl')) { + return; +} + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!defined('U_IDNA_PROHIBITED_ERROR')) { + define('U_IDNA_PROHIBITED_ERROR', 66560); +} +if (!defined('U_IDNA_ERROR_START')) { + define('U_IDNA_ERROR_START', 66560); +} +if (!defined('U_IDNA_UNASSIGNED_ERROR')) { + define('U_IDNA_UNASSIGNED_ERROR', 66561); +} +if (!defined('U_IDNA_CHECK_BIDI_ERROR')) { + define('U_IDNA_CHECK_BIDI_ERROR', 66562); +} +if (!defined('U_IDNA_STD3_ASCII_RULES_ERROR')) { + define('U_IDNA_STD3_ASCII_RULES_ERROR', 66563); +} +if (!defined('U_IDNA_ACE_PREFIX_ERROR')) { + define('U_IDNA_ACE_PREFIX_ERROR', 66564); +} +if (!defined('U_IDNA_VERIFICATION_ERROR')) { + define('U_IDNA_VERIFICATION_ERROR', 66565); +} +if (!defined('U_IDNA_LABEL_TOO_LONG_ERROR')) { + define('U_IDNA_LABEL_TOO_LONG_ERROR', 66566); +} +if (!defined('U_IDNA_ZERO_LENGTH_LABEL_ERROR')) { + define('U_IDNA_ZERO_LENGTH_LABEL_ERROR', 66567); +} +if (!defined('U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR')) { + define('U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR', 66568); +} +if (!defined('U_IDNA_ERROR_LIMIT')) { + define('U_IDNA_ERROR_LIMIT', 66569); +} +if (!defined('U_STRINGPREP_PROHIBITED_ERROR')) { + define('U_STRINGPREP_PROHIBITED_ERROR', 66560); +} +if (!defined('U_STRINGPREP_UNASSIGNED_ERROR')) { + define('U_STRINGPREP_UNASSIGNED_ERROR', 66561); +} +if (!defined('U_STRINGPREP_CHECK_BIDI_ERROR')) { + define('U_STRINGPREP_CHECK_BIDI_ERROR', 66562); +} +if (!defined('IDNA_DEFAULT')) { + define('IDNA_DEFAULT', 0); +} +if (!defined('IDNA_ALLOW_UNASSIGNED')) { + define('IDNA_ALLOW_UNASSIGNED', 1); +} +if (!defined('IDNA_USE_STD3_RULES')) { + define('IDNA_USE_STD3_RULES', 2); +} +if (!defined('IDNA_CHECK_BIDI')) { + define('IDNA_CHECK_BIDI', 4); +} +if (!defined('IDNA_CHECK_CONTEXTJ')) { + define('IDNA_CHECK_CONTEXTJ', 8); +} +if (!defined('IDNA_NONTRANSITIONAL_TO_ASCII')) { + define('IDNA_NONTRANSITIONAL_TO_ASCII', 16); +} +if (!defined('IDNA_NONTRANSITIONAL_TO_UNICODE')) { + define('IDNA_NONTRANSITIONAL_TO_UNICODE', 32); +} +if (!defined('INTL_IDNA_VARIANT_2003')) { + define('INTL_IDNA_VARIANT_2003', 0); +} +if (!defined('INTL_IDNA_VARIANT_UTS46')) { + define('INTL_IDNA_VARIANT_UTS46', 1); +} +if (!defined('IDNA_ERROR_EMPTY_LABEL')) { + define('IDNA_ERROR_EMPTY_LABEL', 1); +} +if (!defined('IDNA_ERROR_LABEL_TOO_LONG')) { + define('IDNA_ERROR_LABEL_TOO_LONG', 2); +} +if (!defined('IDNA_ERROR_DOMAIN_NAME_TOO_LONG')) { + define('IDNA_ERROR_DOMAIN_NAME_TOO_LONG', 4); +} +if (!defined('IDNA_ERROR_LEADING_HYPHEN')) { + define('IDNA_ERROR_LEADING_HYPHEN', 8); +} +if (!defined('IDNA_ERROR_TRAILING_HYPHEN')) { + define('IDNA_ERROR_TRAILING_HYPHEN', 16); +} +if (!defined('IDNA_ERROR_HYPHEN_3_4')) { + define('IDNA_ERROR_HYPHEN_3_4', 32); +} +if (!defined('IDNA_ERROR_LEADING_COMBINING_MARK')) { + define('IDNA_ERROR_LEADING_COMBINING_MARK', 64); +} +if (!defined('IDNA_ERROR_DISALLOWED')) { + define('IDNA_ERROR_DISALLOWED', 128); +} +if (!defined('IDNA_ERROR_PUNYCODE')) { + define('IDNA_ERROR_PUNYCODE', 256); +} +if (!defined('IDNA_ERROR_LABEL_HAS_DOT')) { + define('IDNA_ERROR_LABEL_HAS_DOT', 512); +} +if (!defined('IDNA_ERROR_INVALID_ACE_LABEL')) { + define('IDNA_ERROR_INVALID_ACE_LABEL', 1024); +} +if (!defined('IDNA_ERROR_BIDI')) { + define('IDNA_ERROR_BIDI', 2048); +} +if (!defined('IDNA_ERROR_CONTEXTJ')) { + define('IDNA_ERROR_CONTEXTJ', 4096); +} + +if (\PHP_VERSION_ID < 70400) { + if (!function_exists('idn_to_ascii')) { + function idn_to_ascii($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_2003, &$idna_info = null) { return p\Idn::idn_to_ascii($domain, $flags, $variant, $idna_info); } + } + if (!function_exists('idn_to_utf8')) { + function idn_to_utf8($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_2003, &$idna_info = null) { return p\Idn::idn_to_utf8($domain, $flags, $variant, $idna_info); } + } +} else { + if (!function_exists('idn_to_ascii')) { + function idn_to_ascii($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_UTS46, &$idna_info = null) { return p\Idn::idn_to_ascii($domain, $flags, $variant, $idna_info); } + } + if (!function_exists('idn_to_utf8')) { + function idn_to_utf8($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_UTS46, &$idna_info = null) { return p\Idn::idn_to_utf8($domain, $flags, $variant, $idna_info); } + } +} diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-php83/bootstrap.php b/compat-scanner/tests/symfony-polyfill/polyfill-php83/bootstrap.php new file mode 100644 index 00000000..95cf7830 --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-php83/bootstrap.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Php83 as p; + +if (\PHP_VERSION_ID >= 80300) { + return; +} + +if (!function_exists('json_validate')) { + function json_validate(string $json, int $depth = 512, int $flags = 0): bool { return p\Php83::json_validate($json, $depth, $flags); } +} + +if (!function_exists('stream_context_set_options')) { + function stream_context_set_options($context, array $options): bool { return stream_context_set_option($context, $options); } +} + +if (!function_exists('str_increment')) { + function str_increment(string $string): string { return p\Php83::str_increment($string); } +} + +if (!function_exists('str_decrement')) { + function str_decrement(string $string): string { return p\Php83::str_decrement($string); } +} + +if (\PHP_VERSION_ID < 80000) { + require __DIR__.'/bootstrap72.php'; +} + +if (extension_loaded('mbstring')) { + if (!function_exists('mb_str_pad')) { + function mb_str_pad(?string $string, ?int $length, ?string $pad_string = ' ', ?int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Php83::mb_str_pad((string) $string, (int) $length, (string) $pad_string, (int) $pad_type, $encoding); } + } +} + +if (\PHP_VERSION_ID >= 80100) { + return require __DIR__.'/bootstrap81.php'; +} + +if (!function_exists('ldap_exop_sync') && function_exists('ldap_exop')) { + function ldap_exop_sync($ldap, string $request_oid, ?string $request_data = null, ?array $controls = null, &$response_data = null, &$response_oid = null): bool { return ldap_exop($ldap, $request_oid, $request_data, $response_data, $response_oid); } +} + +if (!function_exists('ldap_connect_wallet') && function_exists('ldap_connect')) { + function ldap_connect_wallet(?string $uri, string $wallet, string $password, int $auth_mode = \GSLC_SSL_NO_AUTH) { return ldap_connect($uri, $wallet, $password, $auth_mode); } +} diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-php83/bootstrap81.php b/compat-scanner/tests/symfony-polyfill/polyfill-php83/bootstrap81.php new file mode 100644 index 00000000..4c258113 --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-php83/bootstrap81.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Php83 as p; + +if (\PHP_VERSION_ID >= 80300) { + return; +} + +if (!function_exists('json_validate')) { + function json_validate(string $json, int $depth = 512, int $flags = 0): bool { return p\Php83::json_validate($json, $depth, $flags); } +} + +if (!function_exists('str_increment')) { + function str_increment(string $string): string { return p\Php83::str_increment($string); } +} + +if (!function_exists('str_decrement')) { + function str_decrement(string $string): string { return p\Php83::str_decrement($string); } +} + +if (extension_loaded('mbstring') && !function_exists('mb_str_pad')) { + function mb_str_pad(?string $string, ?int $length, ?string $pad_string = ' ', ?int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Php83::mb_str_pad((string) $string, (int) $length, (string) $pad_string, (int) $pad_type, $encoding); } +} + +if (!function_exists('ldap_exop_sync') && function_exists('ldap_exop')) { + function ldap_exop_sync(\LDAP\Connection $ldap, string $request_oid, ?string $request_data = null, ?array $controls = null, &$response_data = null, &$response_oid = null): bool { return ldap_exop($ldap, $request_oid, $request_data, $response_data, $response_oid); } +} + +if (!function_exists('ldap_connect_wallet') && function_exists('ldap_connect')) { + function ldap_connect_wallet(?string $uri, string $wallet, #[\SensitiveParameter] string $password, int $auth_mode = \GSLC_SSL_NO_AUTH): \LDAP\Connection|false { return ldap_connect($uri, $wallet, $password, $auth_mode); } +} diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/Deprecated.php b/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/Deprecated.php new file mode 100644 index 00000000..f3e6a4f8 --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/Deprecated.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80400) { + #[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION | Attribute::TARGET_CLASS_CONSTANT)] + final class Deprecated + { + public readonly ?string $message; + public readonly ?string $since; + + public function __construct(?string $message = null, ?string $since = null) + { + $this->message = $message; + $this->since = $since; + } + } +} diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/RoundingMode.php b/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/RoundingMode.php new file mode 100644 index 00000000..a267309c --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/RoundingMode.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80400) { + enum RoundingMode + { + case HalfAwayFromZero; + case HalfTowardsZero; + case HalfEven; + case HalfOdd; + case TowardsZero; + case AwayFromZero; + case NegativeInfinity; + case PositiveInfinity; + } +} diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/Deprecated.php b/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/Deprecated.php new file mode 100644 index 00000000..cbc731ec --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/Deprecated.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80100) { + #[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION | Attribute::TARGET_CLASS_CONSTANT)] + final class Deprecated + { + /** + * @readonly + */ + public ?string $message; + + /** + * @readonly + */ + public ?string $since; + + public function __construct(?string $message = null, ?string $since = null) + { + $this->message = $message; + $this->since = $since; + } + } +} elseif (\PHP_VERSION_ID < 80400) { + require dirname(__DIR__).'/Deprecated.php'; +} diff --git a/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/RoundingMode.php b/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/RoundingMode.php new file mode 100644 index 00000000..b7f29f17 --- /dev/null +++ b/compat-scanner/tests/symfony-polyfill/polyfill-php84/Resources/stubs/RoundingMode.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80100) { + final class RoundingMode + { + const HalfAwayFromZero = 0; + const HalfTowardsZero = 1; + const HalfEven = 2; + const HalfOdd = 3; + const TowardsZero = 4; + const AwayFromZero = 5; + const NegativeInfinity = 6; + const PositiveInfinity = 7; + + private function __construct() + { + } + + public static function cases(): array + { + return [ + self::HalfAwayFromZero, + self::HalfTowardsZero, + self::HalfEven, + self::HalfOdd, + self::TowardsZero, + self::AwayFromZero, + self::NegativeInfinity, + self::PositiveInfinity, + ]; + } + } +} elseif (\PHP_VERSION_ID < 80400) { + require dirname(__DIR__).'/RoundingMode.php'; +} From b4b5e92428c0970cc0fc3619ed25d372a62344dd Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:37:08 +0530 Subject: [PATCH 65/80] fix(compat-scanner): let the doc root's .user.ini Off hold over a short-tag default A file was checked with short tags on whenever the default was on or any .user.ini on its way down turned them on. A doc root .user.ini that turns them off decides for every script there, though: with a pool `php_value short_open_tag On` and `short_open_tag = Off` in htdocs/.user.ini, PHP-FPM runs htdocs/list.php with short tags off, and the scanner called its `cfg['short_tags'] || $this->cfg['short_locked'] || ! $this->shortIni ) { + if ( $this->cfg['short_locked'] || ! $this->shortIni ) { return $this->cfg['short_tags']; } - $root = is_string( $this->cfg['served'] ) && '' !== $this->cfg['served'] ? $this->cfg['served'] : $this->cfg['path']; - $dir = dirname( $path ); - if ( $dir !== $root && 0 !== strpos( $dir, $root . '/' ) ) { - return $this->shortIni[ $root ] ?? false; + $root = is_string( $this->cfg['served'] ) && '' !== $this->cfg['served'] ? $this->cfg['served'] : $this->cfg['path']; + $dir = dirname( $path ); + $short = $this->shortIni[ $root ] ?? $this->cfg['short_tags']; + if ( $short || ( $dir !== $root && 0 !== strpos( $dir, $root . '/' ) ) ) { + return $short; } - for ( $at = $root; ; $at .= '/' . strtok( substr( $dir, strlen( $at ) + 1 ), '/' ) ) { + for ( $at = $root; $at !== $dir; ) { + $at .= '/' . strtok( substr( $dir, strlen( $at ) + 1 ), '/' ); if ( $this->shortIni[ $at ] ?? false ) { return true; } - if ( $at === $dir ) { - return false; - } } + return false; } /** Steps 2 to 4 for one file. */ diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index c484decc..468a4908 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1188,6 +1188,9 @@ function counts( string $name ): array { eq( finding_files( report( 'shortini' ) ), $want, 'shortini: short tags on where a .user.ini from the doc root down turns them on, and beside the doc root' ); $want = [ 'directory:sub::off/below.php', 'directory:sub::on.php' ]; eq( finding_files( report( 'shortdeep' ) ), $want, 'shortdeep: a .user.ini that turns short tags on reaches the dirs below it, not those above' ); +foreach ( [ 'shortrootoff', 'shortrootoff-on' ] as $name ) { + eq( finding_files( report( $name ) ), [ 'directory:sub::on.php' ], "$name: the doc root's .user.ini Off holds there over the default, a deeper On still counts" ); +} foreach ( [ 'shortiniwp-flat', 'shortiniwp-release' ] as $name ) { eq( finding_files( report( $name ) ), [ 'plugin:p::view.php' ], "$name: a WordPress root's .user.ini turns short tags on for its plugins" ); } diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 18d333a6..a7abccee 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1405,6 +1405,13 @@ if ( \\PHP_VERSION_ID >= 80500 ) { chmod -R a+rX "$1" chmod 0 "$v/acme/unreadsib/load.php" } +# short_open_tag off in the doc root's .user.ini, on again in sub/: the doc root's value holds for the scripts there, whatever the default. +shortrootoff_fixture() { + local h="$1/htdocs" f + mkdir -p "$h/sub" && printf 'short_open_tag = Off\n' > "$h/.user.ini" && printf 'short_open_tag = On\n' > "$h/sub/.user.ini" + for f in top.php sub/on.php; do printf '\n\n' > "$h/$f"; done + chmod -R a+rX "$1" +} # gatechain_fixture : package files loaded only from the next minors on through if/elseif chains (PHP 8.4 syntax in x.php, a PHP 8.2 class in b81.php), and loads that don't gate them. gatechain_fixture() { local v="$1/htdocs/vendor" d diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 84ff91ff..3a9280c5 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -509,6 +509,9 @@ scan shortini "$WORK/shortini" php /var/www/htdocs 8.0 600 scan shortini-locked "$WORK/shortini" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG_LOCKED=1 shortdeep_fixture "$WORK/shortdeep" scan shortdeep "$WORK/shortdeep" php /var/www/htdocs 8.0 600 +shortrootoff_fixture "$WORK/shortrootoff" +scan shortrootoff "$WORK/shortrootoff" php /var/www/htdocs 8.0 600 +scan shortrootoff-on "$WORK/shortrootoff" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 for v in flat release; do shortiniwp_fixture "$WORK/shortiniwp-$v" "$v"; done scan shortiniwp-flat "$WORK/shortiniwp-flat" wp /var/www/htdocs 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 scan shortiniwp-release "$WORK/shortiniwp-release" wp /var/www/htdocs/current 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 From 8a800ce9aafbf597e8921818568051a088b8d33b Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:45:54 +0530 Subject: [PATCH 66/80] fix(compat-scanner): keep the kind of a new interface finding The kind match for site-declared names read `NewInterfaces` as no kind, so a new interface finding lost its name and was never matched: symfony/polyfill-php82's Random\Engine\Secure, which implements the polyfill's own Random\CryptoSafeEngine, became an error at 8.0 and 8.1. The test site gets both stubs. --- compat-scanner/src/LinesReport.php | 2 +- compat-scanner/tests/fixture.sh | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/compat-scanner/src/LinesReport.php b/compat-scanner/src/LinesReport.php index 7b2154c0..25dd350e 100644 --- a/compat-scanner/src/LinesReport.php +++ b/compat-scanner/src/LinesReport.php @@ -54,7 +54,7 @@ public function generateFileReport( array $report, File $phpcsFile, bool $showSo $at = $at ?? $this->positions( $phpcsFile ); $ptr = $at[ "$line:$column" ] ?? null; // The message names a namespaced class in full; the source mangles its `\`. - if ( preg_match( '/\.New(Class|Interface)es\./', $message['source'], $kind ) ) { + if ( preg_match( '/\.New(Class|Interface)e?s\./', $message['source'], $kind ) ) { if ( preg_match( '/^The built-in (?:class|interface) \\\\?(\S+) is /', $message['message'], $c ) ) { $name = strtolower( $c[1] ); } diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index a7abccee..73319ea5 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1500,6 +1500,14 @@ if ( \PHP_VERSION_ID < 80200 ) { php_file "$h/vendor/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php" 'namespace Random; if ( \PHP_VERSION_ID < 80200 ) { class BrokenRandomEngineError extends RandomError {} +}' + php_file "$h/vendor/symfony/polyfill-php82/Resources/stubs/Random/CryptoSafeEngine.php" 'namespace Random; +if ( \PHP_VERSION_ID < 80200 ) { + interface CryptoSafeEngine {} +}' + php_file "$h/vendor/symfony/polyfill-php82/Resources/stubs/Random/Engine/Secure.php" 'namespace Random\Engine; +if ( \PHP_VERSION_ID < 80200 ) { + final class Secure implements \Random\CryptoSafeEngine {} }' php_file "$h/app/random.php" '$r = new \Random\Randomizer();' php_file "$h/app/use.php" '$e = new DateRangeError();' From 3f5c97d4badca7b0900bf599267b8fb1bb20f916 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 10:48:47 +0530 Subject: [PATCH 67/80] fix(compat-scanner): check every file with short tags on when any .user.ini turns them on A deeper .user.ini that turns short tags on counted only for the files below it. PHP-FPM applies the requested script's chain, though, and that script may include any file: with sub/.user.ini On, sub/up.php including ../top.php runs top.php's ` short_open_tag of the .user.ini files that set it, by their directory as walked. */ private $shortIni = []; - /** @var bool short_open_tag of the files PHPCS and the lint check now. */ + /** @var bool short_open_tag PHPCS and the lint check every file with. */ private $short = false; /** @var array The classes and interfaces the scanned files declare where that runs on the target, keyed as the PHPCS report names them. */ private $declared = []; @@ -1612,16 +1612,11 @@ private function timed( array $paths ): float { private function scan(): array { $atListing = $this->notCheckedCount; rewind( $this->listFh ); - $batch = []; - $read = 0; + $batch = []; + $read = 0; + $this->short = $this->shortTags(); while ( null !== ( $rec = $this->nextFile() ) ) { $read++; - $rec['short'] = $this->shortFor( $rec['path'] ); - // One short_open_tag per run. - if ( $batch && $batch[0]['short'] !== $rec['short'] ) { - $this->runBatch( $batch ); - $batch = []; - } $batch[] = $rec; if ( count( $batch ) >= $this->cfg['batch_size'] ) { $this->runBatch( $batch ); @@ -1698,7 +1693,6 @@ private function prepare( array $batch ): array { */ private function runBatch( array $batch ): void { $this->checkPins(); - $this->short = $batch[0]['short']; $batch = $this->prepare( $batch ); foreach ( $this->lint( $batch ) as $k => $result ) { $batch[ $k ]['lint'] = $result; @@ -1766,25 +1760,19 @@ private function runBatch( array $batch ): void { } /** - * short_open_tag for a file, unless the pool locks it: the doc root's value (its .user.ini, else the default), or on when a deeper .user.ini on the way to the file's directory turns it on. PHP-FPM applies the requested script's chain, and a script higher up may include the file; for a file outside the doc root, the doc root's value. + * short_open_tag for every file, unless the pool locks it: on when the doc root's value (its .user.ini, else the default) is on or any .user.ini below the doc root turns it on. PHP-FPM applies the requested script's chain, and that script may include any file of the site. */ - private function shortFor( string $path ): bool { - if ( $this->cfg['short_locked'] || ! $this->shortIni ) { + private function shortTags(): bool { + $root = is_string( $this->cfg['served'] ) && '' !== $this->cfg['served'] ? $this->cfg['served'] : $this->cfg['path']; + if ( $this->cfg['short_locked'] ) { return $this->cfg['short_tags']; } - $root = is_string( $this->cfg['served'] ) && '' !== $this->cfg['served'] ? $this->cfg['served'] : $this->cfg['path']; - $dir = dirname( $path ); - $short = $this->shortIni[ $root ] ?? $this->cfg['short_tags']; - if ( $short || ( $dir !== $root && 0 !== strpos( $dir, $root . '/' ) ) ) { - return $short; - } - for ( $at = $root; $at !== $dir; ) { - $at .= '/' . strtok( substr( $dir, strlen( $at ) + 1 ), '/' ); - if ( $this->shortIni[ $at ] ?? false ) { + foreach ( $this->shortIni as $dir => $on ) { + if ( $on && 0 === strpos( $dir . '/', $root . '/' ) && $dir !== $root ) { return true; } } - return false; + return $this->shortIni[ $root ] ?? $this->cfg['short_tags']; } /** Steps 2 to 4 for one file. */ diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 468a4908..77c1a4ea 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1186,10 +1186,11 @@ function counts( string $name ): array { eq( [ counts( 'shorttag-on' ), finding_files( report( 'shorttag-on' ) ) ], $want, 'shorttag-on: with short tags on, `= 80500 ) { chmod -R a+rX "$1" chmod 0 "$v/acme/unreadsib/load.php" } -# short_open_tag off in the doc root's .user.ini, on again in sub/: the doc root's value holds for the scripts there, whatever the default. +# short_open_tag off in the doc root's .user.ini (on /htdocs/sub/.user.ini too with a second argument): the doc root's value holds over the default. shortrootoff_fixture() { local h="$1/htdocs" f - mkdir -p "$h/sub" && printf 'short_open_tag = Off\n' > "$h/.user.ini" && printf 'short_open_tag = On\n' > "$h/sub/.user.ini" + mkdir -p "$h/sub" && printf 'short_open_tag = Off\n' > "$h/.user.ini" + if [ -n "${2:-}" ]; then printf 'short_open_tag = On\n' > "$h/sub/.user.ini"; fi for f in top.php sub/on.php; do printf '\n\n' > "$h/$f"; done chmod -R a+rX "$1" } @@ -1540,11 +1541,12 @@ shortini_fixture() { mkdir -p "$1/lib" && printf '\n\n' > "$1/lib/beside.php" chmod -R a+rX "$1" } -# short_open_tag off by default, on in sub/ and off again below it: PHP-FPM applies the entry script's chain, so sub/off/ may run with it on. +# short_open_tag off by default, on in sub/ and off again below it: PHP-FPM applies the requested script's chain, and sub/'s scripts may include files anywhere. shortdeep_fixture() { local h="$1/htdocs" f mkdir -p "$h/sub/off" && printf 'short_open_tag = On\n' > "$h/sub/.user.ini" && printf 'short_open_tag = Off\n' > "$h/sub/off/.user.ini" printf ' "$h/sub/index.php" + printf ' "$h/sub/up.php" for f in top.php sub/on.php sub/off/below.php; do printf '\n\n' > "$h/$f"; done chmod -R a+rX "$1" } diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 3a9280c5..f09b3c3f 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -510,8 +510,10 @@ scan shortini-locked "$WORK/shortini" php /var/www/htdocs 8.0 600 -e COMPAT_SHOR shortdeep_fixture "$WORK/shortdeep" scan shortdeep "$WORK/shortdeep" php /var/www/htdocs 8.0 600 shortrootoff_fixture "$WORK/shortrootoff" -scan shortrootoff "$WORK/shortrootoff" php /var/www/htdocs 8.0 600 scan shortrootoff-on "$WORK/shortrootoff" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 +shortrootoff_fixture "$WORK/shortrootsub" sub +scan shortrootsub "$WORK/shortrootsub" php /var/www/htdocs 8.0 600 +scan shortrootsub-on "$WORK/shortrootsub" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 for v in flat release; do shortiniwp_fixture "$WORK/shortiniwp-$v" "$v"; done scan shortiniwp-flat "$WORK/shortiniwp-flat" wp /var/www/htdocs 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 scan shortiniwp-release "$WORK/shortiniwp-release" wp /var/www/htdocs/current 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 From 38733e6fa002a6741ae0ef6cd9269535c88b15c9 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 11:17:27 +0530 Subject: [PATCH 68/80] fix(compat-scanner): read .user.ini directive names case-sensitively PHP ignores a .user.ini directive whose name isn't in its own case, so `Short_Open_Tag=Off` left a default On in place while the scanner read it as Off, and `AUTO_APPEND_FILE` named a file PHP never loads. Keys now match as PHP reads them; values stay case-insensitive. --- compat-scanner/bin/compat-scanner.php | 5 +++-- compat-scanner/tests/assert.php | 1 + compat-scanner/tests/fixture.sh | 9 ++++++++- compat-scanner/tests/run.sh | 2 ++ 4 files changed, 14 insertions(+), 3 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index a8ca85f3..7d7eaf91 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -358,8 +358,9 @@ private function userIni( string $path, string $real ): void { // As PHP's ini scanner reads it: a BOM first, a bare \r ends a line, `[section] key=` on one line. $line = 0 === $n ? (string) preg_replace( '/^\xEF\xBB\xBF/', '', $line ) : $line; foreach ( explode( "\r", $line ) as $part ) { - $value = preg_match( '/^\s*(?:\[[^\]]*\]\s*)*' . $keys . '\s*=(.*)$/i', $part, $m ) ? ini_value( $m[2] ) : ''; - $key = strtolower( $m[1] ?? '' ); + // Directive names are case-sensitive: PHP ignores a mis-cased one. + $value = preg_match( '/^\s*(?:\[[^\]]*\]\s*)*' . $keys . '\s*=(.*)$/', $part, $m ) ? ini_value( $m[2] ) : ''; + $key = $m[1] ?? ''; if ( 'short_open_tag' === $key ) { // PHP's boolean: on, yes or true, else the number (an unquoted Off reads as ''). $this->shortIni[ dirname( $path ) ] = in_array( strtolower( $value ), [ 'on', 'yes', 'true' ], true ) || 0 !== (int) $value; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 77c1a4ea..9b598cec 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1192,6 +1192,7 @@ function counts( string $name ): array { foreach ( [ 'shortrootsub', 'shortrootsub-on' ] as $name ) { eq( finding_files( report( $name ) ), [ 'directory:sub::on.php', 'other:::top.php' ], "$name: a deeper On counts over the doc root's Off" ); } +eq( [ finding_files( report( 'shortcase-on' ) ), report( 'shortcase-on' )['not_checked'] ?? null ], [ [ 'other:::top.php' ], [] ], 'shortcase-on: PHP ignores a mis-cased .user.ini key, so the default On holds and nothing is prepended' ); foreach ( [ 'shortiniwp-flat', 'shortiniwp-release' ] as $name ) { eq( finding_files( report( $name ) ), [ 'plugin:p::view.php' ], "$name: a WordPress root's .user.ini turns short tags on for its plugins" ); } diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 1631c19d..652b2ec8 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -936,7 +936,7 @@ require_fixture() { printf ' "$h/wp-cli.phar" printf 'auto_prepend_file = "/var/www/htdocs/wordfence-waf.php" ; Wordfence\nauto_append_file = none\n' > "$h/.user.ini" mkdir -p "$h/wp-content/uploads" - printf "auto_prepend_file='waf.php'\nAUTO_APPEND_FILE = /opt/append.php\n" > "$h/wp-content/uploads/.user.ini" + printf "auto_prepend_file='waf.php'\nauto_append_file = /opt/append.php\n" > "$h/wp-content/uploads/.user.ini" chmod -R a+rX "$1" } @@ -1413,6 +1413,13 @@ shortrootoff_fixture() { for f in top.php sub/on.php; do printf '\n\n' > "$h/$f"; done chmod -R a+rX "$1" } +# Mis-cased keys in the doc root's .user.ini, which PHP ignores: the default holds and nothing is prepended. +shortcase_fixture() { + local h="$1/htdocs" + mkdir -p "$h" && printf 'Short_Open_Tag = Off\nAuto_Prepend_File = /var/www/none.php\n' > "$h/.user.ini" + printf '\n\n' > "$h/top.php" + chmod -R a+rX "$1" +} # gatechain_fixture : package files loaded only from the next minors on through if/elseif chains (PHP 8.4 syntax in x.php, a PHP 8.2 class in b81.php), and loads that don't gate them. gatechain_fixture() { local v="$1/htdocs/vendor" d diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index f09b3c3f..59a04e10 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -514,6 +514,8 @@ scan shortrootoff-on "$WORK/shortrootoff" php /var/www/htdocs 8.0 600 -e COMPAT_ shortrootoff_fixture "$WORK/shortrootsub" sub scan shortrootsub "$WORK/shortrootsub" php /var/www/htdocs 8.0 600 scan shortrootsub-on "$WORK/shortrootsub" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 +shortcase_fixture "$WORK/shortcase" +scan shortcase-on "$WORK/shortcase" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 for v in flat release; do shortiniwp_fixture "$WORK/shortiniwp-$v" "$v"; done scan shortiniwp-flat "$WORK/shortiniwp-flat" wp /var/www/htdocs 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 scan shortiniwp-release "$WORK/shortiniwp-release" wp /var/www/htdocs/current 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 From b323539ddab2caf925d838dfae96d74a3f6cb85f Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 11:19:31 +0530 Subject: [PATCH 69/80] fix(compat-scanner): match .user.ini directories to the doc root by real path A .user.ini short_open_tag value was keyed by the directory as walked and compared with the doc root as spelled, so a linked doc root lost its .user.ini when the walk met the link's target first. The doc root's own value is now matched by real path, an On counts below the doc root by either name, and directories linked in below the doc root count as below it, since PHP-FPM builds the .user.ini chain from the request path. --- compat-scanner/bin/compat-scanner.php | 40 ++++++++++++++++++++++----- compat-scanner/tests/assert.php | 8 ++++++ compat-scanner/tests/fixture.sh | 26 +++++++++++++++++ compat-scanner/tests/run.sh | 10 +++++++ 4 files changed, 77 insertions(+), 7 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 7d7eaf91..09bd9538 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -161,8 +161,10 @@ final class Scanner { private $skippedDirs = []; /** @var string A PHP open tag, as a regex. */ private $openTag; - /** @var array short_open_tag of the .user.ini files that set it, by their directory as walked. */ + /** @var array short_open_tag of the .user.ini files that set it, by the real path of their directory and the path as walked. */ private $shortIni = []; + /** @var array Real targets of the links to directories met, by the link's real directory and name. */ + private $dirLinks = []; /** @var bool short_open_tag PHPCS and the lint check every file with. */ private $short = false; /** @var array The classes and interfaces the scanned files declare where that runs on the target, keyed as the PHPCS report names them. */ @@ -362,8 +364,12 @@ private function userIni( string $path, string $real ): void { $value = preg_match( '/^\s*(?:\[[^\]]*\]\s*)*' . $keys . '\s*=(.*)$/', $part, $m ) ? ini_value( $m[2] ) : ''; $key = $m[1] ?? ''; if ( 'short_open_tag' === $key ) { + $dir = (string) $this->resolve( dirname( $path ) ); // PHP's boolean: on, yes or true, else the number (an unquoted Off reads as ''). - $this->shortIni[ dirname( $path ) ] = in_array( strtolower( $value ), [ 'on', 'yes', 'true' ], true ) || 0 !== (int) $value; + $on = in_array( strtolower( $value ), [ 'on', 'yes', 'true' ], true ) || 0 !== (int) $value; + // The doc root's own value is matched by real path, an On below it by either name. + $this->shortIni[ $dir ] = $on; + $this->shortIni[ dirname( $path ) ] = $on; continue; } if ( '' === $value || ( 'zend.multibyte' === $key && '0' === $value ) ) { @@ -906,6 +912,9 @@ private function visit( string $path, string $name, int $comp ): void { } if ( is_dir( $real ) ) { + if ( is_link( $path ) ) { + $this->dirLinks[ $this->resolve( dirname( $path ) ) . '/' . $name ] = $real; + } if ( $this->markDir( $real ) ) { $this->walk( $path, $comp ); } @@ -1761,19 +1770,36 @@ private function runBatch( array $batch ): void { } /** - * short_open_tag for every file, unless the pool locks it: on when the doc root's value (its .user.ini, else the default) is on or any .user.ini below the doc root turns it on. PHP-FPM applies the requested script's chain, and that script may include any file of the site. + * short_open_tag for every file, unless the pool locks it: on when the doc root's value (its .user.ini, else the default) is on or any .user.ini below the doc root, by either name or through a link in it, turns it on. PHP-FPM applies the requested script's chain, and that script may include any file of the site. */ private function shortTags(): bool { $root = is_string( $this->cfg['served'] ) && '' !== $this->cfg['served'] ? $this->cfg['served'] : $this->cfg['path']; if ( $this->cfg['short_locked'] ) { return $this->cfg['short_tags']; } - foreach ( $this->shortIni as $dir => $on ) { - if ( $on && 0 === strpos( $dir . '/', $root . '/' ) && $dir !== $root ) { - return true; + $real = $this->pins[ $root ] ?: $root; + $on = array_keys( $this->shortIni, true, true ); + foreach ( $on ? array_merge( [ $root ], $this->rootTops( $real ) ) : [] as $top ) { + foreach ( $on as $dir ) { + if ( 0 === strpos( $dir . '/', $top . '/' ) ) { + return true; + } + } + } + return $this->shortIni[ $real ] ?? $this->cfg['short_tags']; + } + + /** The real doc root and the real targets of the links to directories below it, through which PHP spells request paths too. */ + private function rootTops( string $root ): array { + $tops = [ $root ]; + for ( $i = 0; $i < count( $tops ); $i++ ) { + foreach ( $this->dirLinks as $link => $target ) { + if ( 0 === strpos( $link, $tops[ $i ] . '/' ) && ! in_array( $target, $tops, true ) ) { + $tops[] = $target; + } } } - return $this->shortIni[ $root ] ?? $this->cfg['short_tags']; + return $tops; } /** Steps 2 to 4 for one file. */ diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 9b598cec..5669d47d 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1193,6 +1193,14 @@ function counts( string $name ): array { eq( finding_files( report( $name ) ), [ 'directory:sub::on.php', 'other:::top.php' ], "$name: a deeper On counts over the doc root's Off" ); } eq( [ finding_files( report( 'shortcase-on' ) ), report( 'shortcase-on' )['not_checked'] ?? null ], [ [ 'other:::top.php' ], [] ], 'shortcase-on: PHP ignores a mis-cased .user.ini key, so the default On holds and nothing is prepended' ); +foreach ( [ 'app' => 'directory:app::public/view.php', 'zz' => 'directory:public::view.php' ] as $d => $file ) { + eq( finding_files( report( "shortlink-$d" ) ), [ $file ], "shortlink-$d: the On of a linked doc root's .user.ini counts whichever name the walk reaches first" ); +} +foreach ( [ 'app' => 'directory:app::view.php', 'zz' => 'directory:public::shared/view.php' ] as $d => $file ) { + eq( finding_files( report( "shortshared-$d" ) ), [ $file ], "shortshared-$d: a .user.ini On in a directory linked in below the doc root counts" ); +} +eq( finding_files( report( 'shortwplink' ) ), [ 'plugin:p::view.php' ], 'shortwplink: a .user.ini On in a plugin linked in from outside the doc root counts' ); +eq( finding_files( report( 'shortlinkoff-on' ) ), [], "shortlinkoff-on: a linked doc root's .user.ini Off holds over the default" ); foreach ( [ 'shortiniwp-flat', 'shortiniwp-release' ] as $name ) { eq( finding_files( report( $name ) ), [ 'plugin:p::view.php' ], "$name: a WordPress root's .user.ini turns short tags on for its plugins" ); } diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 652b2ec8..1cff1a3e 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1420,6 +1420,32 @@ shortcase_fixture() { printf '\n\n' > "$h/top.php" chmod -R a+rX "$1" } +# shortlink_fixture : the doc root htdocs/public links to /public, whose .user.ini sets short_open_tag; the walk may reach either name first. +shortlink_fixture() { + local h="$1/htdocs" + mkdir -p "$h/$2/public" && ln -s "$2/public" "$h/public" + printf 'short_open_tag = %s\n' "$3" > "$h/$2/public/.user.ini" + printf '\n\n' > "$h/$2/public/view.php" + chmod -R a+rX "$1" +} +# WordPress whose plugin p links to /var/www/shared/p, outside htdocs, where a .user.ini turns short tags on. +shortwplink_fixture() { + local h="$1/htdocs" + wp_core "$h" 6.8.3 + mkdir -p "$1/shared/p" "$h/wp-content/plugins" && ln -s ../../../shared/p "$h/wp-content/plugins/p" + printf 'short_open_tag = On\n' > "$1/shared/p/.user.ini" + php_file "$1/shared/p/p.php" '/* Plugin Name: P */' + printf '\n\n' > "$1/shared/p/view.php" + chmod -R a+rX "$1" +} +# shortshared_fixture : htdocs/public/shared links to htdocs/, whose .user.ini turns short tags on for scripts requested through the link. +shortshared_fixture() { + local h="$1/htdocs" + mkdir -p "$h/public" "$h/$2" && ln -s "../$2" "$h/public/shared" + printf 'short_open_tag = On\n' > "$h/$2/.user.ini" + printf '\n\n' > "$h/$2/view.php" + chmod -R a+rX "$1" +} # gatechain_fixture : package files loaded only from the next minors on through if/elseif chains (PHP 8.4 syntax in x.php, a PHP 8.2 class in b81.php), and loads that don't gate them. gatechain_fixture() { local v="$1/htdocs/vendor" d diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 59a04e10..77074e0d 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -516,6 +516,16 @@ scan shortrootsub "$WORK/shortrootsub" php /var/www/htdocs 8.0 600 scan shortrootsub-on "$WORK/shortrootsub" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 shortcase_fixture "$WORK/shortcase" scan shortcase-on "$WORK/shortcase" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 +for d in app zz; do + shortlink_fixture "$WORK/shortlink-$d" "$d" On + scan "shortlink-$d" "$WORK/shortlink-$d" php /var/www/htdocs 8.0 600 -e COMPAT_SERVED=/var/www/htdocs/public + shortshared_fixture "$WORK/shortshared-$d" "$d" + scan "shortshared-$d" "$WORK/shortshared-$d" php /var/www/htdocs 8.0 600 -e COMPAT_SERVED=/var/www/htdocs/public +done +shortlink_fixture "$WORK/shortlinkoff" app Off +shortwplink_fixture "$WORK/shortwplink" +scan shortwplink "$WORK/shortwplink" wp /var/www/htdocs 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 +scan shortlinkoff-on "$WORK/shortlinkoff" php /var/www/htdocs 8.0 600 -e COMPAT_SERVED=/var/www/htdocs/public -e COMPAT_SHORT_OPEN_TAG=1 for v in flat release; do shortiniwp_fixture "$WORK/shortiniwp-$v" "$v"; done scan shortiniwp-flat "$WORK/shortiniwp-flat" wp /var/www/htdocs 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 scan shortiniwp-release "$WORK/shortiniwp-release" wp /var/www/htdocs/current 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 From 3e9976fb1d1c31944d97d2a1b04fd56186c9f5e6 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 11:21:35 +0530 Subject: [PATCH 70/80] fix(compat-scanner): ignore the scan path's .user.ini Off when the doc root is unknown With COMPAT_SERVED empty the real doc root may lie below the scan path, where the scan path's .user.ini doesn't apply, so its Off no longer holds over COMPAT_SHORT_OPEN_TAG=1. An On anywhere below still counts, and an absent COMPAT_SERVED keeps the scan path as the doc root. --- compat-scanner/bin/compat-scanner.php | 6 +++++- compat-scanner/tests/assert.php | 1 + compat-scanner/tests/run.sh | 1 + 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 09bd9538..a724eabf 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -1770,7 +1770,7 @@ private function runBatch( array $batch ): void { } /** - * short_open_tag for every file, unless the pool locks it: on when the doc root's value (its .user.ini, else the default) is on or any .user.ini below the doc root, by either name or through a link in it, turns it on. PHP-FPM applies the requested script's chain, and that script may include any file of the site. + * short_open_tag for every file, unless the pool locks it: on when the doc root's value (its .user.ini, else the default; only the default when COMPAT_SERVED is empty) is on or any .user.ini below the doc root, by either name or through a link in it, turns it on. PHP-FPM applies the requested script's chain, and that script may include any file of the site. */ private function shortTags(): bool { $root = is_string( $this->cfg['served'] ) && '' !== $this->cfg['served'] ? $this->cfg['served'] : $this->cfg['path']; @@ -1786,6 +1786,10 @@ private function shortTags(): bool { } } } + // COMPAT_SERVED empty: the real doc root may lie deeper, where the scan path's Off doesn't apply. + if ( '' === $this->cfg['served'] ) { + return $this->cfg['short_tags']; + } return $this->shortIni[ $real ] ?? $this->cfg['short_tags']; } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 5669d47d..2c60e9a8 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1189,6 +1189,7 @@ function counts( string $name ): array { $want = [ 'directory:sub::off/below.php', 'directory:sub::on.php', 'other:::top.php' ]; eq( finding_files( report( 'shortdeep' ) ), $want, 'shortdeep: a .user.ini that turns short tags on anywhere below the doc root counts for every file' ); eq( finding_files( report( 'shortrootoff-on' ) ), [], "shortrootoff-on: the doc root's .user.ini Off holds over the default" ); +eq( finding_files( report( 'shortrootoff-unsure' ) ), [ 'directory:sub::on.php', 'other:::top.php' ], "shortrootoff-unsure: with COMPAT_SERVED empty the doc root may lie deeper, so the scan path's Off doesn't hold over the default" ); foreach ( [ 'shortrootsub', 'shortrootsub-on' ] as $name ) { eq( finding_files( report( $name ) ), [ 'directory:sub::on.php', 'other:::top.php' ], "$name: a deeper On counts over the doc root's Off" ); } diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 77074e0d..1e9c19c2 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -511,6 +511,7 @@ shortdeep_fixture "$WORK/shortdeep" scan shortdeep "$WORK/shortdeep" php /var/www/htdocs 8.0 600 shortrootoff_fixture "$WORK/shortrootoff" scan shortrootoff-on "$WORK/shortrootoff" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 +scan shortrootoff-unsure "$WORK/shortrootoff" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 -e COMPAT_SERVED= shortrootoff_fixture "$WORK/shortrootsub" sub scan shortrootsub "$WORK/shortrootsub" php /var/www/htdocs 8.0 600 scan shortrootsub-on "$WORK/shortrootsub" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 From caabc54471843d3b26a61faf791fbec7aee39d29 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 11:25:04 +0530 Subject: [PATCH 71/80] fix(compat-scanner): check package files Composer's autoloader loads A file named in vendor/composer/autoload_files.php is loaded on every PHP version, so it is never left out as loaded only above the target, even when a version-gated require in its package names it too. --- compat-scanner/bin/compat-scanner.php | 41 +++++++++++++++++++++++++-- compat-scanner/tests/assert.php | 3 ++ compat-scanner/tests/fixture.sh | 10 +++++++ 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index a724eabf..21630615 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -169,6 +169,8 @@ final class Scanner { private $short = false; /** @var array The classes and interfaces the scanned files declare where that runs on the target, keyed as the PHPCS report names them. */ private $declared = []; + /** @var array autoloadList() of each vendor dir met, by path. */ + private $autoloadFiles = []; /** @var array loadsIn() of each directory read, by path. */ private $loads = []; /** @var string What sniff() matches in a file's first SNIFF_BYTES, as one regex (no NUL anywhere, then an open tag), for the manifest. */ @@ -1335,18 +1337,51 @@ private function packageTemplate( string $path ): bool { return preg_match( '#/vendor/[^/]+/[^/]+/(?:[^/]+/)*(?:stubs|templates)/(?:[^/]+/)*[^/]+\.(?:stub|tpl)\z#i', $path ) && $this->inPackage( $path ); } - /** Whether the path lies in vendor/// of a Composer vendor dir (one holding composer/installed.json or autoload.php). */ + /** Whether the path lies in vendor/// of a Composer vendor dir. */ private function inPackage( string $path ): bool { + return [] !== $this->vendorDirs( $path ); + } + + /** @return string[] The Composer vendor dirs (holding composer/installed.json or autoload.php) whose vendor/// the path lies in. */ + private function vendorDirs( string $path ): array { preg_match_all( '#/vendor/[^/]+/[^/]+/#', $path, $m, PREG_OFFSET_CAPTURE ); + $dirs = []; foreach ( $m[0] as list( , $at ) ) { $vendor = substr( $path, 0, $at ) . '/vendor'; if ( is_file( $vendor . '/composer/installed.json' ) || is_file( $vendor . '/autoload.php' ) ) { + $dirs[] = $vendor; + } + } + return $dirs; + } + + /** Whether a Composer autoload_files.php names the file, so the autoloader loads it on every version. */ + private function autoloaded( string $path ): bool { + foreach ( $this->vendorDirs( $path ) as $vendor ) { + if ( ! array_key_exists( $vendor, $this->autoloadFiles ) ) { + $this->autoloadFiles[ $vendor ] = $this->autoloadList( $vendor . '/composer/autoload_files.php' ); + } + if ( isset( $this->autoloadFiles[ $vendor ][ substr( $path, strlen( $vendor ) ) ] ) ) { return true; } } return false; } + /** + * @return array The strings of an autoload_files.php (`'/org/package/file.php'` after `$vendorDir .`); none for + * an unreadable one, which the walk already reports as unreadable. + */ + private function autoloadList( string $list ): array { + $names = []; + foreach ( code_tokens( $list ) ?? [] as list( $id, $text ) ) { + if ( T_CONSTANT_ENCAPSED_STRING === $id ) { + $names[ substr( $text, 1, -1 ) ] = true; + } + } + return $names; + } + /** `.phar` and the archive forms PHP's phar extension also opens (`.phar.tar`, `.phar.tar.gz`, `.phar.zip`, ...). */ private function isPharName( string $name ): bool { return (bool) preg_match( PHAR_REGEX, $name ); @@ -2480,8 +2515,8 @@ private function lint( array $batch ): array { * Whether its Composer package loads a file only above the target, as Symfony's polyfills load bootstrap85.php or Resources/Deprecated.php: every string naming it in the code files of its directory and their direct subdirectories is a gated load (gatedLoad()), and there is one. */ private function loadedOnlyAbove( string $real, string $path ): bool { - // App code may load it from anywhere; a package is loaded through its own files. - if ( ! $this->inPackage( $path ) ) { + // App code may load it from anywhere; a package is loaded through its own files, unless the autoloader loads it. + if ( ! $this->inPackage( $path ) || $this->autoloaded( $path ) ) { return false; } $dir = dirname( $real ); diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 2c60e9a8..b8c89cbc 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1077,6 +1077,7 @@ function counts( string $name ): array { $names = 'PHPCompatibility.Namespaces.ReservedNames.'; $always = [ "acme/always/bootstrap85.php:$parse", + "acme/autoloaded/bootstrap85.php:$parse", "acme/bigsib/bootstrap85.php:$parse", "acme/gatetxt/broken.php:$parse", "acme/quoted/bootstrap85.php:$parse", @@ -1088,6 +1089,7 @@ function counts( string $name ): array { // A gate 8.4.1 passes loads it on 8.4; a sibling too big or unreadable to check may load it too. '8.2' => [ "acme/always/bootstrap85.php:$parse", + "acme/autoloaded/bootstrap85.php:$parse", "acme/bigsib/bootstrap85.php:$parse", "acme/gatetxt/broken.php:$parse", "acme/quoted/bootstrap85.php:$parse", @@ -1096,6 +1098,7 @@ function counts( string $name ): array { ], '8.4' => [ "acme/always/bootstrap85.php:$parse", + "acme/autoloaded/bootstrap85.php:$parse", "acme/bigsib/bootstrap85.php:$parse", "acme/from84/bootstrap85.php:$parse", "acme/gate841/bootstrap85.php:$parse", diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 1cff1a3e..b3d02621 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1397,6 +1397,16 @@ if ( \\PHP_VERSION_ID >= 80500 ) { done { printf ' "$v/acme/bigsib/load.php" php_file "$v/acme/unreadsib/load.php" "require __DIR__ . '/bootstrap85.php';" + # A gated file Composer's autoloader also loads, as its files list names it. + mkdir -p "$v/acme/autoloaded" && cp "$HERE/symfony-polyfill/polyfill-uuid/bootstrap85.php" "$v/acme/autoloaded/" + php_file "$v/acme/autoloaded/bootstrap.php" "if ( \\PHP_VERSION_ID >= 80500 ) { + require __DIR__ . '/bootstrap85.php'; +}" + php_file "$v/composer/autoload_files.php" "\$vendorDir = dirname(__DIR__); +return array( + 'a1' => \$vendorDir . '/acme/autoloaded/bootstrap.php', + 'a2' => \$vendorDir . '/acme/autoloaded/bootstrap85.php', +);" # A gate naming a file that isn't code. php_file "$v/acme/gatetxt/bootstrap.php" "if ( \\PHP_VERSION_ID >= 80500 ) { require __DIR__ . '/notes.txt'; From 17e5cc1c82419665df98723363ea78a84f383d26 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 11:27:32 +0530 Subject: [PATCH 72/80] fix(compat-scanner): apply a linked .user.ini to every directory that names it A .user.ini is read once per file, so a link to another directory's .user.ini lost its short_open_tag in the directory where the walk met it second. PHP reads the linked file as that directory's own, so its value now counts there too. --- compat-scanner/bin/compat-scanner.php | 19 +++++++++++++------ compat-scanner/tests/assert.php | 2 ++ compat-scanner/tests/fixture.sh | 8 ++++++++ compat-scanner/tests/run.sh | 4 ++++ 4 files changed, 27 insertions(+), 6 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 21630615..49f311d9 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -128,7 +128,7 @@ final class Scanner { private $seenDirs = []; /** @var array> Listed files by device and inode. */ private $seenFiles = []; - /** @var array> .user.ini files read, by device and inode: another name of one may be code. */ + /** @var array> Real directory of the .user.ini files read, by device and inode: another name of one may be code. */ private $seenInis = []; /** @var array Real paths of the site path and content root when listed. */ private $pins = []; @@ -335,11 +335,19 @@ private function iniIn( string $dir ): void { /** userIni() once per file, whichever route reaches it. */ private function userIniOnce( string $path, string $real ): void { $st = @stat( $real ); - if ( false === $st || isset( $this->seenInis[ $st['dev'] ][ $st['ino'] ] ) ) { + if ( false === $st ) { return; } - $this->seenInis[ $st['dev'] ][ $st['ino'] ] = true; - $this->userIni( $path, $real ); + $dir = (string) $this->resolve( dirname( $path ) ); + $first = $this->seenInis[ $st['dev'] ][ $st['ino'] ] ?? null; + if ( null === $first ) { + $this->seenInis[ $st['dev'] ][ $st['ino'] ] = $dir; + $this->userIni( $path, $real, $dir ); + } elseif ( isset( $this->shortIni[ $first ] ) ) { + // PHP reads a linked .user.ini as this directory's own. + $this->shortIni[ $dir ] = $this->shortIni[ $first ]; + $this->shortIni[ dirname( $path ) ] = $this->shortIni[ $first ]; + } } /** @@ -347,7 +355,7 @@ private function userIniOnce( string $path, string $real ): void { * zend.script_encoding (PHP then reads the code in another encoding than PHPCS), makes the file itself an unreadable * entry, as EE does for its ini files. */ - private function userIni( string $path, string $real ): void { + private function userIni( string $path, string $real, string $dir ): void { $fh = open_regular( $real ); if ( null === $fh ) { return; @@ -366,7 +374,6 @@ private function userIni( string $path, string $real ): void { $value = preg_match( '/^\s*(?:\[[^\]]*\]\s*)*' . $keys . '\s*=(.*)$/', $part, $m ) ? ini_value( $m[2] ) : ''; $key = $m[1] ?? ''; if ( 'short_open_tag' === $key ) { - $dir = (string) $this->resolve( dirname( $path ) ); // PHP's boolean: on, yes or true, else the number (an unquoted Off reads as ''). $on = in_array( strtolower( $value ), [ 'on', 'yes', 'true' ], true ) || 0 !== (int) $value; // The doc root's own value is matched by real path, an On below it by either name. diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index b8c89cbc..73a161e8 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1205,6 +1205,8 @@ function counts( string $name ): array { } eq( finding_files( report( 'shortwplink' ) ), [ 'plugin:p::view.php' ], 'shortwplink: a .user.ini On in a plugin linked in from outside the doc root counts' ); eq( finding_files( report( 'shortlinkoff-on' ) ), [], "shortlinkoff-on: a linked doc root's .user.ini Off holds over the default" ); +eq( finding_files( report( 'shortinilink' ) ), [ 'directory:public::view.php' ], "shortinilink: a .user.ini linked into the doc root counts there, whichever name the walk reads first" ); +eq( finding_files( report( 'shortinilinkoff-on' ) ), [], "shortinilinkoff-on: a .user.ini Off linked into the doc root holds over the default there" ); foreach ( [ 'shortiniwp-flat', 'shortiniwp-release' ] as $name ) { eq( finding_files( report( $name ) ), [ 'plugin:p::view.php' ], "$name: a WordPress root's .user.ini turns short tags on for its plugins" ); } diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index b3d02621..f9a72b02 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1456,6 +1456,14 @@ shortshared_fixture() { printf '\n\n' > "$h/$2/view.php" chmod -R a+rX "$1" } +# shortinilink_fixture : the doc root htdocs/public's .user.ini links to htdocs/app/.user.ini, which sets short_open_tag and which the walk reads first. +shortinilink_fixture() { + local h="$1/htdocs" + mkdir -p "$h/app" "$h/public" && printf 'short_open_tag = %s\n' "$2" > "$h/app/.user.ini" + ln -s ../app/.user.ini "$h/public/.user.ini" + printf '\n\n' > "$h/public/view.php" + chmod -R a+rX "$1" +} # gatechain_fixture : package files loaded only from the next minors on through if/elseif chains (PHP 8.4 syntax in x.php, a PHP 8.2 class in b81.php), and loads that don't gate them. gatechain_fixture() { local v="$1/htdocs/vendor" d diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 1e9c19c2..d13b42ee 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -527,6 +527,10 @@ shortlink_fixture "$WORK/shortlinkoff" app Off shortwplink_fixture "$WORK/shortwplink" scan shortwplink "$WORK/shortwplink" wp /var/www/htdocs 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 scan shortlinkoff-on "$WORK/shortlinkoff" php /var/www/htdocs 8.0 600 -e COMPAT_SERVED=/var/www/htdocs/public -e COMPAT_SHORT_OPEN_TAG=1 +shortinilink_fixture "$WORK/shortinilink" On +scan shortinilink "$WORK/shortinilink" php /var/www/htdocs 8.0 600 -e COMPAT_SERVED=/var/www/htdocs/public +shortinilink_fixture "$WORK/shortinilinkoff" Off +scan shortinilinkoff-on "$WORK/shortinilinkoff" php /var/www/htdocs 8.0 600 -e COMPAT_SERVED=/var/www/htdocs/public -e COMPAT_SHORT_OPEN_TAG=1 for v in flat release; do shortiniwp_fixture "$WORK/shortiniwp-$v" "$v"; done scan shortiniwp-flat "$WORK/shortiniwp-flat" wp /var/www/htdocs 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 scan shortiniwp-release "$WORK/shortiniwp-release" wp /var/www/htdocs/current 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 From 40219f3fd422eee75fa77158a91f4917f1b6104a Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 11:29:39 +0530 Subject: [PATCH 73/80] fix(compat-scanner): flag a .user.ini include_path into a left-out old release When old releases are left out, an include_path entry holding `${`, or an absolute entry whose real path is in an old release (through `previous`, say), lets PHP load code the scan skipped. Such a .user.ini is now an unreadable entry, as zend.multibyte is. Relative entries aren't judged. --- compat-scanner/bin/compat-scanner.php | 39 +++++++++++++++++++++------ compat-scanner/tests/assert.php | 5 ++++ compat-scanner/tests/fixture.sh | 11 ++++++++ compat-scanner/tests/run.sh | 6 +++++ 4 files changed, 53 insertions(+), 8 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 49f311d9..572eb379 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -351,16 +351,16 @@ private function userIniOnce( string $path, string $real ): void { } /** - * Collects a .user.ini's auto_prepend_file and auto_append_file values. A line too long to read, or zend.multibyte or - * zend.script_encoding (PHP then reads the code in another encoding than PHPCS), makes the file itself an unreadable - * entry, as EE does for its ini files. + * Collects a .user.ini's auto_prepend_file and auto_append_file values. A line too long to read, zend.multibyte or + * zend.script_encoding (PHP then reads the code in another encoding than PHPCS), or an include_path into a left-out + * old release makes the file itself an unreadable entry, as EE does for its ini files. */ private function userIni( string $path, string $real, string $dir ): void { $fh = open_regular( $real ); if ( null === $fh ) { return; } - $keys = '(auto_(?:prepend|append)_file|zend\.multibyte|zend\.script_encoding|short_open_tag)'; + $keys = '(auto_(?:prepend|append)_file|zend\.multibyte|zend\.script_encoding|short_open_tag|include_path)'; $unsure = false; foreach ( lines( $fh, $this->ticker() ) as $n => $line ) { if ( null === $line ) { @@ -381,6 +381,10 @@ private function userIni( string $path, string $real, string $dir ): void { $this->shortIni[ dirname( $path ) ] = $on; continue; } + if ( 'include_path' === $key ) { + $unsure = $unsure || $this->reachesOld( $value ); + continue; + } if ( '' === $value || ( 'zend.multibyte' === $key && '0' === $value ) ) { continue; } @@ -397,6 +401,17 @@ private function userIni( string $path, string $real, string $dir ): void { } } + /** Whether an include_path may lead PHP into a left-out old release: an absolute entry into one, or a `${` PHP fills in from the environment. */ + private function reachesOld( string $includePath ): bool { + foreach ( $this->oldReleases ? explode( ':', $includePath ) : [] as $entry ) { + $real = '/' === substr( $entry, 0, 1 ) ? $this->resolve( $entry ) : null; + if ( false !== strpos( $entry, '${' ) || ( null !== $real && $this->inOldRelease( $real ) ) ) { + return true; + } + } + return false; + } + /** * What nginx serves, which decides whether old releases are left out: COMPAT_SERVED; a v3.11.1 call has none, and * then php sites use the scan path and WordPress sites leave nothing out. '' leaves nothing out. @@ -1224,10 +1239,8 @@ private function outOfScope( string $real ): bool { * ancestor, walked anyway), 'core' (the live root's core) or 'nested' (another install's core); null when in scope. */ private function scopeWhy( string $real ): ?string { - foreach ( $this->oldReleases as $old ) { - if ( 0 === strpos( $real . '/', $old . '/' ) ) { - return 'old'; - } + if ( $this->inOldRelease( $real ) ) { + return 'old'; } foreach ( [ $this->contentReal, $this->rootReal ] as $anchor ) { if ( null !== $anchor && 0 === strpos( $anchor . '/', $real . '/' ) ) { @@ -1241,6 +1254,16 @@ private function scopeWhy( string $real ): ?string { return $install === $this->live ? 'core' : 'nested'; } + /** Whether a real path is a left-out old release or inside one. */ + private function inOldRelease( string $real ): bool { + foreach ( $this->oldReleases as $old ) { + if ( 0 === strpos( $real . '/', $old . '/' ) ) { + return true; + } + } + return false; + } + /** * A link to what the scanner never reads (an old release, the root's core) is not_checked as the link itself: dropping * it would leave code it serves or includes unread. Links to an ancestor are walked through their real path, and diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 73a161e8..3b0e0220 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1207,6 +1207,11 @@ function counts( string $name ): array { eq( finding_files( report( 'shortlinkoff-on' ) ), [], "shortlinkoff-on: a linked doc root's .user.ini Off holds over the default" ); eq( finding_files( report( 'shortinilink' ) ), [ 'directory:public::view.php' ], "shortinilink: a .user.ini linked into the doc root counts there, whichever name the walk reads first" ); eq( finding_files( report( 'shortinilinkoff-on' ) ), [], "shortinilinkoff-on: a .user.ini Off linked into the doc root holds over the default there" ); +$ui = [ nc( 'other', '', null, '/var/www/htdocs/current/public/.user.ini', 'unreadable' ) ]; +foreach ( [ 'prev' => $ui, 'env' => $ui, 'usr' => [], 'live' => [], 'rel' => [] ] as $row => $want ) { + eq( report( "userinc-$row" )['not_checked'] ?? null, $want, "userinc-$row: a .user.ini include_path is an unreadable entry only when it may lead into a left-out old release" ); +} +eq( [ counts( 'userinc-prev-unsure' ), finding_files( report( 'userinc-prev-unsure' ) ) ], [ [ 'ok', false, 1, 3, 0 ], [ 'directory:previous::lib/x.php' ] ], 'userinc-prev-unsure: with nothing left out, the old release is checked and the include_path gives no entry' ); foreach ( [ 'shortiniwp-flat', 'shortiniwp-release' ] as $name ) { eq( finding_files( report( $name ) ), [ 'plugin:p::view.php' ], "$name: a WordPress root's .user.ini turns short tags on for its plugins" ); } diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index f9a72b02..ef8ad834 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1464,6 +1464,17 @@ shortinilink_fixture() { printf '\n\n' > "$h/public/view.php" chmod -R a+rX "$1" } +# userinc_fixture : release 2 is current and release 1 previous; release 2's public/.user.ini sets include_path, and only release 1 has lib/x.php. +userinc_fixture() { + local h="$1/htdocs" + mkdir -p "$h/releases/1/lib" "$h/releases/1/public" "$h/releases/2/lib" "$h/releases/2/public" + ln -s releases/2 "$h/current" && ln -s releases/1 "$h/previous" + printf 'include_path = "%s"\n' "$2" > "$h/releases/2/public/.user.ini" + php_file "$h/releases/2/public/index.php" 'require "x.php";' + php_file "$h/releases/1/public/index.php" 'echo 1;' + php_file "$h/releases/1/lib/x.php" '$a = [ 1 ]; each( $a );' + chmod -R a+rX "$1" +} # gatechain_fixture : package files loaded only from the next minors on through if/elseif chains (PHP 8.4 syntax in x.php, a PHP 8.2 class in b81.php), and loads that don't gate them. gatechain_fixture() { local v="$1/htdocs/vendor" d diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index d13b42ee..e34cf99a 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -531,6 +531,12 @@ shortinilink_fixture "$WORK/shortinilink" On scan shortinilink "$WORK/shortinilink" php /var/www/htdocs 8.0 600 -e COMPAT_SERVED=/var/www/htdocs/public shortinilink_fixture "$WORK/shortinilinkoff" Off scan shortinilinkoff-on "$WORK/shortinilinkoff" php /var/www/htdocs 8.0 600 -e COMPAT_SERVED=/var/www/htdocs/public -e COMPAT_SHORT_OPEN_TAG=1 +# A .user.ini include_path that may lead into a left-out old release, and ones that can't. +for row in 'prev:.:/var/www/htdocs/previous/lib' 'env:.:${INC}' 'usr:.:/usr/share/php' 'live:.:/var/www/htdocs/current/lib' 'rel:../lib'; do + userinc_fixture "$WORK/userinc-${row%%:*}" "${row#*:}" + scan "userinc-${row%%:*}" "$WORK/userinc-${row%%:*}" php /var/www/htdocs/current/public 8.0 600 +done +scan userinc-prev-unsure "$WORK/userinc-prev" php /var/www/htdocs/current/public 8.0 600 -e COMPAT_SERVED= for v in flat release; do shortiniwp_fixture "$WORK/shortiniwp-$v" "$v"; done scan shortiniwp-flat "$WORK/shortiniwp-flat" wp /var/www/htdocs 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 scan shortiniwp-release "$WORK/shortiniwp-release" wp /var/www/htdocs/current 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 From aafa13abae5893355d3f9fd2ab1b3673597f0b1a Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 11:33:08 +0530 Subject: [PATCH 74/80] test(compat-scanner): pin the short-tag hiding case as a known limit With short tags on for some requests, every file is checked with them on, so a ` "$h/sub/.user.ini" + printf '\n\n\n\n' > "$h/page.php" + chmod -R a+rX "$1" +} # gatechain_fixture : package files loaded only from the next minors on through if/elseif chains (PHP 8.4 syntax in x.php, a PHP 8.2 class in b81.php), and loads that don't gate them. gatechain_fixture() { local v="$1/htdocs/vendor" d diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index e34cf99a..00ea1f7e 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -537,6 +537,8 @@ for row in 'prev:.:/var/www/htdocs/previous/lib' 'env:.:${INC}' 'usr:.:/usr/shar scan "userinc-${row%%:*}" "$WORK/userinc-${row%%:*}" php /var/www/htdocs/current/public 8.0 600 done scan userinc-prev-unsure "$WORK/userinc-prev" php /var/www/htdocs/current/public 8.0 600 -e COMPAT_SERVED= +shorthide_fixture "$WORK/shorthide" +scan shorthide "$WORK/shorthide" php /var/www/htdocs 8.0 600 for v in flat release; do shortiniwp_fixture "$WORK/shortiniwp-$v" "$v"; done scan shortiniwp-flat "$WORK/shortiniwp-flat" wp /var/www/htdocs 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 scan shortiniwp-release "$WORK/shortiniwp-release" wp /var/www/htdocs/current 8.0 600 -e COMPAT_WP_SUPPORTED=6.8 From a1d95e88c32a40cd1057eaaf837ca8a571a56046 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 12:06:55 +0530 Subject: [PATCH 75/80] fix(compat-scanner): never let a .user.ini turn short tags off PHP-FPM applies the doc root's .user.ini chain only when SCRIPT_FILENAME starts with DOCUMENT_ROOT as text, and only when user_ini.filename is set. With `SCRIPT_FILENAME $realpath_root$fastcgi_script_name` and a linked doc root (the Deployer `current` layout), or an empty user_ini.filename, a doc-root Off is skipped and a script in a subdirectory runs with the pool's On, so holding that Off gave a false safe verdict. A .user.ini can now only turn short tags on for the scan: EE's value on, or an On below the doc root by any name, checks every file with them on; a locked value from EE still decides alone. This removes the doc-root and linked Off handling and the special case for an empty COMPAT_SERVED, which is now the same rule. --- compat-scanner/bin/compat-scanner.php | 94 +++++++++++++++------------ compat-scanner/tests/assert.php | 7 +- compat-scanner/tests/fixture.sh | 2 +- compat-scanner/tests/run.sh | 1 - 4 files changed, 55 insertions(+), 49 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 572eb379..eb933ddf 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -128,8 +128,8 @@ final class Scanner { private $seenDirs = []; /** @var array> Listed files by device and inode. */ private $seenFiles = []; - /** @var array> Real directory of the .user.ini files read, by device and inode: another name of one may be code. */ - private $seenInis = []; + /** @var array Directories naming each .user.ini read (real and as walked), by `dev:ino`: PHP reads a linked one as theirs. */ + private $iniDirs = []; /** @var array Real paths of the site path and content root when listed. */ private $pins = []; /** @var int */ @@ -161,8 +161,8 @@ final class Scanner { private $skippedDirs = []; /** @var string A PHP open tag, as a regex. */ private $openTag; - /** @var array short_open_tag of the .user.ini files that set it, by the real path of their directory and the path as walked. */ - private $shortIni = []; + /** @var array The .user.ini files that turn short_open_tag on, by `dev:ino`. */ + private $shortOn = []; /** @var array Real targets of the links to directories met, by the link's real directory and name. */ private $dirLinks = []; /** @var bool short_open_tag PHPCS and the lint check every file with. */ @@ -338,30 +338,28 @@ private function userIniOnce( string $path, string $real ): void { if ( false === $st ) { return; } - $dir = (string) $this->resolve( dirname( $path ) ); - $first = $this->seenInis[ $st['dev'] ][ $st['ino'] ] ?? null; - if ( null === $first ) { - $this->seenInis[ $st['dev'] ][ $st['ino'] ] = $dir; - $this->userIni( $path, $real, $dir ); - } elseif ( isset( $this->shortIni[ $first ] ) ) { - // PHP reads a linked .user.ini as this directory's own. - $this->shortIni[ $dir ] = $this->shortIni[ $first ]; - $this->shortIni[ dirname( $path ) ] = $this->shortIni[ $first ]; + $key = $st['dev'] . ':' . $st['ino']; + $first = ! isset( $this->iniDirs[ $key ] ); + $this->iniDirs[ $key ][] = $this->resolve( dirname( $path ) ) ?? dirname( $path ); + $this->iniDirs[ $key ][] = dirname( $path ); + if ( $first ) { + $this->userIni( $path, $real, $key ); } } /** - * Collects a .user.ini's auto_prepend_file and auto_append_file values. A line too long to read, zend.multibyte or - * zend.script_encoding (PHP then reads the code in another encoding than PHPCS), or an include_path into a left-out - * old release makes the file itself an unreadable entry, as EE does for its ini files. + * Collects a .user.ini's auto_prepend_file and auto_append_file values, and whether it turns short tags on. A line too + * long to read, zend.multibyte or zend.script_encoding (PHP then reads the code in another encoding than PHPCS), or an + * include_path into a left-out old release makes the file itself an unreadable entry, as EE does for its ini files. */ - private function userIni( string $path, string $real, string $dir ): void { + private function userIni( string $path, string $real, string $key ): void { $fh = open_regular( $real ); if ( null === $fh ) { return; } $keys = '(auto_(?:prepend|append)_file|zend\.multibyte|zend\.script_encoding|short_open_tag|include_path)'; $unsure = false; + $short = false; foreach ( lines( $fh, $this->ticker() ) as $n => $line ) { if ( null === $line ) { $unsure = true; @@ -372,23 +370,20 @@ private function userIni( string $path, string $real, string $dir ): void { foreach ( explode( "\r", $line ) as $part ) { // Directive names are case-sensitive: PHP ignores a mis-cased one. $value = preg_match( '/^\s*(?:\[[^\]]*\]\s*)*' . $keys . '\s*=(.*)$/', $part, $m ) ? ini_value( $m[2] ) : ''; - $key = $m[1] ?? ''; - if ( 'short_open_tag' === $key ) { + $name = $m[1] ?? ''; + if ( 'short_open_tag' === $name ) { // PHP's boolean: on, yes or true, else the number (an unquoted Off reads as ''). - $on = in_array( strtolower( $value ), [ 'on', 'yes', 'true' ], true ) || 0 !== (int) $value; - // The doc root's own value is matched by real path, an On below it by either name. - $this->shortIni[ $dir ] = $on; - $this->shortIni[ dirname( $path ) ] = $on; + $short = in_array( strtolower( $value ), [ 'on', 'yes', 'true' ], true ) || 0 !== (int) $value; continue; } - if ( 'include_path' === $key ) { + if ( 'include_path' === $name ) { $unsure = $unsure || $this->reachesOld( $value ); continue; } - if ( '' === $value || ( 'zend.multibyte' === $key && '0' === $value ) ) { + if ( '' === $value || ( 'zend.multibyte' === $name && '0' === $value ) ) { continue; } - if ( 0 === strpos( $key, 'auto_' ) ) { + if ( 0 === strpos( $name, 'auto_' ) ) { $this->required[] = $value; } else { $unsure = true; @@ -396,6 +391,9 @@ private function userIni( string $path, string $real, string $dir ): void { } } fclose( $fh ); + if ( $short ) { + $this->shortOn[ $key ] = true; + } if ( $unsure ) { $this->notChecked( $this->comp( 'other', '', null, MOUNT_ROOT ), $path, 'unreadable', $real ); } @@ -1835,33 +1833,33 @@ private function runBatch( array $batch ): void { } /** - * short_open_tag for every file, unless the pool locks it: on when the doc root's value (its .user.ini, else the default; only the default when COMPAT_SERVED is empty) is on or any .user.ini below the doc root, by either name or through a link in it, turns it on. PHP-FPM applies the requested script's chain, and that script may include any file of the site. + * short_open_tag for every file, unless the pool locks it: on when EE's value is on or a .user.ini below the doc root, + * by any name, turns it on. PHP-FPM applies the requested script's chain, and that script may include any file of the + * site. An Off never counts: FPM skips the doc root's chain when SCRIPT_FILENAME spells the root differently. */ private function shortTags(): bool { - $root = is_string( $this->cfg['served'] ) && '' !== $this->cfg['served'] ? $this->cfg['served'] : $this->cfg['path']; - if ( $this->cfg['short_locked'] ) { + if ( $this->cfg['short_locked'] || $this->cfg['short_tags'] ) { return $this->cfg['short_tags']; } - $real = $this->pins[ $root ] ?: $root; - $on = array_keys( $this->shortIni, true, true ); - foreach ( $on ? array_merge( [ $root ], $this->rootTops( $real ) ) : [] as $top ) { - foreach ( $on as $dir ) { - if ( 0 === strpos( $dir . '/', $top . '/' ) ) { + $tops = $this->rootTops(); + foreach ( array_keys( $this->shortOn ) as $key ) { + foreach ( $this->iniDirs[ $key ] as $dir ) { + if ( under( $dir, $tops ) ) { return true; } } } - // COMPAT_SERVED empty: the real doc root may lie deeper, where the scan path's Off doesn't apply. - if ( '' === $this->cfg['served'] ) { - return $this->cfg['short_tags']; - } - return $this->shortIni[ $real ] ?? $this->cfg['short_tags']; + return false; } - /** The real doc root and the real targets of the links to directories below it, through which PHP spells request paths too. */ - private function rootTops( string $root ): array { - $tops = [ $root ]; - for ( $i = 0; $i < count( $tops ); $i++ ) { + /** + * The doc root as sent and by its real path, then the real targets of the links to directories below it, through + * which PHP spells request paths too. + */ + private function rootTops(): array { + $root = is_string( $this->cfg['served'] ) && '' !== $this->cfg['served'] ? $this->cfg['served'] : $this->cfg['path']; + $tops = [ $root, $this->pins[ $root ] ?: $root ]; + for ( $i = 1; $i < count( $tops ); $i++ ) { foreach ( $this->dirLinks as $link => $target ) { if ( 0 === strpos( $link, $tops[ $i ] . '/' ) && ! in_array( $target, $tops, true ) ) { $tops[] = $target; @@ -3108,6 +3106,16 @@ function tool_versions( string $image ): array { return $out; } +/** Whether a path is one of the directories or lies below one. */ +function under( string $path, array $dirs ): bool { + foreach ( $dirs as $dir ) { + if ( 0 === strpos( $path . '/', $dir . '/' ) ) { + return true; + } + } + return false; +} + function odd_path( string $path ): bool { return trim( $path ) !== $path || false !== strpbrk( $path, "\r\n" ); } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index b003bbe9..4755ba9c 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1191,8 +1191,7 @@ function counts( string $name ): array { eq( finding_files( report( 'shortini' ) ), $want, 'shortini: short tags on where a .user.ini from the doc root down turns them on, and beside the doc root' ); $want = [ 'directory:sub::off/below.php', 'directory:sub::on.php', 'other:::top.php' ]; eq( finding_files( report( 'shortdeep' ) ), $want, 'shortdeep: a .user.ini that turns short tags on anywhere below the doc root counts for every file' ); -eq( finding_files( report( 'shortrootoff-on' ) ), [], "shortrootoff-on: the doc root's .user.ini Off holds over the default" ); -eq( finding_files( report( 'shortrootoff-unsure' ) ), [ 'directory:sub::on.php', 'other:::top.php' ], "shortrootoff-unsure: with COMPAT_SERVED empty the doc root may lie deeper, so the scan path's Off doesn't hold over the default" ); +eq( finding_files( report( 'shortrootoff-on' ) ), [ 'directory:sub::on.php', 'other:::top.php' ], "shortrootoff-on: a .user.ini Off never holds over EE's On, since PHP-FPM may skip the doc root's .user.ini" ); foreach ( [ 'shortrootsub', 'shortrootsub-on' ] as $name ) { eq( finding_files( report( $name ) ), [ 'directory:sub::on.php', 'other:::top.php' ], "$name: a deeper On counts over the doc root's Off" ); } @@ -1204,9 +1203,9 @@ function counts( string $name ): array { eq( finding_files( report( "shortshared-$d" ) ), [ $file ], "shortshared-$d: a .user.ini On in a directory linked in below the doc root counts" ); } eq( finding_files( report( 'shortwplink' ) ), [ 'plugin:p::view.php' ], 'shortwplink: a .user.ini On in a plugin linked in from outside the doc root counts' ); -eq( finding_files( report( 'shortlinkoff-on' ) ), [], "shortlinkoff-on: a linked doc root's .user.ini Off holds over the default" ); +eq( finding_files( report( 'shortlinkoff-on' ) ), [ 'directory:app::public/view.php' ], "shortlinkoff-on: a linked doc root's .user.ini Off doesn't hold over EE's On" ); eq( finding_files( report( 'shortinilink' ) ), [ 'directory:public::view.php' ], "shortinilink: a .user.ini linked into the doc root counts there, whichever name the walk reads first" ); -eq( finding_files( report( 'shortinilinkoff-on' ) ), [], "shortinilinkoff-on: a .user.ini Off linked into the doc root holds over the default there" ); +eq( finding_files( report( 'shortinilinkoff-on' ) ), [ 'directory:public::view.php' ], "shortinilinkoff-on: a .user.ini Off linked into the doc root doesn't hold over EE's On" ); $ui = [ nc( 'other', '', null, '/var/www/htdocs/current/public/.user.ini', 'unreadable' ) ]; foreach ( [ 'prev' => $ui, 'env' => $ui, 'usr' => [], 'live' => [], 'rel' => [] ] as $row => $want ) { eq( report( "userinc-$row" )['not_checked'] ?? null, $want, "userinc-$row: a .user.ini include_path is an unreadable entry only when it may lead into a left-out old release" ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 78016a3c..9aebe604 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1415,7 +1415,7 @@ return array( chmod -R a+rX "$1" chmod 0 "$v/acme/unreadsib/load.php" } -# short_open_tag off in the doc root's .user.ini (on /htdocs/sub/.user.ini too with a second argument): the doc root's value holds over the default. +# short_open_tag off in the doc root's .user.ini (on /htdocs/sub/.user.ini too with a second argument). shortrootoff_fixture() { local h="$1/htdocs" f mkdir -p "$h/sub" && printf 'short_open_tag = Off\n' > "$h/.user.ini" diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index 00ea1f7e..a552cbd2 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -511,7 +511,6 @@ shortdeep_fixture "$WORK/shortdeep" scan shortdeep "$WORK/shortdeep" php /var/www/htdocs 8.0 600 shortrootoff_fixture "$WORK/shortrootoff" scan shortrootoff-on "$WORK/shortrootoff" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 -scan shortrootoff-unsure "$WORK/shortrootoff" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 -e COMPAT_SERVED= shortrootoff_fixture "$WORK/shortrootsub" sub scan shortrootsub "$WORK/shortrootsub" php /var/www/htdocs 8.0 600 scan shortrootsub-on "$WORK/shortrootsub" php /var/www/htdocs 8.0 600 -e COMPAT_SHORT_OPEN_TAG=1 From c43805ff96fb71046dafad28063bff5b6058f401 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 12:10:18 +0530 Subject: [PATCH 76/80] fix(compat-scanner): count a .user.ini On reached through a link to an ancestor A link below the doc root to its parent or higher (`public/up -> ..`) isn't walked, so it was never recorded, and a .user.ini On reached through it (`/public/up/app/view.php`) didn't count. Links the walk doesn't follow are now recorded too. --- compat-scanner/bin/compat-scanner.php | 13 ++++++++++--- compat-scanner/tests/assert.php | 3 +++ compat-scanner/tests/fixture.sh | 9 +++++++++ compat-scanner/tests/run.sh | 4 ++++ 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index eb933ddf..2919fbca 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -935,7 +935,7 @@ private function visit( string $path, string $name, int $comp ): void { if ( is_dir( $real ) ) { if ( is_link( $path ) ) { - $this->dirLinks[ $this->resolve( dirname( $path ) ) . '/' . $name ] = $real; + $this->dirLinks[ $this->linkLocation( $path ) ] = $real; } if ( $this->markDir( $real ) ) { $this->walk( $path, $comp ); @@ -1269,11 +1269,18 @@ private function inOldRelease( string $real ): bool { * pointer (`previous -> releases/1`), like `current` itself. */ private function unreadLink( string $path, string $real, int $comp, string $file ): void { - $why = $this->scopeWhy( $real ); - if ( ! is_link( $path ) || ( 'old' !== $why && 'core' !== $why ) ) { + if ( ! is_link( $path ) ) { return; } $dir = is_dir( $real ); + // PHP spells request paths through it even when the walk doesn't follow it. + if ( $dir ) { + $this->dirLinks[ $this->linkLocation( $path ) ] = $real; + } + $why = $this->scopeWhy( $real ); + if ( 'old' !== $why && 'core' !== $why ) { + return; + } if ( 'old' === $why && $dir && in_array( $real, $this->oldReleases, true ) && dirname( $real ) === @realpath( dirname( $path ) ) . '/releases' ) { return; } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 4755ba9c..ff4abed3 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1206,6 +1206,9 @@ function counts( string $name ): array { eq( finding_files( report( 'shortlinkoff-on' ) ), [ 'directory:app::public/view.php' ], "shortlinkoff-on: a linked doc root's .user.ini Off doesn't hold over EE's On" ); eq( finding_files( report( 'shortinilink' ) ), [ 'directory:public::view.php' ], "shortinilink: a .user.ini linked into the doc root counts there, whichever name the walk reads first" ); eq( finding_files( report( 'shortinilinkoff-on' ) ), [ 'directory:public::view.php' ], "shortinilinkoff-on: a .user.ini Off linked into the doc root doesn't hold over EE's On" ); +foreach ( [ 'htdocs' => 'directory:../app::view.php', 'public' => 'directory:app::view.php' ] as $r => $file ) { + eq( finding_files( report( "shortup-$r" ) ), [ $file ], "shortup-$r: a .user.ini On reached through a link below the doc root to its parent counts" ); +} $ui = [ nc( 'other', '', null, '/var/www/htdocs/current/public/.user.ini', 'unreadable' ) ]; foreach ( [ 'prev' => $ui, 'env' => $ui, 'usr' => [], 'live' => [], 'rel' => [] ] as $row => $want ) { eq( report( "userinc-$row" )['not_checked'] ?? null, $want, "userinc-$row: a .user.ini include_path is an unreadable entry only when it may lead into a left-out old release" ); diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 9aebe604..c58d177d 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1475,6 +1475,15 @@ userinc_fixture() { php_file "$h/releases/1/lib/x.php" '$a = [ 1 ]; each( $a );' chmod -R a+rX "$1" } +# shortup_fixture : /up links to its parent, whose app/.user.ini turns short tags on for scripts requested through the link. +shortup_fixture() { + local a + a=$(dirname "$1/$2")/app + mkdir -p "$1/$2" "$a" && ln -s .. "$1/$2/up" + printf 'short_open_tag = On\n' > "$a/.user.ini" + printf '\n\n' > "$a/view.php" + chmod -R a+rX "$1" +} # sub/.user.ini turns short tags on; page.php's ` Date: Sun, 29 Nov 2026 12:12:20 +0530 Subject: [PATCH 77/80] fix(compat-scanner): ignore the include_path of a .user.ini above the doc root PHP never reads a .user.ini above the doc root (`releases/2/.user.ini` with doc root `current/public`), so its include_path into an old release is no longer an unreadable entry. It still is when any name of the file lies at or below the doc root, through a linked .user.ini or a link to its directory, which is only known once the walk ends. --- compat-scanner/bin/compat-scanner.php | 27 +++++++++++++++++++++++---- compat-scanner/tests/assert.php | 4 ++++ compat-scanner/tests/fixture.sh | 8 ++++++-- compat-scanner/tests/run.sh | 5 +++++ 4 files changed, 38 insertions(+), 6 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 2919fbca..70c7fd5f 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -163,6 +163,8 @@ final class Scanner { private $openTag; /** @var array The .user.ini files that turn short_open_tag on, by `dev:ino`. */ private $shortOn = []; + /** @var array Path and real path of the .user.ini files whose include_path may lead into an old release, by `dev:ino`. */ + private $incOld = []; /** @var array Real targets of the links to directories met, by the link's real directory and name. */ private $dirLinks = []; /** @var bool short_open_tag PHPCS and the lint check every file with. */ @@ -277,6 +279,7 @@ private function listFiles(): void { foreach ( $this->coreDirsMet() as $dir ) { $this->iniIn( $dir ); } + $this->checkIncludePaths(); $this->checkRequired(); $this->judgeInstalls(); } @@ -348,9 +351,9 @@ private function userIniOnce( string $path, string $real ): void { } /** - * Collects a .user.ini's auto_prepend_file and auto_append_file values, and whether it turns short tags on. A line too - * long to read, zend.multibyte or zend.script_encoding (PHP then reads the code in another encoding than PHPCS), or an - * include_path into a left-out old release makes the file itself an unreadable entry, as EE does for its ini files. + * Collects a .user.ini's auto_prepend_file and auto_append_file values, and whether it turns short tags on or sets an + * include_path into a left-out old release. A line too long to read, zend.multibyte or zend.script_encoding (PHP then + * reads the code in another encoding than PHPCS) makes the file itself an unreadable entry, as EE does for its ini files. */ private function userIni( string $path, string $real, string $key ): void { $fh = open_regular( $real ); @@ -360,6 +363,7 @@ private function userIni( string $path, string $real, string $key ): void { $keys = '(auto_(?:prepend|append)_file|zend\.multibyte|zend\.script_encoding|short_open_tag|include_path)'; $unsure = false; $short = false; + $inc = false; foreach ( lines( $fh, $this->ticker() ) as $n => $line ) { if ( null === $line ) { $unsure = true; @@ -377,7 +381,7 @@ private function userIni( string $path, string $real, string $key ): void { continue; } if ( 'include_path' === $name ) { - $unsure = $unsure || $this->reachesOld( $value ); + $inc = $inc || $this->reachesOld( $value ); continue; } if ( '' === $value || ( 'zend.multibyte' === $name && '0' === $value ) ) { @@ -396,6 +400,21 @@ private function userIni( string $path, string $real, string $key ): void { } if ( $unsure ) { $this->notChecked( $this->comp( 'other', '', null, MOUNT_ROOT ), $path, 'unreadable', $real ); + } elseif ( $inc ) { + $this->incOld[ $key ] = [ $path, $real ]; + } + } + + /** An include_path into an old release is an unreadable entry, unless every name of its .user.ini lies above the doc root: PHP never reads it there. */ + private function checkIncludePaths(): void { + $tops = $this->rootTops(); + foreach ( $this->incOld as $key => list( $path, $real ) ) { + foreach ( $this->iniDirs[ $key ] as $dir ) { + if ( under( $dir, $tops ) || ! ( under( $tops[0], [ $dir ] ) || under( $tops[1], [ $dir ] ) ) ) { + $this->notChecked( $this->comp( 'other', '', null, MOUNT_ROOT ), $path, 'unreadable', $real ); + break; + } + } } } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index ff4abed3..6a0dd8b2 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1214,6 +1214,10 @@ function counts( string $name ): array { eq( report( "userinc-$row" )['not_checked'] ?? null, $want, "userinc-$row: a .user.ini include_path is an unreadable entry only when it may lead into a left-out old release" ); } eq( [ counts( 'userinc-prev-unsure' ), finding_files( report( 'userinc-prev-unsure' ) ) ], [ [ 'ok', false, 1, 3, 0 ], [ 'directory:previous::lib/x.php' ] ], 'userinc-prev-unsure: with nothing left out, the old release is checked and the include_path gives no entry' ); +$ui = [ nc( 'other', '', null, '/var/www/htdocs/current/.user.ini', 'unreadable' ) ]; +foreach ( [ 'above' => [], 'abovelink' => $ui, 'aboveup' => $ui ] as $row => $want ) { + eq( report( "userinc-$row" )['not_checked'] ?? null, $want, "userinc-$row: a .user.ini above the doc root is an unreadable entry only when public/ links to it" ); +} // A documented limit: short tags on for the whole scan check page.php without the block they hide. eq( counts( 'shorthide' ), [ 'ok', true, 0, 1, 0 ], 'shorthide: a `\n\n' > "$h/public/view.php" chmod -R a+rX "$1" } -# userinc_fixture : release 2 is current and release 1 previous; release 2's public/.user.ini sets include_path, and only release 1 has lib/x.php. +# userinc_fixture [ [ini|up]]: release 2 is current and release 1 previous; release 2's /.user.ini (public by default) sets include_path, and only release 1 has lib/x.php. `ini` links public/.user.ini to it, `up` links public/up to release 2. userinc_fixture() { local h="$1/htdocs" mkdir -p "$h/releases/1/lib" "$h/releases/1/public" "$h/releases/2/lib" "$h/releases/2/public" ln -s releases/2 "$h/current" && ln -s releases/1 "$h/previous" - printf 'include_path = "%s"\n' "$2" > "$h/releases/2/public/.user.ini" + printf 'include_path = "%s"\n' "$2" > "$h/releases/2/${3:-public}/.user.ini" + case ${4:-} in + ini) ln -s ../.user.ini "$h/releases/2/public/.user.ini" ;; + up) ln -s .. "$h/releases/2/public/up" ;; + esac php_file "$h/releases/2/public/index.php" 'require "x.php";' php_file "$h/releases/1/public/index.php" 'echo 1;' php_file "$h/releases/1/lib/x.php" '$a = [ 1 ]; each( $a );' diff --git a/compat-scanner/tests/run.sh b/compat-scanner/tests/run.sh index d385559f..c06bcafd 100755 --- a/compat-scanner/tests/run.sh +++ b/compat-scanner/tests/run.sh @@ -540,6 +540,11 @@ for row in 'prev:.:/var/www/htdocs/previous/lib' 'env:.:${INC}' 'usr:.:/usr/shar scan "userinc-${row%%:*}" "$WORK/userinc-${row%%:*}" php /var/www/htdocs/current/public 8.0 600 done scan userinc-prev-unsure "$WORK/userinc-prev" php /var/www/htdocs/current/public 8.0 600 -e COMPAT_SERVED= +# The same include_path in release 2's own .user.ini, above the doc root: applied only when public/ links to it. +for row in above: abovelink:ini aboveup:up; do + userinc_fixture "$WORK/userinc-${row%%:*}" .:/var/www/htdocs/previous/lib . "${row#*:}" + scan "userinc-${row%%:*}" "$WORK/userinc-${row%%:*}" php /var/www/htdocs/current/public 8.0 600 +done shorthide_fixture "$WORK/shorthide" scan shorthide "$WORK/shorthide" php /var/www/htdocs 8.0 600 for v in flat release; do shortiniwp_fixture "$WORK/shortiniwp-$v" "$v"; done From 0ef9e6650b97a583319012d9147e28384967ca3f Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Sun, 29 Nov 2026 12:15:26 +0530 Subject: [PATCH 78/80] fix(compat-scanner): flag a link to releases/ or an ancestor of it A link such as `shared/rels -> ../releases` or `shared/up -> ..` reaches the left-out old releases by name, so code requiring `rels/1/lib/x.php` through it ran an old release while the scan said safe. Such a link is now an unreadable entry, like a link to an old release, unless nginx serves through it (`htdocs -> project`). --- compat-scanner/bin/compat-scanner.php | 25 +++++++++++++++++++------ compat-scanner/tests/assert.php | 5 +++++ compat-scanner/tests/fixture.sh | 9 +++++++++ compat-scanner/tests/run.sh | 4 ++++ 4 files changed, 37 insertions(+), 6 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index 70c7fd5f..e5d71808 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -917,7 +917,21 @@ private function scanTop( string $root, array $entries, int $loose, string $pref */ private function inScope( string $path, string $real ): bool { $why = $this->scopeWhy( $real ); - return null === $why || ( 'anchor' === $why && $path === $real && ! in_array( $real, [ MOUNT_ROOT, $this->rootReal, $this->contentReal ], true ) ); + $in = null === $why || ( 'anchor' === $why && $path === $real && ! in_array( $real, [ MOUNT_ROOT, $this->rootReal, $this->contentReal ], true ) ); + return $in && ! $this->linkAboveOld( $path, $real ); + } + + /** A link to the releases/ dir or an ancestor of it leads into the old releases, unless nginx serves through it (`htdocs -> project`). */ + private function linkAboveOld( string $path, string $real ): bool { + if ( ! is_link( $path ) || under( $this->servedPath(), [ $path ] ) ) { + return false; + } + foreach ( $this->oldReleases as $old ) { + if ( 0 === strpos( $old, $real . '/' ) ) { + return true; + } + } + return false; } private function walk( string $dir, int $comp ): void { @@ -1282,10 +1296,9 @@ private function inOldRelease( string $real ): bool { } /** - * A link to what the scanner never reads (an old release, the root's core) is not_checked as the link itself: dropping - * it would leave code it serves or includes unread. Links to an ancestor are walked through their real path, and - * another install's core is its nested_wordpress entry. A link beside `current` to a whole old release is a release - * pointer (`previous -> releases/1`), like `current` itself. + * A link to what the scanner never reads (an old release, releases/ or an ancestor of it, the root's core) is not_checked as + * the link itself: dropping it would leave code it serves or includes unread. Other ancestors are walked by their real path, + * another install's core is its nested_wordpress entry, and `previous -> releases/1` is a release pointer like `current`. */ private function unreadLink( string $path, string $real, int $comp, string $file ): void { if ( ! is_link( $path ) ) { @@ -1296,7 +1309,7 @@ private function unreadLink( string $path, string $real, int $comp, string $file if ( $dir ) { $this->dirLinks[ $this->linkLocation( $path ) ] = $real; } - $why = $this->scopeWhy( $real ); + $why = $this->linkAboveOld( $path, $real ) ? 'old' : $this->scopeWhy( $real ); if ( 'old' !== $why && 'core' !== $why ) { return; } diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 6a0dd8b2..04859ef8 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1218,6 +1218,11 @@ function counts( string $name ): array { foreach ( [ 'above' => [], 'abovelink' => $ui, 'aboveup' => $ui ] as $row => $want ) { eq( report( "userinc-$row" )['not_checked'] ?? null, $want, "userinc-$row: a .user.ini above the doc root is an unreadable entry only when public/ links to it" ); } +foreach ( [ 'rels' => [ 'rels/', '/var/www/htdocs' ], 'up' => [ 'up/', '/var/www/htdocs' ], 'project' => [ null, '/var/www/project' ] ] as $v => list( $file, $site ) ) { + $want = [ $file ? [ nc( 'directory', 'shared', null, $file, 'unreadable' ) ] : [], [ "$site/releases/1" ] ]; + $r = report( "rellink-$v" ); + eq( [ $r['not_checked'] ?? null, $r['excluded_old_releases'] ?? null ], $want, "rellink-$v: a link to releases/ or an ancestor of it is an unreadable entry, unless nginx serves through it" ); +} // A documented limit: short tags on for the whole scan check page.php without the block they hide. eq( counts( 'shorthide' ), [ 'ok', true, 0, 1, 0 ], 'shorthide: a `\n\n' > "$a/view.php" chmod -R a+rX "$1" } +# rellink_fixture : php_release_fixture with shared/rels -> ../releases, shared/up -> .., or htdocs a link to project/, through which nginx serves. +rellink_fixture() { + php_release_fixture "$1" real + case $2 in + rels) ln -s ../releases "$1/htdocs/shared/rels" ;; + up) ln -s .. "$1/htdocs/shared/up" ;; + project) mv "$1/htdocs" "$1/project" && ln -s project "$1/htdocs" ;; + esac +} # sub/.user.ini turns short tags on; page.php's ` Date: Sun, 29 Nov 2026 12:31:15 +0530 Subject: [PATCH 79/80] perf(compat-scanner): skip the doc root's link names when no .user.ini needs them The names of the doc root (its real path and the targets of the directory links below it) were built on every scan, twice, though only a .user.ini that turns short tags on or sets an include_path into a left-out old release uses them. Building them is quadratic in the directory links: a site with 12,000 linked directories and no .user.ini took about 18 s instead of 1 s. The report is unchanged. --- compat-scanner/bin/compat-scanner.php | 7 +++++-- compat-scanner/tests/assert.php | 1 + compat-scanner/tests/fixture.sh | 9 +++++++++ compat-scanner/tests/run.sh | 4 ++++ 4 files changed, 19 insertions(+), 2 deletions(-) diff --git a/compat-scanner/bin/compat-scanner.php b/compat-scanner/bin/compat-scanner.php index e5d71808..06630d47 100644 --- a/compat-scanner/bin/compat-scanner.php +++ b/compat-scanner/bin/compat-scanner.php @@ -407,6 +407,9 @@ private function userIni( string $path, string $real, string $key ): void { /** An include_path into an old release is an unreadable entry, unless every name of its .user.ini lies above the doc root: PHP never reads it there. */ private function checkIncludePaths(): void { + if ( ! $this->incOld ) { + return; + } $tops = $this->rootTops(); foreach ( $this->incOld as $key => list( $path, $real ) ) { foreach ( $this->iniDirs[ $key ] as $dir ) { @@ -1877,7 +1880,7 @@ private function runBatch( array $batch ): void { * site. An Off never counts: FPM skips the doc root's chain when SCRIPT_FILENAME spells the root differently. */ private function shortTags(): bool { - if ( $this->cfg['short_locked'] || $this->cfg['short_tags'] ) { + if ( $this->cfg['short_locked'] || $this->cfg['short_tags'] || ! $this->shortOn ) { return $this->cfg['short_tags']; } $tops = $this->rootTops(); @@ -1893,7 +1896,7 @@ private function shortTags(): bool { /** * The doc root as sent and by its real path, then the real targets of the links to directories below it, through - * which PHP spells request paths too. + * which PHP spells request paths too. Quadratic in those links, so callers skip it when they have nothing to test. */ private function rootTops(): array { $root = is_string( $this->cfg['served'] ) && '' !== $this->cfg['served'] ? $this->cfg['served'] : $this->cfg['path']; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 04859ef8..752d0089 100644 --- a/compat-scanner/tests/assert.php +++ b/compat-scanner/tests/assert.php @@ -1232,6 +1232,7 @@ function counts( string $name ): array { eq( counts( 'burst' ), [ 'ok', false, 2, 402, 0 ], 'burst: a lint per file, one after another, stays within a pids limit of 8' ); tool_error( 'slowlint', 'timed out after 2 s at htdocs/big.tpl', 1 ); +eq( counts( 'dirlinks' ), [ 'ok', true, 0, 1, 0 ], 'dirlinks: 12,000 directory links with no .user.ini setting to test finish within 10 s' ); foreach ( [ 'wpextra-dir', 'wpextra-parent' ] as $name ) { $cfg = comp_of( report( $name ), 'other', 'wp-config.php' )['findings'][0] ?? []; diff --git a/compat-scanner/tests/fixture.sh b/compat-scanner/tests/fixture.sh index 4637f669..5191d45e 100644 --- a/compat-scanner/tests/fixture.sh +++ b/compat-scanner/tests/fixture.sh @@ -1242,6 +1242,15 @@ burst_fixture() { chmod -R a+rX "$1" } +# dirlinks_fixture : a php site with one file and 12,000 links to empty directories below its doc root, and no .user.ini. +dirlinks_fixture() { + local h="$1/htdocs" + php_file "$h/index.php" "echo 1;" + mkdir -p "$h/l" + (cd "$h" && seq 12000 | sed 's#^#d/#' | xargs mkdir -p && seq 12000 | sed 's#^#../d/#' | xargs ln -s -t l) + chmod -R a+rX "$1" +} + # slowlint_fixture : a php site whose only code is a template-named file starting with ` Date: Sun, 29 Nov 2026 12:36:31 +0530 Subject: [PATCH 80/80] test(compat-scanner): run each truth row from its own checked fixture file The truth modes of guards.php and use-guards.php reused one temporary file for every row and ignored a failed write, so PHP could judge an empty file or the previous row's fixture and the table would be checked against the wrong code. Each row now gets its own file from tempnam(), the row fails if the file or the write fails, and the file is removed in a finally block. --- compat-scanner/tests/guards.php | 27 +++++++++++++++++++-------- compat-scanner/tests/use-guards.php | 29 ++++++++++++++++++++--------- 2 files changed, 39 insertions(+), 17 deletions(-) diff --git a/compat-scanner/tests/guards.php b/compat-scanner/tests/guards.php index 56c38012..583a34f9 100644 --- a/compat-scanner/tests/guards.php +++ b/compat-scanner/tests/guards.php @@ -126,17 +126,28 @@ file_put_contents( "$argv[2]/$id.php", "&1', $out, $rc ); - $got = 0 === $rc ? 'ok' : 'fatal'; - if ( $got !== $php ) { - echo "$id: PHP " . PHP_VERSION . " says $got, the table $php\n"; + // A file per row, checked before PHP runs it: a failed write must not run another row's fixture. + $tmp = tempnam( sys_get_temp_dir(), 'guard' ); + if ( false === $tmp ) { + echo "$id: no temporary file\n"; + continue; + } + try { + if ( false === file_put_contents( $tmp, "&1', $out, $rc ); + $got = 0 === $rc ? 'ok' : 'fatal'; + if ( $got !== $php ) { + echo "$id: PHP " . PHP_VERSION . " says $got, the table $php\n"; + } + $out = []; + } finally { + unlink( $tmp ); } - $out = []; } - unlink( $tmp ); echo "checked\n"; } return $rows; diff --git a/compat-scanner/tests/use-guards.php b/compat-scanner/tests/use-guards.php index dd4d5445..a01d0d90 100644 --- a/compat-scanner/tests/use-guards.php +++ b/compat-scanner/tests/use-guards.php @@ -117,21 +117,32 @@ } } } elseif ( 'truth' === ( $argv[1] ?? '' ) ) { - $tmp = tempnam( sys_get_temp_dir(), 'use' ); foreach ( $rows as list( $id, $target, $php, , $code ) ) { if ( $target !== $argv[2] ) { continue; } - file_put_contents( $tmp, $source( $code ) ); - exec( 'php -d error_reporting=-1 -d display_errors=1 ' . escapeshellarg( $tmp ) . ' 2>&1', $out, $rc ); - $got = preg_grep( '/^(PHP )?Deprecated: /', $out ) ? 'deprecated' : 'ok'; - $got = 0 === $rc ? $got : 'fatal'; - if ( $got !== $php ) { - echo "$id: PHP " . PHP_VERSION . " says $got, the table $php\n"; + // A file per row, checked before PHP runs it: a failed write must not run another row's fixture. + $tmp = tempnam( sys_get_temp_dir(), 'use' ); + if ( false === $tmp ) { + echo "$id: no temporary file\n"; + continue; + } + try { + if ( false === file_put_contents( $tmp, $source( $code ) ) ) { + echo "$id: the fixture was not written\n"; + continue; + } + exec( 'php -d error_reporting=-1 -d display_errors=1 ' . escapeshellarg( $tmp ) . ' 2>&1', $out, $rc ); + $got = preg_grep( '/^(PHP )?Deprecated: /', $out ) ? 'deprecated' : 'ok'; + $got = 0 === $rc ? $got : 'fatal'; + if ( $got !== $php ) { + echo "$id: PHP " . PHP_VERSION . " says $got, the table $php\n"; + } + $out = []; + } finally { + unlink( $tmp ); } - $out = []; } - unlink( $tmp ); echo "checked\n"; } return $rows;