public static function setAbsolutePaths($string, $document = null, $hostUrl = null)
{
if ($document && $document instanceof Model\Document == false) {
throw new \Exception('$document has to be an instance of Document');
}
$replacePrefix = "";
if (!$hostUrl && $document) {
// try to determine if the newsletter is within a site
$site = \Pimcore\Tool\Frontend::getSiteForDocument($document);
if ($site) {
$hostUrl = "http://" . $site->getMainDomain();
$replacePrefix = $site->getRootPath();
}
// fallback
if (!$hostUrl) {
$hostUrl = \Pimcore\Tool::getHostUrl();
}
}
//matches all links
preg_match_all("@(href|src)\\s*=[\"']([^(http|mailto|javascript|data:|#)].*?(css|jpe?g|gif|png)?)[\"']@is", $string, $matches);
if (!empty($matches[0])) {
foreach ($matches[0] as $key => $value) {
$path = $matches[2][$key];
if (strpos($path, '//') === 0) {
$absolutePath = "http:" . $path;
} elseif (strpos($path, '/') === 0) {
$absolutePath = preg_replace("@^" . $replacePrefix . "/@", "/", $path);
$absolutePath = $hostUrl . $absolutePath;
} else {
$absolutePath = $hostUrl . "/{$path}";
$netUrl = new \Net_URL2($absolutePath);
$absolutePath = $netUrl->getNormalizedURL();
}
$path = preg_quote($path);
$string = preg_replace("!([\"']){$path}([\"'])!is", "\\1" . $absolutePath . "\\2", $string);
}
}
preg_match_all("@srcset\\s*=[\"'](.*?)[\"']@is", $string, $matches);
foreach ((array) $matches[1] as $i => $value) {
$parts = explode(',', $value);
foreach ($parts as $key => $v) {
$parts[$key] = $hostUrl . trim($v);
}
$s = ' srcset="' . implode(', ', $parts) . '" ';
if ($matches[0][$i]) {
$string = str_replace($matches[0][$i], $s, $string);
}
}
return $string;
}