<?php
namespace ZBateson\MailMimeParser\Header\Part;
use Psr\Log\LoggerInterface;
use ZBateson\MbWrapper\MbWrapper;
class MimeToken extends Token
{
public const MIME_PART_PATTERN = '=\?[^?=]+\?[QBqb]\?[^\?]+\?=';
public const MIME_PART_PATTERN_NO_QUOTES = '=\?[^\?=]+\?[QBqb]\?[^\?"]+\?=';
protected ?string $language = null;
protected ?string $charset = null;
public function __construct(LoggerInterface $logger, MbWrapper $charsetConverter, string $value)
{
parent::__construct($logger, $charsetConverter, $value);
$this->value = $this->decodeMime(\preg_replace('/\r|\n/', '', $this->value));
$pattern = self::MIME_PART_PATTERN;
$this->canIgnoreSpacesBefore = (bool) \preg_match("/^\s*{$pattern}|\s+/", $this->rawValue);
$this->canIgnoreSpacesAfter = (bool) \preg_match("/{$pattern}\s*|\s+\$/", $this->rawValue);
}
protected function decodeMime(string $value) : string
{
if (\preg_match('/^=\?([A-Za-z\-_0-9]+)\*?([A-Za-z\-_0-9]+)?\?([QBqb])\?([^\?]*)\?=$/', $value, $matches)) {
return $this->decodeMatchedEntity($matches);
}
return $this->convertEncoding($value);
}
private function decodeMatchedEntity(array $matches) : string
{
$body = $matches[4];
if (\strtoupper($matches[3]) === 'Q') {
$body = \quoted_printable_decode(\str_replace('_', '=20', $body));
} else {
$body = \base64_decode($body);
}
$this->charset = $matches[1];
$this->language = (!empty($matches[2])) ? $matches[2] : null;
if ($this->charset !== null) {
return $this->convertEncoding($body, $this->charset, true);
}
return $this->convertEncoding($body, 'ISO-8859-1', true);
}
public function getLanguage() : ?string
{
return $this->language;
}
public function getCharset() : ?string
{
return $this->charset;
}
public function getRawValue() : string
{
return $this->rawValue;
}
}