Back to documentation

Class: UploadGuard

__construct ($config = array())

@param array $config avMode (clamd|clamscan|skip; skip only with env UPLOAD_GUARD_ENV=test|dev),
clamd (socket|host,port,timeoutMs), clamscan (binary, dbDir, lockFile, timeoutMs, lockWaitMs,
maxDbAgeHours), auditLog, policyDir, tmpDir, onScannerDown, maxDbAgeHours (72, clamd only),
maxEntryBytes (5 MiB)
@throws InvalidArgumentException on an invalid avMode (the only thing the constructor validates)

cleanup ()

Remove temporary directories created by this instance (sanitized files not yet finalized).

cmpLenDesc ($a, $b)

:convertHeicToJpeg ($path, $opts = array())

csvSafeCell ($cell)

Neutralise a spreadsheet cell for CSV/XLSX export (formula injection).

extractText ($path, $type, $claimedName = '')

Text that would be sent to a model for an inspected file (name + metadata + body), capped.

finalize ($verdict, $destDir, $originalPath = null)

Move/write an accepted file into $destDir under a random name; returns the stored path.
$originalPath is only needed for an 'accept' verdict of a different guard instance.

:findExecutable ($name)

foldCb ($m)

inspect ($path, $claimed = array(), $profile = '', $context = array())

Inspect a file that is already stored temporarily outside the webroot.
Never throws; any internal failure produces a reject verdict (fail closed).

inspectMany ($items)

Batch API: items = array(array('path' =>, 'claimed' =>, 'profile' =>, 'context' =>), ...); returns the verdicts in the
same order. S0-S4 run per item, then ALL pending files go through ONE AV phase (avMode clamscan: one clamscan run,
one database load), then S6/S7 per item; one audit line per item. Never throws.

pdfHexCb ($m)

pdfNameCb ($m)

:procRun ($argv, $timeoutMs, $capture)

:randomBytes ($n)

rtfHexCb ($m)

scanText ($text, $opts = array())

Heuristic scan of untrusted text. Returns array(score, findings, cleaned, level ok|flag|high).

unescCb ($m)

wrapUntrusted ($text, $label = 'data')

Wrap untrusted text for a prompt in a block with a random nonce (spec 6.3).


audit ($v, $profile, $claimed, $context, $warnings = array())

avClamd (&$j)

avClamscan (&$jobs, $todo)

avMode clamscan: all files of all pending jobs (main files and unpacked zip entries) in ONE clamscan run.

avPhase (&$jobs)

S5 for every job that survived S1-S4: known-bad list, then clamd per item or ONE clamscan run for the batch.

badZipName ($n)

bmffImageOk ($path, $size)

heic / heif / avif box tree (spec 5, mirrors bmff.py): top-level boxes add up exactly to the file size, ftyp first and
well-formed (size >= 16, (size-16) % 4 == 0), exactly one meta; meta (full box) and iprp/ipco/dinf are walked with the
same rule. Caps: 64 top-level boxes, 4096 in total, depth 6. Reads headers only.

bmffWalk ($fp, $start, $end, $depth, $top, &$counter, &$kinds)

boxEnd ($d)

boxesOk ($fp, $size)

ISO BMFF top-level box chain (mp4 / mov) must tile the whole file; ftyp first; moov, mdat or moof present.

cfg ($key, $default)

------------------------------------------------------------------ // policy / config helpers // ------------------------------------------------------------------

checkExecutable ($type, $path, $size, $profile, &$st, &$r)

------------------------------------------------------------------ // S4: executability // ------------------------------------------------------------------

checkImage ($type, $path, $size, $profile, &$st, &$r)

------------------------------------------------------------------ // S3: images // ------------------------------------------------------------------

checkMedia ($type, $path, $size, &$r)

------------------------------------------------------------------ // S3: binary containers (audio, video, fonts) // ------------------------------------------------------------------

checkName ($name, $profile, &$reasons)

