/**
  * 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();
 }
Exemplo n.º 2
0
 /**
  * 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);
 }
 /**
  * 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;
 }
 /**
  * Bootstrap the application services.
  */
 public function boot()
 {
     $converter = new CssToInlineStyles();
     $converter->setUseInlineStylesBlock(true);
     $converter->setStripOriginalStyleTags(true);
     $this->app[Mailer::class]->getSwiftMailer()->registerPlugin(new CssInlinerPlugin($converter));
 }
Exemplo n.º 5
0
 /**
  * @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;
 }
 public function renderHbs($templateName, array $params = [], $inlineCss = false)
 {
     $html = $this->handlebars->render($templateName, $params);
     if ($inlineCss) {
         $html = $this->cssToInlineStyles->convert($html);
     }
     return $html;
 }
 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();
 }
Exemplo n.º 8
0
 /**
  * @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());
     }
 }
Exemplo n.º 9
0
 /**
  * @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();
 }
Exemplo n.º 10
0
function inline_newsletter($css, $content)
{
    // create instance
    $cssToInlineStyles = new CssToInlineStyles();
    $cssToInlineStyles->setHTML($content);
    $cssToInlineStyles->setCSS($css);
    // output
    return $cssToInlineStyles->convert();
}
 /**
  * @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));
         }
     }
 }
 /**
  * @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()));
         }
     }
 }
Exemplo n.º 13
0
 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()));
     }
 }
Exemplo n.º 14
0
 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;
 }
Exemplo n.º 15
0
 /**
  * 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);
 }
Exemplo n.º 16
0
 /**
  * Configure the internal inliner.
  */
 protected function configure()
 {
     $this->internalInliner->setCleanup($this->options['cleanup']);
     $this->internalInliner->setUseInlineStylesBlock($this->options['use_inline_styles_block']);
     $this->internalInliner->setStripOriginalStyleTags($this->options['strip_original_tags']);
     $this->internalInliner->setExcludeMediaQueries($this->options['exclude_media_queries']);
 }
 /**
  * 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);
 }
Exemplo n.º 18
0
 /**
  *	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 &nbsp; 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 &nbsp;
     $sInlineCode = str_replace('{{nbsp}}', '&nbsp;', $sInlineCode);
     $sInlineCode = str_replace('{{padding}}', $this->aSettings['padding'], $sInlineCode);
     return $sInlineCode;
 }
Exemplo n.º 19
0
 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();
 }
 /**
  * @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->setStripOriginalStyleTags();
     $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());
         }
     }
 }
Exemplo n.º 21
0
 /**
  * @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());
 }
Exemplo n.º 22
0
 /**
  * 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();
 }
Exemplo n.º 23
0
 /**
  * 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;
 }
Exemplo n.º 24
0
 /**
  * {@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)]]);
 }
Exemplo n.º 25
0
 /**
  * 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();
 }
Exemplo n.º 26
0
 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;
 }
Exemplo n.º 27
0
 /**
  * @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;
 }
Exemplo n.º 28
0
 /**
  * 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);
 }
Exemplo n.º 29
0
 /**
  *    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;
 }
Exemplo n.º 30
0
 /**
  * @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;
 }