diff --git a/src/helpers/ExportHelper.php b/src/helpers/ExportHelper.php index 2f1bbaa..d3f3618 100644 --- a/src/helpers/ExportHelper.php +++ b/src/helpers/ExportHelper.php @@ -186,16 +186,24 @@ protected static function generateRow(array $row, $delimiter, $enclose) } /** - * Undocumented function - * - * @param [type] $value - * @return void + * + * @param string $value + * @return string * @see https://owasp.org/www-community/attacks/CSV_Injection */ public static function sanitizeValue($value) { - return str_replace([ - '";', '",', '"', "'" - ], '', trim($value)); + $value = str_replace([ + '"', + ], [ + '""', + ], trim($value)); + + $firstChar = substr($value, 0, 1); + if (in_array($firstChar, ['=', '+', '-', '@', PHP_EOL, "\t", "\n"])) { + $value = StringHelper::replaceFirst($firstChar, "'$firstChar", $value); + } + + return $value; } } diff --git a/tests/helpers/ExportHelperTest.php b/tests/helpers/ExportHelperTest.php index 3000b5f..fb25cc9 100644 --- a/tests/helpers/ExportHelperTest.php +++ b/tests/helpers/ExportHelperTest.php @@ -137,8 +137,9 @@ public function testSpecialCharsEncoding() { $content = ExportHelper::csv([ ['&', "'", 'a"b"c'], + ['nix', 'nix', '=1+2";=1+2'] ], [], false); - $this->assertSameTrimmed('"&","","abc"', $content); + $this->assertSameTrimmed('"&","\'","a""b""c" "nix","nix","\'=1+2"";=1+2"', $content); } }