Exemplo n.º 1
1
 public function apply_style_inline($content)
 {
     if (in_array($this->get_content_format(), array('text/html', 'multipart/alternative')) && class_exists('DOMDocument')) {
         // get CSS styles
         ob_start();
         learn_press_get_template('emails/email-styles.php');
         $css = apply_filters('learn_press_email_styles', ob_get_clean());
         try {
             LP()->_include('libraries/class-emogrifier.php');
             // apply CSS styles inline for picky email clients
             $emogrifier = new Emogrifier($content, $css);
             $content = $emogrifier->emogrify();
         } catch (Exception $e) {
         }
     }
     return $content;
 }
Exemplo n.º 2
0
 function acymailing_replaceusertags(&$email, &$user, $addbody = true)
 {
     if (!$email->sendHTML) {
         return;
     }
     $email->body = preg_replace('#< *(tr|td|table)([^>]*)(style="[^"]*)background-image *: *url\\(\'?([^)\']*)\'?\\);?#Ui', '<$1 background="$4" $2 $3', $email->body);
     $email->body = acymailing::absoluteURL($email->body);
     $email->body = preg_replace('#< *img([^>]*)(style="[^"]*)(float *: *)(right|left|top|bottom|middle)#Ui', '<img$1 align="$4" hspace="5" $2$3$4', $email->body);
     if (empty($email->tempid)) {
         return;
     }
     if (!isset($this->templates[$email->tempid])) {
         $this->templates[$email->tempid] = array();
         if (empty($this->templateClass)) {
             $this->templateClass = acymailing::get('class.template');
         }
         $template = $this->templateClass->get($email->tempid);
         if (!empty($template->stylesheet)) {
             $this->stylesheets[$email->tempid] = $template->stylesheet;
         }
         if (!empty($template->styles)) {
             foreach ($template->styles as $class => $style) {
                 if (preg_match('#^tag_(.*)$#', $class, $result)) {
                     $this->tags[$email->tempid]['#< *' . $result[1] . '((?:(?!style).)*)>#Ui'] = '<' . $result[1] . ' style="' . $style . '" $1>';
                 } elseif ($class == 'color_bg') {
                     $this->others[$email->tempid][$class] = $style;
                 } else {
                     $this->templates[$email->tempid]['class="' . $class . '"'] = 'style="' . $style . '"';
                 }
             }
         }
     }
     if ($addbody and !strpos($email->body, '</body>')) {
         $before = '<html><head>' . "\n";
         $before .= '<meta http-equiv="Content-Type" content="text/html; charset=' . $this->config->get('charset') . '">' . "\n";
         $before .= '<title>' . $email->subject . '</title>' . "\n";
         $before .= '</head>' . "\n" . '<body';
         if (!empty($this->others[$email->tempid]['color_bg'])) {
             $before .= ' bgcolor="' . $this->others[$email->tempid]['color_bg'] . '" ';
         }
         $before .= '>' . "\n";
         $email->body = $before . $email->body . '</body>' . "\n" . '</html>';
     }
     if (!empty($this->templates[$email->tempid])) {
         $email->body = str_replace(array_keys($this->templates[$email->tempid]), $this->templates[$email->tempid], $email->body);
     }
     if (!empty($this->tags[$email->tempid])) {
         $email->body = preg_replace(array_keys($this->tags[$email->tempid]), $this->tags[$email->tempid], $email->body);
     }
     if (!empty($this->stylesheets[$email->tempid]) and class_exists('Emogrifier')) {
         $emogrifier = new Emogrifier($email->body, $this->stylesheets[$email->tempid]);
         $email->body = $emogrifier->emogrify();
         if (!$addbody and strpos($email->body, '<!DOCTYPE') !== false) {
             $email->body = preg_replace('#<\\!DOCTYPE.*<body([^>]*)>#Usi', '', $email->body);
             $email->body = preg_replace('#</body>.*$#si', '', $email->body);
         }
     }
 }
Exemplo n.º 3
0
 /**
  * Runs the content through Emogrifier to merge css style inline before sending
  * 
  * @see Email::parseVariables()
  */
 protected function parseVariables($isPlain = false)
 {
     parent::parseVariables($isPlain);
     // if it's an html email, filter it through emogrifier
     if (!$isPlain && preg_match('/<style[^>]*>(?:<\\!--)?(.*)(?:-->)?<\\/style>/ims', $this->body, $match)) {
         $css = $match[1];
         $html = str_replace(array("<p>\n<table>", "</table>\n</p>", '&copy ', $match[0]), array("<table>", "</table>", '', ''), $this->body);
         $emog = new Emogrifier($html, $css);
         $this->body = $emog->emogrify();
     }
 }
Exemplo n.º 4
0
 static function InlineStyles($message)
 {
     if (false === strpos($message, '<html')) {
         return $message;
     }
     $cssfile = Shopp::locate_template(array('email.css'));
     $stylesheet = file_get_contents($cssfile);
     if (!empty($stylesheet)) {
         $Emogrifier = new Emogrifier($message, $stylesheet);
         $message = $Emogrifier->emogrify();
     }
     return $message;
 }
 /**
  * Render with Emogrification
  *
  * @param string $view
  * @param string $layout
  * @return mixed
  * @throws NotFoundException
  */
 public function render($view = null, $layout = null)
 {
     // Let the parent do it's rendering thing first
     parent::render($view, $layout);
     // Parse out the CSS into a string and remove any CSS from the output
     $css = $this->_extractAndRemoveCss();
     // Import the Emogrifier class
     App::import('Vendor', 'Emogrifier.emogrifier');
     $Emogrifier = new Emogrifier($this->output, $css);
     // Emogrification!
     $this->output = @$Emogrifier->emogrify();
     //debug($this->output);
     return $this->output;
 }
