Skip to content

Commit 6c6f331

Browse files
authored
Merge pull request #213 from spatie/fix/ics-escape-string-rfc5545
Fix ICS text escaping per RFC 5545 section 3.3.11
2 parents 5dd6d82 + caccb71 commit 6c6f331

2 files changed

Lines changed: 35 additions & 1 deletion

File tree

src/Generators/Ics.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,11 @@ protected function buildFile(array $propertiesAndComponents): string
110110
/** @see https://tools.ietf.org/html/rfc5545.html#section-3.3.11 */
111111
protected function escapeString(string $field): string
112112
{
113-
return addcslashes($field, "\r\n,;");
113+
return str_replace(
114+
['\\', ';', ',', "\r\n", "\r", "\n"],
115+
['\\\\', '\\;', '\\,', '\\n', '\\n', '\\n'],
116+
$field
117+
);
114118
}
115119

116120
/** @see https://tools.ietf.org/html/rfc5545#section-3.8.4.7 */

tests/Generators/IcsGeneratorTest.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use DateTimeZone;
99
use Spatie\CalendarLinks\Generator;
1010
use Spatie\CalendarLinks\Generators\Ics;
11+
use Spatie\CalendarLinks\Link;
1112
use Spatie\CalendarLinks\Tests\TestCase;
1213

1314
/**
@@ -94,4 +95,33 @@ public function it_can_generate_with_a_custom_reminder(): void
9495
]])->generate($this->createShortEventLink())
9596
);
9697
}
98+
99+
/** @test */
100+
public function it_escapes_backslashes_in_text_fields(): void
101+
{
102+
$link = Link::create(
103+
'Event with \\ backslash',
104+
DateTime::createFromFormat('Y-m-d H:i', '2024-01-01 09:00', new DateTimeZone('UTC')),
105+
DateTime::createFromFormat('Y-m-d H:i', '2024-01-01 10:00', new DateTimeZone('UTC')),
106+
)->description('Path: C:\\Users\\test');
107+
108+
$output = $this->generator()->generate($link);
109+
110+
$this->assertStringContainsString('SUMMARY:Event with \\\\ backslash', $output);
111+
$this->assertStringContainsString('DESCRIPTION:Path: C:\\\\Users\\\\test', $output);
112+
}
113+
114+
/** @test */
115+
public function it_escapes_newlines_as_backslash_n(): void
116+
{
117+
$link = Link::create(
118+
'Event',
119+
DateTime::createFromFormat('Y-m-d H:i', '2024-01-01 09:00', new DateTimeZone('UTC')),
120+
DateTime::createFromFormat('Y-m-d H:i', '2024-01-01 10:00', new DateTimeZone('UTC')),
121+
)->description("Line 1\r\nLine 2\rLine 3\nLine 4");
122+
123+
$output = $this->generator()->generate($link);
124+
125+
$this->assertStringContainsString('DESCRIPTION:Line 1\\nLine 2\\nLine 3\\nLine 4', $output);
126+
}
97127
}

0 commit comments

Comments
 (0)