Skip to content
Closed
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
24 changes: 2 additions & 22 deletions src/MailPanel.body.latte
Original file line number Diff line number Diff line change
@@ -1,22 +1,2 @@
{* Little magic here. Create iframe and then render message into it (needed because HTML messages) *}
{if $message->getHtmlBody() !== ''}
{$message->getHtmlBody()|noescape}
{else}
<!doctype html>
<meta charset="utf-8">
<style>
html, body {
margin: 0;
padding: 0;
border: none;
font-family: sans-serif;
font-size: 12px;
white-space: pre;
}

body {
padding: 10px;
}
</style>
<body>{$message|plainText}</body>
{/if}
{* Render a standalone HTML preview document or fragment. *}
{$message|previewHtml|noescape}
17 changes: 6 additions & 11 deletions src/MailPanel.latte
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,7 @@
</tr>

<tr class="nextras-mail-panel-preview-html tracy-collapsed">
{capture $htmlPreview}{include MailPanel.body.latte, message => $message}{/capture}
<td colspan="2" data-content="{$htmlPreview}"></td>
<td colspan="2" data-src="{link('preview', ['message-id' => $messageId])}"></td>
</tr>
</table>
{/foreach}
Expand All @@ -130,22 +129,18 @@
var iframe = document.createElement('iframe');
preview.appendChild(iframe);

iframe.contentWindow.document.write(preview.dataset.content);
iframe.contentWindow.document.close();
delete preview.dataset.content;

var baseTag = iframe.contentWindow.document.createElement('base');
baseTag.target = '_parent';
iframe.contentWindow.document.body.appendChild(baseTag);

var fixHeight = function (ev) {
var iframeDocument = iframe.contentWindow.document;
var iframeBody = iframeDocument.body || iframeDocument.documentElement;
iframe.style.height = 0;
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
iframe.style.height = iframeBody.scrollHeight + 'px';
iframe.contentWindow.removeEventListener(ev.type, fixHeight);
};

iframe.contentWindow.addEventListener('load', fixHeight);
iframe.contentWindow.addEventListener('resize', fixHeight);
iframe.src = preview.dataset.src;
delete preview.dataset.src;
actions.removeEventListener('tracy-toggle', initHtmlPreview);
actions.removeEventListener('click', initHtmlPreview);
};
Expand Down
148 changes: 132 additions & 16 deletions src/MailPanel.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Nette;
use Nette\Http;
use Nette\Mail\Mailer;
use Nette\Mail\Message;
use Nette\Mail\MimePart;
use Nette\Utils\Strings;
use Tracy\Debugger;
Expand Down Expand Up @@ -43,6 +44,9 @@ class MailPanel implements IBarPanel
/** @var Latte\Engine|NULL */
private $latte;

/** @var \ReflectionProperty|NULL */
private $mimePartPartsProperty;


public function __construct(?string $tempDir, Http\IRequest $request, Mailer $mailer, int $messagesLimit = self::DEFAULT_COUNT)
{
Expand Down Expand Up @@ -135,29 +139,97 @@ private function getLatte(): Latte\Engine
});

$this->latte->addFilter('plainText', function (MimePart $part) {
$ref = new \ReflectionProperty('Nette\Mail\MimePart', 'parts');

$queue = [$part];
for ($i = 0; $i < count($queue); $i++) {
/** @var MimePart $subPart */
foreach ($ref->getValue($queue[$i]) as $subPart) {
$contentType = $subPart->getHeader('Content-Type');
if (Strings::startsWith($contentType, 'text/plain') && $subPart->getHeader('Content-Transfer-Encoding') !== 'base64') { // Take first available plain text
return $subPart->getBody();
} elseif (Strings::startsWith($contentType, 'multipart/alternative')) {
$queue[] = $subPart;
}
}
$plainText = $this->findBodyByContentType($part, 'text/plain');
if ($plainText !== null) {
return $plainText;
}

return $this->decodeBody($part);
});

$this->latte->addFilter('previewHtml', function (MimePart $part): string {
$htmlBody = $this->extractHtmlBody($part);
if ($htmlBody !== '') {
return $htmlBody;
}

return $part->getBody();
$plainText = $this->findBodyByContentType($part, 'text/plain') ?? $this->decodeBody($part);
return '<!doctype html>'
. '<meta charset="utf-8">'
. '<style>html,body{margin:0;padding:0;border:none;font-family:sans-serif;font-size:12px;white-space:pre;}body{padding:10px;}</style>'
. '<body>' . htmlspecialchars($plainText, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</body>';
});
}

return $this->latte;
}


