protected function renderContents($html, $css = '') { $emogrifier = new \Pelago\Emogrifier(); $emogrifier->setHtml($html); $emogrifier->setCss($css); return $emogrifier->emogrify(true); }
/** * @param string $html * @return mixed */ public static function inlineCss($html) { if (class_exists('\\Pelago\\Emogrifier')) { $emogrifier = new \Pelago\Emogrifier($html); return $emogrifier->emogrify(); } else { return $html; } }
function sendHTML($to, $from, $subject, $htmlContent, $attachedFiles = false, $customheaders = false, $plainContent = false) { $cssFileLocation = Director::baseFolder() . Config::inst()->get("EmogrifierMailer", "css_file"); $cssFileHandler = fopen($cssFileLocation, 'r'); $css = fread($cssFileHandler, filesize($cssFileLocation)); fclose($cssFileHandler); $emog = new \Pelago\Emogrifier($htmlContent, $css); $htmlContent = $emog->emogrify(); return parent::sendHTML($to, $from, $subject, $htmlContent, $attachedFiles, $customheaders, $plainContent); }
protected function sendEmail($to, $subj, $text, $html = null) { $email = new \SendGrid\Email(); $email->addCategory($subj); $email->addTo($to); $email->setFrom('*****@*****.**'); $email->setFromName('Edge conf'); $email->setSubject($subj); $email->setText($text); if ($html) { $emogrifier = new \Pelago\Emogrifier($html, file_get_contents(realpath(__DIR__ . '/../../../public/css/email.css'))); $email->setHtml($emogrifier->emogrify()); } $sendgrid = new \SendGrid($this->app->config->sendgrid->username, $this->app->config->sendgrid->password); $resp = $sendgrid->send($email); }
/** * turns an html document into a formatted html document * using the emogrify method. * @param $html * @return String HTML */ public static function emogrify_html($html) { //get required files $baseFolder = Director::baseFolder(); if (!class_exists('\\Pelago\\Emogrifier')) { require_once $baseFolder . '/ecommerce/thirdparty/Emogrifier.php'; } $cssFileLocation = Director::baseFolder() . "/" . EcommerceConfig::get("Order_Email", "css_file_location"); $cssFileHandler = fopen($cssFileLocation, 'r'); $css = fread($cssFileHandler, filesize($cssFileLocation)); fclose($cssFileHandler); $emogrifier = new \Pelago\Emogrifier($html, $css); $html = $emogrifier->emogrify(); //make links absolute! $html = HTTP::absoluteURLs($html); return $html; }
public function inlineCss($source) { try { $e = new \Pelago\Emogrifier($source); $html = $e->emogrify(); } catch (\Exception $exception) { $html = $source; echo $exception->getMessage(); if ($exception->getMessage() == 'DOMXPath::query(): Invalid expression') { $trace = $exception->getTrace(); if (isset($trace[1]['args'][0])) { echo ' ', $trace[1]['args'][0]; } } } return $html; }
/** * Outputs the template to the browser. * * [!] Overloaded to remove portion that sets headers. * * @param boolean $caching If true, cache the output * @param array $params Associative array of attributes * @return The rendered data */ public function render($caching = false, $params = array()) { if (!isset($params['template'])) { if (App::isAdmin()) { $db = App::get('db'); $db->setQuery("SELECT s.`template`, e.protected FROM `#__template_styles` AS s INNER JOIN `#__extensions` AS e ON e.`element`=s.`template` WHERE s.`client_id`=0 AND s.`home`=1"); $result = $db->loadObject(); } else { $result = App::get('template'); } $params['template'] = $result->template; $params['directory'] = ($result->protected ? PATH_CORE : PATH_APP) . DS . 'templates'; } if (!isset($params['file'])) { $params['file'] = 'email.php'; } if (!file_exists($params['directory'] . DS . $params['template'] . DS . $params['file'])) { $params['template'] = 'system'; $params['directory'] = PATH_CORE . DS . 'templates'; } $this->_caching = $caching; if (!empty($this->_template)) { $data = $this->_renderTemplate(); } else { $this->parse($params); $data = $this->_renderTemplate(); } if (class_exists('\\Pelago\\Emogrifier') && $data) { $data = str_replace('&#', '{_ANDNUM_}', $data); $emogrifier = new \Pelago\Emogrifier(); $emogrifier->preserveEncoding = true; $emogrifier->setHtml($data); //$emogrifier->setCss($css); $data = $emogrifier->emogrify(); $data = str_replace('{_ANDNUM_}', '&#', $data); } return $data; }
/** * This function converts CSS to inline style, the CSS needs to be found in a <style> element * * @param string $html_text the html text to be converted * * @return false|string */ 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(); $emo = new Pelago\Emogrifier($html_text, $css); $result = $emo->emogrify(); } return $result; }
/** * Inline styles using Pelago Emogrifier * * @param string $html * @return string */ protected function inlineStyles($html) { if (!class_exists("\\Pelago\\Emogrifier")) { throw new Exception("You must run composer require pelago/emogrifier"); } $emogrifier = new \Pelago\Emogrifier(); $emogrifier->setHtml($html); $emogrifier->disableInvisibleNodeRemoval(); $emogrifier->enableCssToHtmlMapping(); $html = $emogrifier->emogrify(); // Ugly hack to avoid gmail reordering your padding // $html = str_replace('padding: 0;', // 'padding-top: 0; padding-bottom: 0; padding-right: 0; padding-left: 0;', // $html); return $html; }
static function compile($template_id, $arguments = array()) { $template = false; $subject = false; $html_template = false; $template_dir = \Openclerk\Config::get('emails_templates', __DIR__ . '/../../../../emails'); if (file_exists($template_dir . "/" . $template_id . ".txt")) { $template = file_get_contents($template_dir . "/" . $template_id . ".txt"); // strip out the subject from the text $template = explode("\n", $template, 2); $subject = $template[0]; $template = $template[1]; } if (file_exists($template_dir . "/" . $template_id . ".html")) { $html_template = file_get_contents($template_dir . "/" . $template_id . ".html"); if (file_exists($template_dir . "/" . "layout.html")) { $html_layout_template = file_get_contents($template_dir . "/" . "layout.html"); $html_template = \Openclerk\Templates::replace($html_layout_template, array('content' => $html_template)); } // strip out the title from the html $matches = false; if (preg_match("#<title>(.+)</title>#im", $html_template, $matches)) { $subject = $matches[1]; } $html_template = preg_replace("#<title>.+</title>#im", "", $html_template); } if (!$template) { if ($html_template) { // use html2text to generate the text body automatically $template = \Html2Text\Html2Text::convert($html_template); } else { throw new MailerException("Email template '{$template_id}' did not exist within '{$template_dir}'"); } } // replace variables $template = \Openclerk\Templates::replace($template, $arguments); $subject = \Openclerk\Templates::replace($subject, $arguments); if ($html_template) { $html_template = \Openclerk\Templates::replace($html_template, $arguments); } // inline CSS? if (file_exists($template_dir . "/layout.css")) { $css = file_get_contents($template_dir . "/layout.css"); // custom CSS? if (\Openclerk\Config::get("emails_additional_css", false)) { $css .= file_get_contents(\Openclerk\Config::get("emails_additional_css", false)); } $emogrifier = new \Pelago\Emogrifier(); $emogrifier->setHtml($html_template); $emogrifier->setCss($css); $html_template = $emogrifier->emogrify(); } return array('subject' => $subject, 'html' => $html_template, 'text' => $template); }
}); /***** Security *****/ $securityFirewalls = array(); /*** Members Area ***/ $securityFirewalls['members-area'] = array('pattern' => '^/', 'anonymous' => true, 'form' => array('login_path' => '/members-area/login', 'check_path' => '/members-area/login/check', 'failure_path' => '/members-area/login', 'default_target_path' => '/members-area', 'use_referer' => true, 'username_parameter' => 'username', 'password_parameter' => 'password', 'csrf_protection' => true, 'csrf_parameter' => 'csrf_token', 'with_csrf' => true, 'use_referer' => true), 'logout' => array('logout_path' => '/members-area/logout', 'target' => '/members-area', 'invalidate_session' => true, 'csrf_parameter' => 'csrf_token'), 'remember_me' => $app['rememberMeOptions'], 'switch_user' => array('parameter' => 'switch_user', 'role' => 'ROLE_ALLOWED_TO_SWITCH'), 'users' => $app['user.provider']); $app->register(new Silex\Provider\SecurityServiceProvider(), array('security.firewalls' => $securityFirewalls)); $app['security.access_rules'] = array(array('^/members-area/login', 'IS_AUTHENTICATED_ANONYMOUSLY'), array('^/members-area/register', 'IS_AUTHENTICATED_ANONYMOUSLY'), array('^/members-area/reset-password', 'IS_AUTHENTICATED_ANONYMOUSLY'), array('^/members-area', 'ROLE_USER'), array('^/members-area/oauth', 'ROLE_USER')); $app['security.role_hierarchy'] = array('ROLE_SUPER_ADMIN' => array('ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'), 'ROLE_ADMIN' => array('ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH')); /* Voters */ $app['security.voters'] = $app->extend('security.voters', function ($voters) use($app) { // Add your own voters here! return $voters; }); /***** Remember Me *****/ $app->register(new Silex\Provider\RememberMeServiceProvider()); /***** Swiftmailer / Mailer *****/ $app->register(new Silex\Provider\SwiftmailerServiceProvider()); $app['swiftmailer.options'] = $app['swiftmailerOptions']; /* Emogrifier */ $app['mailer.css_to_inline_styles_converter'] = $app->protect(function ($twigTemplatePathOrContent, $twigTemplateData = array(), $isTwigTemplate = true) use($app) { $emogrifier = new Pelago\Emogrifier(); $emogrifier->setHtml($isTwigTemplate ? $app['twig']->render($twigTemplatePathOrContent, $twigTemplateData) : $app['twig']->render('emails/blank.html.twig', array_merge($twigTemplateData, array('content' => $twigTemplatePathOrContent)))); return $emogrifier->emogrify(); }); /*** Listeners ***/ $app['dispatcher']->addListener(AuthenticationEvents::AUTHENTICATION_SUCCESS, function ($event) use($app) { $user = $event->getAuthenticationToken()->getUser(); $user->setTimeLastActive(new \DateTime()); $app['orm.em']->persist($user); $app['orm.em']->flush(); });
/** * Sets the HTML message of the e-mail. * * @param string $message the HTML message of the e-mail, must not be empty * * @return void * * @throws InvalidArgumentException */ public function setHTMLMessage($message) { if ($message === '') { throw new InvalidArgumentException('$message must not be empty.', 1331488845); } if ($this->hasCssFile()) { $this->loadEmogrifierClass(); $emogrifier = new \Pelago\Emogrifier($message, $this->getCssFile()); $messageToStore = $emogrifier->emogrify(); } else { $messageToStore = $message; } $this->setAsString('html_message', $messageToStore); }
public static function send_mail($mail) { $mail_stgs = WPEM()->modules['settings']->settings; $mail['recepients'] = self::get_recepients($mail); $mail = self::validate_mail($mail); $errors = $mail['errors']; if ($errors->get_error_code()) { return $mail; } $omit_name = $mail_stgs['mail']['omit_display_names']; // Default the To: and Cc: values to the send email address $to = $omit_name ? $mail['from_email'] : sprintf('%s <%s>', $mail['from_name'], $mail['from_email']); $cc = sprintf('Cc: %s', $to); $headers = array(); // Cc: Sender? $ccsender = $mail_stgs['mail']['copy_sender']; if ($ccsender) { $cc = sprintf('Cc: %s', $to); $headers[] = $cc; } $num_sent = 0; // return value if (empty($mail['recepients'])) { return $num_sent; } // Return path defaults to sender email if not specified $return_path = $mail_stgs['mail']['bounces_address']; if ($return_path == '') { $return_path = $mail['from_email']; } // Build headers $headers[] = $omit_name ? 'From: ' . $mail['from_email'] : sprintf('From: "%s" <%s>', $mail['from_name'], $mail['from_email']); $headers[] = sprintf('Return-Path: <%s>', $return_path); $headers[] = $omit_name ? 'Reply-To: ' . $mail['from_email'] : sprintf('Reply-To: "%s" <%s>', $mail['from_name'], $mail['from_email']); if ($mail_stgs['headers']['x_mailer']) { $headers[] = sprintf('X-Mailer: PHP %s', phpversion()); } $subject = apply_filters('wpem_mail_title', stripslashes($mail['title'])); $message = apply_filters('wpem_mail_body', do_shortcode(stripslashes($mail['body']))); $attachments = array(); if (isset($mail['attachments']) && !empty($mail['attachments'])) { foreach ($mail['attachments'] as $files) { $attachments[] = $files['attachment']; } } if ('html' == $mail['mail_format']) { if ($mail_stgs['headers']['mime']) { //add mime version_header $headers[] = 'MIME-Version: 1.0'; } $headers[] = sprintf('Content-Type: %s; charset="%s"', get_bloginfo('html_type'), get_bloginfo('charset')); $style = ''; if (isset($mail['template']) && absint($mail['template']) && intval($mail['template']) != -1) { $css = get_post_meta(intval($mail['template']), 'wpem_css-box-field', true); if (!empty($css)) { $style = '<style>' . $css . '</style>'; } } if (isset($css) && !empty($css) && $mail_stgs['mail']['inline_style']) { require_once WPEM_PLUGIN_PATH . '/classes/Emogrifier.php'; $html = '<html><head><title>' . $subject . '</title></head><body>' . $message . '</body></html>'; $emogrifier = new \Pelago\Emogrifier($html, $css); $mailtext = $emogrifier->emogrify(); } else { $mailtext = '<html><head><title>' . $subject . '</title>' . $style . '</head><body>' . $message . '</body></html>'; } } else { if ($mail_stgs['headers']['mime']) { $headers[] = 'MIME-Version: 1.0'; } $headers[] = sprintf('Content-Type: text/plain; charset="%s"', get_bloginfo('charset')); $message = preg_replace('|&[^a][^m][^p].{0,3};|', '', $message); $message = preg_replace('|&|', '&', $message); $mailtext = wordwrap(strip_tags($message . "\n" . $footer), 80, "\n"); } $recepients = self::format_recepients($mail['recepients'], $mail_stgs['mail']['max_bcc_recipients'], $omit_name); /* if (WPEM_DEBUG) { wpem_preprint(array_merge($headers, $bcc)); wpem_debug_wp_mail($to, $subject, $mailtext, array_merge($headers, $bcc)); } */ remove_filter('wp_mail', __CLASS__ . '::add_default_template'); if ($mail_stgs['mail']['max_bcc_recipients'] == -1) { $to = array_unique($to); $num_sent = count($recepients['to']); foreach ($recepients['to'] as $to) { @wp_mail($to, $subject, $mailtext, $headers, $attachments); } } else { foreach ($recepients['bcc'] as $bcc) { $bcc = array_unique($bcc); $num_sent = $num_sent + count($bcc); $to = ltrim(array_shift($bcc), "Bcc: "); @wp_mail($to, $subject, $mailtext, array_merge($headers, $bcc), $attachments); } } add_filter('wp_mail', __CLASS__ . '::add_default_template'); return $num_sent; }
/** * * @param SS_HTTPRequest $request */ public function run($request) { $email = $request->getVar('email'); $locale = $request->getVar('locale'); $template = $request->getVar('template'); $inline = $request->getVar('inline'); $to = $request->getVar('to'); if (!$email) { $emailClasses = ClassInfo::subclassesFor('Email'); DB::alteration_message("Please select an email to test or preview"); foreach ($emailClasses as $class) { $link = '/dev/tasks/EmailViewerTask?email=' . $class; DB::alteration_message("<a href='{$link}'>{$class}</a>"); if ($class == 'Email') { DB::alteration_message("<a href='{$link}&template=GenericEmail_ceej'>{$class} (ceej styles)</a>"); DB::alteration_message("<a href='{$link}&template=GenericEmail_vision'>{$class} (vision styles)</a>"); } } return; } if ($locale) { i18n::set_locale($locale); } if ($locale) { DB::alteration_message("Locale is set to " . $locale, "created"); } else { DB::alteration_message("You can set the locale by passing ?locale=fr_FR. Current locale is " . i18n::get_locale()); } if ($inline) { DB::alteration_message("Css are inlined", "created"); } else { DB::alteration_message("You can inline css styles by passing ?inline=1"); } $member = null; if ($to) { $member = Member::get()->filter('Email', $to)->first(); if ($member && $member->ID) { DB::alteration_message("Email sent to " . $member->Email, 'created'); } else { $member = new Member(); $member->Email = $to; $member->FirstName = 'John'; $member->Surname = 'Smith'; DB::alteration_message("A temporary member has been created with email " . $member->Email, "changed"); } } else { DB::alteration_message("You can send this email by passing ?to=email_of_the@member.com"); } $refl = new ReflectionClass($email); $constructorOpts = $refl->getConstructor()->getParameters(); $args = []; if (!empty($constructorOpts)) { /* @var $opt ReflectionParameter */ foreach ($constructorOpts as $opt) { $cl = $opt->getClass(); if (!$cl) { continue; } $type = $opt->getClass()->getName(); if (class_exists($type) && in_array($type, ClassInfo::subclassesFor('DataObject'))) { // We can get record based on an ID passed in the URL $recordID = $request->getVar($type . 'ID'); if ($recordID) { $record = $type::get()->byID($recordID); } else { $record = $type::get()->sort('RAND()')->first(); } if (!$record) { $record = new $type(); } $args[] = $record; } } } /* @var $e Email */ $e = $refl->newInstanceArgs($args); if ($template) { $e->setTemplate($template); } // For a generic email, we should set some content... if ($email == 'Email') { $e->setSubject("Generic email"); $body = "<p class='lead'>Phasellus ultrices nulla quis nibh. Quisque a lectus.</p><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>"; $body .= FoundationEmails::button('Click here', '#', 'brand'); $e->setBody($body); $image = Image::get()->sort('RAND()')->first(); $data = ['PreHeader' => 'This text is only visible in your email client...', 'Callout' => '<h2>Quisque a lectus</h2> <ol> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li>Aliquam tincidunt mauris eu risus.</li> <li>Vestibulum auctor dapibus neque.</li> </ol> <a href="#">Phasellus ultrices nulla</a>', 'SecondaryCallout' => '<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit?</p> <a href="#">Vestibulum auctor</a>', 'Sidebar' => '<nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Clients</a></li> <li><a href="#">Contact Us</a></li> </ul> </nav>']; if ($image) { $data['HeroImage'] = $image; } // Let's add an email footer $sc = SiteConfig::current_site_config(); if (!$sc->EmailFooter) { $sc->EmailFooter = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.'; } if (!$sc->EmailFooter2) { $sc->EmailFooter2 = '© ' . date('Y') . ' - ' . $sc->Title . ' - All Rights Reserved.'; } if (!$sc->EmailFooterLinks) { $sc->EmailFooterLinks = new ArrayList([['Class' => 'twitter', 'Link' => '#', 'Label' => 'Twitter', 'Icon' => 'foundation-emails/images/icon_twitter.png'], ['Class' => 'facebook', 'Link' => '#', 'Label' => 'Facebook', 'Icon' => 'foundation-emails/images/icon_facebook.png'], ['Class' => 'google', 'Link' => '#', 'Label' => 'Google', 'Icon' => 'foundation-emails/images/icon_google.png']]); } $e->populateTemplate($data); } if (!$member) { if (Member::currentUserID()) { $member = Member::currentUser(); } else { $member = Member::get()->sort('RAND()')->first(); } } if ($member) { $e->populateTemplate($member); } $e->debug(); // Call debug to trigger parseVariables if ($inline) { if (!class_exists("\\Pelago\\Emogrifier")) { throw new Exception("You must run composer require pelago/emogrifier"); } $emogrifier = new \Pelago\Emogrifier(); $emogrifier->setHtml($e->body); $emogrifier->disableInvisibleNodeRemoval(); $emogrifier->enableCssToHtmlMapping(); $body = $emogrifier->emogrify(); $e->setBody($body); } else { $body = $e->body; } if ($member && $to) { $e->setTo($member->Email); $result = $e->send(); echo '<hr/>'; if ($result) { echo '<span style="color:green">Email sent</span>'; } else { echo '<span style="color:red">Failed to send email</span>'; } } echo '<hr/><center>Subject : ' . $e->subject . '</center>'; echo '<hr/>'; echo $body; echo '<hr/><pre style="font-size:12px;line-height:12px;">'; echo htmlentities($body); echo '</pre>'; }
/** * @param mixed $mResponse * @param string $sParent * @param array $aParameters = array() * * @return mixed */ protected function responseObject($mResponse, $sParent = '', $aParameters = array()) { $mResult = $mResponse; if (\is_object($mResponse)) { $bHook = true; $self = $this; $sClassName = \get_class($mResponse); $bHasSimpleJsonFunc = \method_exists($mResponse, 'ToSimpleJSON'); $bThumb = $this->GetCapa(false, \RainLoop\Enumerations\Capa::ATTACHMENT_THUMBNAILS); $oAccountCache = null; $fGetAccount = function () use($self, &$oAccountCache) { if (null === $oAccountCache) { $oAccount = $self->getAccountFromToken(false); $oAccountCache = $oAccount; } return $oAccountCache; }; $aCheckableFoldersCache = null; $fGetCheckableFolder = function () use($self, &$aCheckableFoldersCache) { if (null === $aCheckableFoldersCache) { $oAccount = $self->getAccountFromToken(false); $oSettingsLocal = $self->SettingsProvider(true)->Load($oAccount); $sCheckable = $oSettingsLocal->GetConf('CheckableFolder', '[]'); $aCheckable = @\json_decode($sCheckable); if (!\is_array($aCheckable)) { $aCheckable = array(); } $aCheckableFoldersCache = $aCheckable; } return $aCheckableFoldersCache; }; if ($bHasSimpleJsonFunc) { $mResult = \array_merge($this->objectData($mResponse, $sParent, $aParameters), $mResponse->ToSimpleJSON(true)); } else { if ('MailSo\\Mail\\Message' === $sClassName) { $oAccount = \call_user_func($fGetAccount); $iDateTimeStampInUTC = $mResponse->InternalTimeStampInUTC(); if (0 === $iDateTimeStampInUTC || !!$this->Config()->Get('labs', 'date_from_headers', false)) { $iDateTimeStampInUTC = $mResponse->HeaderTimeStampInUTC(); if (0 === $iDateTimeStampInUTC) { $iDateTimeStampInUTC = $mResponse->InternalTimeStampInUTC(); } } $mResult = \array_merge($this->objectData($mResponse, $sParent, $aParameters), array('Folder' => $mResponse->Folder(), 'Uid' => (string) $mResponse->Uid(), 'Subject' => \trim(\MailSo\Base\Utils::Utf8Clear($mResponse->Subject())), 'MessageId' => $mResponse->MessageId(), 'Size' => $mResponse->Size(), 'DateTimeStampInUTC' => $iDateTimeStampInUTC, 'ReplyTo' => $this->responseObject($mResponse->ReplyTo(), $sParent, $aParameters), 'From' => $this->responseObject($mResponse->From(), $sParent, $aParameters), 'To' => $this->responseObject($mResponse->To(), $sParent, $aParameters), 'Cc' => $this->responseObject($mResponse->Cc(), $sParent, $aParameters), 'Bcc' => $this->responseObject($mResponse->Bcc(), $sParent, $aParameters), 'Sender' => $this->responseObject($mResponse->Sender(), $sParent, $aParameters), 'DeliveredTo' => $this->responseObject($mResponse->DeliveredTo(), $sParent, $aParameters), 'Priority' => $mResponse->Priority(), 'Threads' => $mResponse->Threads(), 'Sensitivity' => $mResponse->Sensitivity(), 'ExternalProxy' => false, 'ReadReceipt' => '')); $mResult['SubjectParts'] = $this->explodeSubject($mResult['Subject']); $oAttachments = $mResponse->Attachments(); $iAttachmentsCount = $oAttachments ? $oAttachments->Count() : 0; $mResult['HasAttachments'] = 0 < $iAttachmentsCount; $mResult['AttachmentsSpecData'] = $mResult['HasAttachments'] ? $oAttachments->SpecData() : array(); $sSubject = $mResult['Subject']; $mResult['Hash'] = \md5($mResult['Folder'] . $mResult['Uid']); $mResult['RequestHash'] = \RainLoop\Utils::EncodeKeyValuesQ(array('V' => APP_VERSION, 'Account' => $oAccount ? \md5($oAccount->Hash()) : '', 'Folder' => $mResult['Folder'], 'Uid' => $mResult['Uid'], 'MimeType' => 'message/rfc822', 'FileName' => (0 === \strlen($sSubject) ? 'message-' . $mResult['Uid'] : \MailSo\Base\Utils::ClearXss($sSubject)) . '.eml')); // Flags $aFlags = $mResponse->FlagsLowerCase(); $mResult['IsSeen'] = \in_array('\\seen', $aFlags); $mResult['IsFlagged'] = \in_array('\\flagged', $aFlags); $mResult['IsAnswered'] = \in_array('\\answered', $aFlags); $mResult['IsDeleted'] = \in_array('\\deleted', $aFlags); $sForwardedFlag = $this->Config()->Get('labs', 'imap_forwarded_flag', ''); $sReadReceiptFlag = $this->Config()->Get('labs', 'imap_read_receipt_flag', ''); $mResult['IsForwarded'] = 0 < \strlen($sForwardedFlag) && \in_array(\strtolower($sForwardedFlag), $aFlags); $mResult['IsReadReceipt'] = 0 < \strlen($sReadReceiptFlag) && \in_array(\strtolower($sReadReceiptFlag), $aFlags); if (!$this->GetCapa(false, \RainLoop\Enumerations\Capa::COMPOSER, $oAccount)) { $mResult['IsReadReceipt'] = true; } $mResult['TextPartIsTrimmed'] = false; if ('Message' === $sParent) { $oAttachments = $mResponse->Attachments(); $bHasExternals = false; $mFoundedCIDs = array(); $aContentLocationUrls = array(); $mFoundedContentLocationUrls = array(); if ($oAttachments && 0 < $oAttachments->Count()) { $aList =& $oAttachments->GetAsArray(); foreach ($aList as $oAttachment) { if ($oAttachment) { $sContentLocation = $oAttachment->ContentLocation(); if ($sContentLocation && 0 < \strlen($sContentLocation)) { $aContentLocationUrls[] = $oAttachment->ContentLocation(); } } } } $sPlain = ''; $sHtml = \trim($mResponse->Html()); if (0 === \strlen($sHtml)) { $sPlain = \trim($mResponse->Plain()); } $mResult['DraftInfo'] = $mResponse->DraftInfo(); $mResult['InReplyTo'] = $mResponse->InReplyTo(); $mResult['References'] = $mResponse->References(); $fAdditionalDomReader = null; if (0 < \strlen($sHtml) && $this->Config()->Get('labs', 'emogrifier', false)) { if (!\class_exists('Pelago\\Emogrifier', false)) { include_once APP_VERSION_ROOT_PATH . 'app/libraries/emogrifier/Emogrifier.php'; } if (\class_exists('Pelago\\Emogrifier', false)) { $fAdditionalDomReader = function ($oDom) { $oEmogrifier = new \Pelago\Emogrifier(); $oEmogrifier->preserveEncoding = false; return $oEmogrifier->emogrify($oDom); }; } } $fAdditionalExternalFilter = null; if (!!$this->Config()->Get('labs', 'use_local_proxy_for_external_images', false)) { $fAdditionalExternalFilter = function ($sUrl) { return './?/ProxyExternal/' . \RainLoop\Utils::EncodeKeyValuesQ(array('Rnd' => \md5(\microtime(true)), 'Token' => \RainLoop\Utils::GetConnectionToken(), 'Url' => $sUrl)) . '/'; }; } $sHtml = \preg_replace_callback('/(<pre[^>]*>)([\\s\\S\\r\\n\\t]*?)(<\\/pre>)/mi', function ($aMatches) { return \preg_replace('/[\\r\\n]+/', '<br />', $aMatches[1] . \trim($aMatches[2]) . $aMatches[3]); }, $sHtml); $mResult['Html'] = 0 === \strlen($sHtml) ? '' : \MailSo\Base\HtmlUtils::ClearHtml($sHtml, $bHasExternals, $mFoundedCIDs, $aContentLocationUrls, $mFoundedContentLocationUrls, false, false, $fAdditionalExternalFilter, $fAdditionalDomReader, !!$this->Config()->Get('labs', 'try_to_detect_hidden_images', false)); $mResult['ExternalProxy'] = null !== $fAdditionalExternalFilter; $mResult['Plain'] = $sPlain; // $mResult['Plain'] = 0 === \strlen($sPlain) ? '' : \MailSo\Base\HtmlUtils::ConvertPlainToHtml($sPlain); $mResult['TextHash'] = \md5($mResult['Html'] . $mResult['Plain']); $mResult['TextPartIsTrimmed'] = $mResponse->TextPartIsTrimmed(); $mResult['PgpSigned'] = $mResponse->PgpSigned(); $mResult['PgpEncrypted'] = $mResponse->PgpEncrypted(); $mResult['PgpSignature'] = $mResponse->PgpSignature(); unset($sHtml, $sPlain); $mResult['HasExternals'] = $bHasExternals; $mResult['HasInternals'] = \is_array($mFoundedCIDs) && 0 < \count($mFoundedCIDs) || \is_array($mFoundedContentLocationUrls) && 0 < \count($mFoundedContentLocationUrls); $mResult['FoundedCIDs'] = $mFoundedCIDs; $mResult['Attachments'] = $this->responseObject($oAttachments, $sParent, \array_merge($aParameters, array('FoundedCIDs' => $mFoundedCIDs, 'FoundedContentLocationUrls' => $mFoundedContentLocationUrls))); $mResult['ReadReceipt'] = $mResponse->ReadReceipt(); if (0 < \strlen($mResult['ReadReceipt']) && !$mResult['IsReadReceipt']) { if (0 < \strlen($mResult['ReadReceipt'])) { try { $oReadReceipt = \MailSo\Mime\Email::Parse($mResult['ReadReceipt']); if (!$oReadReceipt) { $mResult['ReadReceipt'] = ''; } } catch (\Exception $oException) { unset($oException); } } if (0 < \strlen($mResult['ReadReceipt']) && '1' === $this->Cacher($oAccount)->Get(\RainLoop\KeyPathHelper::ReadReceiptCache($oAccount->Email(), $mResult['Folder'], $mResult['Uid']), '0')) { $mResult['ReadReceipt'] = ''; } } } } else { if ('MailSo\\Mime\\Email' === $sClassName) { $mResult = \array_merge($this->objectData($mResponse, $sParent, $aParameters), array('Name' => \MailSo\Base\Utils::Utf8Clear($mResponse->GetDisplayName()), 'Email' => \MailSo\Base\Utils::Utf8Clear($mResponse->GetEmail(true)), 'DkimStatus' => $mResponse->GetDkimStatus(), 'DkimValue' => $mResponse->GetDkimValue())); } else { if ('RainLoop\\Providers\\AddressBook\\Classes\\Contact' === $sClassName) { $mResult = \array_merge($this->objectData($mResponse, $sParent, $aParameters), array('IdContact' => $mResponse->IdContact, 'Display' => \MailSo\Base\Utils::Utf8Clear($mResponse->Display), 'ReadOnly' => $mResponse->ReadOnly, 'IdPropertyFromSearch' => $mResponse->IdPropertyFromSearch, 'Properties' => $this->responseObject($mResponse->Properties, $sParent, $aParameters))); } else { if ('RainLoop\\Providers\\AddressBook\\Classes\\Tag' === $sClassName) { $mResult = \array_merge($this->objectData($mResponse, $sParent, $aParameters), array('IdContactTag' => $mResponse->IdContactTag, 'Name' => \MailSo\Base\Utils::Utf8Clear($mResponse->Name), 'ReadOnly' => $mResponse->ReadOnly)); } else { if ('RainLoop\\Providers\\AddressBook\\Classes\\Property' === $sClassName) { // Simple hack if ($mResponse && $mResponse->IsWeb()) { $mResponse->Value = \preg_replace('/(skype|ftp|http[s]?)\\\\:\\/\\//i', '$1://', $mResponse->Value); } $mResult = \array_merge($this->objectData($mResponse, $sParent, $aParameters), array('IdProperty' => $mResponse->IdProperty, 'Type' => $mResponse->Type, 'TypeStr' => $mResponse->TypeStr, 'Value' => \MailSo\Base\Utils::Utf8Clear($mResponse->Value))); } else { if ('MailSo\\Mail\\Attachment' === $sClassName) { $oAccount = $this->getAccountFromToken(false); $mFoundedCIDs = isset($aParameters['FoundedCIDs']) && \is_array($aParameters['FoundedCIDs']) && 0 < \count($aParameters['FoundedCIDs']) ? $aParameters['FoundedCIDs'] : null; $mFoundedContentLocationUrls = isset($aParameters['FoundedContentLocationUrls']) && \is_array($aParameters['FoundedContentLocationUrls']) && 0 < \count($aParameters['FoundedContentLocationUrls']) ? $aParameters['FoundedContentLocationUrls'] : null; if ($mFoundedCIDs || $mFoundedContentLocationUrls) { $mFoundedCIDs = \array_merge($mFoundedCIDs ? $mFoundedCIDs : array(), $mFoundedContentLocationUrls ? $mFoundedContentLocationUrls : array()); $mFoundedCIDs = 0 < \count($mFoundedCIDs) ? $mFoundedCIDs : null; } $mResult = \array_merge($this->objectData($mResponse, $sParent, $aParameters), array('Folder' => $mResponse->Folder(), 'Uid' => (string) $mResponse->Uid(), 'Framed' => false, 'MimeIndex' => (string) $mResponse->MimeIndex(), 'MimeType' => $mResponse->MimeType(), 'FileName' => \MailSo\Base\Utils::ClearFileName(\MailSo\Base\Utils::ClearXss($mResponse->FileName(true))), 'EstimatedSize' => $mResponse->EstimatedSize(), 'CID' => $mResponse->Cid(), 'ContentLocation' => $mResponse->ContentLocation(), 'IsInline' => $mResponse->IsInline(), 'IsThumbnail' => $bThumb, 'IsLinked' => $mFoundedCIDs && \in_array(\trim(\trim($mResponse->Cid()), '<>'), $mFoundedCIDs) || $mFoundedContentLocationUrls && \in_array(\trim($mResponse->ContentLocation()), $mFoundedContentLocationUrls))); $mResult['Framed'] = $this->isFileHasFramedPreview($mResult['FileName']); if ($mResult['IsThumbnail']) { $mResult['IsThumbnail'] = $this->isFileHasThumbnail($mResult['FileName']); } $mResult['Download'] = \RainLoop\Utils::EncodeKeyValuesQ(array('V' => APP_VERSION, 'Account' => $oAccount ? \md5($oAccount->Hash()) : '', 'Folder' => $mResult['Folder'], 'Uid' => $mResult['Uid'], 'MimeIndex' => $mResult['MimeIndex'], 'MimeType' => $mResult['MimeType'], 'FileName' => $mResult['FileName'], 'Framed' => $mResult['Framed'])); } else { if ('MailSo\\Mail\\Folder' === $sClassName) { $aExtended = null; // $mStatus = $mResponse->Status(); // if (\is_array($mStatus) && isset($mStatus['MESSAGES'], $mStatus['UNSEEN'], $mStatus['UIDNEXT'])) // { // $aExtended = array( // 'MessageCount' => (int) $mStatus['MESSAGES'], // 'MessageUnseenCount' => (int) $mStatus['UNSEEN'], // 'UidNext' => (string) $mStatus['UIDNEXT'], // 'Hash' => $this->MailClient()->GenerateFolderHash( // $mResponse->FullNameRaw(), $mStatus['MESSAGES'], $mStatus['UNSEEN'], $mStatus['UIDNEXT'], // empty($mStatus['HIGHESTMODSEQ']) ? '' : $mStatus['HIGHESTMODSEQ']) // ); // } $aCheckableFolder = \call_user_func($fGetCheckableFolder); if (!\is_array($aCheckableFolder)) { $aCheckableFolder = array(); } $mResult = \array_merge($this->objectData($mResponse, $sParent, $aParameters), array('Name' => $mResponse->Name(), 'FullName' => $mResponse->FullName(), 'FullNameRaw' => $mResponse->FullNameRaw(), 'FullNameHash' => $this->hashFolderFullName($mResponse->FullNameRaw(), $mResponse->FullName()), 'Delimiter' => (string) $mResponse->Delimiter(), 'HasVisibleSubFolders' => $mResponse->HasVisibleSubFolders(), 'IsSubscribed' => $mResponse->IsSubscribed(), 'IsExists' => $mResponse->IsExists(), 'IsSelectable' => $mResponse->IsSelectable(), 'Flags' => $mResponse->FlagsLowerCase(), 'Checkable' => \in_array($mResponse->FullNameRaw(), $aCheckableFolder), 'Extended' => $aExtended, 'SubFolders' => $this->responseObject($mResponse->SubFolders(), $sParent, $aParameters))); } else { if ('MailSo\\Mail\\MessageCollection' === $sClassName) { $mResult = \array_merge($this->objectData($mResponse, $sParent, $aParameters), array('MessageCount' => $mResponse->MessageCount, 'MessageUnseenCount' => $mResponse->MessageUnseenCount, 'MessageResultCount' => $mResponse->MessageResultCount, 'Folder' => $mResponse->FolderName, 'FolderHash' => $mResponse->FolderHash, 'UidNext' => $mResponse->UidNext, 'ThreadUid' => $mResponse->ThreadUid, 'NewMessages' => $this->responseObject($mResponse->NewMessages), 'Filtered' => $mResponse->Filtered, 'Offset' => $mResponse->Offset, 'Limit' => $mResponse->Limit, 'Search' => $mResponse->Search)); } else { if ('MailSo\\Mail\\AttachmentCollection' === $sClassName) { $mResult = \array_merge($this->objectData($mResponse, $sParent, $aParameters), array('InlineCount' => $mResponse->InlineCount())); } else { if ('MailSo\\Mail\\FolderCollection' === $sClassName) { $mResult = \array_merge($this->objectData($mResponse, $sParent, $aParameters), array('Namespace' => $mResponse->GetNamespace(), 'FoldersHash' => isset($mResponse->FoldersHash) ? $mResponse->FoldersHash : '', 'IsThreadsSupported' => $mResponse->IsThreadsSupported, 'Optimized' => $mResponse->Optimized, 'CountRec' => $mResponse->CountRec(), 'SystemFolders' => isset($mResponse->SystemFolders) && \is_array($mResponse->SystemFolders) ? $mResponse->SystemFolders : array())); } else { if ($mResponse instanceof \MailSo\Base\Collection) { $aList =& $mResponse->GetAsArray(); if (100 < \count($aList) && $mResponse instanceof \MailSo\Mime\EmailCollection) { $aList = \array_slice($aList, 0, 100); } $mResult = $this->responseObject($aList, $sParent, $aParameters); $bHook = false; } else { $mResult = '["' . \get_class($mResponse) . '"]'; $bHook = false; } } } } } } } } } } } } if ($bHook) { $this->Plugins()->RunHook('filter.response-object', array($sClassName, $mResult), false); } } else { if (\is_array($mResponse)) { foreach ($mResponse as $iKey => $oItem) { $mResponse[$iKey] = $this->responseObject($oItem, $sParent, $aParameters); } $mResult = $mResponse; } } unset($mResponse); return $mResult; }
/** * Wraps HTML notification into a proper markup * * @param string $hook "format" * @param string $type "notification" * @param string $notification Notificaiton * @param array $params Hook params * @return array */ function notifications_html_handler_format($hook, $type, $notification, $params) { if (!$notification instanceof \Elgg\Notifications\Notification) { return; } $view = elgg_view('page/notification', array('notification' => $notification)); $css = elgg_view('page/notification.css'); $emogrifier = new \Pelago\Emogrifier($view, $css); $notification->body = $emogrifier->emogrify(); return $notification; }
<?php require 'vendor/autoload.php'; $templates = new League\Plates\Engine(__DIR__); $html = $templates->render('content'); $css = file_get_contents('style.css'); $emogrifier = new \Pelago\Emogrifier($html, $css); $mergedHtml = $emogrifier->emogrify(); echo $mergedHtml;
/** * @param HTTPRequest * @return Array - just so the template is still displayed **/ function sendreceipt(SS_HTTPRequest $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(); if (!class_exists('\\Pelago\\Emogrifier')) { require_once Director::baseFolder() . '/ecommerce/thirdparty/Emogrifier.php'; } Requirements::clear(); isset($project) ? $themeBaseFolder = $project : ($themeBaseFolder = "mysite"); Requirements::themedCSS("typography", $themeBaseFolder); // LEAVE HERE - NOT EASY TO INCLUDE VIA TEMPLATE Requirements::themedCSS("OrderReport", "ecommerce"); // LEAVE HERE - NOT EASY TO INCLUDE VIA TEMPLATE Requirements::themedCSS("Order_Invoice", "ecommerce", "print"); // LEAVE HERE - NOT EASY TO INCLUDE VIA TEMPLATE Config::nest(); Config::inst()->update('SSViewer', 'theme_enabled', true); $html = $this->renderWith("Order_ReceiptEmail"); Config::unnest(); // 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 \Pelago\Emogrifier($html, $css); $html = $emog->emogrify(); return $html; }