Exemplo n.º 6
0
 /**
  * @return string Result
  */
 protected function _processEmogrifier($html, $css)
 {
     //$css .= $this->_extractAndRemoveCss($html);
     App::import('Vendor', 'Tools.Emogrifier', array('file' => 'Emogrifier/Emogrifier.php'));
     $Emogrifier = new Emogrifier($html, $css);
     //$Emogrifier->preserveEncoding = true;
     $result = $Emogrifier->emogrify();
     if ($this->config['cleanup']) {
         // Remove comments and whitespace
         $result = preg_replace('/<!--(.|\\s)*?-->/', '', $result);
         //$result = preg_replace( '/\s\s+/', '\s', $result);
         // Result classes and ids
         $result = preg_replace('/\\bclass="[^"]*"/', '', $result);
         $result = preg_replace('/\\bid="[^"]*"/', '', $result);
     }
     return $result;
 }
 /**
  * Performs processing on the email content to make CSS styles inline. This
  * wraps the emogrified library, but extracts external an inline css
  * defitions.
  *
  * @param  string $content
  * @return string
  */
 protected function emogrify($content)
 {
     require_once 'emogrifier/emogrifier.php';
     // order here is seemingly important; 'tidy' seems to strip stuff important for detecting encoding??
     $encoding = mb_detect_encoding($content);
     $content = $this->tidy($content, $encoding);
     $content = mb_convert_encoding($content, 'HTML-ENTITIES', $encoding);
     $emog = new Emogrifier($content);
     $css = array();
     if (!$encoding) {
         $encoding = 'UTF-8';
     }
     $document = new DOMDocument();
     $document->encoding = $encoding;
     $document->strictErrorChecking = false;
     // some versions of tidy don't remove duplicate attrs
     libxml_use_internal_errors(true);
     $document->loadHTML($content);
     $document->normalizeDocument();
     $xpath = new DOMXPath($document);
     foreach ($xpath->query("//link[@rel='stylesheet']") as $link) {
         $media = $link->getAttribute('media');
         $file = $this->findCSSFile($link->getAttribute('href'));
         if (file_exists($file)) {
             $contents = trim(file_get_contents($file));
             if ($contents && (!$media || in_array($media, array('all', 'screen')))) {
                 $css[] = $contents;
             }
         }
     }
     foreach ($xpath->query('//style') as $style) {
         $type = $style->getAttribute('type');
         $content = trim($style->textContent);
         if ($content && (!$type || $type == 'text/css')) {
             $css[] = $content;
         }
     }
     $emog->setCSS(implode("\n", $css));
     $content = $emog->emogrify();
     // clean up crap from emogrify
     $content = str_replace('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">', '', $content);
     return $content;
 }
Exemplo n.º 8
0
 /**
  * @return string Result
  */
 protected function _processEmogrifier($html, $css)
 {
     if (class_exists('\\Pelago\\Emogrifier')) {
         $Emogrifier = new \Pelago\Emogrifier($html, $css);
     } else {
         App::import('Vendor', 'Tools.Emogrifier', ['file' => 'Emogrifier/Emogrifier.php']);
         $Emogrifier = new Emogrifier($html, $css);
     }
     //$Emogrifier->preserveEncoding = true;
     $result = $Emogrifier->emogrify();
     if ($this->config['cleanup']) {
         // Remove comments and whitespace
         $result = preg_replace('/<!--(.|\\s)*?-->/', '', $result);
         //$result = preg_replace( '/\s\s+/', '\s', $result);
         // Result classes and ids
         if (!$this->config['responsive']) {
             $result = preg_replace('/\\bclass="[^"]*"/', '', $result);
             $result = preg_replace('/\\bid="[^"]*"/', '', $result);
         }
     }
     return $result;
 }
