#!/usr/bin/env bash
# shellcheck disable=SC2094  # we read config files; join_path does not write them
# check-php-security-release.sh: offline, read-only checker for the PHP 19 Nov 2026 security release
# (17 php-src advisories plus the uriparser bump listed in the 8.5.13 and 8.6.0 notes). Pack 1.0.0,
# CybaVerse threat hunt.
#
# It never runs php, never touches the network, never writes a file and never prints secrets or file
# contents. It reads only what you pass: a version string, saved php -v / php -i output, and php.ini,
# FPM pool, nginx, Apache or HAProxy files (and the files they include).
#
# Usage:
#   check-php-security-release.sh [--php-version 8.4.27] [--version-file php-v.txt] [--php-i-file php-i.txt]
#       [--ini FILE] [--fpm-pool FILE] [--nginx-conf FILE] [--apache-conf FILE] [--haproxy-conf FILE]
#   Config flags may be repeated.
#
# Exit codes:
#   0 FIXED             supported (or 8.6.0+) version is at or above the fixed build
#   1                   not used (reserved for unexpected runtime errors)
#   2 AFFECTED          a supported branch below the fixed build, or an 8.6 pre-release
#   3 REVIEW            version unknown, sources disagree, a newer undocumented branch, or a scan warning
#   4 EOL               PHP 8.1 or earlier (unsupported; treat as unfixed)
#   5 USAGE OR READ ERROR
set -u
export LC_ALL=C
VERSION_TAG="check-php-security-release 1.0.0"
MAX_FILES=256
MAX_SIZE=4194304
MAX_DEPTH=16

# CVE|score|rating|GHSA|title|min8.2|min8.3|min8.4|min8.5|min8.6pre
# min token: version or - (not applicable on that branch). 8.6 GA (8.6.0) is FIXED for every row.
DATA='CVE-2026-115560|9.2|Critical|GHSA-658j-r8rw-q6mx|Session serializer mismatch can lead to remote code execution|8.2.0|8.3.0|8.4.0|8.5.0|8.6.0
CVE-2026-126714|9.2|Critical|GHSA-fm2m-fjf5-v3cp|Partially overwritten session files can lead to remote code execution|8.2.0|8.3.0|8.4.0|8.5.0|8.6.0
CVE-2026-129182|9.2|Critical|GHSA-2fjv-p558-g82m|Use-after-free via last_fatal_error_backtrace after shutdown|-|-|-|8.5.0|8.6.0
CVE-2026-129289|9.2|Critical|GHSA-qc49-hpvq-g2w6|PHP-FPM request smuggling through an unread HTTP request body|8.2.0|8.3.0|8.4.0|8.5.0|8.6.0
CVE-2026-129474|9.2|Critical|GHSA-8mjj-2r7p-4hg2|Use-after-free in magic method backtraces can lead to remote code execution|-|-|-|8.5.0|8.6.0
CVE-2026-129481|9.2|Critical|GHSA-g3vh-838c-65v7|Use-after-free after interrupted session shutdown|-|8.3.0|8.4.0|8.5.0|8.6.0
CVE-2026-129496|9.2|Critical|GHSA-gr4f-wgx5-jpfv|Timezone cache use-after-free can lead to remote code execution|8.2.0|8.3.0|8.4.0|8.5.0|8.6.0
CVE-2026-129291|8.8|High|GHSA-jm4m-qfqx-967m|PHP-FPM epoll use-after-free can lead to local privilege escalation|8.2.7|8.3.0|8.4.0|8.5.0|8.6.0
CVE-2026-127960|8.7|High|GHSA-mmf9-xm3v-hg2x|Denial of service through folded HTTP response headers|8.2.28|8.3.18|8.4.5|8.5.0|8.6.0
CVE-2026-128064|8.2|High|GHSA-f6gg-rchx-xw8j|Mixed-case HTTPS and FTPS URLs can expose data in plaintext|8.2.0|8.3.0|8.4.0|8.5.0|8.6.0
CVE-2026-128090|7.7|High|GHSA-68fq-fh7h-f8gr|PHAR OpenSSL signature bypass via algorithm downgrade|8.2.0|8.3.0|8.4.0|8.5.0|8.6.0
CVE-2026-129538|6.9|Medium|GHSA-5j3f-64r7-f564|PHP-CGI out-of-bounds read and write during PATH_INFO correction|8.2.0|8.3.0|8.4.0|8.5.0|8.6.0
CVE-2026-129438|6.3|Medium|GHSA-mg3p-mxj9-g2mm|Incorrect RFC 3986 URI serialization for oversized input|-|-|-|8.5.0|8.6.0
CVE-2026-129501|6.3|Medium|GHSA-x8r7-mg3g-74hg|Double free during DOM XML serialization|-|-|8.4.0|8.5.0|8.6.0
CVE-2026-129506|6.3|Medium|GHSA-4646-p932-gw34|SOAP use-after-free when processing DTD entity references|8.2.0|8.3.0|8.4.0|8.5.0|8.6.0
CVE-2026-15353|6.3|Medium|GHSA-q23r-hr55-xmpg|SOAP information disclosure through malformed array dimensions|8.2.0|8.3.0|8.4.0|8.5.0|8.6.0
CVE-2026-129292|5.3|Medium|GHSA-3mg3-cr28-46gc|PHP-FPM status endpoint XSS via unescaped user and script fields|8.2.0|8.3.0|8.4.0|8.5.0|8.6.0'

