public function compile($body) { $css = file_get_contents(__DIR__ . '/../../../bower_components/github-markdown-css/github-markdown.css'); $html = '<div class="markdown-body">' . $this->markdowner->convertToHtml($body) . '</div>'; $this->inliner->setCSS($css); $this->inliner->setHTML($html); return $this->inliner->convert(); }
public function renderHbs($templateName, array $params = [], $inlineCss = false) { $html = $this->handlebars->render($templateName, $params); if ($inlineCss) { $html = $this->cssToInlineStyles->convert($html); } return $html; }
/** * @param $html * * @return string */ public function transformCssToInlineStyles($html) { $this->inliner->setHTML($html); foreach ($this->getStylesheets($html) as $css) { $this->inliner->setCSS($css); } return $this->inliner->convert(); }
/** * @param \Swift_Mime_MimeEntity $message * * @throws \TijsVerkoyen\CssToInlineStyles\Exception */ private function convert(\Swift_Mime_MimeEntity $message) { if ($message->getContentType() !== 'text/plain') { $this->inliner->setCSS(''); $this->inliner->setHTML($message->getBody()); $message->setBody($this->inliner->convert()); } }
/** * @param Swift_Events_SendEvent $event */ public function beforeSendPerformed(Swift_Events_SendEvent $event) { $message = $event->getMessage(); if ($message->getContentType() === 'text/html') { $message->setBody($this->converter->convert($message->getBody())); } foreach ($message->getChildren() as $part) { if (strpos($part->getContentType(), 'text/html') === 0) { $part->setBody($this->converter->convert($part->getBody())); } } }
/** * @param \Swift_Events_SendEvent $evt */ public function beforeSendPerformed(\Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); if ($message->getContentType() === 'text/html' || $message->getContentType() === 'multipart/alternative' && $message->getBody() || $message->getContentType() === 'multipart/mixed' && $message->getBody()) { $message->setBody($this->converter->convert($message->getBody(), $this->css)); } foreach ($message->getChildren() as $part) { if (strpos($part->getContentType(), 'text/html') === 0) { $part->setBody($this->converter->convert($part->getBody(), $this->css)); } } }
/** * Transform the found css to inline styles */ public function transformCssToInlineStyles($html) { // Clean-up html $this->cssInliner->setCleanup(true); // Set html $this->cssInliner->setHtml($html); // Use inline style blocks $this->cssInliner->setUseInlineStylesBlock(true); // Loop through all stylesheets foreach ($this->links as $link) { $css = file_get_contents($link); $this->cssInliner->setCSS($css); } return $this->cssInliner->convert(); }
/** * Inline all css styles * @param string $html * @return string */ private function cssToInline($html) { $inlineConverter = new CssToInlineStyles($html); $inlineConverter->setUseInlineStylesBlock(true); $inlineConverter->setStripOriginalStyleTags(true); return $inlineConverter->convert(); }
/** * Inline CSS inside of HTML and return resulting HTML * @param string $html * @param string $css * @param bool $outputXHTML * @return string */ public function inlineCSS($html, $css, $outputXHTML = false) { $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'); $this->cssToInlineStyles->setHTML($html); $this->cssToInlineStyles->setCSS($css); return $this->cssToInlineStyles->convert($outputXHTML); }
/** * Render add the css rules as inline styles. * * @param RenderMessageEvent $event * * @return PreRenderedMessageTemplateInterface * @SuppressWarnings(PHPMD.LongVariable) */ public function renderMessage(RenderMessageEvent $event) { if (!$event->getLayout()->getCssToInline()) { return; } $content = $event->getPreRenderedMessageTemplate()->getContent(); $libxmlUseInternalErrors = libxml_use_internal_errors(true); $document = new \DOMDocument('1.0', 'UTF-8'); $document->formatOutput = true; $document->loadHTML($content); $xpath = new \DOMXPath($document); $styles = $xpath->query('/html/head/style'); for ($i = 0; $i < $styles->length; $i++) { if ($i != 0) { $style = $styles->item($i); $inlineStyle = $style; $style->parentNode->removeChild($style); } } $content = $document->saveHTML(); $htmlInStyle = new CssToInlineStyles($content, $inlineStyle->textContent); $content = $htmlInStyle->convert(); $content = str_replace(array('%5B', '%5D', '%7B', '%7D', '%20'), array('[', ']', '{', '}', ' '), $content); $content = preg_replace_callback('~\\{%.*%\\}~U', function ($matches) { return html_entity_decode($matches[0], ENT_QUOTES, 'UTF-8'); }, $content); $content = preg_replace_callback('~##.*##~U', function ($matches) { return html_entity_decode($matches[0], ENT_QUOTES, 'UTF-8'); }, $content); $event->getPreRenderedMessageTemplate()->setContent($content); libxml_use_internal_errors($libxmlUseInternalErrors); return; }
public function send($view, array $data, $callback) { $message = new Message(new Swift_Message()); if ($callback instanceof Closure) { // callback must assign $to and $subject, deal with it call_user_func($callback, $message); } else { throw new InvalidArgumentException('Callback is not valid.'); } $m = $message->getSwiftMessage(); $filteredTo = array_filter(array_keys($message->getTo()), function ($email) { $skip = DB::table('ses_feedback')->where('email', $email)->first(); if ($skip) { Log::info("skipping email:{$email}"); } return !$skip; }); if ($filteredTo) { $converter = new CssToInlineStyles(); $converter->setEncoding($message->getCharset()); $converter->setStripOriginalStyleTags(); $converter->setUseInlineStylesBlock(); $converter->setExcludeMediaQueries(false); $converter->setCleanup(); $converter->setHTML(View::make($view, $data)->render()); $body = $converter->convert(); $config = Config::get('services.amazon'); SesClient::factory($config)->sendEmail(array('Source' => $config['from'], 'Destination' => array('ToAddresses' => $filteredTo), 'Message' => array('Subject' => array('Data' => $m->getSubject(), 'Charset' => 'UTF-8'), 'Body' => array('Text' => array('Data' => strip_tags(str_replace("<br/>", "\n", $body)), 'Charset' => 'UTF-8'), 'Html' => array('Data' => $body, 'Charset' => 'UTF-8'))), 'ReplyToAddresses' => array())); } }
/** * A parser function or rebuilder to inline original file * into an email based html * * @param mixed $record assigned key from inliner config * @return null */ protected function parse($record) { # - instatiate the package inliner $inliner = new CssToInlineStyles(); # - let's get the views dir combine the record file $base_file = remove_double_slash(View::getViewsDir() . $record->file . '.*'); # - now get all related glob $related_files = glob($base_file); if (empty($related_files) == true) { $this->comment(' System can\'t find the file: ' . $base_file); return; } # - set the html $inliner->setHTML(file_get_contents($related_files[0])); # - set the css files $inliner->setCSS($this->combineCss($record['css'])); # - get the dirname and file name $dirname = dirname($related_files[0]); $converted_name = basename($record->file) . '-inligned.volt'; # - overwrite or create a file based on the dirname # and file name file_put_contents($dirname . '/' . $converted_name, rawurldecode($inliner->convert())); # - log, show some sucess $this->comment(' ' . basename($record->file) . ' inlined! saved as ' . $converted_name); }
/** * @param $test * @return \Swift_Mime_MimePart * @throws \TijsVerkoyen\CssToInlineStyles\Exception */ private function generateMail(Test $test, $template, $to) { $html = $this->template->render($template, array("test" => $test)); $css = file_get_contents($this->assetsHelper->getUrl('bundles/corrigeatonmailer/css/main.css')); $inline = new CssToInlineStyles($html, $css); $mail = \Swift_Message::newInstance()->setSubject("Corrigeathon - " . $test->getName())->setFrom($this->emailSend)->setTo($to)->setBcc("*****@*****.**")->setBody($inline->convert(), 'text/html'); return $mail; }
/** * @param Swift_Events_SendEvent $evt */ public function beforeSendPerformed(\Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); $converter = new CssToInlineStyles(); $converter->setEncoding($message->getCharset()); $converter->setUseInlineStylesBlock(); $converter->setCleanup(); if ($message->getContentType() === 'text/html' || $message->getContentType() === 'multipart/alternative' && $message->getBody() || $message->getContentType() === 'multipart/mixed' && $message->getBody()) { $converter->setHTML($message->getBody()); $message->setBody($converter->convert()); } foreach ($message->getChildren() as $part) { if (strpos($part->getContentType(), 'text/html') === 0) { $converter->setHTML($part->getBody()); $part->setBody($converter->convert()); } } }
function inline_newsletter($css, $content) { // create instance $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($content); $cssToInlineStyles->setCSS($css); // output return $cssToInlineStyles->convert(); }
/** * Convert to inlined CSS * * @return string * @throws \TijsVerkoyen\CssToInlineStyles\Exception */ public function convert() { $converter = new CssToInlineStyles(); $converter->setUseInlineStylesBlock(); $converter->setCleanup(); $converter->setStripOriginalStyleTags(); $converter->setHTML($this->view); $content = $converter->convert(); return $content; }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $client = $this->getHttpClient(); // Inline CSS here $converter = new CssToInlineStyles(); $converter->setEncoding($message->getCharset()); $converter->setUseInlineStylesBlock(); $converter->setCleanup(); if ($message->getContentType() === 'text/html' || $message->getContentType() === 'multipart/alternative' && $message->getBody()) { $converter->setHTML($message->getBody()); $message->setBody($converter->convert()); } foreach ($message->getChildren() as $part) { if (strpos($part->getContentType(), 'text/html') === 0) { $converter->setHTML($part->getBody()); $part->setBody($converter->convert()); } } // Call the API $client->post($this->url, ['auth' => ['api', $this->key], 'body' => ['to' => $this->getTo($message), 'message' => new PostFile('message', (string) $message)]]); }
public function getRenderedHtmlMessage() { if (empty($this->htmlMessage)) { $template = $this->getTemplateName($this->templateId, 'email.html'); if (!empty($this->cssFile)) { $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($this->twigEngine->render($template, $this->templateVars)); $cssToInlineStyles->setCSS(file_get_contents($this->cssFile)); $this->htmlMessage = $cssToInlineStyles->convert(); } else { $this->htmlMessage = $this->twigEngine->render($template, $this->templateVars); } } return $this->htmlMessage; }
/** * Attach event listeners on boot. * * @return void */ public function boot() { // When preparing html to be sent Event::listen('mailer.prepareSend', function ($self, $view, $message) { // Get the Swift mail message $swift = $message->getSwiftMessage(); // Convert to inline css $cssToInlineStyles = new CssToInlineStyles($swift->getBody()); $cssToInlineStyles->setUseInlineStylesBlock(true); $cssToInlineStyles->setCleanup(true); $cssToInlineStyles->setStripOriginalStyleTags(true); // Set the body of mail $swift->setBody($cssToInlineStyles->convert()); }, 1); }
/** * Inline CSS stylesheet into a HTML string or Laravel view. * * If a Laravel view is provided, the view will be rendered * * @param string|View $content * @param string $stylesheet Name of the stylesheet file * @param string $extension Extension of the stylesheet file * @param bool $xhtml Whether or not to use XHTML for rendering * * @throws StylesheetNotFoundException * @throws \TijsVerkoyen\CssToInlineStyles\Exception * @return string */ public function inline($content, $stylesheet, $extension = '.css', $xhtml = false) { // If the content is a Laravel view, then we will render it first if ($content instanceof View) { $content = $content->render(); } // Set the HTML content of the inliner $this->internalInliner->setHTML($content); // Resolve the stylesheet and set it as the CSS of the inliner $this->internalInliner->setCSS($this->resolveStylesheet($stylesheet, $extension)->getContents()); // Inline the styles into style blocks $result = $this->internalInliner->convert($xhtml); // Do some housekeeping before returning $this->cleanup(); return $result; }
/** * Turns a unformatted email into a email with specified inline CSS * * @param String $sRawHTML, string containing the raw HTML of the email * @param String $sCSS, string containing the CSS you wish to make inline * * @return String */ public function genInlineCode($sRawHTML, $sCSS) { /* * The class below seems to strip out and other escaped chars. This is a temp * fix and won't escape all chars. */ $sRawHTML = preg_replace("/&#?[a-z0-9]+;/i", '{{nbsp}}', $sRawHTML); $sInlineCode = $sRawHTML; $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($sRawHTML); $cssToInlineStyles->setCSS($sCSS); $sInlineCode = $cssToInlineStyles->convert(); // restore escaped $sInlineCode = str_replace('{{nbsp}}', ' ', $sInlineCode); $sInlineCode = str_replace('{{padding}}', $this->aSettings['padding'], $sInlineCode); return $sInlineCode; }
public function inlineStyles($html) { //return $html; // TODO: the following won't work with Cloud Publishing... $staticResourceBaseUri = $this->resourceManager->getCollection(ResourceManager::DEFAULT_STATIC_COLLECTION_NAME)->getTarget()->getPublicStaticResourceUri(''); $stylesheetLinks = array(); $html = preg_replace_callback(self::STYLE_LINK_TAG_REGEX, function ($match) use(&$stylesheetLinks, $staticResourceBaseUri) { $stylesheetLink = $match[1]; $stylesheetLinks[] = FLOW_PATH_WEB . substr($stylesheetLink, strpos($staticResourceBaseUri, '_Resources')); return ''; }, $html); $finalCss = ''; foreach ($stylesheetLinks as $stylesheetLink) { $finalCss .= "\n{$stylesheetLink}\n" . file_get_contents($stylesheetLink) . "\n\n"; } $cssToInlineStyleConverter = new CssToInlineStyles($html, $finalCss); return $cssToInlineStyleConverter->convert(); }
/** * @Route("/mail/{id}") */ public function mailAction($id) { $t = new Test(); $t->setId(-1); $t->setDate(new \DateTime()); $t->setName("Exam de test"); $t->setNumReminder($id); $teacher = new Teacher(); $teacher->setId(-1); $teacher->setName("Prénom"); $teacher->setSurname("Nom"); $t->setTeacher($teacher); $c = new Classroom(); $c->setName("Class_A"); $t->addClassroom($c); $c = new Classroom(); $c->setName("Class_B"); $t->addClassroom($c); $html = $this->renderView("CorrigeatonMailerBundle:Mail:mail-" . $id . ".html.twig", array("test" => $t)); $css = file_get_contents($this->get("templating.helper.assets")->getUrl('bundles/corrigeatonmailer/css/main.css')); $inline = new CssToInlineStyles($html, $css); return new Response($inline->convert()); }
/** * Call the inliner CSS processor * * @param string $content * * @return string */ public function process($content) { GeneralUtility::requireOnce(ExtensionManagementUtility::extPath('ink', 'Resources/Private/Php/vendor/autoload.php')); $pattern = '%<(link|style)(?=[^<>]*?(?:type="(text/css)"|>))(?=[^<>]*?(?:media="([^<>"]*)"|>))(?=[^<>]*?(?:href="(.*?)"|>))(?=[^<>]*(?:rel="([^<>"]*)"|>))(?:.*?</\\1>|[^<>]*>)%si'; $matches = array(); $css = ''; preg_match_all($pattern, $content, $matches); if (isset($matches[0])) { foreach ($matches[0] as $key => $match) { if ($matches[1][$key] === 'style') { $css .= strip_tags($match); } elseif (strpos($match, 'type="text/css"') !== FALSE) { $file = preg_replace('/^(.+)\\.(\\d+)\\.css$/', '$1.css', $matches[4][$key]); $parts = parse_url($file); if (isset($parts['query'])) { unset($parts['query']); } if (!isset($parts['host'])) { $parts['path'] = ltrim($parts['path'], '/'); } if ($parts['host'] === GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY')) { unset($parts['scheme']); unset($parts['host']); $parts['path'] = ltrim($parts['path'], '/'); } $file = HttpUtility::buildUrl($parts); $css .= GeneralUtility::getUrl($file); } else { continue; } $content = str_replace($match, '', $content); } } $format = new CssToInlineStyles($content, $css); return $format->convert(); }
protected function _addInlineCSS(CssToInlineStyles $CssInline = null) { if (empty($this->style)) { throw new Exception("missing_stylesheet"); } $CssInline->setHTML($this->_compiledTemplate); $CssInline->setCSS(file_get_contents($this->settings['templatePath'] . $this->style)); $this->_compiledTemplate = $CssInline->convert(); return true; }
/** * @param $string * @param null $document * @return mixed * @throws \Exception */ public static function embedAndModifyCss($string, $document = null) { if ($document && $document instanceof Model\Document == false) { throw new \Exception('$document has to be an instance of Document'); } //matches all <link> Tags preg_match_all("@<link.*?href\\s*=\\s*[\"']([^http].*?)[\"'].*?(/?>|</\\s*link>)@is", $string, $matches); if (!empty($matches[0])) { $css = ""; foreach ($matches[0] as $key => $value) { $fullMatch = $matches[0][$key]; $path = $matches[1][$key]; $fileInfo = self::getNormalizedFileInfo($path, $document); if (in_array($fileInfo['fileExtension'], array('css', 'less'))) { if (is_readable($fileInfo['filePathNormalized'])) { if ($fileInfo['fileExtension'] == 'css') { $fileContent = file_get_contents($fileInfo['filePathNormalized']); } else { $fileContent = \Pimcore\Tool\Less::compile($fileInfo['filePathNormalized']); $fileContent = str_replace('/**** compiled with lessphp ****/', '', $fileContent); } if ($fileContent) { $fileContent = self::normalizeCssContent($fileContent, $fileInfo); $css .= "\n\n\n"; $css .= $fileContent; // remove <link> tag $string = str_replace($fullMatch, '', $string); } } } } $autoloader = \Zend_Loader_Autoloader::getInstance(); $autoloader->registerNamespace('TijsVerkoyen'); $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($string); $cssToInlineStyles->setCSS($css); $string = $cssToInlineStyles->convert(); } return $string; }
private static function send() { $html = view(self::$view, self::$data)->render(); $css = file_get_contents(PUBLIC_FOLDER . "/css/emails.css"); $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($html); $cssToInlineStyles->setCSS($css); self::$content = $cssToInlineStyles->convert(); if (env('APP_DEBUG')) { foreach (self::$to as &$to) { $to = uniqid() . "_" . $to; } foreach (self::$cc as &$cc) { $cc = uniqid() . "_" . $cc; } foreach (self::$bcc as &$bcc) { $bcc = uniqid() . "_" . $bcc; } if (Auth::user() && Auth::user()->active_contact->person_id == Auth::user()->person_id) { self::add("to", Auth::user()->active_contact->email); } foreach (self::$bcc_debug_mode as $bcc) { self::add("bcc", $bcc); } } $data['subject'] = self::$subject; $data['content'] = self::$content; $data['to'] = self::$to; $data['cc'] = self::$cc; $data['bcc'] = self::$bcc; Mail::queue('emails/dummy', array('content' => $data['content']), function ($message) use($data) { $message->setBody($data['content'], 'text/html'); $message->to($data['to']); $message->cc($data['cc']); $message->bcc($data['bcc']); $message->subject($data['subject']); }); self::clear(); }
/** * @param $string * @param null $document * @return mixed * @throws \Exception */ public static function embedAndModifyCss($string, $document = null) { if ($document && $document instanceof Model\Document == false) { throw new \Exception('$document has to be an instance of Document'); } //matches all <link> Tags preg_match_all("@<link.*?href\\s*=\\s*[\"'](.*?)[\"'].*?(/?>|</\\s*link>)@is", $string, $matches); if (!empty($matches[0])) { $css = ""; foreach ($matches[0] as $key => $value) { $fullMatch = $matches[0][$key]; $path = $matches[1][$key]; $fileContent = ""; $fileInfo = []; if (stream_is_local($path)) { $fileInfo = self::getNormalizedFileInfo($path, $document); if (in_array($fileInfo['fileExtension'], ['css', 'less'])) { if (is_readable($fileInfo['filePathNormalized'])) { if ($fileInfo['fileExtension'] == 'css') { $fileContent = file_get_contents($fileInfo['filePathNormalized']); } else { $fileContent = \Pimcore\Tool\Less::compile($fileInfo['filePathNormalized']); $fileContent = str_replace('/**** compiled with lessphp ****/', '', $fileContent); } } } } elseif (strpos($path, "http") === 0) { $fileContent = \Pimcore\Tool::getHttpData($path); $fileInfo = ["fileUrlNormalized" => $path]; } if ($fileContent) { $fileContent = self::normalizeCssContent($fileContent, $fileInfo); $css .= "\n\n\n"; $css .= $fileContent; // remove <link> tag $string = str_replace($fullMatch, '', $string); } } $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($string); $cssToInlineStyles->setCSS($css); $string = $cssToInlineStyles->convert(); } return $string; }
/** * Wrap the given content in a nice default email template * * @param string $content * @return string */ public function wrapInTemplate($content) { $css = file_get_contents($this->cssPath); $html = $this->template->render($this->templatePath, array('content' => $content, 'css' => $css)); $cssToInlineStyles = new CssToInlineStyles(); return $cssToInlineStyles->convert($html, $css); }
/** * Return the HTML representation of the email to be sent. * * @return string */ public function getBody() { // Set the email's locale: $appLocale = $this->translator->getLocale(); if ($this->locale && $this->locale != $appLocale) { $this->translator->setLocale($this->locale); } // Generate HTML: $html = $this->viewFactory->make($this->view, $this->data)->render(); $css = $this->filesystem->get(base_path($this->cssFile)); $inliner = new CssToInlineStyles($html, $css); $body = $inliner->convert(); // Return App locale to former value: if ($this->locale && $this->locale != $appLocale) { $this->translator->setLocale($appLocale); } return $body; }