Exemplo n.º 9
0
    /**
     * Render the contents using the current layout and template.
     *
     * @param string $content Content to render
     * @return array Email ready to be sent
     * @access private
     */
	public function __renderTemplate($content) {
		$viewClass = $this->Controller->view;

		if ($viewClass != 'View') {
			if (strpos($viewClass, '.') !== false) {
				list($plugin, $viewClass) = explode('.', $viewClass);
			}
			$viewClass = $viewClass . 'View';
			App::import('View', $this->Controller->view);
		}
		$View = new $viewClass($this->Controller, false);
		$View->layout = $this->layout;
		$msg = array();

		$content = implode("\n", $content);

		if ($this->sendAs === 'both')
		{
			$htmlContent = $content;
			if (!empty($this->attachments))
			{
				$msg[] = '--' . $this->__boundary;
				$msg[] = 'Content-Type: multipart/alternative; boundary="alt-' . $this->__boundary . '"';
				$msg[] = '';
			}
			$msg[] = '--alt-' . $this->__boundary;
			$msg[] = 'Content-Type: text/plain; charset=' . $this->charset;
			$msg[] = 'Content-Transfer-Encoding: 7bit';
			$msg[] = '';

			$content = $View->element('email' . DS . 'text' . DS . $this->template, array('content' => $content), true);
			$View->layoutPath = 'email' . DS . 'text';
			$content = explode("\n", str_replace(array("\r\n", "\r"), "\n", $View->renderLayout($content)));
			$msg = array_merge($msg, $content);

			$msg[] = '';
			$msg[] = '--alt-' . $this->__boundary;
			$msg[] = 'Content-Type: text/html; charset=' . $this->charset;
			$msg[] = 'Content-Transfer-Encoding: 7bit';
			$msg[] = '';

			$htmlContent = $View->element('email' . DS . 'html' . DS . $this->template, array('content' => $htmlContent), true);
			$View->layoutPath = 'email' . DS . 'html';
			$htmlContent = explode("\n", str_replace(array("\r\n", "\r"), "\n", $View->renderLayout($htmlContent)));
			if ($this->cssStylesheet !== null)
			{
			    $css = $View->element('email' . DS . 'css' . DS . $this->cssStylesheet);
			    $emo = new Emogrifier($htmlContent, $css);
			    $htmlContent = $emo->emogrify();
			}
			$msg = array_merge($msg, $htmlContent);
			$msg[] = '';
			$msg[] = '--alt-' . $this->__boundary . '--';
			$msg[] = '';

			return $msg;
		}

		if (!empty($this->attachments)) {
			if ($this->sendAs === 'html') {
				$msg[] = '';
				$msg[] = '--' . $this->__boundary;
				$msg[] = 'Content-Type: text/html; charset=' . $this->charset;
				$msg[] = 'Content-Transfer-Encoding: 7bit';
				$msg[] = '';
			} else {
				$msg[] = '--' . $this->__boundary;
				$msg[] = 'Content-Type: text/plain; charset=' . $this->charset;
				$msg[] = 'Content-Transfer-Encoding: 7bit';
				$msg[] = '';
			}
		}

		$content = $View->element('email' . DS . $this->sendAs . DS . $this->template, array('content' => $content), true);
		$View->layoutPath = 'email' . DS . $this->sendAs;
		
        if ($this->sendAs === 'html' && $this->cssStylesheet !== null)
        {
            $css = $View->element('email' . DS . 'css' . DS . $this->cssStylesheet);
            $emo = new Emogrifier($content, $css);
            $content = $emo->emogrify();
        }
        else
        {
            $content = $View->renderLayout($content);
        }
		$content = explode("\n", str_replace(array("\r\n", "\r"), "\n", $content));
		$msg = array_merge($msg, $content);

		return $msg;
	}
 /**
  * Applies $this->css to $this->html and returns the HTML with the CSS
  * applied.
  *
  * This method places the CSS inline.
  *
  * @return string
  *
  * @throws BadMethodCallException
  */
 public function emogrify()
 {
     if ($this->html === '') {
         throw new BadMethodCallException('Please set some HTML first before calling emogrify.', 1390393096);
     }
     self::$_media = '';
     // reset
     $xmlDocument = $this->createXmlDocument();
     $this->process($xmlDocument);
     return $xmlDocument->saveHTML();
 }
 public static function createHtmlBody($name, $body)
 {
     $stylesheets = self::getNotificationEmailStylesheets($name);
     $css = '';
     $err = array();
     foreach ($stylesheets as $stylesheet) {
         $ss = file_get_contents(self::getStylesheetPath($stylesheet));
         if (false === $ss) {
             $err[] = $stylesheet;
         } else {
             $css .= $ss;
         }
     }
     if (count($err)) {
         throw new sfException('Cannot find following stylesheets: %s', implode(', ', $err));
     }
     $emog = new Emogrifier($body, $css);
     $body = $emog->emogrify();
     return $body;
 }
Exemplo n.º 12
0
 /**
  * Apply inline styles to dynamic content.
  *
  * @param string|null $content
  * @return string
  */
 public function style_inline($content)
 {
     // make sure we only inline CSS for html emails
     if (in_array($this->get_content_type(), array('text/html', 'multipart/alternative')) && class_exists('DOMDocument')) {
         // get CSS styles
         ob_start();
         wc_get_template('emails/email-styles.php');
         $css = apply_filters('woocommerce_email_styles', ob_get_clean());
         try {
             // apply CSS styles inline for picky email clients
             $emogrifier = new Emogrifier($content, $css);
             $content = $emogrifier->emogrify();
         } catch (Exception $e) {
             $logger = new WC_Logger();
             $logger->add('emogrifier', $e->getMessage());
         }
     }
     return $content;
 }
Exemplo n.º 13
0
/**
 * This function converts CSS to inline style, the CSS needs to be found in a <style> element
 *
 * @param $html_text => STR with the html text to be converted
 * @return false | converted html text
 */