usage() {
  printf '%s\n' "Usage: check-php-security-release.sh [--php-version 8.4.27] [--version-file FILE] [--php-i-file FILE]"
  printf '%s\n' "       [--ini FILE] [--fpm-pool FILE] [--nginx-conf FILE] [--apache-conf FILE] [--haproxy-conf FILE]"
  printf '%s\n' "Exit codes: 0 FIXED, 2 AFFECTED, 3 REVIEW, 4 EOL, 5 USAGE OR READ ERROR (1 not used)."
}

die_usage() { printf '%s\n' "ERROR: $1"; usage; exit 5; }

# Compare dotted numeric versions (missing parts = 0). 0 equal, 1 if $1>$2, 2 if $1<$2.
ver_cmp() {
  local a=$1 b=$2 i pa pb
  IFS=. read -r -a aa <<< "$a"
  IFS=. read -r -a bb <<< "$b"
  for i in 0 1 2 3; do
    pa=${aa[i]:-0}; pb=${bb[i]:-0}
    pa=${pa:-0}; pb=${pb:-0}
    if [ "$pa" -gt "$pb" ] 2>/dev/null; then return 1; fi
    if [ "$pa" -lt "$pb" ] 2>/dev/null; then return 2; fi
  done
  return 0
}
ver_ge() { ver_cmp "$1" "$2"; local r=$?; [ "$r" -eq 0 ] || [ "$r" -eq 1 ]; }
ver_lt() { ver_cmp "$1" "$2"; [ $? -eq 2 ]; }

# Parse a version out of a string or file text. Sets: PV_MAJOR PV_MINOR PV_PATCH PV_PRE PV_TEXT
# PV_PRE is empty for a final release, or the pre-release suffix (rc7, alpha1, beta3, dev).
# grep -E is used because bash [[ =~ ]] treats ">" in "=>" as a syntax error.
parse_version_text() {
  local text=$1 cand pre
  PV_MAJOR=""; PV_MINOR=""; PV_PATCH=""; PV_PRE=""; PV_TEXT=""
  cand=$(printf '%s\n' "$text" | grep -Eo 'PHP[[:space:]]+Version[[:space:]]*=+>[[:space:]]*[0-9]+\.[0-9]+\.[0-9]+[A-Za-z0-9._+-]*' | head -n1)
  if [ -z "$cand" ]; then
    cand=$(printf '%s\n' "$text" | grep -Eo '(^|[^A-Za-z0-9])PHP[[:space:]]+[0-9]+\.[0-9]+\.[0-9]+[A-Za-z0-9._+-]*' | head -n1)
  fi
  if [ -z "$cand" ]; then
    cand=$(printf '%s\n' "$text" | grep -Eo '[0-9]+\.[0-9]+\.[0-9]+[A-Za-z0-9._+-]*' | head -n1)
  fi
  [ -n "$cand" ] || return 1
  # Isolate the x.y.z plus optional suffix
  cand=$(printf '%s\n' "$cand" | grep -Eo '[0-9]+\.[0-9]+\.[0-9]+[A-Za-z0-9._+-]*' | head -n1)
  PV_MAJOR=${cand%%.*}
  rest=${cand#*.}
  PV_MINOR=${rest%%.*}
  rest=${rest#*.}
  PV_PATCH=${rest}
  PV_PRE=""
  # Split patch from suffix: 27, 27RC7, 27-1ubuntu, 27+debian, 0RC7, 0-dev
  if [[ $PV_PATCH =~ ^([0-9]+)(.*)$ ]]; then
    PV_PATCH=${BASH_REMATCH[1]}
    PV_PRE=${BASH_REMATCH[2]}
  fi
  # Distro suffix -1ubuntu0.1 or +debian is not a pre-release.
  if [[ $PV_PRE =~ ^[+-] ]]; then PV_PRE=""; fi
  if [ -n "$PV_PRE" ]; then
    pre=$(printf '%s' "$PV_PRE" | tr '[:upper:]' '[:lower:]')
    pre=${pre#-}
    PV_PRE=$pre
  fi
  PV_TEXT="${PV_MAJOR}.${PV_MINOR}.${PV_PATCH}"
  [ -z "$PV_PRE" ] || PV_TEXT="${PV_TEXT}${PV_PRE}"
  return 0
}

is_prerelease() {
  [ -n "${PV_PRE:-}" ] || return 1
  case $PV_PRE in rc*|alpha*|beta*|dev*|pre*) return 0 ;; *) return 0 ;; esac
}

fixed_for_branch() {
  case "$1.$2" in
    8.6) printf '%s\n' "8.6.0" ;;
    8.5) printf '%s\n' "8.5.13" ;;
    8.4) printf '%s\n' "8.4.28" ;;
    8.3) printf '%s\n' "8.3.37" ;;
    8.2) printf '%s\n' "8.2.36" ;;
    *) printf '%s\n' "" ;;
  esac
}

