Skip to content

Commit

Permalink
fix: added sanitizer for CSV
Browse files Browse the repository at this point in the history
  • Loading branch information
thorsten committed Jul 1, 2023
1 parent f753e9c commit 03946ec
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
3 changes: 2 additions & 1 deletion phpmyfaq/admin/report.export.php
Expand Up @@ -116,7 +116,8 @@

$content = '';
foreach ($text as $row) {
$content .= implode(';', $row);
$csvRow = array_map(['phpMyFAQ\Report', 'sanitize'], $row);
$content .= implode(';', $csvRow);
$content .= "\r\n";
}

Expand Down
16 changes: 15 additions & 1 deletion phpmyfaq/src/phpMyFAQ/Report.php
Expand Up @@ -28,7 +28,7 @@ class Report
/**
* @var Configuration
*/
private $config;
private Configuration $config;

/**
* Constructor.
Expand Down Expand Up @@ -147,4 +147,18 @@ public function convertEncoding(string $outputString = ''): string
$toBeRemoved = ['=', '+', '-', 'HYPERLINK'];
return str_replace($toBeRemoved, '', $outputString);
}

/**
* Sanitizes input to avoid CSV injection.
* @param string|int $value
* @return string
*/
public static function sanitize($value): string
{
if (preg_match('/[=\+\-\@\|]/', $value)) {
$value = '"' . str_replace('"', '""', $value) . '"';
}

return $value;
}
}
31 changes: 31 additions & 0 deletions tests/phpMyFAQ/ReportTest.php
@@ -0,0 +1,31 @@
<?php

namespace phpMyFAQ;

use PHPUnit\Framework\TestCase;

class ReportTest extends TestCase
{

public function testSanitize(): void
{
$data = [
['John Doe', 'john.doe@example.com', '12345'],
['Jane Smith', 'jane.smith@example.com', '=SUM(A1:A10)'],
];

$actual = [];

$expected = [
'John Doe,"john.doe@example.com",12345',
'Jane Smith,"jane.smith@example.com","=SUM(A1:A10)"'
];

foreach ($data as $row) {
$csvRow = array_map(['phpMyFAQ\Report', 'sanitize'], $row);
$actual[] = implode(',', $csvRow);
}

$this->assertEquals($expected, $actual);
}
}

0 comments on commit 03946ec

Please sign in to comment.