function html_email_handler_css_inliner($html_text)
{
    $result = false;
    if (!empty($html_text) && defined("XML_DOCUMENT_NODE")) {
        $css = "";
        // set custom error handling
        libxml_use_internal_errors(true);
        $dom = new DOMDocument();
        $dom->loadHTML($html_text);
        $styles = $dom->getElementsByTagName("style");
        if (!empty($styles)) {
            $style_count = $styles->length;
            for ($i = 0; $i < $style_count; $i++) {
                $css .= $styles->item($i)->nodeValue;
            }
        }
        // clear error log
        libxml_clear_errors();
        elgg_load_library("emogrifier");
        $emo = new Emogrifier($html_text, $css);
        $result = $emo->emogrify();
    }
    return $result;
}
Exemplo n.º 14
0
 function _applyTemplate(&$email, $addbody)
 {
     if (empty($email->tempid)) {
         return;
     }
     if (!isset($this->templates[$email->tempid])) {
         $this->templates[$email->tempid] = array();
         if (empty($this->templateClass)) {
             $this->templateClass = acymailing::get('class.template');
         }
         $template = $this->templateClass->get($email->tempid);
         if (!empty($template->styles) or !empty($template->stylesheet)) {
             $this->stylesheets[$email->tempid] = $this->templateClass->buildCSS($template->styles, $template->stylesheet);
         }
         if (!empty($template->styles)) {
             foreach ($template->styles as $class => $style) {
                 if (empty($style)) {
                     continue;
                 }
                 if (preg_match('#^tag_(.*)$#', $class, $result)) {
                     $this->tags[$email->tempid]['#< *' . $result[1] . '((?:(?!style).)*)>#Ui'] = '<' . $result[1] . ' style="' . $style . '" $1>';
                     if (strpos($style, '!important')) {
                         $this->headerstyles[$email->tempid][] = $result[1] . '{ ' . str_replace('!important', '', $style) . ' }';
                     }
                 } elseif ($class == 'color_bg') {
                     $this->others[$email->tempid][$class] = $style;
                 } else {
                     $this->templates[$email->tempid]['class="' . $class . '"'] = 'style="' . $style . '"';
                 }
             }
         }
     }
     if ($addbody and !strpos($email->body, '</body>')) {
         $before = '<html><head>' . "\n";
         $before .= '<meta http-equiv="Content-Type" content="text/html; charset=' . strtolower($this->config->get('charset')) . '">' . "\n";
         $before .= '<title>' . $email->subject . '</title>' . "\n";
         if (!empty($this->headerstyles[$email->tempid])) {
             $before .= '<style type="text/css">' . "\n";
             $before .= implode("\n", $this->headerstyles[$email->tempid]) . "\n";
             $before .= '</style>' . "\n";
         }
         $before .= '</head>' . "\n" . '<body';
         if (!empty($this->others[$email->tempid]['color_bg'])) {
             $before .= ' bgcolor="' . $this->others[$email->tempid]['color_bg'] . '" ';
         }
         $before .= '>' . "\n";
         $email->body = $before . $email->body . '</body>' . "\n" . '</html>';
     }
     if (!empty($this->templates[$email->tempid])) {
         $email->body = str_replace(array_keys($this->templates[$email->tempid]), $this->templates[$email->tempid], $email->body);
     }
     if (!empty($this->tags[$email->tempid])) {
         $email->body = preg_replace(array_keys($this->tags[$email->tempid]), $this->tags[$email->tempid], $email->body);
     }
     if (!empty($this->stylesheets[$email->tempid]) and class_exists('Emogrifier')) {
         $emogrifier = new Emogrifier($email->body, $this->stylesheets[$email->tempid]);
         $email->body = $emogrifier->emogrify();
         if (!$addbody and strpos($email->body, '<!DOCTYPE') !== false) {
             $email->body = preg_replace('#<\\!DOCTYPE.*<body([^>]*)>#Usi', '', $email->body);
             $email->body = preg_replace('#</body>.*$#si', '', $email->body);
         }
     }
 }
Exemplo n.º 15
0
 function emogrify($toemogrify)
 {
     jincimport('utility.servicelocator');
     $servicelocator = ServiceLocator::getInstance();
     $logger = $servicelocator->getLogger();
     $body = $toemogrify;
     if ($newsletter = $this->loadNewsletter()) {
         if ($this->tem_id != 0) {
             $template = $this->loadTemplate();
             if (!empty($template)) {
                 $logger->debug(get_class($this) . ': emogrifing message.');
                 jincimport('utility.emogrifier');
                 $emogrifier = new Emogrifier($body, $template->getCSSFileContent());
                 $body = $emogrifier->emogrify();
             }
         }
     }
     return $body;
 }
 /**
  * Render with Emogrification
  *
  * @param string $view
  * @param string $layout
  * @return mixed
  * @throws NotFoundException
  */
 public function render($view = null, $layout = null)
 {
     // If it is the text/both version of an email: ->emailFormat('both')
     if (strpos($this->layoutPath, 'Emails' . DS . 'text') !== false && strpos($this->viewPath, 'Emails' . DS . 'text') !== false) {
         return parent::render($view, $layout);
     }
     // Let the parent do it's rendering thing first
     parent::render($view, $layout);
     // Parse out the CSS into a string and remove any CSS from the output
     $css = preg_replace('/\\s+/', " ", $this->_extractAndRemoveCss());
     // Work hard to find and locate the Emogrifier external class
     $emogrifier_include = $this->_locateEmogrifierInclude();
     if (!$emogrifier_include) {
         throw new Exception('Unable to locate Emogrifier vendor library!');
     }
     // Include the Emogrifier class
     include_once $emogrifier_include;
     // Try and instantiate
     $Emogrifier = null;
     if (in_array('Pelago\\Emogrifier', get_declared_classes())) {
         $Emogrifier = new Pelago\Emogrifier($this->output, $css);
     } else {
         $Emogrifier = new Emogrifier($this->output, $css);
     }
     // Emogrification!
     $this->output = @$Emogrifier->emogrify();
     //echo $this->output;exit;
     return $this->output;
 }
 /**
  * Apply inline styles to dynamic content.
  *
  * @param string|null $content
  * @return string
  */
 public function style_inline($content)
 {
     // make sure we only inline CSS for html emails
     if (class_exists('DOMDocument')) {
         ob_start();
         ph_get_template('emails/email-styles.php');
         $css = apply_filters('propertyhive_email_styles', ob_get_clean());
         // apply CSS styles inline for picky email clients
         try {
             $emogrifier = new Emogrifier($content, $css);
             $content = $emogrifier->emogrify();
         } catch (Exception $e) {
             die("Error converting CSS styles to be inline. Error as follows: " . $e->getMessage());
         }
     }
     return $content;
 }