Returns the lowercase extension (last part) or null; appends reason codes to $reasons.

checkPdf ($data, &$r, &$st, $wantText)

------------------------------------------------------------------ // S3: PDF // ------------------------------------------------------------------

checkRtf ($data, &$r, &$st, $wantText)

RTF (spec 5, mirrors structure.check_rtf): embedded objects (\\object, \\objdata ...), DDE/INCLUDE fields -> ACTIVE_CONTENT,
external templates -> EXTERNAL_REF, raw \\binN data (cannot be inspected) -> PARSE_FAIL. Plain text for S6 goes to $st['texts'].

checkStructure ($type, $path, $size, $profile, $det, &$st, &$r)

------------------------------------------------------------------ // S3 dispatcher // ------------------------------------------------------------------

checkSvg ($data, $profile, &$st, &$r)

------------------------------------------------------------------ // SVG: strict re-serialising sanitizer (own tokenizer, no DOM, no network) // ------------------------------------------------------------------

checkXmlBytes ($data, &$r)

Returns the text decoded to UTF-8; appends XML_DTD / EXTERNAL_REF / PARSE_FAIL to $r.

checkZipContainer ($type, $path, $size, $profile, $det, &$st, &$r)

clamAgeHours ($ver)

clamCommand ($c, $cmd)

clamConnect ($c)

clamReadReply ($fp)

clamdHealth ($c)

Health check (PING + VERSION), cached 5 minutes. Returns array('age' => hours|null) or null if clamd is down.

clamdScanFile ($c, $file)

Returns array('found' => bool, 'sig' => string|null) or null when clamd misbehaved (= DOWN).

clamscanLock ($lockFile, $waitMs, $timeoutMs)

Exclusive host-wide lock (shared protocol, identical in all ports): the lock file is created with fopen(..., 'x')
(O_EXCL) and holds " "; a file whose mtime is older than timeoutMs + 30 s is stale (a dead scan) and is
unlinked; retries every 200 ms up to $waitMs. Returns true when the lock is held (release with clamscanUnlock) or false
(= scanner down).

clamscanRun ($files)

Returns array('res' => path => signature|null, 'age' => hours, 'maxAge' => hours) or null when the scanner is down.

clamscanUnlock ($lockFile)

classifyBmff ($path, $size, $h)

ISO-BMFF with ftyp at offset 4: avif | heic | heif | mov | mp4 | null (spec 4.1). Major brand qt = mov; a compatible
brand is only considered when the major brand is not an mp4 brand; the ftyp size must be sane (>= 16, (size-16) % 4 == 0).

classifyZip ($zd, $path)

compiledPatterns ()

convertEnc ($data, $from)

crashAll (&$jobs, $e)

crashed (&$j, $e)

csvShape ($s)

cutChars ($s, $max)

decodeForScan ($data)

Decode XML bytes in any UTF flavour into UTF-8 for textual scans (never throws).

detectBinary ($h, $size)

Magic-at-offset-0 types. Returns type, 'zip' for a zip container, or null.

detectFile ($path, $size, $profile, $ext)

Content based detection. Returns array('type' => string|null, 'zip' => directory|null).
$ext is the claimed lowercase extension (used only to enable csv/json, which are plain text).

detectText ($data, $ext, $profile)

ensureUtf8 ($s)

exifRotate ($im, $path, &$st)

extractTextFor ($type, $path, $size, $name, &$st)

------------------------------------------------------------------ // S6: text extraction // ------------------------------------------------------------------

failed ($v, $reason)

foldCompat ($t)

Minimal NFKC substitute (fullwidth ASCII, mathematical alphanumerics, exotic spaces) when intl is missing.

freeImage ($im)

freeState (&$st)

gdDecode ($type, $path)

getProfile ($name)

gifSkipSub ($d, $q, $n)

gifWalk ($d)

Walks the GIF block structure. Returns array(end, frames, headEnd, keep[]) or false.