# --- args ---
PHP_VERSION=""
VERSION_FILE=""
PHP_I_FILE=""
INI_FILES=()
FPM_FILES=()
NGINX_FILES=()
APACHE_FILES=()
HAPROXY_FILES=()

if [ "$#" -eq 0 ]; then usage; exit 5; fi
while [ "$#" -gt 0 ]; do
  case $1 in
    --php-version|-PhpVersion) [ "$#" -ge 2 ] || die_usage "missing value for $1"; PHP_VERSION=$2; shift 2 ;;
    --version-file|-VersionFile) [ "$#" -ge 2 ] || die_usage "missing value for $1"; VERSION_FILE=$2; shift 2 ;;
    --php-i-file|-PhpIFile) [ "$#" -ge 2 ] || die_usage "missing value for $1"; PHP_I_FILE=$2; shift 2 ;;
    --ini|-Ini) [ "$#" -ge 2 ] || die_usage "missing value for $1"; INI_FILES+=("$2"); shift 2 ;;
    --fpm-pool|-FpmPool) [ "$#" -ge 2 ] || die_usage "missing value for $1"; FPM_FILES+=("$2"); shift 2 ;;
    --nginx-conf|-NginxConf) [ "$#" -ge 2 ] || die_usage "missing value for $1"; NGINX_FILES+=("$2"); shift 2 ;;
    --apache-conf|-ApacheConf) [ "$#" -ge 2 ] || die_usage "missing value for $1"; APACHE_FILES+=("$2"); shift 2 ;;
    --haproxy-conf|-HaproxyConf) [ "$#" -ge 2 ] || die_usage "missing value for $1"; HAPROXY_FILES+=("$2"); shift 2 ;;
    -h|--help) usage; exit 5 ;;
    *) die_usage "unknown option $1" ;;
  esac
done

# --- helpers ---
readable() {
  [ -f "$1" ] && [ -r "$1" ]
}

file_size() {
  wc -c < "$1" | tr -d ' '
}

# Lowercase a token
lc() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; }

is_true() {
  case $(lc "$1") in
    1|on|yes|true|enable|enabled) return 0 ;;
    *) return 1 ;;
  esac
}
is_false() {
  case $(lc "$1") in
    0|off|no|false|disable|disabled|none|"" ) return 0 ;;
    *) return 1 ;;
  esac
}

secret_value() {
  local v=$1
  case $v in
    *CANARY_SECRET*|*Bearer*|[Pp]assword=*|[Aa][Pp][Ii]_[Kk][Ee][Yy]*|[Ss]ecret*|[Tt]oken*|*BEGIN\ *) return 0 ;;
  esac
  return 1
}

safe_val() {
  if secret_value "$1"; then printf '%s' "(value withheld)"; else printf '%s' "$1"; fi
}

REVIEW=0
NFILES=0
FLAGS=()
NOTES=()
declare -A SEEN
SEEN=()

add_flag() { FLAGS+=("$1"); }
add_note() { NOTES+=("$1"); }
mark_review() { REVIEW=1; }