Exemplo n.º 18
0
 /**
  * Applies the CSS you submit to the HTML you submit.
  *
  * This method places the CSS inline.
  *
  * @return string
  *
  * @throws BadMethodCallException
  */
 public function emogrify()
 {
     if ($this->html === '') {
         throw new BadMethodCallException('Please set some HTML first before calling emogrify.', 1390393096);
     }
     $xmlDocument = $this->createXmlDocument();
     $xpath = new DOMXPath($xmlDocument);
     $this->clearAllCaches();
     // before be begin processing the CSS file, parse the document and normalize all existing CSS attributes (changes 'DISPLAY: none' to 'display: none');
     // we wouldn't have to do this if DOMXPath supported XPath 2.0.
     // also store a reference of nodes with existing inline styles so we don't overwrite them
     $this->purgeVisitedNodes();
     $nodesWithStyleAttributes = $xpath->query('//*[@style]');
     if ($nodesWithStyleAttributes !== false) {
         /** @var $nodeWithStyleAttribute DOMNode */
         foreach ($nodesWithStyleAttributes as $node) {
             $normalizedOriginalStyle = preg_replace_callback('/[A-z\\-]+(?=\\:)/S', array($this, 'strtolower'), $node->getAttribute('style'));
             // in order to not overwrite existing style attributes in the HTML, we have to save the original HTML styles
             $nodePath = $node->getNodePath();
             if (!isset($this->styleAttributesForNodes[$nodePath])) {
                 $this->styleAttributesForNodes[$nodePath] = $this->parseCssDeclarationBlock($normalizedOriginalStyle);
                 $this->visitedNodes[$nodePath] = $node;
             }
             $node->setAttribute('style', $normalizedOriginalStyle);
         }
     }
     // grab any existing style blocks from the html and append them to the existing CSS
     // (these blocks should be appended so as to have precedence over conflicting styles in the existing CSS)
     $allCss = $this->css;
     $allCss .= $this->getCssFromAllStyleNodes($xpath);
     $cssParts = $this->splitCssAndMediaQuery($allCss);
     self::$_media = '';
     // reset
     $cssKey = md5($cssParts['css']);
     if (!isset($this->caches[self::CACHE_KEY_CSS][$cssKey])) {
         // process the CSS file for selectors and definitions
         preg_match_all('/(?:^|[\\s^{}]*)([^{]+){([^}]*)}/mis', $cssParts['css'], $matches, PREG_SET_ORDER);
         $allSelectors = array();
         foreach ($matches as $key => $selectorString) {
             // if there is a blank definition, skip
             if (!strlen(trim($selectorString[2]))) {
                 continue;
             }
             // else split by commas and duplicate attributes so we can sort by selector precedence
             $selectors = explode(',', $selectorString[1]);
             foreach ($selectors as $selector) {
                 // don't process pseudo-elements and behavioral (dynamic) pseudo-classes; ONLY allow structural pseudo-classes
                 if (strpos($selector, ':') !== false && !preg_match('/:\\S+\\-(child|type)\\(/i', $selector)) {
                     continue;
                 }
                 $allSelectors[] = array('selector' => trim($selector), 'attributes' => trim($selectorString[2]), 'line' => $key);
             }
         }
         // now sort the selectors by precedence
         usort($allSelectors, array($this, 'sortBySelectorPrecedence'));
         $this->caches[self::CACHE_KEY_CSS][$cssKey] = $allSelectors;
     }
     foreach ($this->caches[self::CACHE_KEY_CSS][$cssKey] as $value) {
         // query the body for the xpath selector
         $nodesMatchingCssSelectors = $xpath->query($this->translateCssToXpath($value['selector']));
         /** @var $node \DOMNode */
         foreach ($nodesMatchingCssSelectors as $node) {
             // if it has a style attribute, get it, process it, and append (overwrite) new stuff
             if ($node->hasAttribute('style')) {
                 // break it up into an associative array
                 $oldStyleDeclarations = $this->parseCssDeclarationBlock($node->getAttribute('style'));
             } else {
                 $oldStyleDeclarations = array();
             }
             $newStyleDeclarations = $this->parseCssDeclarationBlock($value['attributes']);
             $node->setAttribute('style', $this->generateStyleStringFromDeclarationsArrays($oldStyleDeclarations, $newStyleDeclarations));
         }
     }
     // now iterate through the nodes that contained inline styles in the original HTML
     foreach ($this->styleAttributesForNodes as $nodePath => $styleAttributesForNode) {
         $node = $this->visitedNodes[$nodePath];
         $currentStyleAttributes = $this->parseCssDeclarationBlock($node->getAttribute('style'));
         $node->setAttribute('style', $this->generateStyleStringFromDeclarationsArrays($currentStyleAttributes, $styleAttributesForNode));
     }
     // This removes styles from your email that contain display:none.
     // We need to look for display:none, but we need to do a case-insensitive search. Since DOMDocument only supports XPath 1.0,
     // lower-case() isn't available to us. We've thus far only set attributes to lowercase, not attribute values. Consequently, we need
     // to translate() the letters that would be in 'NONE' ("NOE") to lowercase.
     $nodesWithStyleDisplayNone = $xpath->query('//*[contains(translate(translate(@style," ",""),"NOE","noe"),"display:none")]');
     // The checks on parentNode and is_callable below ensure that if we've deleted the parent node,
     // we don't try to call removeChild on a nonexistent child node
     if ($nodesWithStyleDisplayNone->length > 0) {
         /** @var $node \DOMNode */
         foreach ($nodesWithStyleDisplayNone as $node) {
             if ($node->parentNode && is_callable(array($node->parentNode, 'removeChild'))) {
                 $node->parentNode->removeChild($node);
             }
         }
     }
     $this->copyCssWithMediaToStyleNode($cssParts, $xmlDocument);
     if ($this->preserveEncoding) {
         if (function_exists('mb_convert_encoding')) {
             return mb_convert_encoding($xmlDocument->saveHTML(), self::ENCODING, 'HTML-ENTITIES');
         } else {
             return htmlspecialchars_decode(utf8_encode(html_entity_decode($xmlDocument->saveHTML(), ENT_COMPAT, self::ENCODING)));
         }
     } else {
         return $xmlDocument->saveHTML();
     }
 }
