Skip to content
Open
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
8 changes: 8 additions & 0 deletions src/Connection/ConnectionInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,10 @@ public function capability(): UntaggedResponse;
*
* Execute a search request.
*
* Declare UTF-8 for non-ASCII literals when the caller omits the charset.
*
* @param array<string|array{string, string}|ImapCommandArgument> $params
*
* @see https://datatracker.ietf.org/doc/html/rfc9051#name-search-command
*/
public function search(array $params): UntaggedResponse;
Expand All @@ -117,6 +121,8 @@ public function search(array $params): UntaggedResponse;
*
* Execute a sort request using RFC 5256.
*
* @param array<string|array{string, string}|ImapCommandArgument> $params
*
* @see https://datatracker.ietf.org/doc/html/rfc5256
*/
public function sort(ImapSortKey $key, string $direction, array $params): UntaggedResponse;
Expand Down Expand Up @@ -204,6 +210,8 @@ public function size(int|array $ids): ResponseCollection;

/**
* Send an IMAP command.
*
* @param array<string|array{string, string}|ImapCommandArgument> $tokens
*/
public function send(string $name, array $tokens = [], ?string &$tag = null): void;

Expand Down
28 changes: 25 additions & 3 deletions src/Connection/ImapCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class ImapCommand implements Stringable

