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' diff --git a/compat-scanner/Dockerfile b/compat-scanner/Dockerfile index 0d1e0813..71d24b02 100644 --- a/compat-scanner/Dockerfile +++ b/compat-scanner/Dockerfile @@ -15,15 +15,43 @@ RUN set -eux; \ php /tmp/select.php /tmp/wordpress/wp-includes /opt/compat-scanner/calibration; \ rm -rf /tmp/wp.tar.gz /tmp/wordpress /tmp/select.php +# Each target's own PHP for `php -l`: only it parses, reserves names and declares functions as the target does. +# Older Alpine bases bring their own libraries; the alpine3.24 ones use the final image's. +FROM php:8.0.30-cli-alpine3.16 AS php80 +FROM php:8.1.34-cli-alpine3.22 AS php81 +FROM php:8.2.36-cli-alpine3.24 AS php82 +FROM php:8.3.37-cli-alpine3.24 AS php83 +FROM php:8.5.13-cli-alpine3.24 AS php85 +FROM php:8.6.0-cli-alpine3.24 AS php86 +# Their libraries beside them, found through the binary's RPATH. +FROM php80 AS libs80 +RUN apk add --no-cache patchelf && mkdir -p /out/lib && cp /usr/local/bin/php /out/ \ + && ldd /usr/local/bin/php | awk '$3 ~ /^\// && $1 !~ /musl/ { print $3 }' | xargs cp -L -t /out/lib \ + && patchelf --set-rpath /opt/php/8.0/lib /out/php +FROM php81 AS libs81 +RUN apk add --no-cache patchelf && mkdir -p /out/lib && cp /usr/local/bin/php /out/ \ + && ldd /usr/local/bin/php | awk '$3 ~ /^\// && $1 !~ /musl/ { print $3 }' | xargs cp -L -t /out/lib \ + && patchelf --set-rpath /opt/php/8.1/lib /out/php + 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 --from=libs80 /out/ /opt/php/8.0/ +COPY --from=libs81 /out/ /opt/php/8.1/ +COPY --from=php82 /usr/local/bin/php /opt/php/8.2/php +COPY --from=php83 /usr/local/bin/php /opt/php/8.3/php +COPY --from=php85 /usr/local/bin/php /opt/php/8.5/php +COPY --from=php86 /usr/local/bin/php /opt/php/8.6/php +RUN mkdir /opt/php/8.4 && ln -s /usr/local/bin/php /opt/php/8.4/php 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"] +# 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 0f1b1c99..06630d47 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+). @@ -29,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. @@ -41,24 +43,39 @@ 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. +// 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; // 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. -const SNIFF_REGEX = '/\\A(?=[^\\x00]*\\z)[\\s\\S]*?<\\?(?:php(?:\\s|\\z)|=)/i'; +// A PHP open tag; with short tags on, `//php. +const PHP_DIR = '/opt/php'; // Never PHP templates, so not sniffed: docs, scripts and styles quote ` 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 = []; /** @var array> Listed files by device and inode. */ private $seenFiles = []; + /** @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 */ @@ -116,20 +145,38 @@ 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. */ + private $pharNamedBy; /** @var int Listed files PHPCS reads through STDIN, one run each (for the estimate). */ private $stdinFiles = 0; - /** @var float Seconds left for searching skipped directories. */ - private $skippedBudget = 0.0; - /** @var float Seconds left for searching a php site's dot dirs of /var/www (their own budget). */ - private $homeBudget = 0.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' => '' ]; - /** @var int */ - private $manBytes = 0; + private $manBuf = [ 'checked' => '', '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 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. */ + 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. */ + private $sniffRegex; /** @var string */ private $work = ''; @@ -137,22 +184,23 @@ 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; 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']; + // 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; $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 { @@ -170,7 +218,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' ); } @@ -185,44 +234,251 @@ 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; + // 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->rootReal = $this->contentReal; - $this->oldReleases = $this->oldReleases( $this->cfg['path'] ); - $other = $this->comp( 'other', '', null, $root ); - $entries = $this->readDir( $root ); - if ( null === $entries ) { - $this->notChecked( $other, './', 'unreadable' ); - return; + $this->scanBeside( $this->comp( 'directory', '..', null, MOUNT_ROOT ), '../', $entered ? [] : [ 'htdocs' ] ); + } 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 ) { + $comp = $this->comp( 'directory', $root, null, $root ); + if ( is_dir( $root ) ) { + $this->skipped( $root, '.', $comp ); + } else { + $this->notChecked( $comp, './', 'unreadable' ); + } + } + // 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->checkIncludePaths(); + $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 ); + } + } + } + + /** @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; + } + } + return $dirs; + } + + /** 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 ); + foreach ( (array) $this->readDir( $d ) as $name ) { + $path = $d . '/' . $name; + if ( is_dir( $path ) && ! is_link( $path ) ) { + $stack[] = $path; + } elseif ( '.user.ini' === $name ) { + $real = $this->resolve( $path ); + if ( null === $real ) { + $this->notChecked( $this->comp( 'other', '', null, MOUNT_ROOT ), $path, 'unreadable', $path ); + } else { + $this->userIniOnce( $path, $real ); + } + } } - $this->scanTop( $root, $entries, $other, '' ); - $this->scanBeside(); + } + } + + /** userIni() once per file, whichever route reaches it. */ + private function userIniOnce( string $path, string $real ): void { + $st = @stat( $real ); + if ( false === $st ) { + return; + } + $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, 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 ); + if ( null === $fh ) { return; } + $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; + 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 ) { + // Directive names are case-sensitive: PHP ignores a mis-cased one. + $value = preg_match( '/^\s*(?:\[[^\]]*\]\s*)*' . $keys . '\s*=(.*)$/', $part, $m ) ? ini_value( $m[2] ) : ''; + $name = $m[1] ?? ''; + if ( 'short_open_tag' === $name ) { + // PHP's boolean: on, yes or true, else the number (an unquoted Off reads as ''). + $short = in_array( strtolower( $value ), [ 'on', 'yes', 'true' ], true ) || 0 !== (int) $value; + continue; + } + if ( 'include_path' === $name ) { + $inc = $inc || $this->reachesOld( $value ); + continue; + } + if ( '' === $value || ( 'zend.multibyte' === $name && '0' === $value ) ) { + continue; + } + if ( 0 === strpos( $name, 'auto_' ) ) { + $this->required[] = $value; + } else { + $unsure = true; + } + } + } + fclose( $fh ); + if ( $short ) { + $this->shortOn[ $key ] = true; + } + if ( $unsure ) { + $this->notChecked( $this->comp( 'other', '', null, MOUNT_ROOT ), $path, 'unreadable', $real ); + } elseif ( $inc ) { + $this->incOld[ $key ] = [ $path, $real ]; + } + } - $wp = $this->cfg['path']; - $top = $this->wpDir( $wp ); - $root = $wp . '/wp-content'; - if ( null === $top ) { + /** 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 ) { + if ( under( $dir, $tops ) || ! ( under( $tops[0], [ $dir ] ) || under( $tops[1], [ $dir ] ) ) ) { + $this->notChecked( $this->comp( 'other', '', null, MOUNT_ROOT ), $path, 'unreadable', $real ); + break; + } + } + } + } + + /** 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. + */ + 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->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( $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; + } 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. + // 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 && $this->inside( $real ) ? $real : $config; - $this->visit( $path, 'wp-config.php', $this->comp( 'other', 'wp-config.php', null, MOUNT_ROOT ) ); + $path = false !== $real && 0 === strpos( $real, MOUNT_ROOT . '/' ) ? $real : $config; + $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; @@ -289,11 +545,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. */ @@ -302,9 +553,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; } /** @@ -341,136 +595,41 @@ 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; } - /** Php sites: what lies in /var/www beside htdocs (code above the public dir). */ - private function scanBeside(): void { + /** + * 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; $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, array $skip = [] ): void { $this->markDir( MOUNT_ROOT ); - $loose = $this->comp( 'directory', '..', null, MOUNT_ROOT ); $entries = $this->readDir( MOUNT_ROOT ); if ( null === $entries ) { $this->notChecked( $loose, './', 'unreadable' ); return; } $links = []; - foreach ( $entries as $name ) { - 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 ); + foreach ( array_diff( $entries, $skip ) as $name ) { + 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 ); - } + $this->scanTop( MOUNT_ROOT, [ $name ], $loose, $prefix ); } - closedir( $handle ); } - $this->homeBudget = max( 0.0, $stop - microtime( true ) ); - if ( $found ) { - return 'skipped'; - } - return $unreadable ? 'unreadable' : null; + $this->scanTop( MOUNT_ROOT, $links, $loose, $prefix ); } /** @@ -495,9 +654,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 beside it. + * Returns the other releases, which aren't scanned. * * @return string[] */ @@ -518,10 +676,18 @@ private function oldReleases( string $publicDir ): array { if ( is_link( $releases ) || ! is_dir( $releases ) || ! $this->inside( $releases ) || dirname( $live ) !== $releases ) { return []; } - $old = []; + // 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 []; + } + $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 ) ) { + $dir = $releases . '/' . $name; + $release = preg_match( RELEASE_NAME, $name ) && ! is_link( $dir ) && is_file( $dir . $marker ); + if ( $dir !== $live && $release && 0 !== strpos( $scan, $dir . '/' ) ) { $old[] = $dir; } } @@ -568,14 +734,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, ]; @@ -749,16 +915,26 @@ 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. */ private function inScope( string $path, string $real ): bool { - return ! $this->outOfScope( $real ) || ( $path === $real && $this->holdsRoot( $real ) ); + $why = $this->scopeWhy( $real ); + $in = null === $why || ( 'anchor' === $why && $path === $real && ! in_array( $real, [ MOUNT_ROOT, $this->rootReal, $this->contentReal ], true ) ); + return $in && ! $this->linkAboveOld( $path, $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; + /** 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 { @@ -794,6 +970,9 @@ private function visit( string $path, string $name, int $comp ): void { } if ( is_dir( $real ) ) { + if ( is_link( $path ) ) { + $this->dirLinks[ $this->linkLocation( $path ) ] = $real; + } if ( $this->markDir( $real ) ) { $this->walk( $path, $comp ); } @@ -804,20 +983,31 @@ private function visit( string $path, string $name, int $comp ): void { if ( false === $st || 0100000 !== ( $st['mode'] & 0170000 ) ) { 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 ) ) { - $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; 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; + } + if ( $this->packageTemplate( $path ) ) { + if ( $this->cfg['manifest'] ) { + $this->manifestAdd( 'information', $real ); + } return; } $tag = $this->sniff( $real ); @@ -827,10 +1017,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 +1044,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 +1054,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 +1075,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 +1088,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 +1122,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,29 +1133,65 @@ 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 ) || '.user.ini' === $name ) { + $hits[ $path ] = false; } } closedir( $handle ); } - $this->skippedBudget = max( 0.0, $stop - microtime( true ) ); ksort( $hits, SORT_STRING ); 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 $path, string $real ): bool { + $fh = open_regular( $real ); + if ( null === $fh ) { + return false; + } + $tail = ''; + $found = false; + while ( ! $found && '' !== ( $chunk = (string) fread( $fh, 65536 ) ) ) { + if ( microtime( true ) >= $this->deadline ) { + fclose( $fh ); + throw $this->timedOutAt( $path ); + } + // 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; + } + + /** @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 @@ -1006,10 +1208,11 @@ 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; } + $this->tick(); $more = fread( $fh, 65536 ); if ( false === $more || ( '' === $more && ! feof( $fh ) ) ) { $ok = false; // A failed read: not known to be data. @@ -1020,7 +1223,7 @@ private function dataOnly( string $path ): bool { } $read += strlen( $more ); if ( $read > DATA_MAX ) { - $ok = false; // Not read to the end: never counted as checked unread. + $ok = false; break; } $rest = substr( $rest, -5 ) . $more; // A tag split across reads. @@ -1041,8 +1244,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'; @@ -1067,13 +1270,11 @@ 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 ) { - 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 . '/' ) ) { @@ -1084,21 +1285,37 @@ private function scopeWhy( string $real ): ?string { if ( null === $install ) { return null; } - return $install === $this->rootReal ? 'core' : 'nested'; + 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 - * 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 { - $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->linkAboveOld( $path, $real ) ? 'old' : $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; } @@ -1125,12 +1342,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 ); @@ -1143,7 +1357,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; @@ -1182,6 +1396,62 @@ private function isPhpName( string $name ): bool { return (bool) preg_match( '/\.(?:' . implode( '|', CODE_EXTENSIONS ) . ')\z/i', $name ); } + private function isTemplateName( string $name ): bool { + return (bool) preg_match( '/\.(?:' . implode( '|', TEMPLATE_EXTENSIONS ) . ')\z/i', $name ); + } + + /** + * 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. */ + 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 ); @@ -1198,7 +1468,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). */ @@ -1260,7 +1535,14 @@ private function hasEntries( $handle ): bool { return false; } - private function tick(): void { + /** 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 ) { throw new TimedOut( sprintf( 'too large to estimate in %d s: %d PHP files listed before the time ran out; run the check itself, without --estimate', $this->timeoutLabel, $this->listedFiles + $this->notCheckedCount ) ); @@ -1299,6 +1581,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 ); } @@ -1383,6 +1669,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(); } @@ -1392,7 +1680,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' ); @@ -1411,6 +1699,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'], @@ -1436,9 +1725,11 @@ private function timed( array $paths ): float { // ------------------------------------------------------------------- scan 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++; $batch[] = $rec; @@ -1455,6 +1746,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(); @@ -1478,13 +1774,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 ); @@ -1500,9 +1791,32 @@ 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; + $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 ) ) { + $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 ); + foreach ( $this->lint( $batch ) as $k => $result ) { + $batch[ $k ]['lint'] = $result; + } + + $plain = []; + foreach ( $batch as $k => $f ) { + if ( null !== $f['real'] && ! $f['stdin'] && ! isset( $f['lint'] ) ) { + $plain[ $f['real'] ] = $k; } } @@ -1527,7 +1841,16 @@ 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' ); + } else { + $this->dropped++; + } + continue; + } + if ( isset( $f['lint'] ) ) { + $this->recordLint( $f ); continue; } if ( null !== $reader && ! $f['stdin'] ) { @@ -1551,6 +1874,43 @@ private function runBatch( array $batch ): void { } } + /** + * 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 { + if ( $this->cfg['short_locked'] || $this->cfg['short_tags'] || ! $this->shortOn ) { + return $this->cfg['short_tags']; + } + $tops = $this->rootTops(); + foreach ( array_keys( $this->shortOn ) as $key ) { + foreach ( $this->iniDirs[ $key ] as $dir ) { + if ( under( $dir, $tops ) ) { + return true; + } + } + } + return false; + } + + /** + * 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. 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']; + $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; + } + } + } + return $tops; + } + /** Steps 2 to 4 for one file. */ private function runSingle( array $f ): void { if ( $f['stdin'] && $f['size'] > STDIN_MAX ) { @@ -1596,9 +1956,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 ); } @@ -1612,8 +1971,14 @@ 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( substr( $path, strlen( MOUNT_ROOT ) + 1 ) ) ) ); + $done = array_sum( array_column( $this->comps, 'files' ) ); + $all = $this->listedFiles + $this->dataFiles; + $at = clean_text( $this->relMount( $path ) ); + // 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 ) ); } /** A file missing from a finished run on a nearly full disk is a write failure, not `error`. */ @@ -1634,6 +1999,44 @@ 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. */ + 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; + } + 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']; @@ -1646,12 +2049,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() ) ) { - 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; @@ -1659,9 +2063,17 @@ 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; + } $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.' ) ) { @@ -1672,7 +2084,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 { @@ -1691,13 +2107,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`. */ @@ -1710,6 +2120,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 +2137,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,28 +2145,21 @@ 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 ) { $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, @@ -1761,20 +2167,15 @@ private function writeManifest(): void { 'phar_regex' => PHAR_REGEX, 'sniff' => [ 'bytes' => SNIFF_BYTES, - 'regex' => SNIFF_REGEX, - 'exclude_extensions' => NO_SNIFF_EXTENSIONS, + '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 ) ) ), ], - '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'; @@ -1795,6 +2196,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 ); @@ -1816,7 +2220,11 @@ 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(); + foreach ( $listed as $idx ) { + $this->settleClasses( $idx ); + } $errors = $warnings = $checked = $bytes = $withErrors = 0; foreach ( $listed as $idx ) { @@ -1862,7 +2270,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() ) ); @@ -1917,7 +2327,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 ); @@ -1929,6 +2343,67 @@ 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' => [] ]; + 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 ) ) { @@ -1958,7 +2433,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} */ @@ -1975,28 +2450,13 @@ 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', + '-d', 'short_open_tag=' . (int) $this->short, 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, @@ -2013,27 +2473,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; } @@ -2041,12 +2488,252 @@ 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 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} 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 ]; + $left = $this->deadline - microtime( true ); + if ( $left <= 0 ) { + $res['timeout'] = true; + return $res; + } + $capped = $cap > 0 && $cap < $left; + $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( $cmd, $spec, $pipes ); + set_fsize( null ); + if ( ! is_resource( $proc ) ) { + throw new ToolError( 'could not start ' . basename( end( $cmd ) ) ); + } + $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; + $res['rc'] = $status['signaled'] ? 128 + $status['termsig'] : $status['exitcode']; + if ( $killed && 137 === $res['rc'] ) { + $res[ $capped ? 'capped' : 'timeout' ] = true; + } + return $res; + } + + /** + * `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 ], a not_checked reason, or true when its package loads it only above the target. + */ + private function lint( array $batch ): array { + $paths = []; + foreach ( $batch as $k => $f ) { + if ( null !== $f['real'] && ( ! $f['mixed'] || $this->isTemplateName( basename( $f['path'] ) ) ) ) { + $paths[ $k ] = $f['real']; + } + } + if ( ! $paths || version_compare( $this->cfg['version'], '8.0', '<' ) ) { + return []; + } + if ( ! is_file( $this->lintPhp() ) ) { + throw new ToolError( 'no PHP ' . $this->cfg['version'] . ' in the image to lint with' ); + } + if ( ! $this->lintsEach() && 0 === $this->lintRun( array_values( $paths ), (float) $this->cfg['file_timeout'] )['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'] ) { + $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'] ) ) { + $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; + } + } + return $failed; + } + + /** + * 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, unless the autoloader loads it. + if ( ! $this->inPackage( $path ) || $this->autoloaded( $path ) ) { + return false; + } + $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 ); + } + $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 ] ) ) { + $gated += $names[ $name ][0]; + $all += $names[ $name ][1]; + } + } + return null !== $this->loads[ $dir ] && $gated > 0 && $gated === $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 ( $files as $file => $child ) { + 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 ) ) { + $count = $loads[ $file ][ $named ] ?? [ 0, 0 ]; + + $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 `[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; + } + $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; + } + $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] ); + } + } + 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. */ + 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'; + } + + private function lintRun( array $paths, float $cap ): array { + $err = $this->work . '/lint.err'; + $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 ) ] ); + // 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 why the file isn't checked. */ + private function lintResult( array $res, string $real ) { + if ( $res['capped'] ) { + return 'timeout'; + } + if ( 137 === $res['rc'] || false !== strpos( $res['stderr'], 'Allowed memory size' ) ) { + return 'memory'; + } + if ( 255 !== $res['rc'] ) { + return 'error'; + } + // 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'] ) ); + preg_match( '/^(.*?)(?: on line (\d+))?$/s', $text, $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. @@ -2203,7 +2890,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; @@ -2288,7 +2975,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 { @@ -2296,7 +2987,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; @@ -2352,6 +3044,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 ); } @@ -2442,6 +3148,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" ); } @@ -2495,6 +3211,104 @@ 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 = '…';` 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 ); + if ( null === $fh ) { + return ''; + } + $lines = []; + 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; + } + 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 ) ) { + return ''; + } + 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. + * $tick runs per read, so a huge file can't outlast the deadline. + * + * @param resource $fh + * @return 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; + } + 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; + } +} + +/** @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 null; + } + $code = fread( $fh, 1048577 ); + fclose( $fh ); + if ( false === $code || strlen( $code ) > 1048576 ) { + return null; + } + $tokens = []; + foreach ( token_get_all( $code ) as $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 $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] : ''; +} + function parse_args( array $argv, array &$cfg ): void { $cfg['mode'] = $argv[0] ?? ''; $cfg['site_type'] = $argv[1] ?? ''; @@ -2508,12 +3322,8 @@ 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'] = $path; + $cfg['path'] = mount_path( $cfg['path'], 'path' ); + parse_contract_env( $cfg ); if ( ! preg_match( '/^\d+\.\d+\z/', $cfg['version'] ) ) { throw new BadArgs( 'version must look like 8.4' ); } @@ -2527,23 +3337,55 @@ 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 ); $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' ); } } +/** 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' ); + 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; + } + $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; + $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 ) { + if ( ! preg_match( '/^\d+\.\d+\z/', $branch ) ) { + throw new BadArgs( 'COMPAT_WP_SUPPORTED must be branches like 6.8, comma-separated' ); + } + } +} + function emit( array $doc, int $code, bool $report ): void { global $emitted; $emitted = true; diff --git a/compat-scanner/src/CompatScanner/Guard.php b/compat-scanner/src/CompatScanner/Guard.php new file mode 100644 index 00000000..752cf179 --- /dev/null +++ b/compat-scanner/src/CompatScanner/Guard.php @@ -0,0 +1,253 @@ + 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, 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 ); + $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; + } + + /** 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; + } + } + // 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 ) ); ) { + 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 ); + 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 ) { + 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. + */ + private 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', '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 ); + } + + /** + * 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. */ + 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 new file mode 100644 index 00000000..a384ac4e --- /dev/null +++ b/compat-scanner/src/CompatScanner/Sniffs/Classes/NativeDeclaredSniff.php @@ -0,0 +1,74 @@ + [ '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 ] ]; + } + + /** + * 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 ] ) || 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 ( $this->onlyReturns( $phpcsFile, $if ) && $tokens[ $if ]['scope_closer'] < $stackPtr && Guard::any( $phpcsFile, $if, true, $exists ) ) { + return true; + } + } + return false; + } + + /** 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; + } + $return = $phpcsFile->findNext( Tokens::EMPTY_TOKENS, $tokens[ $if ]['scope_opener'] + 1, null, true ); + if ( T_RETURN !== $tokens[ $return ]['code'] ) { + 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 new file mode 100644 index 00000000..17032b70 --- /dev/null +++ b/compat-scanner/src/CompatScanner/Sniffs/Files/InertSniff.php @@ -0,0 +1,60 @@ +numTokens; + } + $tokens = $phpcsFile->getTokens(); + $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'] ) ) { + // 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 ) { + 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; + } + + /** 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 new file mode 100644 index 00000000..ab8f4b49 --- /dev/null +++ b/compat-scanner/src/CompatScanner/Sniffs/Functions/NativeDeclaredSniff.php @@ -0,0 +1,82 @@ +|null The native-name table, by lowercase name. */ + protected $table; + + public function register() { + return [ T_FUNCTION ]; + } + + public function process( File $phpcsFile, int $stackPtr ) { + $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 one. + if ( '' !== Namespaces::determineNamespace( $phpcsFile, $stackPtr ) ) { + return; + } + $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; + } + // 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; + } + $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'] ] ); + } + + /** @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; + } + + /** 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 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 { + 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 { + 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/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/LinesReport.php b/compat-scanner/src/LinesReport.php index 81e31b6e..25dd350e 100644 --- a/compat-scanner/src/LinesReport.php +++ b/compat-scanner/src/LinesReport.php @@ -1,18 +1,16 @@ ","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":[<"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; +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; class LinesReport implements Report { @@ -22,31 +20,82 @@ 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', + 'PHPCompatibility.Constants.NewConstants.' => 'defined', + 'PHPCompatibility.Constants.RemovedConstants.' => 'defined', + ]; + + /** @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; - 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; + // The message names a namespaced class in full; the source mangles its `\`. + 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] ); + } + $message['class'] = strtolower( $kind[1] ) . " $name"; + } + // 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 ]; + $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; + } + } + $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; + $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; @@ -55,4 +104,90 @@ 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 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.' ) || 'defined' === $check ? 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 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, $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, $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 ); + } + + /** 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). + * + * @return string[] + */ + private function declared( File $phpcsFile ): array { + $tokens = $phpcsFile->getTokens(); + $names = []; + foreach ( $tokens as $ptr => $token ) { + // 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 ); + $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, $full ) ); + } + if ( $runs ) { + $names[] = ( T_INTERFACE === $token['code'] ? 'interface ' : 'class ' ) . strtolower( $full ); + } + } + 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; + $target = $this->target; + $covers = static fn ( $r ) => $r[0] <= $target[0] && $r[1] >= $target[1]; + foreach ( (array) $ops as $op ) { + if ( ! Guard::tests( $phpcsFile, $op, [ 'class_exists', 'interface_exists' ], $name, false, $covers ) ) { + return false; + } + } + return null !== $ops; + } } diff --git a/compat-scanner/src/native-classes.php b/compat-scanner/src/native-classes.php new file mode 100644 index 00000000..da3db9b5 --- /dev/null +++ b/compat-scanner/src/native-classes.php @@ -0,0 +1,50 @@ + [ '8.0', '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 new file mode 100644 index 00000000..08e09e35 --- /dev/null +++ b/compat-scanner/src/native-functions.php @@ -0,0 +1,44 @@ + '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', + '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', + 'stream_socket_get_crypto_status' => '8.6', +]; diff --git a/compat-scanner/tests/assert.php b/compat-scanner/tests/assert.php index 36cc323e..752d0089 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( @@ -204,7 +206,8 @@ 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' ); 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 ], [ 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' => 48 ], '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' ); @@ -260,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/current/wp-content/\S+\.php$#', $t['detail'] ?? '' ), 'timeout: detail names the file (' . ( $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 @@ -280,7 +285,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 @@ -288,7 +294,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" ); } @@ -309,6 +315,11 @@ 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, 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 @@ -358,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, (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' ); @@ -436,13 +449,24 @@ 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, 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 +499,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 +522,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 +564,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' ); @@ -582,7 +607,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' ], @@ -591,42 +616,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' ); -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' -); - +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' ); @@ -650,30 +648,29 @@ 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, 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 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)' ); +$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' ); @@ -735,14 +733,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' ); @@ -753,10 +751,17 @@ function finding_files( array $report ): array { // 20,000 not_checked entries in 10M of entrypoint memory: the manifest keeps no set of them. $pf = out( 'pharflood' ); eq( [ $pf['status'] ?? null, $pf['files_not_checked'] ?? null ], [ 'ok', 20000 ], 'pharflood: many not_checked entries in little memory' ); +$pi = out( 'pharflood-info' ); +eq( [ $pi['status'] ?? null, field( $pi, 'safe_to_upgrade' ), $pi['files_not_checked'] ?? null, count( report( 'pharflood-info' )['phars'] ?? [] ) ], [ 'ok', true, 0, 20000 ], 'pharflood-info: many phars kept as information in little memory' ); // ----------------------------------------------------------- file manifest -// 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 +$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' ); + +// 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' ); @@ -767,16 +772,22 @@ 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( [ $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)' ); @@ -788,13 +799,16 @@ 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; 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,19 +833,433 @@ 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)' ); eq( json_decode( raw( 'wpcfg-parent.manifest.json' ), true )['checked'] ?? null, [ '/var/www/wp-config.php', '/var/www/htdocs/wp-content/plugins/p/p.php' ], 'manifest: the parent wp-config.php WordPress loads is checked' ); $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']['root'] ?? null, '/var/www/htdocs/releases/1/', 'manifest: core root is the resolved WordPress root' ); +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' ); check( in_array( '/var/www/htdocs/releases/1/wp-content/plugins/hardlink/h1.php', $m['checked'] ?? [], true ) xor in_array( '/var/www/htdocs/releases/1/wp-content/plugins/hardlink/h2.php', $m['checked'] ?? [], true ), 'manifest: a hard-linked file is listed once' ); $m = json_decode( raw( 'nested.manifest.json' ), true ); eq( $m['not_checked'] ?? null, [ '/var/www/htdocs/old/', '/var/www/htdocs/wp-content/plugins/fakecore/' ], 'manifest: nested installs are directory entries' ); +// The whole of /var/www, and every install judged by its version. + +/** 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' : '' ); + }, + $all + ); +} + +/** [ status, verdict, errors, files_checked, files_not_checked ] of a run. */ +function counts( string $name ): array { + $d = out( $name ); + return [ $d['status'] ?? null, field( $d, 'safe_to_upgrade' ), $d['errors'] ?? null, $d['files_checked'] ?? null, $d['files_not_checked'] ?? null ]; +} + +$wa = report( 'wpapp' ); +eq( counts( 'wpapp' ), [ 'ok', false, 5, 7, 1 ], 'wpapp: everything in /var/www beside the WordPress root is scanned' ); +eq( finding_files( $wa ), [ 'directory:::.wp-cli/packages/vendor/x/legacy.php', 'directory:::adminer.php', 'directory:htdocs-backup::wp-content/plugins/q/q.php', 'directory:vendor::autoload.php', 'other:::uploads/u.php' ], 'wpapp: vendor/, adminer.php, the copy\'s plugin, a WP-CLI package; uploads/ by name only' ); +eq( $wa['not_checked'] ?? null, [ nc( 'directory', 'htdocs-backup', null, './', 'nested_wordpress' ) ], 'wpapp: the copy\'s 6.1 core isn\'t supported: nested_wordpress' ); +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' ); +$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( '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' ); +$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, 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, 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, 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' ); +eq( counts( 'extraroot' ), [ 'ok', false, 2, 3, 0 ], 'extraroot: uploads linked into a mounted dir is followed; the other mount is searched by name' ); +eq( finding_files( $er ), [ 'directory:/srv/shared::lib/y.inc', 'other:::uploads/2026/x.php' ], 'extraroot: findings by the link\'s path, and by the mount\'s' ); +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' ); + +$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" ); + $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' ); +eq( + array_column( report( 'require' )['not_checked'] ?? [], 'file' ), + [ '/usr/local/etc/php/xhprof.php', '/var/www/htdocs/wp-includes/version.php', '/var/www/htdocs/wp-cli.phar', '/var/www/htdocs/notes.txt', 'rel.php', 'waf.php', '/opt/append.php' ], + '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, 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' ); +$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 ); +eq( counts( 'userini' ), [ 'ok', null, 0, 1, 6 ], 'userini: every prepend target is unread' ); +$ui = report( 'userini' )['not_checked'] ?? []; +$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/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', '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"; + $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" ); +} +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' ); + +$li = report( 'lint' ); +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 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:$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 ); + $r = report( "native-$v" ); + $got = array_map( static function ( $f ) { return $f['file'] . ':' . $f['source']; }, comp_of( $r, 'plugin', 'p' )['findings'] ?? [] ); + sort( $got ); + $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 ) { + $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" ); +} +$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\.|Syntax\.ParseError\z)/', $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' ); + +// 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" ); +} + +// 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/autoloaded/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", + "acme/autoloaded/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/autoloaded/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" ], +]; +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" ); +} +// PHP 8.5 parses bootstrap85.php: only the unreadable sibling is an entry. +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)" ); +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 ( $useGuards as list( $id, $target, $php, $scanner ) ) { + $bad = ( 'reported' === $scanner ) !== isset( $reported[ $id ] ) || ( 'ok' !== $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" ); +} + +// Old polyfill stubs only a classmap loads, and the guarded current one, are quiet; a site's own Attribute isn't. +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', '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' => [], + '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 ` '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' ) ), [ '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" ); +} +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" ); +} +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 ` [], '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' ); + +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 ); +tool_error( 'badargs-short', 'bad arguments: COMPAT_SHORT_OPEN_TAG must be', 2, false ); +tool_error( 'badargs-locked', 'bad arguments: COMPAT_SHORT_OPEN_TAG_LOCKED must be', 2, false ); +eq( report( 'wpverout' )['wordpress_installs'] ?? null, [ [ 'dir' => '/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 b301856f..5191d45e 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" "/** @@ -83,10 +83,10 @@ function clean_plugin() { return 1; }' php_file "$wc/plugins/loop/loop.php" '/* Plugin Name: Loop */' ln -s /var/www/htdocs/current/wp-content/plugins/loop "$wc/plugins/loop/self" - # Syntax error plus a removed function: still tokenized and sniffed. - php_file "$wc/plugins/broken/broken.php" "/* Plugin Name: Broken */ + # A syntax error: the lint's finding. + [ "$errors" = 1 ] && php_file "$wc/plugins/broken/broken.php" "/* Plugin Name: Broken */ function broken( \$a, { -$( [ "$errors" = 1 ] && printf '%s' 'each( $a );' )" +each( \$a );" # PHPCS annotations are ignored: none of these hides the error. php_file "$wc/plugins/annotated/annotated.php" "/* Plugin Name: Annotated */ @@ -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' @@ -344,7 +345,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" @@ -427,6 +428,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 */ @@ -462,6 +465,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 );' @@ -597,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 );' @@ -644,7 +649,7 @@ cache_fixture() { printf '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" @@ -724,6 +729,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" @@ -791,16 +797,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() { @@ -808,7 +804,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" } @@ -821,3 +817,873 @@ 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" +} + +# 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" +} + +# 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 + 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}";' + # 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" +} + +# 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" +} + +# 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 a word starting `.phar`). +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';" ;; + 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) + printf " "$p/boot.php" + ;; + esac + 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() { + 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" + printf '

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