Exemplo n.º 19
0
 /** public static function to put the CSS in the mailing
  * @param string $body
  * @param int $templateId
  */
 public static function includeStyles(&$body, $templateId)
 {
     static $checkMe = true;
     $body = preg_replace('#< *(tr|td|table)([^>]*)(style="[^"]*)background-image *: *url\\(\'?([^)\']*)\'?\\);?#Ui', '<$1 background="$4" $2 $3', $body);
     jNews_ProcessMail::normalizeURL($body);
     $body = preg_replace('#< *img([^>]*)(style="[^"]*)(float *: *)(right|left|top|bottom|middle)#Ui', '<img$1 align="$4" hspace="5" $2$3$4', $body);
     //load template
     $template = jNews_Templates::loadOneTemplate('*', $templateId);
     $template->csstyle = jNews_Templates::cleanCSSComments($template->csstyle);
     if (!empty($template->styles) || !empty($template->csstyle)) {
         $csstyle = jNews_Templates::convertCSSInline($template->styles, $template->csstyle);
     }
     $themeCSS = array();
     if (!empty($template->styles)) {
         foreach ($template->styles as $cName => $sContent) {
             if ($cName != 'color_bg') {
             } elseif (preg_match('#^tag_(.*)$#', $cName, $result)) {
                 $mainStyle['#< *' . $result[1] . '((?:(?!style).)*)>#Ui'] = '<' . $result[1] . ' style="' . $sContent . '" $1>';
             } else {
                 $themeCSS['class="' . $cName . '"'] = 'style="' . $sContent . '"';
             }
         }
     }
     if (!empty($mainStyle)) {
         $body = preg_replace(array_keys($mainStyle), $mainStyle, $body);
     }
     if (!empty($themeCSS)) {
         $body = str_replace(array_keys($themeCSS), $themeCSS, $body);
     }
     if (!empty($template->styles['color_bg'])) {
         $pattern1 = '#^([^<]*<[^>]*background-color:)([^;">]{1,10})#i';
         $found = false;
         if (preg_match($pattern1, $body)) {
             $body = preg_replace($pattern1, '$1' . $template->styles['color_bg'], $body);
             $found = true;
         }
         $pattern2 = '#^([^<]*<[^>]*bgcolor=")([^;">]{1,10})#i';
         if (preg_match($pattern2, $body)) {
             $body = preg_replace($pattern2, '$1' . $template->styles['color_bg'], $body);
             $found = true;
         }
         if (!$found) {
             $body = '<div style="background-color:' . $template->styles['color_bg'] . ';" width="100%">' . $body . '</div>';
         }
     }
     if ($checkMe) {
         if (version_compare(PHP_VERSION, '5.0.0', '>=') && class_exists('DOMDocument') && function_exists('mb_convert_encoding')) {
             require_once JNEWS_PATH_INCLUDES . 'emogrifier' . DS . 'emogrifier.php';
         }
         $checkMe = false;
     }
     if (!empty($csstyle) && class_exists('Emogrifier')) {
         $emogrifier = new Emogrifier($body, $csstyle);
         $body = $emogrifier->emogrify();
         if (strpos($body, '<!DOCTYPE') !== false) {
             $body = preg_replace('#<\\!DOCTYPE.*<body([^>]*)>#Usi', '', $body);
             $body = preg_replace('#</body>.*$#si', '', $body);
         }
     }
 }
Exemplo n.º 20
0
/**
 * Moves CSS rules contained in the <style> tag to inline CSS.
 * Used for compatibility with Gmail and such clients
 * @since 2.6
 *
 * @param string $content
 * @return string
 */
function move_css_to_body($content)
{
    include_once PHPWG_ROOT_PATH . 'include/emogrifier.class.php';
    $e = new Emogrifier($content);
    return @$e->emogrify();
}
Exemplo n.º 21
0
 /**
  * public function to get the inline css html code from the emogrifier
  *
  * @param   STRING  $prev     prev.
  * @param   STRING  $cssdata  cssdata
  *
  * @return  STRING
  */
 public function getEmogrify($prev, $cssdata)
 {
     $path = JPATH_SITE . "/components/com_quick2cart/models/emogrifier.php";
     if (!class_exists('Emogrifier')) {
         JLoader::register('Emogrifier', $path);
         JLoader::load('Emogrifier');
     }
     // Condition to check if mbstring is enabled
     if (!function_exists('mb_convert_encoding')) {
         echo JText::_("MB_EXT");
         return $prev;
     }
     $emogr = new Emogrifier($prev, $cssdata);
     $emorg_data = $emogr->emogrify();
     return $emorg_data;
 }
