Skip to content

Instantly share code, notes, and snippets.

@beyondlimits
Created November 29, 2018 11:34
Show Gist options
  • Save beyondlimits/46a10516605e3132deb4b594e7b939f1 to your computer and use it in GitHub Desktop.
Save beyondlimits/46a10516605e3132deb4b594e7b939f1 to your computer and use it in GitHub Desktop.
<?php
return function($html)
{
$allowedTags = array(
'body',
'p', 'div', 'span',
'b', 'i', 'u',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'font',
'li', 'ul', 'ol',
'hr', 'br',
'a', 'blockquote',
'img',
);
$mimetypes = array(
'image/jpeg' => 'jpeg',
'image/gif' => 'gif',
'image/png' => 'png',
);
$html = "<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>$html</body></html>";
$dom = new DOMDocument;
set_error_handler(function($number, $error) {
if (preg_match('/^DOMDocument::loadHTML\(\): (.+)$/', $error, $m) == 1) {
throw new Error($m[1]);
}
});
try {
$dom->loadHTML($html);
} catch (Exception $e) {
$dom = null;
}
restore_error_handler();
if (!$dom) {
return;
}
$stack = array();
$current = $dom->getElementsByTagName('body')->item(0);
# usuń niedozwolone tagi oraz atrybuty
do {
$passed = true;
if ($current instanceof DOMElement) {
if (!in_array($current->tagName, $allowedTags)) {
$passed = false;
if ($current->childNodes instanceof Traversable) {
foreach (iterator_to_array($current->childNodes) as $child) {
$stack[] = $current->parentNode->insertBefore($child, $current);
}
}
$current->parentNode->removeChild($current);
}
}
if ($passed) {
$attributes = $current->attributes;
if ($attributes) {
foreach ($attributes as $name => $value) {
if (substr($name, 0, 2) == 'on') {
$current->removeAttribute($name);
}
}
}
if ($current->childNodes instanceof Traversable) {
foreach ($current->childNodes as $child) {
$stack[] = $child;
}
}
}
$current = array_pop($stack);
} while ($current);
# przekształć IMG
$host = getservbyport($_SERVER['SERVER_PORT'], 'tcp') . '://' . $_SERVER['SERVER_NAME'];
foreach ($dom->getElementsByTagName('img') as $img) {
$src = $img->getAttribute('src');
if ($src) {
$url = parse_url($src);
if ($url['scheme'] == 'data') {
$md5 = md5_file($src);
$mime = mime_content_type($src);
$ext = $mimetypes[$mime];
if (!$ext) {
return;
}
$dest = MAINDIR . '/' . FILEDIR . "/newsletter/$md5.$ext";
if (!file_exists($dest)) {
copy($src, $dest);
}
$img->setAttribute('src', "$host/pub/newsletter/$md5.$ext");
}
}
}
$result = '';
foreach ($dom->getElementsByTagName('body')->item(0)->childNodes as $node) {
$result .= $dom->saveHTML($node);
}
return $result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment