Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/warm-apples-invite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"posthog-php": patch
---

Preserve escaped characters in gzip-compressed fork-curl event payloads.
3 changes: 2 additions & 1 deletion .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ jobs:
uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
with:
php-version: ${{ matrix.php-version }}
extensions: zlib
tools: composer, phpunit

- name: Install Dependencies
Expand All @@ -111,7 +112,7 @@ jobs:
uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
with:
php-version: 8.4
extensions: xdebug
extensions: xdebug, zlib
tools: composer, phpunit

- name: Install Dependencies
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Thanks for your interest in improving the PostHog PHP SDK.

## Development setup

1. Install [PHP](https://www.php.net/manual/en/install.php) and [Composer](https://getcomposer.org/download/).
1. Install [PHP](https://www.php.net/manual/en/install.php) and [Composer](https://getcomposer.org/download/). Enable PHP's `zlib` extension for the gzip regression tests. This is a development-only dependency, not an SDK runtime requirement.
2. Install dependencies using the same command CI uses:

```bash
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
},
"require-dev": {
"phpunit/phpunit": "^11.0",
"squizlabs/php_codesniffer": "^4.0"
"squizlabs/php_codesniffer": "^4.0",
"ext-zlib": "*"
},
"autoload": {
"psr-4": {
Expand Down
6 changes: 4 additions & 2 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/Consumer/ForkCurl.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public function flushBatch($messages)
if ($this->compress_request) {
// Compress request to file
$tmpfname = tempnam("/tmp", "forkcurl_");
$cmd2 = "echo " . $payload . " | gzip > " . $tmpfname;
$cmd2 = "printf '%s' " . $payload . " | gzip > " . $tmpfname;
exec($cmd2, $output, $exit);

if (0 == $exit) {
Expand Down
51 changes: 51 additions & 0 deletions test/ForkCurlCompressionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace PostHog\Test;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use PostHog\Consumer\ForkCurl;

class ForkCurlCompressionTest extends TestCase
{
public static function compressionCases(): array
{
return ['plain JSON' => [false], 'gzip' => [true]];
}

#[DataProvider('compressionCases')]
public function testEscapedCharactersSurviveDelivery(bool $compressed): void
{
$server = new LocalHttpServer();
try {
$consumer = new ForkCurl('test-key', [
'host' => $server->address(),
'ssl' => false,
'debug' => true,
'compress_request' => $compressed,
]);
$message = [
'event' => 'quoted "event" with an apostrophe\'',
'distinct_id' => 'test-user',
'properties' => [
'controls' => "line one\nline two\tvalue\rreturn",
'literal_backslashes' => '\\n \\t C:\\path\\file',
'format_string' => '%s %b %n',
'unicode' => 'café 🌍',
],
];

self::assertTrue($consumer->flushBatch([$message]));
$requests = $server->requests();
self::assertCount(1, $requests);
self::assertSame('POST /batch/ HTTP/1.1', $requests[0]['requestLine']);
self::assertSame($compressed ? 'gzip' : null, $requests[0]['headers']['content-encoding'] ?? null);
self::assertSame(
['batch' => [$message], 'api_key' => 'test-key'],
json_decode($requests[0]['body'], true, 512, JSON_THROW_ON_ERROR)
);
} finally {
$server->stop();
}
}
}
68 changes: 68 additions & 0 deletions test/LocalHttpServer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

namespace PostHog\Test;

use RuntimeException;

final class LocalHttpServer
{
private $process;
private string $requestsFile;
private string $errorsFile;
private string $address;

public function __construct(array $responses = [])
{
$this->requestsFile = tempnam(sys_get_temp_dir(), 'posthog-requests-');
$this->errorsFile = tempnam(sys_get_temp_dir(), 'posthog-server-');
$this->process = proc_open(
[PHP_BINARY, __DIR__ . '/fixtures/http-server.php', $this->requestsFile, json_encode($responses)],
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['file', $this->errorsFile, 'a']],
$pipes
);
if (!is_resource($this->process)) {
$this->stop();
throw new RuntimeException('Could not start local HTTP server');
}
fclose($pipes[0]);
stream_set_timeout($pipes[1], 5);
$this->address = trim(fgets($pipes[1]) ?: '');
fclose($pipes[1]);
if ($this->address === '') {
$error = file_get_contents($this->errorsFile);
$this->stop();
throw new RuntimeException('Local HTTP server did not become ready: ' . $error);
}
}

public function address(): string
{
return $this->address;
}

public function requests(): array
{
return array_map(
static fn(string $line): array => json_decode($line, true, 512, JSON_THROW_ON_ERROR),
file($this->requestsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
);
}

public function stop(): void
{
if (is_resource($this->process)) {
proc_terminate($this->process);
proc_close($this->process);
}
foreach ([$this->requestsFile, $this->errorsFile] as $file) {
if (is_file($file)) {
unlink($file);
}
}
}

public function __destruct()
{
$this->stop();
}
}
57 changes: 57 additions & 0 deletions test/fixtures/http-server.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

$server = stream_socket_server('tcp://127.0.0.1:0', $errno, $error);
if ($server === false) {
throw new RuntimeException($error, $errno);
}
$responses = json_decode($argv[2], true, 512, JSON_THROW_ON_ERROR);
echo stream_socket_get_name($server, false) . "\n";
flush();

while ($connection = stream_socket_accept($server, 30)) {
stream_set_timeout($connection, 5);
$requestLine = trim(fgets($connection));
$headers = [];
while (($line = fgets($connection)) !== false && trim($line) !== '') {
[$name, $value] = explode(':', $line, 2);
$headers[strtolower($name)] = trim($value);
}
if (strtolower($headers['expect'] ?? '') === '100-continue') {
fwrite($connection, "HTTP/1.1 100 Continue\r\n\r\n");
}
$length = (int) ($headers['content-length'] ?? 0);
$body = '';
while (strlen($body) < $length) {
$chunk = fread($connection, $length - strlen($body));
if ($chunk === false || $chunk === '') {
throw new RuntimeException('Incomplete request body');
}
$body .= $chunk;
}
if (($headers['content-encoding'] ?? '') === 'gzip') {
$body = gzdecode($body);
Comment thread
marandaneto marked this conversation as resolved.
}
file_put_contents($argv[1], json_encode([
'requestLine' => $requestLine,
'headers' => $headers,
'body' => $body,
], JSON_THROW_ON_ERROR) . "\n", FILE_APPEND);

$response = array_shift($responses) ?? [];
$status = $response['status'] ?? 200;
$body = $response['body'] ?? '{"status":1}';
$headers = '';
foreach ($response['headers'] ?? [] as $name => $value) {
$headers .= "$name: $value\r\n";
}
$wire = "HTTP/1.1 $status Response\r\n" . $headers
. 'Content-Length: ' . strlen($body) . "\r\nConnection: close\r\n\r\n" . $body;
while ($wire !== '') {
$written = fwrite($connection, $wire);
if ($written === false || $written === 0) {
break;
}
$wire = substr($wire, $written);
}
fclose($connection);
}
Loading