Exemplo n.º 22
0
 /**
  * moves CSS to inline CSS in email
  * @param Boolean $isPlain - should we send the email as HTML or as TEXT
  * @author Mark Guinn
  */
 protected function parseVariables($isPlain = false)
 {
     require_once Director::baseFolder() . '/ecommerce/thirdparty/Emogrifier.php';
     parent::parseVariables($isPlain);
     // if it's an html email, filter it through emogrifier
     $cssFileLocation = Director::baseFolder() . "/" . EcommerceConfig::get("Order_Email", "css_file_location");
     $cssFileHandler = fopen($cssFileLocation, 'r');
     $css = fread($cssFileHandler, filesize($cssFileLocation));
     fclose($cssFileHandler);
     $emog = new Emogrifier($this->body, $css);
     $this->body = $emog->emogrify();
 }
Exemplo n.º 23
0
 /**
  * Apply inline styles to dynamic content.
  *
  * @param string|null $content
  * @return string
  */
 public function style_inline($content)
 {
     // make sure we only inline CSS for html emails
     if (in_array($this->get_content_type(), array('text/html', 'multipart/alternative'))) {
         // get CSS styles
         ob_start();
         wc_get_template('emails/email-styles.php');
         $css = apply_filters('woocommerce_email_styles', ob_get_clean());
         // apply CSS styles inline for picky email clients
         $emogrifier = new Emogrifier($content, $css);
         $content = $emogrifier->emogrify();
     }
     return $content;
 }
 /**
  * Apply inline styles to dynamic content.
  *
  * @param string|null $content
  * @return string
  */
 public function style_inline($content)
 {
     // Make sure we only inline CSS for HTML emails.
     if (in_array($this->get_content_type(), array('text/html', 'multipart/alternative')) && class_exists('DOMDocument')) {
         // Get CSS styles
         ob_start();
         bp_email_get_template('email-styles.php');
         $css = apply_filters('welcome_buddy_styles', ob_get_clean());
         // Apply CSS styles inline for picky email clients.
         $emogrifier = new Emogrifier($content, $css);
         $content = $emogrifier->emogrify();
     }
     return $content;
 }
