protected function sort($messages, $sortCriteria, $reverse = false)
{
$uid = $this->options->uidReferencing ? self::UID : self::NO_UID;
if ($this->state != self::STATE_SELECTED && $this->state != self::STATE_SELECTED_READONLY) {
throw new ezcMailTransportException("Can't call sort() on the IMAP transport when a mailbox is not selected.");
}
$result = array();
$query = ucfirst(strtolower($sortCriteria));
$messageNumbers = implode(',', $messages);
$tag = $this->getNextTag();
$this->connection->sendData("{$tag} {$uid}FETCH {$messageNumbers} (BODY.PEEK[HEADER.FIELDS ({$query})])");
$response = trim($this->connection->getLine());
while (strpos($response, $tag) === false) {
if (strpos($response, ' FETCH (') !== false) {
if ($this->options->uidReferencing) {
preg_match('/^\\* [0-9]+ FETCH \\(UID ([0-9]+)/', $response, $matches);
} else {
preg_match('/^\\* ([0-9]+) FETCH/', $response, $matches);
}
$messageNumber = $matches[1];
}
if (strpos($response, $query) !== false) {
$strippedResponse = trim(trim(str_replace("{$query}: ", '', $response)), '"');
switch ($query) {
case 'Date':
$strippedResponse = strtotime($strippedResponse);
break;
case 'Subject':
case 'From':
case 'Sender':
case 'To':
$strippedResponse = ezcMailTools::mimeDecode($strippedResponse);
break;
default:
break;
}
$result[$messageNumber] = $strippedResponse;
}
// in case the mail doesn't have the $sortCriteria header (like junk mail missing Subject header)
if (strpos($response, ')') !== false && !isset($result[$messageNumber])) {
$result[$messageNumber] = '';
}
$response = trim($this->connection->getLine());
}
if ($this->responseType($response) != self::RESPONSE_OK) {
throw new ezcMailTransportException("The IMAP server could not sort the messages: {$response}.");
}
if ($reverse === true) {
natcasesort($result);
$result = array_reverse($result, true);
} else {
natcasesort($result);
}
return $result;
}