hi

\n "$p/views/unclosed.tpl" + 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() { + 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" + 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" +} + +# 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" +} + +# 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 + 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 );' + 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" +} + +# 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" +} + +# 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" +} + +# history_fixture : 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" +} + +# 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 + 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; }' + 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() {}' + 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/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 {} +}" + 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; } +function p_poly() {} +function p_poly() {}' + 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; 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" +} + +# 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" +} + +# 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" +} + +# 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" +} + +# 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" +} + +# 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 ` "$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" +} + +# 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" +} + +# shorttag_fixture : 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" + # 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" +} + +# 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" +} + +# 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" "$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; +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'; +}" + # 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'; +}" + # 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 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'; +}" + printf ' strlen(...);\n' > "$v/acme/gatetxt/broken.php" + 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). +shortrootoff_fixture() { + local h="$1/htdocs" f + 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" +} +# 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" +} +# 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" +} +# 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" +} +# 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/${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 );' + 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" +} +# 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 ` "$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 + 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" + 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/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/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();' + 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" +} +# 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" +} +# 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 new file mode 100644 index 00000000..583a34f9 --- /dev/null +++ b/compat-scanner/tests/guards.php @@ -0,0 +1,153 @@ + | 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();" ], + // 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-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 . ' }' ], + [ '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 . ' }' ], + [ '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; }" ], + // 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 . ' }' ], +]; + +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 = []; + } finally { + unlink( $tmp ); + } + } + echo "checked\n"; +} +return $rows; diff --git a/compat-scanner/tests/manifest-check.php b/compat-scanner/tests/manifest-check.php index bf417b72..093eb7f7 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,15 +73,25 @@ } 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; } $inodes[ $st['dev'] . ':' . $st['ino'] ] = true; } +// 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 ) ) || $template( $p ) ) ) { + $problems[] = "information entry not a phar or package template: $p"; + } +} $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 +110,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 +164,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 7475cc6a..191f4841 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. +# 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 ] && 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 + local out rc=0 mounts + 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 @@ -46,9 +54,9 @@ 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_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 @@ -72,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 @@ -114,9 +122,9 @@ 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 "$@" \ + -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" @@ -153,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. @@ -162,6 +171,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" @@ -176,7 +187,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 @@ -204,6 +216,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 @@ -212,6 +226,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 @@ -222,7 +241,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=$? @@ -275,9 +294,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 @@ -308,30 +324,292 @@ 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 +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" -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 +# 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 +# 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 +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 +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 +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" +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 +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. +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 + +# 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' + +# 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 \ + -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 + +# 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" +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 +phar_fixture "$WORK/phar-upper" upper +phar_fixture "$WORK/phar-split" split +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 +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. +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 +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 + +# 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 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 + +# symfony/polyfill files PHP never loads or runs on the target, and look-alikes it would. +polyfill_fixture "$WORK/polyfill" +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. +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 +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 +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 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 +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 r in htdocs htdocs/public; do + shortup_fixture "$WORK/shortup-${r##*/}" "$r" + scan "shortup-${r##*/}" "$WORK/shortup-${r##*/}" php /var/www/htdocs 8.0 600 -e COMPAT_SERVED="/var/www/$r" +done +# 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= +# 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 +for v in rels up project; do + rellink_fixture "$WORK/rellink-$v" "$v" + scan "rellink-$v" "$WORK/rellink-$v" php /var/www/htdocs/current/public 8.4 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 +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" +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" +# Many directory links and nothing a .user.ini set: the scan doesn't spend its time on the links. +dirlinks_fixture "$WORK/dirlinks" +scan dirlinks "$WORK/dirlinks" php /var/www/htdocs 8.4 10 +rm -rf "$WORK/dirlinks" + +# 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 +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 +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" \ --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/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-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-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-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/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-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'; +} 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; diff --git a/compat-scanner/tests/use-guards.php b/compat-scanner/tests/use-guards.php new file mode 100644 index 00000000..a01d0d90 --- /dev/null +++ b/compat-scanner/tests/use-guards.php @@ -0,0 +1,148 @@ + 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 );'; +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. + [ '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-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' ); }" ], + [ '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 . ' }' ], + [ '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 ], + // 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}" ], + // 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;" ], + [ '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 . ' }' ], + [ '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 ], + // 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(); }" ], + // 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();" ], + // 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. + [ '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(); }' ], +]; + +// 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'; + if ( $got !== $php ) { + echo "$id: PHP " . PHP_VERSION . " says $got, the table $php\n"; + } + $out = []; + } finally { + unlink( $tmp ); + } + } + echo "checked\n"; +} +return $rows;