Exemplo n.º 25
0
 function _applyTemplate(&$email, $addbody)
 {
     if (empty($email->tempid)) {
         return;
     }
     if (!isset($this->templates[$email->tempid])) {
         $this->headerstyles[$email->tempid] = array();
         $this->headerstyles[$email->tempid][] = '.ReadMsgBody{width: 100%;}';
         $this->headerstyles[$email->tempid][] = '.ExternalClass{width: 100%;}';
         $this->headerstyles[$email->tempid][] = 'div, p, a, li, td { -webkit-text-size-adjust:none; }';
         $this->templates[$email->tempid] = array();
         if (empty($this->templateClass)) {
             $this->templateClass = acymailing_get('class.template');
         }
         $template = $this->templateClass->get($email->tempid);
         if (!empty($template->styles) or !empty($template->stylesheet)) {
             $this->stylesheets[$email->tempid] = $this->templateClass->buildCSS($template->styles, $template->stylesheet);
             if (preg_match_all('#@media[^{]*{({[^{]*}|[^{]*)*}#Uis', $this->stylesheets[$email->tempid], $results)) {
                 foreach ($results[0] as $oneResult) {
                     $this->stylesheets[$email->tempid] = str_replace($oneResult, '', $this->stylesheets[$email->tempid]);
                     $this->headerstyles[$email->tempid][] = trim($oneResult);
                 }
             }
             if (preg_match_all('#}([^}]+:hover[^{]*{[^{]*})#Uis', '} ' . $this->stylesheets[$email->tempid], $results)) {
                 foreach ($results[1] as $oneResult) {
                     $this->stylesheets[$email->tempid] = str_replace($oneResult, '', $this->stylesheets[$email->tempid]);
                     $this->headerstyles[$email->tempid][] = trim($oneResult);
                 }
             }
         }
         if (!empty($template->styles)) {
             foreach ($template->styles as $class => $style) {
                 if (empty($style)) {
                     continue;
                 }
                 if (preg_match('#^tag_(.*)$#', $class, $result)) {
                     $this->tags[$email->tempid]['#< *' . $result[1] . '((?:(?!style).)*)>#Ui'] = '<' . $result[1] . ' style="' . $style . '" $1>';
                     if (strpos($style, '!important')) {
                         $this->headerstyles[$email->tempid][] = $result[1] . '{ ' . str_replace('!important', '', $style) . ' }';
                     }
                 } elseif ($class == 'color_bg') {
                     $this->others[$email->tempid][$class] = $style;
                 } else {
                     $this->templates[$email->tempid]['class="' . $class . '"'] = 'style="' . $style . '"';
                 }
             }
             if (!empty($template->styles['tag_a'])) {
                 $this->headerstyles[$email->tempid][] = 'a:visited{' . $template->styles['tag_a'] . '}';
             }
         }
     }
     if ($addbody and !strpos($email->body, '</body>')) {
         $before = '<html><head>' . "\n";
         $before .= '<meta http-equiv="Content-Type" content="text/html; charset=' . strtolower($this->config->get('charset')) . '" />' . "\n";
         $before .= '<meta name="viewport" content="width=device-width, initial-scale=1.0" />' . "\n";
         $before .= '<title>' . $email->subject . '</title>' . "\n";
         if (!empty($this->headerstyles[$email->tempid])) {
             $before .= '<style type="text/css">' . "\n";
             $before .= implode("\n", $this->headerstyles[$email->tempid]) . "\n";
             $before .= '</style>' . "\n";
         }
         $before .= '</head>' . "\n" . '<body';
         if (!empty($this->others[$email->tempid]['color_bg'])) {
             $before .= ' bgcolor="' . $this->others[$email->tempid]['color_bg'] . '" ';
         }
         $before .= '>' . "\n";
         $email->body = $before . $email->body . '</body>' . "\n" . '</html>';
     }
     if (!empty($this->stylesheets[$email->tempid]) and class_exists('Emogrifier')) {
         $emogrifier = new Emogrifier($email->body, $this->stylesheets[$email->tempid]);
         $email->body = $emogrifier->emogrify();
         if (!$addbody and strpos($email->body, '<!DOCTYPE') !== false) {
             $email->body = preg_replace('#<\\!DOCTYPE.*<body([^>]*)>#Usi', '', $email->body);
             $email->body = preg_replace('#</body>.*$#si', '', $email->body);
         }
     } else {
         if (!empty($this->templates[$email->tempid])) {
             $email->body = str_replace(array_keys($this->templates[$email->tempid]), $this->templates[$email->tempid], $email->body);
         }
         if (!empty($this->tags[$email->tempid])) {
             $email->body = preg_replace(array_keys($this->tags[$email->tempid]), $this->tags[$email->tempid], $email->body);
         }
     }
     if ($addbody) {
         $newbody = preg_replace('#(<[^>]*)(class|id)="[^"]*"#Ui', '$1', $email->body);
         if (!empty($newbody)) {
             $email->body = $newbody;
         }
     }
 }
 /**
  *@return Array - just so the template is still displayed
  **/
 function sendreceipt($request)
 {
     if ($o = $this->currentOrder) {
         if ($m = $o->Member()) {
             if ($m->Email) {
                 $subject = _t("Account.COPYONLY", "--- COPY ONLY ---");
                 $message = _t("Account.COPYONLY", "--- COPY ONLY ---");
                 $o->sendReceipt($subject, $message, true);
                 $this->message = _t('OrderConfirmationPage.RECEIPTSENT', 'An order receipt has been sent to: ') . $m->Email . '.';
             } else {
                 $this->message = _t('OrderConfirmationPage.RECEIPTNOTSENTNOTSENDING', 'Email could NOT be sent.');
             }
         } else {
             $this->message = _t('OrderConfirmationPage.RECEIPTNOTSENTNOEMAIL', 'No email could be found for sending this receipt.');
         }
     } else {
         $this->message = _t('OrderConfirmationPage.RECEIPTNOTSENTNOORDER', 'Order could not be found.');
     }
     $baseFolder = Director::baseFolder();
     require_once $baseFolder . '/ecommerce/thirdparty/Emogrifier.php';
     Requirements::clear();
     Requirements::themedCSS("typography");
     // LEAVE HERE - NOT EASY TO INCLUDE VIA TEMPLATE
     Requirements::themedCSS("OrderReport");
     // LEAVE HERE - NOT EASY TO INCLUDE VIA TEMPLATE
     Requirements::themedCSS("Order_Invoice", "print");
     // LEAVE HERE - NOT EASY TO INCLUDE VIA TEMPLATE
     $html = $this->renderWith("Order_ReceiptEmail");
     // if it's an html email, filter it through emogrifier
     $cssFileLocation = $baseFolder . "/" . EcommerceConfig::get("Order_Email", "css_file_location");
     $html .= "\r\n\r\n<!-- CSS can be found here: {$cssFileLocation} -->";
     $cssFileHandler = fopen($cssFileLocation, 'r');
     $css = fread($cssFileHandler, filesize($cssFileLocation));
     fclose($cssFileHandler);
     $emog = new Emogrifier($html, $css);
     $html = $emog->emogrify();
     return $html;
 }
 /**
  * Apply inline styles to dynamic content.
  *
  * @since   1.1.8
  *
  * @param   string|null $content
  *
  * @return  string
  * @author  Alberto Ruggiero
  */
 public function style_inline($content)
 {
     // make sure we only inline CSS for html emails
     if (in_array($this->get_content_type(), array('text/html', 'multipart/alternative')) && class_exists('DOMDocument')) {
         ob_start();
         if (array_key_exists($this->template_type, YITH_WRR()->_email_templates)) {
             $path = YITH_WRR()->_email_templates[$this->template_type]['path'];
             $folder = YITH_WRR()->_email_templates[$this->template_type]['folder'];
             wc_get_template($folder . '/email-styles.php', array(), '', $path);
             $css = ob_get_clean();
         } else {
             wc_get_template('emails/email-styles.php');
             $css = apply_filters('woocommerce_email_styles', ob_get_clean());
         }
         // apply CSS styles inline for picky email clients
         try {
             $emogrifier = new Emogrifier($content, $css);
             $content = $emogrifier->emogrify();
         } catch (Exception $e) {
             $logger = new WC_Logger();
             $logger->add('emogrifier', $e->getMessage());
         }
     }
     return $content;
 }