/**
* Constructor.
*
* @param array<string|array{string, string}|ImapCommandArgument> $tokens
*/
public function __construct(
protected string $tag,
Expand All @@ -41,6 +43,8 @@ public function command(): string

/**
* Get the IMAP tokens.
*
* @return array<string|array{string, string}|ImapCommandArgument>
*/
public function tokens(): array
{
Expand All @@ -65,7 +69,7 @@ public function compile(): array

$line = trim("{$this->tag} {$this->command}");

foreach ($this->tokens as $token) {
foreach ($this->parts() as $token) {
if (is_array($token)) {
// For tokens provided as arrays, the first element is a placeholder
// (for example, "{20}") that signals a literal value will follow.
Expand All @@ -75,15 +79,15 @@ public function compile(): array
Assert::hasNoControlCharacters($length);

$lines[] = new ImapCommandLine(
value: "{$line} {$length}",
value: $line.$length,
synchronizing: ! str_contains($length, '+'),
);

$line = $literal;
} else {
Assert::hasNoControlCharacters($token);

$line .= " {$token}";
$line .= $token;
}
}

Expand All @@ -92,6 +96,24 @@ public function compile(): array
return $this->compiled = $lines;
}

/**
* Separate command arguments with spaces while preserving their internal syntax.
*
* @return iterable<string|array{string, string}>
*/
protected function parts(): iterable
{
foreach ($this->tokens as $token) {
yield ' ';

if ($token instanceof ImapCommandArgument) {
yield from $token->parts;
} else {
yield $token;
}
}
}

/**
* Get a redacted version of the command for safe exposure.
*/
Expand Down
32 changes: 32 additions & 0 deletions src/Connection/ImapCommandArgument.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace DirectoryTree\ImapEngine\Connection;

/**
* A command argument assembled from syntax fragments and IMAP literals.
*/
class ImapCommandArgument
{
/**
* Create an argument whose parts are joined without inserting spaces.
*
* @param list<string|array{string, string}> $parts Syntax fragments or pairs of literal markers and payloads.
*/
public function __construct(
public readonly array $parts,
) {}

/**
* Determine if any literal contains non-ASCII bytes.
*/
public function hasNonAsciiLiteral(): bool
{
foreach ($this->parts as $part) {
if (is_array($part) && preg_match('/[\x80-\xFF]/', $part[1])) {
return true;
}
}

return false;
}
}
32 changes: 32 additions & 0 deletions src/Connection/ImapConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,10 @@ public function size(int|array $ids): ResponseCollection
*/
public function search(array $params): UntaggedResponse
{
if ($this->requiresSearchCharset($params)) {
array_unshift($params, 'CHARSET UTF-8');
}

$this->send('UID SEARCH', $params, tag: $tag);

$this->assertTaggedResponse($tag);
Expand All @@ -502,6 +506,30 @@ public function search(array $params): UntaggedResponse
);
}

/**
* Determine whether search literals need a charset declaration.
*/
protected function requiresSearchCharset(array $params): bool
{
$first = reset($params);

if (is_string($first) && preg_match('/^\s*CHARSET(?:\s|$)/i', $first)) {
return false;
}

foreach ($params as $param) {
if ($param instanceof ImapCommandArgument && $param->hasNonAsciiLiteral()) {
return true;
}

if (is_array($param) && preg_match('/[\x80-\xFF]/', $param[1])) {
return true;
}
}

return false;
}

/**
* {@inheritDoc}
*/
Expand Down Expand Up @@ -751,6 +779,10 @@ protected function assertTaggedResponse(string $tag, ?callable $exception = null
*/
protected function assertContinuationResponse(ImapCommand $command): void
{
if (in_array(strtoupper($command->command()), ['LOGIN', 'AUTHENTICATE'], true)) {
$command = $command->redacted();
}

$this->assertNextResponse(
fn (Response $response) => (
$response instanceof ContinuationResponse || (
Expand Down
127 changes: 33 additions & 94 deletions src/Connection/ImapQueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -353,11 +353,37 @@ public function isEmpty(): bool
}

/**
* Transform the instance into an IMAP-compatible query string.
* Compile the criteria as a single query string.
*/
public function toImap(): string
{
return $this->compileWheres($this->wheres);
return ltrim((string) new ImapCommand('', '', $this->toImapTokens()), ' ');
}

/**
* Compile search criteria for transmission, preserving literal arguments.
*
* @return list<string|ImapCommandArgument>
*/
public function toImapTokens(): array
{
return $this->grammar()->compile($this->wheres);
}

/**
* Get the conditions recorded by the builder.
*/
public function getWheres(): array
{
return $this->wheres;
}

/**
* Get the grammar used to compile search conditions.
*/
protected function grammar(): ImapSearchGrammar
{
return new ImapSearchGrammar;
}

/**
Expand All @@ -373,23 +399,19 @@ protected function newQuery(): static
*/
protected function addBasicCondition(string $boolean, mixed $column, mixed $value, bool $not = false): void
{
$value = $this->prepareWhereValue($value);

$column = Str::enum($column);

$this->wheres[] = [
'type' => 'basic',
'not' => $not,
'key' => $column,
'value' => $value,
'key' => Str::enum($column),
'value' => $this->normalizeWhereValue($value),
'boolean' => $boolean,
];
}

/**
* Prepare the where value, escaping it as needed.
* Normalize the where value for compilation.
*/
protected function prepareWhereValue(mixed $value): RawQueryValue|string|null
protected function normalizeWhereValue(mixed $value): RawQueryValue|string|null
{
if (is_null($value)) {
return null;
Expand All @@ -411,7 +433,7 @@ protected function prepareWhereValue(mixed $value): RawQueryValue|string|null
$value = $value->format($this->dateFormat);
}

return Str::escape($value);
return $value;
}

/**
Expand Down Expand Up @@ -441,87 +463,4 @@ protected function parseDate(mixed $date): CarbonInterface

return Carbon::parse($date);
}

/**
* Build a single expression node from a basic or nested where.
*
* @param array{type: 'basic'|'nested', boolean: 'AND'|'OR', query: ImapQueryBuilder} $where
*/
protected function makeExpressionNode(array $where): array
{
return match ($where['type']) {
'basic' => [
'expr' => $this->compileBasic($where),
'boolean' => $where['boolean'],
],

'nested' => [
'expr' => $where['query']->toImap(),
'boolean' => $where['boolean'],
]
};
}

/**
* Merge the existing expression with the next expression, respecting the boolean operator.
*
* @param 'AND'|'OR' $boolean
*/
protected function mergeExpressions(string $existing, string $next, string $boolean): string
{
return match ($boolean) {
// AND is implicit – just append.
'AND' => $existing.' '.$next,

// IMAP's OR is binary; nest accordingly.
'OR' => 'OR ('.$existing.') ('.$next.')',
};
}

/**
* Recursively compile the wheres array into an IMAP-compatible string.
*/
protected function compileWheres(array $wheres): string
{
if (empty($wheres)) {
return '';
}

// Convert each "where" into a node for later merging.
$exprNodes = array_map(fn (array $where) => (
$this->makeExpressionNode($where)
), $wheres);

// Start with the first expression.
$combined = array_shift($exprNodes)['expr'];

// Merge the rest of the expressions.
foreach ($exprNodes as $node) {
$combined = $this->mergeExpressions(
$combined, $node['expr'], $node['boolean']
);
}

return trim($combined);
}

/**
* Compile a basic where condition into an IMAP-compatible string.
*/
protected function compileBasic(array $where): string
{
$part = strtoupper($where['key']);

if ($where['value'] instanceof RawQueryValue) {
$part .= ' '.$where['value']->value;
} elseif ($where['value']) {
$part .= ' "'.Str::toImapUtf7($where['value']).'"';
}

if ($where['not']) {
$part = 'NOT '.$part;
}

return $part;
}
}
Loading
Loading