private function extractHtmlBody(MimePart $part): string
{
if ($part instanceof Message && $part->getHtmlBody() !== '') {
return $part->getHtmlBody();
}

return $this->findBodyByContentType($part, 'text/html') ?? '';
}


private function findBodyByContentType(MimePart $part, string $contentTypePrefix): ?string
{
$queue = [$part];
for ($i = 0; $i < count($queue); $i++) {
$currentPart = $queue[$i];
$contentType = $currentPart->getHeader('Content-Type');
if (is_string($contentType) && Strings::startsWith(strtolower($contentType), $contentTypePrefix)) {
return $this->decodeBody($currentPart);
}

/** @var MimePart $subPart */
foreach ($this->getMimePartParts($currentPart) as $subPart) {
$queue[] = $subPart;
}
}

return null;
}


/**
* @return MimePart[]
*/
private function getMimePartParts(MimePart $part): array
{
if ($this->mimePartPartsProperty === null) {
$this->mimePartPartsProperty = new \ReflectionProperty(MimePart::class, 'parts');
if (PHP_VERSION_ID < 80100) {
$this->mimePartPartsProperty->setAccessible(true);
}
}

$parts = $this->mimePartPartsProperty->getValue($part);
return is_array($parts) ? $parts : [];
}


private function decodeBody(MimePart $part): string
{
$body = $part->getBody();
$transferEncoding = strtolower((string) $part->getHeader('Content-Transfer-Encoding'));

if ($transferEncoding === MimePart::EncodingQuotedPrintable) {
return quoted_printable_decode($body);
}

if ($transferEncoding === MimePart::EncodingBase64) {
$decodedBody = base64_decode($body, true);
return is_string($decodedBody) ? $decodedBody : $body;
}

return $body;
}


private function tryHandleRequest(): void
{
if (Debugger::$productionMode !== false) {
Expand All @@ -168,7 +240,10 @@ private function tryHandleRequest(): void
$messageId = $this->request->getQuery('nextras-mail-panel-message-id');
$attachmentId = $this->request->getQuery('nextras-mail-panel-attachment-id');

if ($action === 'detail' && is_string($messageId)) {
if ($action === 'preview' && is_string($messageId)) {
$this->handlePreview($messageId);

} elseif ($action === 'detail' && is_string($messageId)) {
$this->handleDetail($messageId);

} elseif ($action === 'source' && is_string($messageId)) {
Expand All @@ -192,7 +267,18 @@ private function handleDetail(string $messageId): void
$message = $this->mailer->getMessage($messageId);

header('Content-Type: text/html');
$this->getLatte()->render(__DIR__ . '/MailPanel.body.latte', ['message' => $message]);
echo $this->renderMessagePreview($message);
exit;
}


private function handlePreview(string $messageId): void
{
assert($this->mailer !== null);
$message = $this->mailer->getMessage($messageId);

header('Content-Type: text/html');
echo $this->addParentBaseTarget($this->renderMessagePreview($message));
exit;
}

Expand All @@ -208,6 +294,36 @@ private function handleSource(string $messageId): void
}


private function renderMessagePreview(MimePart $message): string
{
return $this->getLatte()->renderToString(__DIR__ . '/MailPanel.body.latte', ['message' => $message]);
}


private function addParentBaseTarget(string $html): string
{
$baseTag = '<base target="_parent">';

if (preg_match('~<base(?:\s[^>]*)?>~i', $html) === 1) {
return $html;
}

if (preg_match('~<head(?:\s[^>]*)?>~i', $html, $match, PREG_OFFSET_CAPTURE) === 1) {
$headTag = $match[0][0];
$position = $match[0][1] + strlen($headTag);
return substr($html, 0, $position) . $baseTag . substr($html, $position);
}

if (preg_match('~<html(?:\s[^>]*)?>~i', $html, $match, PREG_OFFSET_CAPTURE) === 1) {
$htmlTag = $match[0][0];
$position = $match[0][1] + strlen($htmlTag);
return substr($html, 0, $position) . '<head>' . $baseTag . '</head>' . substr($html, $position);
}

return '<!doctype html><html><head>' . $baseTag . '</head><body>' . $html . '</body></html>';
}


private function handleAttachment(string $messageId, int $attachmentId): void
{
assert($this->mailer !== null);
Expand Down
Loading