# Strip a php.ini / FPM style comment (; or #) outside quotes, crudely.
strip_ini_comment() {
  local s=$1 out="" i c q=""
  for ((i=0; i<${#s}; i++)); do
    c=${s:i:1}
    if [ -n "$q" ]; then
      out+=$c
      if [ "$c" = "$q" ]; then q=""; fi
    else
      if [ "$c" = "'" ] || [ "$c" = '"' ]; then q=$c; out+=$c
      elif [ "$c" = ";" ] || [ "$c" = "#" ]; then break
      else out+=$c
      fi
    fi
  done
  printf '%s' "$out"
}

# Nginx / Apache / HAProxy: strip unquoted #
strip_hash_comment() {
  local s=$1 out="" i c q=""
  for ((i=0; i<${#s}; i++)); do
    c=${s:i:1}
    if [ -n "$q" ]; then
      out+=$c
      if [ "$c" = "$q" ]; then q=""; fi
    else
      if [ "$c" = "'" ] || [ "$c" = '"' ]; then q=$c; out+=$c
      elif [ "$c" = "#" ]; then break
      else out+=$c
      fi
    fi
  done
  printf '%s' "$out"
}

# Expand a glob (or a literal path) in C locale, skip hidden basenames, sort.
expand_glob() {
  local pattern=$1
  # If no glob chars, just echo if it exists as a file.
  case $pattern in
    *[\*\?\[]*) ;;
    *)
      if [ -f "$pattern" ]; then printf '%s\n' "$pattern"; fi
      return
      ;;
  esac
  # Use bash globbing
  local matches=()
  shopt -s nullglob
  # shellcheck disable=SC2206
  matches=($pattern)
  shopt -u nullglob
  if [ "${#matches[@]}" -eq 0 ]; then return; fi
  local m b
  for m in "${matches[@]}"; do
    b=$(basename -- "$m")
    case $b in .*) continue ;; esac
    [ -f "$m" ] || continue
    printf '%s\n' "$m"
  done | LC_ALL=C sort
}

join_path() {
  local parent=$1 rel=$2
  case $rel in
    /*) printf '%s\n' "$rel" ;;
    *) printf '%s\n' "$(dirname -- "$parent")/$rel" ;;
  esac
}

scan_ini_or_fpm() {
  local file=$1 kind=$2 depth=$3
  local path_key
  path_key=$file
  if [ -n "${SEEN[$path_key]:-}" ]; then return; fi
  SEEN[$path_key]=1
  if ! readable "$file"; then
    add_note "UNREADABLE: $file"
    mark_review
    return
  fi
  local sz
  sz=$(file_size "$file")
  if [ "$sz" -gt "$MAX_SIZE" ]; then
    add_note "OVERSIZE: $file"
    mark_review
    return
  fi
  NFILES=$((NFILES + 1))
  if [ "$NFILES" -gt "$MAX_FILES" ]; then
    add_note "FILE LIMIT reached ($MAX_FILES)"
    mark_review
    return
  fi
  local lineno=0 raw line key val
  while IFS= read -r raw || [ -n "$raw" ]; do
    lineno=$((lineno + 1))
    line=$(strip_ini_comment "$raw")
    # trim
    line=${line#"${line%%[![:space:]]*}"}
    line=${line%"${line##*[![:space:]]}"}
    [ -n "$line" ] || continue
    # include= for FPM (and rare ini includes)
    if [[ $line =~ ^[Ii][Nn][Cc][Ll][Uu][Dd][Ee][[:space:]]*=[[:space:]]*(.*)$ ]]; then
      local inc=${BASH_REMATCH[1]}
      inc=${inc#\"}; inc=${inc%\"}; inc=${inc#\'}; inc=${inc%\'}
      inc=${inc#"${inc%%[![:space:]]*}"}
      inc=${inc%"${inc##*[![:space:]]}"}
      if [ "$depth" -ge "$MAX_DEPTH" ]; then
        add_note "INCLUDE DEPTH limit: $inc"
        mark_review
      else
        local resolved found=0 p
        resolved=$(join_path "$file" "$inc")
        while IFS= read -r p; do
          [ -n "$p" ] || continue
          found=1
          scan_ini_or_fpm "$p" "$kind" $((depth + 1))
        done < <(expand_glob "$resolved")
        if [ "$found" -eq 0 ]; then
          add_note "MISSING INCLUDE: $resolved"
          mark_review
        fi
      fi
      continue
    fi
    # setting = value  or setting=value
    if [[ $line =~ ^([A-Za-z0-9_.]+)[[:space:]]*=[[:space:]]*(.*)$ ]]; then
      key=$(lc "${BASH_REMATCH[1]}")
      val=${BASH_REMATCH[2]}
      val=${val#\"}; val=${val%\"}; val=${val#\'}; val=${val%\'}
      val=${val#"${val%%[![:space:]]*}"}
      val=${val%"${val##*[![:space:]]}"}
      case $key in
        session.upload_progress.enabled)
          add_flag "FLAG session.upload_progress.enabled $file:$lineno $(safe_val "$val")"
          ;;
        session.save_handler)
          add_flag "FLAG session.save_handler $file:$lineno $(safe_val "$val")"
          ;;
        session.serialize_handler)
          add_flag "FLAG session.serialize_handler $file:$lineno $(safe_val "$val")"
          ;;
        zend.exception_ignore_args)
          add_flag "FLAG zend.exception_ignore_args $file:$lineno $(safe_val "$val")"
          ;;
        auto_prepend_file)
          if ! is_false "$val"; then
            add_flag "FLAG auto_prepend_file $file:$lineno $(safe_val "$val")"
          fi
          ;;
        allow_url_include)
          if is_true "$val"; then
            add_flag "FLAG allow_url_include $file:$lineno $(safe_val "$val")"
          fi
          ;;
        catch_workers_output)
          if is_true "$val"; then
            add_flag "FLAG catch_workers_output $file:$lineno $(safe_val "$val")"
          fi
          ;;
        cgi.fix_pathinfo)
          add_flag "FLAG cgi.fix_pathinfo $file:$lineno $(safe_val "$val")"
          ;;
        fatal_error_backtraces)
          add_flag "FLAG fatal_error_backtraces $file:$lineno $(safe_val "$val")"
          ;;
      esac
    fi
  done < "$file"
}

scan_nginx() {
  local file=$1 depth=$2
  if [ -n "${SEEN[$file]:-}" ]; then return; fi
  SEEN[$file]=1
  if ! readable "$file"; then
    add_note "UNREADABLE: $file"; mark_review; return
  fi
  local sz; sz=$(file_size "$file")
  if [ "$sz" -gt "$MAX_SIZE" ]; then add_note "OVERSIZE: $file"; mark_review; return; fi
  NFILES=$((NFILES + 1))
  if [ "$NFILES" -gt "$MAX_FILES" ]; then add_note "FILE LIMIT reached ($MAX_FILES)"; mark_review; return; fi
  local lineno=0 raw line
  while IFS= read -r raw || [ -n "$raw" ]; do
    lineno=$((lineno + 1))
    line=$(strip_hash_comment "$raw")
    line=${line#"${line%%[![:space:]]*}"}
    line=${line%"${line##*[![:space:]]}"}
    [ -n "$line" ] || continue
    if [[ $line =~ ^include[[:space:]]+(.+)$ ]]; then
      local inc=${BASH_REMATCH[1]}
      inc=${inc%;}
      inc=${inc#"${inc%%[![:space:]]*}"}
      inc=${inc%"${inc##*[![:space:]]}"}
      inc=${inc#\"}; inc=${inc%\"}; inc=${inc#\'}; inc=${inc%\'}
      if [ "$depth" -ge "$MAX_DEPTH" ]; then
        add_note "INCLUDE DEPTH limit: $inc"; mark_review
      else
        local resolved found=0 p
        resolved=$(join_path "$file" "$inc")
        while IFS= read -r p; do
          [ -n "$p" ] || continue
          found=1
          scan_nginx "$p" $((depth + 1))
        done < <(expand_glob "$resolved")
        if [ "$found" -eq 0 ]; then add_note "MISSING INCLUDE: $resolved"; mark_review; fi
      fi
      continue
    fi
    # fastcgi_keep_conn on;
    local low; low=$(lc "$line")
    if [[ $low =~ ^fastcgi_keep_conn[[:space:]]+([^;]+) ]]; then
      local v=${BASH_REMATCH[1]}
      v=${v#"${v%%[![:space:]]*}"}; v=${v%"${v##*[![:space:]]}"}
      if is_true "$v"; then
        add_flag "FLAG fastcgi_keep_conn $file:$lineno $v"
      fi
    fi
  done < "$file"
}

scan_apache() {
  local file=$1 depth=$2
  if [ -n "${SEEN[$file]:-}" ]; then return; fi
  SEEN[$file]=1
  if ! readable "$file"; then add_note "UNREADABLE: $file"; mark_review; return; fi
  local sz; sz=$(file_size "$file")
  if [ "$sz" -gt "$MAX_SIZE" ]; then add_note "OVERSIZE: $file"; mark_review; return; fi
  NFILES=$((NFILES + 1))
  if [ "$NFILES" -gt "$MAX_FILES" ]; then add_note "FILE LIMIT reached ($MAX_FILES)"; mark_review; return; fi
  local lineno=0 raw line
  while IFS= read -r raw || [ -n "$raw" ]; do
    lineno=$((lineno + 1))
    line=$(strip_hash_comment "$raw")
    line=${line#"${line%%[![:space:]]*}"}
    line=${line%"${line##*[![:space:]]}"}
    [ -n "$line" ] || continue
    local low; low=$(lc "$line")
    if [[ $low =~ ^include(optional)?[[:space:]]+(.+)$ ]]; then
      local inc=${BASH_REMATCH[2]}
      inc=${inc#"${inc%%[![:space:]]*}"}; inc=${inc%"${inc##*[![:space:]]}"}
      inc=${inc#\"}; inc=${inc%\"}; inc=${inc#\'}; inc=${inc%\'}
      local optional=0
      [[ $low =~ ^includeoptional ]] && optional=1
      if [ "$depth" -ge "$MAX_DEPTH" ]; then
        add_note "INCLUDE DEPTH limit: $inc"; mark_review
      else
        local resolved found=0 p
        resolved=$(join_path "$file" "$inc")
        while IFS= read -r p; do
          [ -n "$p" ] || continue
          found=1
          scan_apache "$p" $((depth + 1))
        done < <(expand_glob "$resolved")
        if [ "$found" -eq 0 ] && [ "$optional" -eq 0 ]; then
          add_note "MISSING INCLUDE: $resolved"; mark_review
        fi
      fi
      continue
    fi
    # enablereuse=on (ProxyPass / balancer / SetEnv)
    if [[ $low =~ enablereuse[[:space:]]*=[[:space:]]*([a-z0-9]+) ]]; then
      local v=${BASH_REMATCH[1]}
      if is_true "$v"; then
        add_flag "FLAG enablereuse $file:$lineno $v"
      fi
    fi
  done < "$file"
}

scan_haproxy() {
  local file=$1 depth=$2
  if [ -n "${SEEN[$file]:-}" ]; then return; fi
  SEEN[$file]=1
  if ! readable "$file"; then add_note "UNREADABLE: $file"; mark_review; return; fi
  local sz; sz=$(file_size "$file")
  if [ "$sz" -gt "$MAX_SIZE" ]; then add_note "OVERSIZE: $file"; mark_review; return; fi
  NFILES=$((NFILES + 1))
  if [ "$NFILES" -gt "$MAX_FILES" ]; then add_note "FILE LIMIT reached ($MAX_FILES)"; mark_review; return; fi
  local lineno=0 raw line
  while IFS= read -r raw || [ -n "$raw" ]; do
    lineno=$((lineno + 1))
    line=$(strip_hash_comment "$raw")
    line=${line#"${line%%[![:space:]]*}"}
    line=${line%"${line##*[![:space:]]}"}
    [ -n "$line" ] || continue
    local low; low=$(lc "$line")
    if [[ $low =~ (^|[[:space:]])include[[:space:]]+(.+)$ ]]; then
      local inc=${BASH_REMATCH[2]}
      inc=${inc#"${inc%%[![:space:]]*}"}; inc=${inc%"${inc##*[![:space:]]}"}
      inc=${inc#\"}; inc=${inc%\"}
      if [ "$depth" -ge "$MAX_DEPTH" ]; then
        add_note "INCLUDE DEPTH limit: $inc"; mark_review
      else
        local resolved found=0 p
        resolved=$(join_path "$file" "$inc")
        while IFS= read -r p; do
          [ -n "$p" ] || continue
          found=1
          scan_haproxy "$p" $((depth + 1))
        done < <(expand_glob "$resolved")
        if [ "$found" -eq 0 ]; then add_note "MISSING INCLUDE: $resolved"; mark_review; fi
      fi
      continue
    fi
    if [[ $low =~ (^|[[:space:]])(fcgi-app|use-fcgi-app)($|[[:space:]]) ]] || [[ $low =~ proto[[:space:]]+fcgi($|[[:space:]]) ]]; then
      add_flag "FLAG haproxy_fcgi $file:$lineno present"
    fi
  done < "$file"
}

# --- version ---
declare -a VER_SOURCES
add_ver_source() { VER_SOURCES+=("$1|$2"); }

if [ -n "$PHP_VERSION" ]; then
  if parse_version_text "$PHP_VERSION"; then
    add_ver_source "$PV_TEXT" "--php-version"
  else
    printf '%s\n' "ERROR: could not parse --php-version '$PHP_VERSION'"
    exit 5
  fi
fi
if [ -n "$VERSION_FILE" ]; then
  readable "$VERSION_FILE" || die_usage "cannot read --version-file $VERSION_FILE"
  if parse_version_text "$(cat -- "$VERSION_FILE")"; then
    add_ver_source "$PV_TEXT" "--version-file $VERSION_FILE"
  else
    printf '%s\n' "ERROR: no PHP version found in --version-file $VERSION_FILE"
    exit 5
  fi
fi
if [ -n "$PHP_I_FILE" ]; then
  readable "$PHP_I_FILE" || die_usage "cannot read --php-i-file $PHP_I_FILE"
  if parse_version_text "$(cat -- "$PHP_I_FILE")"; then
    add_ver_source "$PV_TEXT" "--php-i-file $PHP_I_FILE"
  else
    printf '%s\n' "ERROR: no PHP version found in --php-i-file $PHP_I_FILE"
    exit 5
  fi
fi

# Disagreement?
VER_TEXT=""
VER_FROM=""
if [ "${#VER_SOURCES[@]}" -gt 0 ]; then
  local_first=${VER_SOURCES[0]}
  VER_TEXT=${local_first%%|*}
  VER_FROM=${local_first#*|}
  for s in "${VER_SOURCES[@]}"; do
    if [ "${s%%|*}" != "$VER_TEXT" ]; then
      add_note "VERSION DISAGREES: ${s#*|} has ${s%%|*} (also $VER_FROM has $VER_TEXT)"
      mark_review
    fi
  done
  parse_version_text "$VER_TEXT" || true
fi

HAS_CONFIG=0
if [ "${#INI_FILES[@]}" -gt 0 ] || [ "${#FPM_FILES[@]}" -gt 0 ] || [ "${#NGINX_FILES[@]}" -gt 0 ] || [ "${#APACHE_FILES[@]}" -gt 0 ] || [ "${#HAPROXY_FILES[@]}" -gt 0 ]; then
  HAS_CONFIG=1
fi
if [ -z "$VER_TEXT" ] && [ "$HAS_CONFIG" -eq 0 ]; then
  die_usage "provide a version (--php-version, --version-file or --php-i-file) and/or config files"
fi

# Scan configs
for f in "${INI_FILES[@]+"${INI_FILES[@]}"}"; do
  [ -n "$f" ] || continue
  readable "$f" || { printf '%s\n' "ERROR: cannot read --ini $f"; exit 5; }
  scan_ini_or_fpm "$f" ini 0
done
for f in "${FPM_FILES[@]+"${FPM_FILES[@]}"}"; do
  [ -n "$f" ] || continue
  readable "$f" || { printf '%s\n' "ERROR: cannot read --fpm-pool $f"; exit 5; }
  scan_ini_or_fpm "$f" fpm 0
done
for f in "${NGINX_FILES[@]+"${NGINX_FILES[@]}"}"; do
  [ -n "$f" ] || continue
  readable "$f" || { printf '%s\n' "ERROR: cannot read --nginx-conf $f"; exit 5; }
  scan_nginx "$f" 0
done
for f in "${APACHE_FILES[@]+"${APACHE_FILES[@]}"}"; do
  [ -n "$f" ] || continue
  readable "$f" || { printf '%s\n' "ERROR: cannot read --apache-conf $f"; exit 5; }
  scan_apache "$f" 0
done
for f in "${HAPROXY_FILES[@]+"${HAPROXY_FILES[@]}"}"; do
  [ -n "$f" ] || continue
  readable "$f" || { printf '%s\n' "ERROR: cannot read --haproxy-conf $f"; exit 5; }
  scan_haproxy "$f" 0
done

# --- classify version ---
BRANCH_STATUS="REVIEW"
BRANCH_LABEL="unknown"
FIX_BUILD=""
if [ -n "$VER_TEXT" ]; then
  BRANCH_LABEL="${PV_MAJOR}.${PV_MINOR}"
  if [ "$PV_MAJOR" -lt 8 ] 2>/dev/null || { [ "$PV_MAJOR" -eq 8 ] && [ "$PV_MINOR" -le 1 ]; }; then
    BRANCH_STATUS="EOL"
    FIX_BUILD=""
  elif [ "$PV_MAJOR" -eq 8 ] && [ "$PV_MINOR" -ge 2 ] && [ "$PV_MINOR" -le 6 ]; then
    FIX_BUILD=$(fixed_for_branch "$PV_MAJOR" "$PV_MINOR")
    if is_prerelease; then
      # 8.6.0RC7 is before 8.6.0; any pre-release of a fixed-or-lower patch is AFFECTED.
      # A pre-release of a later patch (8.6.1RC1) is REVIEW.
      if ver_lt "${PV_MAJOR}.${PV_MINOR}.${PV_PATCH}" "$FIX_BUILD" || [ "${PV_MAJOR}.${PV_MINOR}.${PV_PATCH}" = "$FIX_BUILD" ]; then
        BRANCH_STATUS="AFFECTED"
      else
        BRANCH_STATUS="REVIEW"
      fi
    else
      if ver_ge "${PV_MAJOR}.${PV_MINOR}.${PV_PATCH}" "$FIX_BUILD"; then
        BRANCH_STATUS="FIXED"
      else
        BRANCH_STATUS="AFFECTED"
      fi
    fi
  else
    # 8.7+ or 9.x: not listed in the 19 Nov advisories
    BRANCH_STATUS="REVIEW"
  fi
else
  BRANCH_STATUS="REVIEW"
  mark_review
fi

# Per-CVE status
cve_status() {
  # args: min82 min83 min84 min85 min86pre
  local min82=$1 min83=$2 min84=$3 min85=$4 min86=$5
  if [ -z "$VER_TEXT" ]; then printf '%s\n' "REVIEW"; return; fi
  if [ "$BRANCH_STATUS" = "REVIEW" ] && { [ "$PV_MAJOR" -ne 8 ] || [ "$PV_MINOR" -gt 6 ]; }; then
    printf '%s\n' "REVIEW"; return
  fi
  local min="-"
  if [ "$PV_MAJOR" -eq 8 ] && [ "$PV_MINOR" -eq 2 ]; then min=$min82
  elif [ "$PV_MAJOR" -eq 8 ] && [ "$PV_MINOR" -eq 3 ]; then min=$min83
  elif [ "$PV_MAJOR" -eq 8 ] && [ "$PV_MINOR" -eq 4 ]; then min=$min84
  elif [ "$PV_MAJOR" -eq 8 ] && [ "$PV_MINOR" -eq 5 ]; then min=$min85
  elif [ "$PV_MAJOR" -eq 8 ] && [ "$PV_MINOR" -eq 6 ]; then min=$min86
  elif [ "$BRANCH_STATUS" = "EOL" ]; then
    # Unsupported: treat as AFFECTED when a lower bound exists on 8.2 (same defect family).
    if [ "$min82" != "-" ]; then printf '%s\n' "AFFECTED"; else printf '%s\n' "REVIEW"; fi
    return
  else
    printf '%s\n' "REVIEW"; return
  fi
  if [ "$min" = "-" ]; then printf '%s\n' "NOT APPLICABLE"; return; fi
  if [ "$BRANCH_STATUS" = "FIXED" ]; then printf '%s\n' "FIXED"; return; fi
  if [ "$BRANCH_STATUS" = "AFFECTED" ]; then
    if is_prerelease && [ "${PV_MAJOR}.${PV_MINOR}.${PV_PATCH}" = "$FIX_BUILD" ]; then
      printf '%s\n' "AFFECTED"; return
    fi
    if ver_lt "${PV_MAJOR}.${PV_MINOR}.${PV_PATCH}" "$min"; then
      printf '%s\n' "NOT APPLICABLE"
    else
      printf '%s\n' "AFFECTED"
    fi
    return
  fi
  if [ "$BRANCH_STATUS" = "REVIEW" ]; then printf '%s\n' "REVIEW"; return; fi
  printf '%s\n' "REVIEW"
}

# --- overall ---
OVERALL=$BRANCH_STATUS
EXIT=3
if [ -z "$VER_TEXT" ]; then OVERALL="REVIEW"; EXIT=3
elif [ "$REVIEW" -eq 1 ] && [ "$BRANCH_STATUS" = "FIXED" ]; then OVERALL="REVIEW"; EXIT=3
elif [ "$BRANCH_STATUS" = "FIXED" ]; then OVERALL="FIXED"; EXIT=0
elif [ "$BRANCH_STATUS" = "AFFECTED" ]; then OVERALL="AFFECTED"; EXIT=2
elif [ "$BRANCH_STATUS" = "EOL" ]; then OVERALL="EOL"; EXIT=4
else OVERALL="REVIEW"; EXIT=3
fi

# --- output ---
printf '%s\n' "$VERSION_TAG"
printf '%s\n' "PHP 19 Nov 2026 security release checker (read only)"
if [ -n "$VER_TEXT" ]; then
  printf '%s\n' "INPUT version: $VER_TEXT (from $VER_FROM)"
  printf '%s\n' "BRANCH: $BRANCH_LABEL"
  printf '%s\n' "VERSION STATUS: $BRANCH_STATUS"
else
  printf '%s\n' "INPUT version: (none supplied)"
  printf '%s\n' "BRANCH: unknown"
  printf '%s\n' "VERSION STATUS: REVIEW"
fi
printf '%s\n' "FIXED BUILDS: 8.2.36, 8.3.37, 8.4.28, 8.5.13, 8.6.0"
printf '%s\n' "CVE source: PHP GHSA advisories published 19 Nov 2026. 8.6.0 fix list: php-src NEWS for PHP 8.6.0."
printf '%s\n' ""
while IFS= read -r row; do
  [ -n "$row" ] || continue
  IFS='|' read -r cve score rating ghsa title min82 min83 min84 min85 min86 <<< "$row"
  st=$(cve_status "$min82" "$min83" "$min84" "$min85" "$min86")
  printf '%s\n' "CVE $cve $st  CVSS 4.0 $score $rating  $ghsa  $title"
done <<< "$DATA"
printf '%s\n' ""
printf '%s\n' "CONFIG: files read $NFILES"
if [ "${#FLAGS[@]}" -gt 0 ]; then
  printf '%s\n' "${FLAGS[@]}" | LC_ALL=C sort
else
  printf '%s\n' "CONFIG: no relevant flags found in scanned files"
fi
if [ "${#NOTES[@]}" -gt 0 ]; then
  printf '%s\n' "${NOTES[@]}"
fi
printf '%s\n' ""
if [ "$BRANCH_STATUS" = "FIXED" ]; then
  printf '%s\n' "FIX: this branch is at or above the 19 Nov 2026 fixed build ($FIX_BUILD). Restart every PHP worker after the upgrade. Confirm the running worker, not only the package, reports the fixed version."
elif [ "$BRANCH_STATUS" = "AFFECTED" ]; then
  printf '%s\n' "FIX: upgrade this branch to $FIX_BUILD (or to 8.6.0 if you are moving to 8.6). Patch now regardless of KEV status."
  printf '%s\n' "INTERIM (PHP, until patched): set session.upload_progress.enabled=0 administratively and restart workers; disable FastCGI keep-alive or connection reuse (leave nginx fastcgi_keep_conn off, leave Apache enablereuse off, close HAProxy FastCGI backends after each request); use php.ini-production defaults (zend.exception_ignore_args=1). On PHP 8.5, fatal_error_backtraces=0 is the advertised workaround for CVE-2026-129182 and also blocks the CVE-2026-129474 path. For CVE-2026-129291, disable catch_workers_output in affected FPM pools. For CVE-2026-129538, cgi.fix_pathinfo=0 is a workaround for php-cgi only."
elif [ "$BRANCH_STATUS" = "EOL" ]; then
  printf '%s\n' "FIX: this PHP branch is end of life (PHP 8.1 and earlier). PHP does not ship fixes for it. Upgrade to a supported fixed build: 8.2.36, 8.3.37, 8.4.28, 8.5.13 or 8.6.0. Apply the same interim settings where the process still runs."
else
  printf '%s\n' "FIX: version could not be placed on a documented branch. Confirm the running PHP version and compare it with 8.2.36, 8.3.37, 8.4.28, 8.5.13 or 8.6.0. Patch now if it is below those builds."
fi
printf '%s\n' "OVERALL: $OVERALL (exit $EXIT)"
exit "$EXIT"
