A free open source IT asset/license management system
Fixed #19982 - use correct EOL handling in exports
snipec877ff4c1594
diff --git a/app/Console/Commands/AuditFileStorage.php b/app/Console/Commands/AuditFileStorage.phpindex 89894acd1e..7ab7c121d3 100644--- a/app/Console/Commands/AuditFileStorage.php+++ b/app/Console/Commands/AuditFileStorage.php@@ -1090,7 +1090,7 @@ class AuditFileStorage extends Commandreturn;}- fputcsv($handle, ['direction', 'table', 'id', 'type', 'file'], escape: '\\');+ fputcsv($handle, ['direction', 'table', 'id', 'type', 'file'], escape: '\\', eol: "\r\n");foreach ($rows as $row) {fputcsv($handle, [$row['direction'] ?? 'missing',@@ -1098,11 +1098,11 @@ class AuditFileStorage extends Command$row['id'],$row['type'],$row['file'],- ], escape: '\\');+ ], escape: '\\', eol: "\r\n");}fclose($handle);- note('Wrote ' . number_format(count($rows)) . " row(s) to $csvPath.");+ note('Wrote '.number_format(count($rows))." row(s) to $csvPath.");}/**diff --git a/app/Http/Controllers/Licenses/LicensesController.php b/app/Http/Controllers/Licenses/LicensesController.phpindex fcbf6ceb5a..c515b28c9a 100755--- a/app/Http/Controllers/Licenses/LicensesController.php+++ b/app/Http/Controllers/Licenses/LicensesController.php@@ -395,7 +395,7 @@ class LicensesController extends Controllertrans('general.created_at'),];- fputcsv($handle, $headers, escape: '\\');+ fputcsv($handle, $headers, escape: '\\', eol: "\r\n");$formatter = new EscapeFormula('`');@@ -432,11 +432,11 @@ class LicensesController extends Controller// CSV_ESCAPE_FORMULAS is set to false in the .envif (config('app.escape_formulas') === false) {- fputcsv($handle, $values, escape: '\\');+ fputcsv($handle, $values, escape: '\\', eol: "\r\n");// CSV_ESCAPE_FORMULAS is set to true or is not set in the .env} else {- fputcsv($handle, $formatter->escapeRecord($values), escape: '\\');+ fputcsv($handle, $formatter->escapeRecord($values), escape: '\\', eol: "\r\n");}}});diff --git a/app/Http/Controllers/Reports/CustomComponentReportController.php b/app/Http/Controllers/Reports/CustomComponentReportController.phpindex e368626d7e..6d69718a06 100644--- a/app/Http/Controllers/Reports/CustomComponentReportController.php+++ b/app/Http/Controllers/Reports/CustomComponentReportController.php@@ -62,7 +62,7 @@ class CustomComponentReportController extends Controller$headerRow = $this->generateHeaders($request, $mappings);Log::debug('Adding headers: '.$this->getExecutionTime());- fputcsv($handle, $headerRow, escape: '\\');+ fputcsv($handle, $headerRow, escape: '\\', eol: "\r\n");Log::debug('Added headers: '.$this->getExecutionTime());$this->buildQuery($request)->orderBy('components.id', 'ASC')->chunk(500, function ($components) use ($handle, $request, $mappings) {@@ -88,11 +88,11 @@ class CustomComponentReportController extends Controller// CSV_ESCAPE_FORMULAS is set to false in the .envif (config('app.escape_formulas') === false) {- fputcsv($handle, $row, escape: '\\');+ fputcsv($handle, $row, escape: '\\', eol: "\r\n");// CSV_ESCAPE_FORMULAS is set to true or is not set in the .env} else {- fputcsv($handle, $formatter->escapeRecord($row), escape: '\\');+ fputcsv($handle, $formatter->escapeRecord($row), escape: '\\', eol: "\r\n");}Log::debug('-- Record '.$count.' Component ID:'.$component->id.' in '.$this->getExecutionTime());diff --git a/app/Http/Controllers/Reports/CustomConsumableReportController.php b/app/Http/Controllers/Reports/CustomConsumableReportController.phpindex 96362ab87c..d0fbd312f4 100644--- a/app/Http/Controllers/Reports/CustomConsumableReportController.php+++ b/app/Http/Controllers/Reports/CustomConsumableReportController.php@@ -73,7 +73,7 @@ class CustomConsumableReportController extends Controller$headerRow = $this->generateHeaders($request, $mappings);Log::debug('Adding headers: '.$this->getExecutionTime());- fputcsv($handle, $headerRow, escape: '\\');+ fputcsv($handle, $headerRow, escape: '\\', eol: "\r\n");Log::debug('Added headers: '.$this->getExecutionTime());$this->buildQuery($request)->orderBy('consumables.id', 'ASC')->chunk(500, function ($consumables) use ($handle, $request, $mappings) {@@ -99,11 +99,11 @@ class CustomConsumableReportController extends Controller// CSV_ESCAPE_FORMULAS is set to false in the .envif (config('app.escape_formulas') === false) {- fputcsv($handle, $row, escape: '\\');+ fputcsv($handle, $row, escape: '\\', eol: "\r\n");// CSV_ESCAPE_FORMULAS is set to true or is not set in the .env} else {- fputcsv($handle, $formatter->escapeRecord($row), escape: '\\');+ fputcsv($handle, $formatter->escapeRecord($row), escape: '\\', eol: "\r\n");}Log::debug('-- Record '.$count.' Consumable ID:'.$consumable->id.' in '.$this->getExecutionTime());@@ -293,7 +293,7 @@ class CustomConsumableReportController extends Controller'orderItems.order.supplier',]);- $request->whenFilled('include_assignments', fn() => $query->with('users.companies'));+ $request->whenFilled('include_assignments', fn () => $query->with('users.companies'));$query = $this->appendLocalConstraints($query, $request, ['by_model_number' => 'consumables.model_number',diff --git a/app/Http/Controllers/ReportsController.php b/app/Http/Controllers/ReportsController.phpindex df71609d4a..8be6b17919 100644--- a/app/Http/Controllers/ReportsController.php+++ b/app/Http/Controllers/ReportsController.php@@ -97,7 +97,7 @@ class ReportsController extends Controllertrans('admin/accessories/general.total'),trans('admin/accessories/general.remaining'),];- fputcsv($handle, $header, escape: '\\');+ fputcsv($handle, $header, escape: '\\', eol: "\r\n");$formatter = new EscapeFormula('`');@@ -112,9 +112,9 @@ class ReportsController extends Controller];if (config('app.escape_formulas') === false) {- fputcsv($handle, $row, escape: '\\');+ fputcsv($handle, $row, escape: '\\', eol: "\r\n");} else {- fputcsv($handle, $formatter->escapeRecord($row), escape: '\\');+ fputcsv($handle, $formatter->escapeRecord($row), escape: '\\', eol: "\r\n");}}});@@ -171,7 +171,7 @@ class ReportsController extends Controllertrans('admin/hardware/table.book_value'),trans('admin/hardware/table.diff'),];- fputcsv($handle, $header, escape: '\\');+ fputcsv($handle, $header, escape: '\\', eol: "\r\n");Asset::with('model', 'assignedTo', 'status', 'defaultLoc', 'assetlog')->orderBy('created_at', 'DESC')@@ -212,9 +212,9 @@ class ReportsController extends Controller];if (config('app.escape_formulas') === false) {- fputcsv($handle, $row, escape: '\\');+ fputcsv($handle, $row, escape: '\\', eol: "\r\n");} else {- fputcsv($handle, $formatter->escapeRecord($row), escape: '\\');+ fputcsv($handle, $formatter->escapeRecord($row), escape: '\\', eol: "\r\n");}}});@@ -349,7 +349,7 @@ class ReportsController extends Controller];$executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];Log::debug('Starting headers: '.$executionTime);- fputcsv($handle, $header, escape: '\\');+ fputcsv($handle, $header, escape: '\\', eol: "\r\n");$executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];Log::debug('Added headers: '.$executionTime);@@ -414,11 +414,11 @@ class ReportsController extends Controller// CSV_ESCAPE_FORMULAS is set to false in the .envif (config('app.escape_formulas') === false) {- fputcsv($handle, $row, escape: '\\');+ fputcsv($handle, $row, escape: '\\', eol: "\r\n");// CSV_ESCAPE_FORMULAS is set to true or is not set in the .env} else {- fputcsv($handle, $formatter->escapeRecord($row), escape: '\\');+ fputcsv($handle, $formatter->escapeRecord($row), escape: '\\', eol: "\r\n");}}});@@ -479,7 +479,7 @@ class ReportsController extends Controllertrans('general.depreciation'),trans('general.purchase_cost'),];- fputcsv($handle, $header, escape: '\\');+ fputcsv($handle, $header, escape: '\\', eol: "\r\n");License::orderBy('created_at', 'DESC')->chunk(500, function ($licenses) use ($handle, $formatter) {foreach ($licenses as $license) {@@ -503,9 +503,9 @@ class ReportsController extends Controller];if (config('app.escape_formulas') === false) {- fputcsv($handle, $row, escape: '\\');+ fputcsv($handle, $row, escape: '\\', eol: "\r\n");} else {- fputcsv($handle, $formatter->escapeRecord($row), escape: '\\');+ fputcsv($handle, $formatter->escapeRecord($row), escape: '\\', eol: "\r\n");}}});@@ -801,7 +801,7 @@ class ReportsController extends Controller// cell like "=cmd|'/c calc.exe'!A1" would evaluate as a// formula on a reports.view user's workstation.$headerFormatter = new EscapeFormula('`');- fputcsv($handle, $headerFormatter->escapeRecord($header), escape: '\\');+ fputcsv($handle, $headerFormatter->escapeRecord($header), escape: '\\', eol: "\r\n");$executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];Log::debug('Added headers: '.$executionTime);@@ -1275,11 +1275,11 @@ class ReportsController extends Controller// CSV_ESCAPE_FORMULAS is set to false in the .envif (config('app.escape_formulas') === false) {- fputcsv($handle, $row, escape: '\\');+ fputcsv($handle, $row, escape: '\\', eol: "\r\n");// CSV_ESCAPE_FORMULAS is set to true or is not set in the .env} else {- fputcsv($handle, $formatter->escapeRecord($row), escape: '\\');+ fputcsv($handle, $formatter->escapeRecord($row), escape: '\\', eol: "\r\n");}$executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];@@ -1343,7 +1343,7 @@ class ReportsController extends Controllertrans('admin/maintenances/form.is_warranty'),trans('admin/maintenances/form.notes'),];- fputcsv($handle, $header, escape: '\\');+ fputcsv($handle, $header, escape: '\\', eol: "\r\n");// No completed-filter here — exports every maintenance, active// or completed. Eager-load the four relations the row loop@@ -1376,9 +1376,9 @@ class ReportsController extends Controller];if (config('app.escape_formulas') === false) {- fputcsv($handle, $row, escape: '\\');+ fputcsv($handle, $row, escape: '\\', eol: "\r\n");} else {- fputcsv($handle, $formatter->escapeRecord($row), escape: '\\');+ fputcsv($handle, $formatter->escapeRecord($row), escape: '\\', eol: "\r\n");}}});diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.phpindex b0a468f021..e2efb0163d 100644--- a/app/Http/Controllers/SettingsController.php+++ b/app/Http/Controllers/SettingsController.php@@ -206,7 +206,7 @@ class SettingsController extends Controller'Item Location','Location Company','Location Company ID',- ], escape: '\\');+ ], escape: '\\', eol: "\r\n");// Formula-escape data rows using the same helper + setting as// ReportsController's exports. Row values include user-editable@@ -218,9 +218,9 @@ class SettingsController extends Controller$formatter = new EscapeFormula('`');foreach ($mismatched as $row) {if (config('app.escape_formulas') === false) {- fputcsv($out, $row, escape: '\\');+ fputcsv($out, $row, escape: '\\', eol: "\r\n");} else {- fputcsv($out, $formatter->escapeRecord($row), escape: '\\');+ fputcsv($out, $formatter->escapeRecord($row), escape: '\\', eol: "\r\n");}}fclose($out);@@ -960,7 +960,7 @@ class SettingsController extends Controllerreturn redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));}- if (!$this->acquireOperationLock(self::BACKUP_RESTORE_LOCK)) {+ if (! $this->acquireOperationLock(self::BACKUP_RESTORE_LOCK)) {return redirect()->route('settings.backups.index')->with('error', $this->operationAlreadyRunningMessage('general.backup_or_restore'));}@@ -1127,7 +1127,7 @@ class SettingsController extends Controllerreturn redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));}- if (!$this->acquireOperationLock(self::BACKUP_RESTORE_LOCK)) {+ if (! $this->acquireOperationLock(self::BACKUP_RESTORE_LOCK)) {return redirect()->route('settings.backups.index')->with('error', $this->operationAlreadyRunningMessage('general.backup_or_restore'));}@@ -1297,12 +1297,12 @@ class SettingsController extends Controller$migrationApplied = DB::table('migrations')->where('migration', $newestMigration)->exists();- if (!$migrationApplied) {+ if (! $migrationApplied) {Log::error('Migrate reported success after restore, but the newest migration ('- . $newestMigration- . ') is not recorded in the migrations table. Schema is out of date. Pre-restore backup available at '- . $preBackupHint+ .$newestMigration+ .') is not recorded in the migrations table. Schema is out of date. Pre-restore backup available at '+ .$preBackupHint);Auth::logout();diff --git a/app/Http/Controllers/Users/UsersController.php b/app/Http/Controllers/Users/UsersController.phpindex d09c13e79e..dea1d5a34c 100755--- a/app/Http/Controllers/Users/UsersController.php+++ b/app/Http/Controllers/Users/UsersController.php@@ -618,7 +618,7 @@ class UsersController extends Controllertrans('admin/licenses/table.deleted_at'),];- fputcsv($handle, $headers, escape: '\\');+ fputcsv($handle, $headers, escape: '\\', eol: "\r\n");$users = User::with('assets',@@ -700,11 +700,11 @@ class UsersController extends Controller// CSV_ESCAPE_FORMULAS is set to false in the .envif (config('app.escape_formulas') === false) {- fputcsv($handle, $values, escape: '\\');+ fputcsv($handle, $values, escape: '\\', eol: "\r\n");// CSV_ESCAPE_FORMULAS is set to true or is not set in the .env} else {- fputcsv($handle, $formatter->escapeRecord($values), escape: '\\');+ fputcsv($handle, $formatter->escapeRecord($values), escape: '\\', eol: "\r\n");}}});diff --git a/tests/Feature/Reporting/Custom/CustomAssetReportMultilineNotesTest.php b/tests/Feature/Reporting/Custom/CustomAssetReportMultilineNotesTest.phpnew file mode 100644index 0000000000..e5279a4068--- /dev/null+++ b/tests/Feature/Reporting/Custom/CustomAssetReportMultilineNotesTest.php@@ -0,0 +1,78 @@+<?php++namespace Tests\Feature\Reporting\Custom;++use App\Models\Asset;+use App\Models\User;+use League\Csv\Reader;+use Tests\TestCase;++/**+ * Notes containing embedded newlines+ * (admins type multi-line text into the notes editor) exported fine+ * per RFC 4180 because fputcsv auto-quotes fields with embedded+ * newlines, but the file was being written with Unix LF record+ * terminators. Excel on Windows reads a bare LF inside a quoted+ * field as a record break anyway, so the asset's row splits across+ * three on open. Switching the row terminator to CRLF puts Excel in+ * the mode where it treats embedded LFs as data and only hard breaks+ * on CRLF.+ */+class CustomAssetReportMultilineNotesTest extends TestCase+{+ public function test_asset_notes_with_embedded_newlines_stay_in_a_single_csv_row(): void+ {+ Asset::factory()->create([+ 'name' => 'notes-asset',+ 'notes' => "Date: 21\nFor: Bob\nFrom: Paul",+ ]);++ $response = $this->actingAs(User::factory()->canViewReports()->create())+ ->post('reports/custom', [+ 'asset_name' => '1',+ 'notes' => '1',+ ])+ ->assertOk();++ $csv = $response->streamedContent();++ // RFC 4180 record terminator so Excel reliably treats bare+ // LFs inside quoted cells as data instead of row breaks.+ $this->assertStringContainsString("\r\n", $csv, 'CSV must terminate rows with CRLF for Excel compatibility.');++ $reader = Reader::createFromString($csv);+ $reader->setHeaderOffset(0);+ $rows = iterator_to_array($reader->getRecords());++ $this->assertCount(1, $rows, 'Multi-line notes field must stay in a single CSV row rather than split across three.');+ $this->assertSame(+ "Date: 21\nFor: Bob\nFrom: Paul",+ array_values($rows)[0]['Notes'] ?? null,+ 'Notes column must preserve the embedded newlines verbatim inside the quoted cell.',+ );+ }++ public function test_asset_notes_with_crlf_embedded_newlines_also_stay_in_a_single_row(): void+ {+ // A user editing notes on Windows produces CRLF line breaks.+ // The quoted-cell handling has to tolerate both LF and CRLF+ // inside the field so Windows-authored text round-trips too.+ Asset::factory()->create([+ 'name' => 'crlf-notes-asset',+ 'notes' => "Date: 21\r\nFor: Bob\r\nFrom: Paul",+ ]);++ $response = $this->actingAs(User::factory()->canViewReports()->create())+ ->post('reports/custom', [+ 'asset_name' => '1',+ 'notes' => '1',+ ])+ ->assertOk();++ $reader = Reader::createFromString($response->streamedContent());+ $reader->setHeaderOffset(0);+ $rows = iterator_to_array($reader->getRecords());++ $this->assertCount(1, $rows);+ }+}diff --git a/tests/Unit/Codebase/CsvEolArgumentTest.php b/tests/Unit/Codebase/CsvEolArgumentTest.phpnew file mode 100644index 0000000000..bdc950f86e--- /dev/null+++ b/tests/Unit/Codebase/CsvEolArgumentTest.php@@ -0,0 +1,146 @@+<?php++namespace Tests\Unit\Codebase;++use PHPUnit\Framework\TestCase;++/**+ * Codebase-shape guardrail for the CSV record terminator argument.+ *+ * PHP's `fputcsv()` defaults the row terminator to PHP_EOL, which is+ * a bare LF on Linux containers. Excel on Windows reads bare LFs+ * inside a quoted field as a record break, which splits any cell+ * carrying embedded newlines (notes, custom field descriptions,+ * composed templates) across multiple rows on open (see #19982).+ *+ * Fix: pass `eol: "\r\n"` explicitly on every call so the file is+ * RFC 4180 compliant and Excel reliably treats embedded LFs as data.+ *+ * This test fails if a new `fputcsv()` call is added without an+ * explicit `eol:` argument, so the regression cannot silently come+ * back.+ */+class CsvEolArgumentTest extends TestCase+{+ private const SCAN_DIRS = ['app'];++ public function test_every_fputcsv_call_passes_an_explicit_eol_argument(): void+ {+ $projectRoot = dirname(__DIR__, 3);+ $hits = [];++ foreach (self::SCAN_DIRS as $dir) {+ foreach ($this->scanPhpFiles($projectRoot.'/'.$dir) as $absolutePath) {+ $relative = ltrim(substr($absolutePath, strlen($projectRoot) + 1), '/');+ $contents = file_get_contents($absolutePath);+ if ($contents === false) {+ continue;+ }++ foreach ($this->findFputcsvCalls($contents) as $call) {+ if ($call['has_eol']) {+ continue;+ }+ $hits[] = $relative.':'.$call['line'].' '.$call['source'];+ }+ }+ }++ $this->assertEmpty(+ $hits,+ "Found fputcsv() call(s) without an explicit \$eol argument.\n".+ "Without eol: \"\\r\\n\", the row terminator defaults to PHP_EOL (bare LF on Linux),\n".+ "and Excel on Windows splits quoted cells with embedded newlines across multiple rows.\n".+ "Pass eol: \"\\r\\n\" explicitly:\n".+ " fputcsv(\$handle, \$row, escape: '\\\\', eol: \"\\r\\n\");\n\n".+ "Hits:\n".implode("\n", $hits),+ );+ }++ private function findFputcsvCalls(string $contents): array+ {+ $calls = [];+ $tokens = token_get_all($contents);+ $count = count($tokens);++ for ($i = 0; $i < $count; $i++) {+ $token = $tokens[$i];+ if (! is_array($token) || $token[0] !== T_STRING) {+ continue;+ }+ if (strtolower($token[1]) !== 'fputcsv') {+ continue;+ }+ $next = $tokens[$i + 1] ?? null;+ if ($next !== '(') {+ continue;+ }+ $closeIndex = $this->findClosingParenthesis($tokens, $i + 1);+ if ($closeIndex === null) {+ continue;+ }++ $calls[] = [+ 'line' => $token[2],+ 'source' => $this->sourceLine($contents, $token[2]),+ 'has_eol' => $this->hasEolArgument($tokens, $i + 2, $closeIndex),+ ];+ }++ return $calls;+ }++ private function findClosingParenthesis(array $tokens, int $openIndex): ?int+ {+ $depth = 0;+ $count = count($tokens);+ for ($i = $openIndex; $i < $count; $i++) {+ $token = $tokens[$i];+ if ($token === '(') {+ $depth++;+ } elseif ($token === ')') {+ $depth--;+ if ($depth === 0) {+ return $i;+ }+ }+ }++ return null;+ }++ private function hasEolArgument(array $tokens, int $from, int $to): bool+ {+ for ($i = $from; $i < $to; $i++) {+ $token = $tokens[$i];+ if (is_array($token) && $token[0] === T_STRING && strtolower($token[1]) === 'eol') {+ $next = $tokens[$i + 1] ?? null;+ if ($next === ':') {+ return true;+ }+ }+ }++ return false;+ }++ private function sourceLine(string $contents, int $line): string+ {+ $lines = explode("\n", $contents);+ $index = $line - 1;++ return isset($lines[$index]) ? trim($lines[$index]) : '';+ }++ private function scanPhpFiles(string $dir): \Generator+ {+ $iterator = new \RecursiveIteratorIterator(+ new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS),+ );+ foreach ($iterator as $file) {+ if ($file->isFile() && $file->getExtension() === 'php') {+ yield $file->getPathname();+ }+ }+ }+}