MDL-72744 dataformat: Escape formulas when exporting spreadsheets

Co-authored-by: Huong Nguyen <[email protected]>
This commit is contained in:
David Woloszyn
2025-12-04 08:57:29 +07:00
committed by Huong Nguyen
co-authored by Huong Nguyen
parent 4fcf6aa947
commit 377a2c30f4
4 changed files with 149 additions and 1 deletions
+39
View File
@@ -168,4 +168,43 @@ class dataformat {
return get_file_storage()->create_file_from_pathname($filerecord, $filepath);
}
/**
* Escape formula spreadsheet values.
*
* Check values being used in spreadsheets and make them safe for inclusion.
* Following OWASP recommendations {@link https://owasp.org/www-community/attacks/CSV_Injection}.
*
* @param mixed $value Value to check.
* @return string|null Return escaped formula if detected.
*/
public static function escape_spreadsheet_formula(mixed $value): ?string {
// Only escape strings; leave numbers and other types unchanged.
if (!is_string($value)) {
return $value;
}
// Moodle's null placeholder: exactly one dash.
if ($value === '-') {
return $value;
}
// Trim only for checking, not for modifying output.
$trimmed = ltrim($value);
if ($trimmed === '') {
return $value;
}
// Characters that trigger formula parsing in Excel/Sheets.
$formulacharacters = ['=', '+', '-', '@'];
// If trimmed version starts with formula character, escape it.
if (in_array($trimmed[0], $formulacharacters, true)) {
// Preserve original whitespace. Do not alter actual content.
return "'" . $value;
}
return $value;
}
}