<?php
namespace FileRun;

use PhpMimeMailParser\Parser;

global $config;
if (!$config) {exit();}

if ($this->isLimitedPreview()) {
	$this->centeredThumb();
	return;
}

$ext = \FM::getExtension($this->data['fileName']);

spl_autoload_register(function($class) {
	$p = false;
	if (strpos($class, 'PhpMimeMailParser') === 0) {
		$p = gluePath($this->path, str_replace('\\', '/', $class).'.php');
	}
	if ($p && is_file($p)) {
		include $p;
		return true;
	}
});

if ($ext != 'eml') {
	$cmd = 'msgconvert --outfile - '.escapeshellarg($this->data['fullPath']);
	$return_text = [];
	$return_code = 0;
	exec($cmd, $return_text, $return_code);
	if ($return_code != 0) {
		exit('Mail format conversion failed!');
	}
	$parser = Parser::fromText(implode("\n", $return_text));
	unset($return_text);
} else {
	$parser = Parser::fromStream($this->readFile(['returnFilePointer' => true]));
}

$headingHtml = '<div>';
$headers = $parser->getHeaders();
foreach ($headers as $k => $v) {
	if (in_array($k, ['from', 'to', 'subject', 'date'])) {
		$headingHtml .= '<b>'.ucfirst($k).'</b>: '.$v.'<br>';
	}
}
$headingHtml .= '</div>';


/*
require $config['path']['classes'] . '/vendor/HTMLPurifier/HTMLPurifier.auto.php';
$cfg = HTMLPurifier_Config::createDefault();
$cfg->set('Cache.SerializerPath', $config['path']['temp'].'/smarty/');
$cfg->set('URI.AllowedSchemes', ['data' => true]);
$cfg->set('AutoFormat.RemoveEmpty', true);
$purifier = new HTMLPurifier($cfg);
*/

$nonce = (new PassPolicy())->generate(['min_length' => 20, 'requires_special' => false]);
$page = [
	'styles' => ['basic'],
	'nonce' => $nonce,
	'loadMsg' => false,
	'manualEnd' => true
];


$csp = "default-src 'none'; base-uri 'self'; form-action 'none';".
	"script-src 'nonce-".$nonce."'; " .
	"font-src 'self' 'nonce-".$nonce."'; " .
	"connect-src 'none'; " .
	"navigate-to 'none'; " .
	"img-src 'self' data:; style-src 'self' 'unsafe-inline';";
header('Content-Security-Policy: '.$csp);
header("X-Content-Type-Options: nosniff");
//header('Content-Security-Policy: sandbox;');
require $config['path']['includes'].'/ui/page/plugin.php';
echo '<style>body {overflow: auto;}</style>';
echo '<div style="padding: 20px;overflow:auto">';
	echo '<div style="border:1px solid var(--hBCol); max-height:100px; overflow:auto; padding:20px; margin:20px 0;border-radius:var(--mBr)">';
	echo $headingHtml;
	echo '</div>';

	echo $parser->getHtml();
echo '</div>';
echo '</body></html>';