Blocks
2 months ago
Columns
5 months ago
PostProcess
4 days ago
BodyRenderer.php
2 months ago
EscapeHelper.php
2 years ago
Preprocessor.php
1 year ago
Renderer.php
1 month ago
StylesHelper.php
2 months ago
Template.html
2 months ago
index.php
3 years ago
Renderer.php
354 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\Newsletter\Renderer; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use Automattic\WooCommerce\EmailEditor\Email_Editor_Container; |
| 9 | use Automattic\WooCommerce\EmailEditor\Engine\Renderer\Html2Text; |
| 10 | use Automattic\WooCommerce\EmailEditor\Engine\Renderer\Renderer as GuntenbergRenderer; |
| 11 | use MailPoet\Config\Env; |
| 12 | use MailPoet\EmailEditor\Integrations\MailPoet\Coupons\CouponBlockFailureTranslator; |
| 13 | use MailPoet\EmailEditor\Integrations\MailPoet\Coupons\CouponBlockGenerationFailureCollector; |
| 14 | use MailPoet\EmailEditor\Integrations\MailPoet\Coupons\EmailContextBuilder; |
| 15 | use MailPoet\EmailEditor\Integrations\MailPoet\ProductCollection\OrderProductCollectionProcessor; |
| 16 | use MailPoet\Entities\NewsletterEntity; |
| 17 | use MailPoet\Entities\SendingQueueEntity; |
| 18 | use MailPoet\Logging\LoggerFactory; |
| 19 | use MailPoet\Newsletter\NewslettersRepository; |
| 20 | use MailPoet\Newsletter\Renderer\EscapeHelper as EHelper; |
| 21 | use MailPoet\Newsletter\Sending\NewsletterReplayMetadata; |
| 22 | use MailPoet\Newsletter\Sending\SendingQueuesRepository; |
| 23 | use MailPoet\NewsletterProcessingException; |
| 24 | use MailPoet\Util\License\Features\CapabilitiesManager; |
| 25 | use MailPoet\Util\pQuery\DomNode; |
| 26 | use MailPoet\WP\Functions as WPFunctions; |
| 27 | |
| 28 | class Renderer { |
| 29 | const NEWSLETTER_TEMPLATE = 'Template.html'; |
| 30 | const FILTER_POST_PROCESS = 'mailpoet_rendering_post_process'; |
| 31 | |
| 32 | /** @var BodyRenderer */ |
| 33 | private $bodyRenderer; |
| 34 | |
| 35 | /** @var GuntenbergRenderer */ |
| 36 | private $guntenbergRenderer; |
| 37 | |
| 38 | /** @var Preprocessor */ |
| 39 | private $preprocessor; |
| 40 | |
| 41 | /** @var \MailPoetVendor\CSS */ |
| 42 | private $cSSInliner; |
| 43 | |
| 44 | /** @var WPFunctions */ |
| 45 | private $wp; |
| 46 | |
| 47 | /*** @var LoggerFactory */ |
| 48 | private $loggerFactory; |
| 49 | |
| 50 | /*** @var NewslettersRepository */ |
| 51 | private $newslettersRepository; |
| 52 | |
| 53 | /*** @var SendingQueuesRepository */ |
| 54 | private $sendingQueuesRepository; |
| 55 | |
| 56 | private CapabilitiesManager $capabilitiesManager; |
| 57 | |
| 58 | private CouponBlockGenerationFailureCollector $couponBlockFailureCollector; |
| 59 | |
| 60 | private EmailContextBuilder $emailContextBuilder; |
| 61 | |
| 62 | private CouponBlockFailureTranslator $couponBlockFailureTranslator; |
| 63 | |
| 64 | private OrderProductCollectionProcessor $orderProductCollectionProcessor; |
| 65 | |
| 66 | public function __construct( |
| 67 | BodyRenderer $bodyRenderer, |
| 68 | Preprocessor $preprocessor, |
| 69 | \MailPoetVendor\CSS $cSSInliner, |
| 70 | WPFunctions $wp, |
| 71 | LoggerFactory $loggerFactory, |
| 72 | NewslettersRepository $newslettersRepository, |
| 73 | SendingQueuesRepository $sendingQueuesRepository, |
| 74 | CapabilitiesManager $capabilitiesManager, |
| 75 | CouponBlockGenerationFailureCollector $couponBlockFailureCollector, |
| 76 | EmailContextBuilder $emailContextBuilder, |
| 77 | CouponBlockFailureTranslator $couponBlockFailureTranslator, |
| 78 | OrderProductCollectionProcessor $orderProductCollectionProcessor |
| 79 | ) { |
| 80 | $this->bodyRenderer = $bodyRenderer; |
| 81 | $this->guntenbergRenderer = Email_Editor_Container::container()->get(GuntenbergRenderer::class); |
| 82 | $this->preprocessor = $preprocessor; |
| 83 | $this->cSSInliner = $cSSInliner; |
| 84 | $this->wp = $wp; |
| 85 | $this->loggerFactory = $loggerFactory; |
| 86 | $this->newslettersRepository = $newslettersRepository; |
| 87 | $this->sendingQueuesRepository = $sendingQueuesRepository; |
| 88 | $this->capabilitiesManager = $capabilitiesManager; |
| 89 | $this->couponBlockFailureCollector = $couponBlockFailureCollector; |
| 90 | $this->emailContextBuilder = $emailContextBuilder; |
| 91 | $this->couponBlockFailureTranslator = $couponBlockFailureTranslator; |
| 92 | $this->orderProductCollectionProcessor = $orderProductCollectionProcessor; |
| 93 | } |
| 94 | |
| 95 | public function render(NewsletterEntity $newsletter, ?SendingQueueEntity $sendingQueue = null, $type = false) { |
| 96 | return $this->_render($newsletter, $sendingQueue, $type); |
| 97 | } |
| 98 | |
| 99 | public function renderAsPreview(NewsletterEntity $newsletter, $type = false, ?string $subject = null) { |
| 100 | return $this->_render($newsletter, null, $type, true, $subject); |
| 101 | } |
| 102 | |
| 103 | private function _render(NewsletterEntity $newsletter, ?SendingQueueEntity $sendingQueue = null, $type = false, $preview = false, $subject = null) { |
| 104 | $language = $this->wp->getBloginfo('language'); |
| 105 | $isRtl = (bool)$this->wp->isRtl(); |
| 106 | $metaRobots = $preview ? '<meta name="robots" content="noindex, nofollow" />' : ''; |
| 107 | $subject = $subject ?: $newsletter->getSubject(); |
| 108 | $wpPostEntity = $newsletter->getWpPost(); |
| 109 | $wpPost = $wpPostEntity ? $wpPostEntity->getWpPostInstance() : null; |
| 110 | if ($wpPost instanceof \WP_Post) { |
| 111 | $this->couponBlockFailureCollector->clear(); |
| 112 | $renderContext = $this->emailContextBuilder->build($newsletter, $sendingQueue, (bool)$preview); |
| 113 | $filterCallback = function (array $context) use ($renderContext): array { |
| 114 | return array_merge($context, $renderContext); |
| 115 | }; |
| 116 | $orderProductsFilter = null; |
| 117 | $abandonedCartPersistentCartFilter = null; |
| 118 | |
| 119 | try { |
| 120 | $this->wp->addFilter('woocommerce_email_editor_rendering_email_context', $filterCallback); |
| 121 | $abandonedCartPersistentCartFilter = $this->orderProductCollectionProcessor |
| 122 | ->createAbandonedCartPersistentCartFilter($renderContext, $sendingQueue); |
| 123 | if ($abandonedCartPersistentCartFilter) { |
| 124 | $this->wp->addFilter('get_user_metadata', $abandonedCartPersistentCartFilter, 10, 4); |
| 125 | } |
| 126 | $orderProductsFilter = $this->orderProductCollectionProcessor->createBlocksFilter($renderContext); |
| 127 | if ($orderProductsFilter) { |
| 128 | $this->wp->addFilter('woocommerce_email_blocks_renderer_parsed_blocks', $orderProductsFilter); |
| 129 | } |
| 130 | $renderedNewsletter = $this->guntenbergRenderer->render($wpPost, $subject, $newsletter->getPreheader(), $language, $metaRobots); |
| 131 | if ($this->couponBlockFailureCollector->hasFailures()) { |
| 132 | throw NewsletterProcessingException::create() |
| 133 | ->withMessage($this->couponBlockFailureTranslator->getFailureMessage($this->couponBlockFailureCollector)); |
| 134 | } |
| 135 | $filteredHtml = $this->wp->applyFilters( |
| 136 | self::FILTER_POST_PROCESS, |
| 137 | $renderedNewsletter['html'] |
| 138 | ); |
| 139 | if (is_string($filteredHtml)) { |
| 140 | $renderedNewsletter['html'] = $filteredHtml; |
| 141 | } |
| 142 | } finally { |
| 143 | $this->wp->removeFilter('woocommerce_email_editor_rendering_email_context', $filterCallback); |
| 144 | if ($orderProductsFilter) { |
| 145 | $this->wp->removeFilter('woocommerce_email_blocks_renderer_parsed_blocks', $orderProductsFilter); |
| 146 | } |
| 147 | if ($abandonedCartPersistentCartFilter) { |
| 148 | $this->wp->removeFilter('get_user_metadata', $abandonedCartPersistentCartFilter); |
| 149 | } |
| 150 | $this->couponBlockFailureCollector->clear(); |
| 151 | } |
| 152 | } else { |
| 153 | $body = (is_array($newsletter->getBody())) |
| 154 | ? $newsletter->getBody() |
| 155 | : []; |
| 156 | $content = (array_key_exists('content', $body)) |
| 157 | ? $body['content'] |
| 158 | : []; |
| 159 | $styles = (array_key_exists('globalStyles', $body)) |
| 160 | ? $body['globalStyles'] |
| 161 | : []; |
| 162 | |
| 163 | $mailPoetLogoInEmails = $this->capabilitiesManager->getCapability('mailpoetLogoInEmails'); |
| 164 | if ( |
| 165 | (isset($mailPoetLogoInEmails) && $mailPoetLogoInEmails->isRestricted) && !$preview |
| 166 | ) { |
| 167 | $content = $this->addMailpoetLogoContentBlock($content, $styles); |
| 168 | } |
| 169 | |
| 170 | $renderedBody = ""; |
| 171 | try { |
| 172 | $content = $this->preprocessor->process($newsletter, $content, $preview, $sendingQueue); |
| 173 | $renderedBody = $this->bodyRenderer->renderBody($newsletter, $content, $isRtl); |
| 174 | } catch (NewsletterProcessingException $e) { |
| 175 | $this->loggerFactory->getLogger(LoggerFactory::TOPIC_COUPONS)->error( |
| 176 | $e->getMessage(), |
| 177 | ['newsletter_id' => $newsletter->getId()] |
| 178 | ); |
| 179 | if (!$sendingQueue || !NewsletterReplayMetadata::isLatestNewsletterReplayMeta($sendingQueue->getMeta())) { |
| 180 | $this->newslettersRepository->setAsCorrupt($newsletter); |
| 181 | } |
| 182 | if ($sendingQueue) { |
| 183 | $this->sendingQueuesRepository->pause($sendingQueue); |
| 184 | } |
| 185 | } |
| 186 | $renderedStyles = $this->renderStyles($styles); |
| 187 | $customFontsLinks = StylesHelper::getCustomFontsLinks($styles); |
| 188 | |
| 189 | $template = $this->injectContentIntoTemplate( |
| 190 | (string)file_get_contents(dirname(__FILE__) . '/' . self::NEWSLETTER_TEMPLATE), |
| 191 | [ |
| 192 | $language, |
| 193 | $isRtl ? ' dir="rtl"' : '', |
| 194 | $metaRobots, |
| 195 | htmlspecialchars($subject, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401), |
| 196 | $renderedStyles, |
| 197 | $customFontsLinks, |
| 198 | $isRtl ? ' style="direction: rtl;"' : '', |
| 199 | $isRtl ? ';direction:rtl' : '', |
| 200 | EHelper::escapeHtmlText($newsletter->getPreheader()), |
| 201 | $renderedBody, |
| 202 | ] |
| 203 | ); |
| 204 | if ($template === null) { |
| 205 | $template = ''; |
| 206 | } |
| 207 | $templateDom = $this->inlineCSSStyles($template); |
| 208 | $template = $this->postProcessTemplate($templateDom); |
| 209 | |
| 210 | $renderedNewsletter = [ |
| 211 | 'html' => $template, |
| 212 | 'text' => $this->renderTextVersion($template), |
| 213 | ]; |
| 214 | } |
| 215 | |
| 216 | return ($type && !empty($renderedNewsletter[$type])) ? |
| 217 | $renderedNewsletter[$type] : |
| 218 | $renderedNewsletter; |
| 219 | } |
| 220 | |
| 221 | /** |
| 222 | * @param array $styles |
| 223 | * @return string |
| 224 | */ |
| 225 | private function renderStyles(array $styles) { |
| 226 | $css = ''; |
| 227 | foreach ($styles as $selector => $style) { |
| 228 | switch ($selector) { |
| 229 | case 'text': |
| 230 | $selector = 'td.mailpoet_paragraph, td.mailpoet_blockquote, li.mailpoet_paragraph, td.mailpoet_footer'; |
| 231 | break; |
| 232 | case 'body': |
| 233 | $selector = 'body, .mailpoet-wrapper'; |
| 234 | break; |
| 235 | case 'link': |
| 236 | $selector = '.mailpoet-wrapper a'; |
| 237 | break; |
| 238 | case 'wrapper': |
| 239 | $selector = '.mailpoet_content-wrapper'; |
| 240 | break; |
| 241 | } |
| 242 | |
| 243 | if (!is_array($style)) { |
| 244 | continue; |
| 245 | } |
| 246 | |
| 247 | $css .= StylesHelper::setStyle($style, $selector); |
| 248 | } |
| 249 | return $css; |
| 250 | } |
| 251 | |
| 252 | /** |
| 253 | * @param string $template |
| 254 | * @param string[] $content |
| 255 | * @return string|null |
| 256 | */ |
| 257 | private function injectContentIntoTemplate($template, $content) { |
| 258 | return preg_replace_callback('/{{\w+}}/', function($matches) use (&$content) { |
| 259 | return array_shift($content); |
| 260 | }, $template); |
| 261 | } |
| 262 | |
| 263 | /** |
| 264 | * @param string $template |
| 265 | * @return DomNode |
| 266 | */ |
| 267 | private function inlineCSSStyles($template) { |
| 268 | return $this->cSSInliner->inlineCSS($template); |
| 269 | } |
| 270 | |
| 271 | /** |
| 272 | * @param string $template |
| 273 | * @return string |
| 274 | */ |
| 275 | private function renderTextVersion($template) { |
| 276 | if (!mb_detect_encoding($template, 'UTF-8', true)) { |
| 277 | $converted = mb_convert_encoding($template, 'UTF-8', mb_list_encodings()); |
| 278 | $template = $converted !== false ? $converted : $template; |
| 279 | } |
| 280 | return @Html2Text::convert($template); |
| 281 | } |
| 282 | |
| 283 | /** |
| 284 | * @param DomNode $templateDom |
| 285 | * @return string |
| 286 | */ |
| 287 | private function postProcessTemplate(DomNode $templateDom) { |
| 288 | // replace spaces in image tag URLs |
| 289 | foreach ($templateDom->query('img') as $image) { |
| 290 | $image->src = str_replace(' ', '%20', $image->src); |
| 291 | } |
| 292 | foreach ($templateDom->query('a') as $anchor) { |
| 293 | // Fix for a TinyMCE bug in smart paste which encodes & as & which is then additionally encoded to &amp; |
| 294 | // when saving the text block content in the editor |
| 295 | $href = str_replace('&amp;', '&', $anchor->href); |
| 296 | // Replace & with & in the href attributes of anchors. URLs are encoded when TinyMCE extracts Text block content via content.innerHTML. |
| 297 | // Links containing & work when placed in an anchor tag in a browser, but they don't work when we redirect to them for example in tracking. |
| 298 | $href = str_replace('&', '&', $href); |
| 299 | $anchor->href = $href; |
| 300 | } |
| 301 | $template = $templateDom->__toString(); |
| 302 | $filtered = $this->wp->applyFilters( |
| 303 | self::FILTER_POST_PROCESS, |
| 304 | $template |
| 305 | ); |
| 306 | return is_string($filtered) ? $filtered : $template; |
| 307 | } |
| 308 | |
| 309 | /** |
| 310 | * @param array $content |
| 311 | * @param array $styles |
| 312 | * @return array |
| 313 | */ |
| 314 | private function addMailpoetLogoContentBlock(array $content, array $styles) { |
| 315 | if (empty($content['blocks'])) return $content; |
| 316 | $content['blocks'][] = [ |
| 317 | 'type' => 'container', |
| 318 | 'orientation' => 'horizontal', |
| 319 | 'styles' => [ |
| 320 | 'block' => [ |
| 321 | 'backgroundColor' => (!empty($styles['body']['backgroundColor'])) ? |
| 322 | $styles['body']['backgroundColor'] : |
| 323 | 'transparent', |
| 324 | ], |
| 325 | ], |
| 326 | 'blocks' => [ |
| 327 | [ |
| 328 | 'type' => 'container', |
| 329 | 'orientation' => 'vertical', |
| 330 | 'styles' => [ |
| 331 | ], |
| 332 | 'blocks' => [ |
| 333 | [ |
| 334 | 'type' => 'image', |
| 335 | 'link' => 'https://www.mailpoet.com/?ref=free-plan-user-email&utm_source=free_plan_user_email&utm_medium=email', |
| 336 | 'src' => Env::$assetsUrl . '/img/mailpoet_logo_newsletter.png', |
| 337 | 'fullWidth' => false, |
| 338 | 'alt' => 'Email Marketing Powered by MailPoet', |
| 339 | 'width' => '108px', |
| 340 | 'height' => '65px', |
| 341 | 'styles' => [ |
| 342 | 'block' => [ |
| 343 | 'textAlign' => 'center', |
| 344 | ], |
| 345 | ], |
| 346 | ], |
| 347 | ], |
| 348 | ], |
| 349 | ], |
| 350 | ]; |
| 351 | return $content; |
| 352 | } |
| 353 | } |
| 354 |