hashEq ($a, $b)

headTail ($path, $size)

hit ($re, $data)

Regex helper: a match OR a regex failure counts as a hit (fail closed).

imageDims ($type, $path)

iniBytes ($val)

invisibleRegex ()

------------------------------------------------------------------ // injection helpers // ------------------------------------------------------------------

isKnownBad ($sha)

isRejectedSignature ($h)

jpegEnd ($d)

jsonOk ($s)

latin1ToUtf8 ($s)

loadPolicy ()

logError ($msg)

looksHtml ($s)

lowerNfkc ($s)

makeTmpDir ()

mp4Brand ($b)

nestedMagic ($d)

newVerdict ()

normReasons ($reasons)

normalizeForScan ($t)

officeNameRules ($name, &$reasons)

officePart ($type, $name, $d, $profile, &$reasons, &$st, $llm)

pdfDecodeNames ($b)

pdfNameSet ($b)

Set of names (decoded) used in a PDF fragment: array(name => true).

pdfSplit ($d, &$streams)

Splits a PDF into the skeleton (stream bodies removed) and the list of streams.

pdfStreamText ($buf)

pdfString ($tok)

pngEnd ($d)

readJson ($file)

rej (&$v, $reasons)

rmTree ($d)

scan ($files)

Scans every file in $files. Returns array(name, result OK|FOUND|DOWN, signature, dbAgeHours, stale).

scanFiles ($j)

scanMarkers ($data, $text, $allowMarkup, &$found)

Marker scan (spec 4.3). $text: whole text type; otherwise a binary view where short markers need context.

scannerDown (&$j)

AV unavailable: reject (AV_DOWN) or, with onScannerDown=hold, quarantine.

sockWrite ($fp, $data)

stage1 (&$j)

S0..S4 (profile, input, name, type identity, structure, executability). Sets $j['done'] on a reject.

stage3 (&$j)

S6 (LLM text) and S7 (result).

stop (&$j, $reasons)

Rejects the job and ends its pipeline.

svgSanitize ($t, &$err)

Parses a restricted XML subset and re-serialises only allow-listed elements/attributes.
Returns the sanitized document or null (with $err = ACTIVE_CONTENT | PARSE_FAIL).

svgText ($seg, $raw, &$stack, $rootSeen, $rootDone, $textEl, &$out, &$err)

Handles a text segment (or CDATA). Returns false on failure ($err set).

svgValueBad ($v)

textOrNull ($data)

Valid UTF-8 text without NUL/control characters (BOM stripped) or null.

trimLead ($s)

Drop a leading UTF-8 BOM and leading whitespace.

u32 ($s)

Unsigned 32-bit big endian (float on 32-bit PHP when >= 2^31).

utf8chr ($cp)

webpDims ($h)

webpEnd ($d)

writeSanitized ($type, $path, &$st)

------------------------------------------------------------------ // S7: sanitized output // ------------------------------------------------------------------

xmlEsc ($s)

xmlLite ($d)

Weak fallback when ext/xml is missing: balanced tags, single root, only predefined entities.

xmlRootName ($t)

Name of the first element after the prolog (xml decl, comments, PIs, DOCTYPE), or null.

xmlToText ($x)

xmlUnescape ($s)

Resolve the 5 predefined entities and numeric references; null if anything else appears.

xmlWellFormed ($data)

zipDirFp ($fp, $size, $maxEntries)

zipDirectory ($path, $size, $maxEntries)

------------------------------------------------------------------ // zip: own central directory parser (no ZipArchive needed), limits, containers // ------------------------------------------------------------------

zipEntry ($name, $d, $profile, &$reasons, &$st)

One entry of a plain zip: runs through name + type + structure + executability checks as a separate file.

zipRead ($fp, $e, $cap, &$err)

Reads and verifies one entry (stored or deflate). Returns data or false with $err set.


Back to documentation

Chameleon Framework © 2012 - 2026