Blocks
10 months ago
Coupons
1 month ago
Endpoints
2 months ago
Patterns
1 month ago
PersonalizationTags
3 days ago
ProductCollection
1 month ago
Templates
2 months ago
AutomationEmailContextProvider.php
1 month ago
AutomationEmailPreviewOrderProvider.php
1 month ago
BlockEmailContentDetector.php
1 month ago
Cli.php
2 weeks ago
DependencyNotice.php
10 months ago
EditorPageRenderer.php
1 week ago
EmailApiController.php
1 week ago
EmailEditor.php
2 months ago
EmailEditorPreviewEmail.php
9 months ago
Logger.php
10 months ago
MailPoetCssInliner.php
8 months ago
MailpoetCssInlinerFactory.php
1 year ago
PersonalizationTagManager.php
5 days ago
index.php
2 years ago
EditorPageRenderer.php
354 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\EmailEditor\Integrations\MailPoet; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use Automattic\WooCommerce\EmailEditor\Email_Editor_Container; |
| 9 | use Automattic\WooCommerce\EmailEditor\Engine\Settings_Controller; |
| 10 | use Automattic\WooCommerce\EmailEditor\Engine\Theme_Controller; |
| 11 | use Automattic\WooCommerce\EmailEditor\Engine\User_Theme; |
| 12 | use MailPoet\Analytics\Analytics; |
| 13 | use MailPoet\Config\Env; |
| 14 | use MailPoet\Config\Installer; |
| 15 | use MailPoet\Config\ServicesChecker; |
| 16 | use MailPoet\EmailEditor\Integrations\MailPoet\EmailEditor as EditorInitController; |
| 17 | use MailPoet\Entities\NewsletterEntity; |
| 18 | use MailPoet\Features\FeaturesController; |
| 19 | use MailPoet\Newsletter\NewslettersRepository; |
| 20 | use MailPoet\Services\AuthorizedEmailsController; |
| 21 | use MailPoet\Services\AuthorizedSenderDomainController; |
| 22 | use MailPoet\Services\Bridge; |
| 23 | use MailPoet\Settings\SettingsController as MailPoetSettings; |
| 24 | use MailPoet\Settings\UserFlagsController; |
| 25 | use MailPoet\Util\CdnAssetUrl; |
| 26 | use MailPoet\Util\FreeDomains; |
| 27 | use MailPoet\Util\License\Features\CapabilitiesManager; |
| 28 | use MailPoet\Util\License\Features\Subscribers as SubscribersFeature; |
| 29 | use MailPoet\WP\Functions as WPFunctions; |
| 30 | |
| 31 | class EditorPageRenderer { |
| 32 | private WPFunctions $wp; |
| 33 | |
| 34 | private Settings_Controller $settingsController; |
| 35 | |
| 36 | private Theme_Controller $themeController; |
| 37 | |
| 38 | private User_Theme $userTheme; |
| 39 | |
| 40 | private DependencyNotice $dependencyNotice; |
| 41 | |
| 42 | private CdnAssetUrl $cdnAssetUrl; |
| 43 | |
| 44 | private ServicesChecker $servicesChecker; |
| 45 | |
| 46 | private SubscribersFeature $subscribersFeature; |
| 47 | |
| 48 | private MailPoetSettings $mailpoetSettings; |
| 49 | |
| 50 | private NewslettersRepository $newslettersRepository; |
| 51 | |
| 52 | private UserFlagsController $userFlagsController; |
| 53 | |
| 54 | private Analytics $analytics; |
| 55 | |
| 56 | private Bridge $bridge; |
| 57 | |
| 58 | private AuthorizedEmailsController $authorizedEmailsController; |
| 59 | |
| 60 | private AuthorizedSenderDomainController $senderDomainController; |
| 61 | |
| 62 | private FeaturesController $featuresController; |
| 63 | |
| 64 | private CapabilitiesManager $capabilitiesManager; |
| 65 | |
| 66 | public function __construct( |
| 67 | WPFunctions $wp, |
| 68 | CdnAssetUrl $cdnAssetUrl, |
| 69 | ServicesChecker $servicesChecker, |
| 70 | SubscribersFeature $subscribersFeature, |
| 71 | DependencyNotice $dependencyNotice, |
| 72 | MailPoetSettings $mailpoetSettings, |
| 73 | NewslettersRepository $newslettersRepository, |
| 74 | UserFlagsController $userFlagsController, |
| 75 | Analytics $analytics, |
| 76 | Bridge $bridge, |
| 77 | AuthorizedEmailsController $authorizedEmailsController, |
| 78 | AuthorizedSenderDomainController $senderDomainController, |
| 79 | FeaturesController $featuresController, |
| 80 | CapabilitiesManager $capabilitiesManager |
| 81 | ) { |
| 82 | $this->wp = $wp; |
| 83 | $this->settingsController = Email_Editor_Container::container()->get(Settings_Controller::class); |
| 84 | $this->cdnAssetUrl = $cdnAssetUrl; |
| 85 | $this->servicesChecker = $servicesChecker; |
| 86 | $this->subscribersFeature = $subscribersFeature; |
| 87 | $this->themeController = Email_Editor_Container::container()->get(Theme_Controller::class); |
| 88 | $this->userTheme = Email_Editor_Container::container()->get(User_Theme::class); |
| 89 | $this->dependencyNotice = $dependencyNotice; |
| 90 | $this->mailpoetSettings = $mailpoetSettings; |
| 91 | $this->newslettersRepository = $newslettersRepository; |
| 92 | $this->userFlagsController = $userFlagsController; |
| 93 | $this->analytics = $analytics; |
| 94 | $this->bridge = $bridge; |
| 95 | $this->authorizedEmailsController = $authorizedEmailsController; |
| 96 | $this->senderDomainController = $senderDomainController; |
| 97 | $this->featuresController = $featuresController; |
| 98 | $this->capabilitiesManager = $capabilitiesManager; |
| 99 | } |
| 100 | |
| 101 | public function render() { |
| 102 | // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- is_numeric guard plus int cast is the sanitization |
| 103 | $rawPostId = $_GET['post'] ?? null; |
| 104 | $postId = is_numeric($rawPostId) ? intval($rawPostId) : 0; |
| 105 | $post = $this->wp->getPost($postId); |
| 106 | if (!$post instanceof \WP_Post || $post->post_type !== EditorInitController::MAILPOET_EMAIL_POST_TYPE) { // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps |
| 107 | return; |
| 108 | } |
| 109 | $currentPostType = $post->post_type; // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps |
| 110 | $newsletter = $this->newslettersRepository->findOneBy(['wpPost' => $postId]); |
| 111 | if (!$newsletter instanceof NewsletterEntity) { |
| 112 | return; |
| 113 | } |
| 114 | $this->dependencyNotice->checkDependenciesAndEventuallyShowNotice(); |
| 115 | |
| 116 | // load analytics (mixpanel) library |
| 117 | if ($this->analytics->isEnabled()) { |
| 118 | add_filter('admin_footer', [$this, 'loadAnalyticsModule'], 24); |
| 119 | } |
| 120 | |
| 121 | // load mailpoet email editor JS integrations |
| 122 | $editorIntegrationAssetsParams = require Env::$assetsPath . '/dist/js/email_editor_integration/email_editor_integration.asset.php'; |
| 123 | $this->wp->wpEnqueueScript( |
| 124 | 'email_editor_integration', |
| 125 | Env::$assetsUrl . '/dist/js/email_editor_integration/email_editor_integration.js', |
| 126 | $editorIntegrationAssetsParams['dependencies'], |
| 127 | $editorIntegrationAssetsParams['version'], |
| 128 | true |
| 129 | ); |
| 130 | $this->wp->wpSetScriptTranslations('email_editor_integration', 'mailpoet'); |
| 131 | $this->wp->wpEnqueueStyle( |
| 132 | 'email_editor_integration', |
| 133 | Env::$assetsUrl . '/dist/js/email_editor_integration/email_editor_integration.css', |
| 134 | [], |
| 135 | $editorIntegrationAssetsParams['version'] |
| 136 | ); |
| 137 | |
| 138 | $styleParams = require Env::$assetsPath . '/dist/js/email-editor/style/style.asset.php'; |
| 139 | $this->wp->wpEnqueueStyle( |
| 140 | 'mailpoet_email_editor', |
| 141 | Env::$assetsUrl . '/dist/js/email-editor/style/style.css', |
| 142 | [], |
| 143 | $styleParams['version'] |
| 144 | ); |
| 145 | |
| 146 | // The email editor needs to load block categories to avoid warning and missing category names. |
| 147 | // See: https://github.com/WordPress/WordPress/blob/753817d462955eb4e40a89034b7b7c375a1e43f3/wp-admin/edit-form-blocks.php#L116-L120. |
| 148 | wp_add_inline_script( |
| 149 | 'wp-blocks', |
| 150 | sprintf('wp.blocks.setCategories( %s );', wp_json_encode(get_block_categories($post), JSON_HEX_TAG | JSON_UNESCAPED_SLASHES)), |
| 151 | 'after' |
| 152 | ); |
| 153 | |
| 154 | // Preload server-registered block schemas to avoid warning about missing block titles. |
| 155 | // See: https://github.com/WordPress/WordPress/blob/753817d462955eb4e40a89034b7b7c375a1e43f3/wp-admin/edit-form-blocks.php#L144C1-L148C3. |
| 156 | wp_add_inline_script( |
| 157 | 'wp-blocks', |
| 158 | sprintf('wp.blocks.unstable__bootstrapServerSideBlockDefinitions( %s );', wp_json_encode(get_block_editor_server_block_settings(), JSON_HEX_TAG | JSON_UNESCAPED_SLASHES)) |
| 159 | ); |
| 160 | |
| 161 | $editorSettings = $this->settingsController->get_settings(); |
| 162 | $editorSettings['displaySendEmailButton'] = true; |
| 163 | |
| 164 | $currentUserEmail = $this->wp->wpGetCurrentUser()->user_email; |
| 165 | |
| 166 | $isAutomationNewsletter = $newsletter->isAutomation() || $newsletter->isAutomationTransactional(); |
| 167 | $automationId = $newsletter->getOptionValue('automationId'); |
| 168 | |
| 169 | $listingUrl = 'page=mailpoet-newsletters'; |
| 170 | $sendUrl = 'page=mailpoet-newsletters#/send/' . $newsletter->getId(); |
| 171 | $backUrl = 'page=mailpoet-newsletters'; |
| 172 | |
| 173 | if ($isAutomationNewsletter) { |
| 174 | $listingUrl = 'page=mailpoet-automation'; |
| 175 | $sendUrl = 'page=mailpoet-automation-editor&id=' . $automationId; |
| 176 | $backUrl = $sendUrl; |
| 177 | } |
| 178 | |
| 179 | $this->wp->wpLocalizeScript( |
| 180 | 'email_editor_integration', |
| 181 | 'WooCommerceEmailEditor', |
| 182 | [ |
| 183 | 'current_post_type' => $currentPostType, |
| 184 | 'current_post_id' => $post->ID, |
| 185 | 'current_wp_user_email' => $currentUserEmail, |
| 186 | 'editor_settings' => $editorSettings, |
| 187 | 'editor_theme' => $this->themeController->get_base_theme()->get_raw_data(), |
| 188 | 'user_theme_post_id' => $this->userTheme->get_user_theme_post()->ID, |
| 189 | 'urls' => [ |
| 190 | 'listings' => admin_url('admin.php?' . $listingUrl), |
| 191 | 'send' => admin_url('admin.php?' . $sendUrl), |
| 192 | 'back' => admin_url('admin.php?' . $backUrl), |
| 193 | ], |
| 194 | ] |
| 195 | ); |
| 196 | |
| 197 | $installedAtDiff = (new \DateTime($this->mailpoetSettings->get('installed_at')))->diff(new \DateTime()); |
| 198 | // Survey should be displayed only if there are 2 and more emails and the user hasn't seen it yet |
| 199 | $displaySurvey = ($this->newslettersRepository->getCountOfEmailsWithWPPost() > 1) && !$this->userFlagsController->get(UserFlagsController::EMAIL_EDITOR_SURVEY); |
| 200 | |
| 201 | // Renders additional script data that some components require e.g. PremiumModal. This is done here instead of using |
| 202 | // PageRenderer since that introduces other dependencies we want to avoid. Used by getUpgradeInfo. |
| 203 | // some of these values are used by the powered by mailpoet block: mailpoet/assets/js/src/mailpoet-custom-email-editor-blocks/powered-by-mailpoet/ |
| 204 | $installer = new Installer(Installer::PREMIUM_PLUGIN_SLUG); |
| 205 | $inline_script_data = [ |
| 206 | 'mailpoet_premium_plugin_installed' => Installer::isPluginInstalled(Installer::PREMIUM_PLUGIN_SLUG), |
| 207 | 'mailpoet_premium_active' => $this->servicesChecker->isPremiumPluginActive(), |
| 208 | 'mailpoet_premium_plugin_download_url' => $this->subscribersFeature->hasValidPremiumKey() ? $installer->generatePluginDownloadUrl() : null, |
| 209 | 'mailpoet_premium_plugin_activation_url' => $installer->generatePluginActivationUrl(Installer::PREMIUM_PLUGIN_PATH), |
| 210 | 'mailpoet_has_valid_api_key' => $this->subscribersFeature->hasValidApiKey(), |
| 211 | 'mailpoet_has_valid_premium_key' => $this->subscribersFeature->hasValidPremiumKey(), |
| 212 | 'mailpoet_has_premium_support' => $this->subscribersFeature->hasPremiumSupport(), |
| 213 | 'mailpoet_mta_method' => $this->mailpoetSettings->get('mta.method'), |
| 214 | 'mailpoet_mss_active' => $this->bridge->isMailpoetSendingServiceEnabled(), |
| 215 | 'mailpoet_authorized_emails' => [], |
| 216 | 'mailpoet_verified_sender_domains' => [], |
| 217 | 'mailpoet_partially_verified_sender_domains' => [], |
| 218 | 'mailpoet_all_sender_domains' => [], |
| 219 | 'mailpoet_sender_restrictions' => [], |
| 220 | 'mailpoet_free_domains' => FreeDomains::FREE_DOMAINS, |
| 221 | 'mailpoet_plugin_partial_key' => $this->servicesChecker->generatePartialApiKey(), |
| 222 | 'mailpoet_subscribers_count' => $this->subscribersFeature->getSubscribersCount(), |
| 223 | 'mailpoet_subscribers_limit' => $this->subscribersFeature->getSubscribersLimit(), |
| 224 | 'mailpoet_subscribers_limit_reached' => $this->subscribersFeature->check(), |
| 225 | // settings needed for Satismeter tracking |
| 226 | 'mailpoet_3rd_party_libs_enabled' => $this->mailpoetSettings->get('3rd_party_libs.enabled') === '1', |
| 227 | 'mailpoet_display_nps_email_editor' => $displaySurvey, |
| 228 | 'mailpoet_display_nps_poll' => true, |
| 229 | 'mailpoet_current_wp_user' => $this->wp->wpGetCurrentUser()->to_array(), |
| 230 | 'mailpoet_current_wp_user_firstname' => $this->wp->wpGetCurrentUser()->user_firstname, |
| 231 | 'mailpoet_cdn_url' => $this->cdnAssetUrl->generateCdnUrl(""), |
| 232 | 'mailpoet_site_url' => $this->wp->siteUrl(), |
| 233 | 'mailpoet_review_request_illustration_url' => $this->cdnAssetUrl->generateCdnUrl('review-request/review-request-illustration.20190815-1427.svg'), |
| 234 | 'mailpoet_installed_days_ago' => (int)$installedAtDiff->format('%a'), |
| 235 | 'mailpoet_segments_api' => [ |
| 236 | 'root' => rtrim($this->wp->escUrlRaw($this->wp->restUrl()), '/'), |
| 237 | 'nonce' => $this->wp->wpCreateNonce('wp_rest'), |
| 238 | ], |
| 239 | 'mailpoet_is_automation_newsletter' => $isAutomationNewsletter, |
| 240 | 'mailpoet_automation_id' => $automationId, |
| 241 | 'mailpoet_feature_flags' => $this->featuresController->getAllFlags(), |
| 242 | 'mailpoet_capabilities' => $this->capabilitiesManager->getCapabilities(), |
| 243 | 'mailpoet_ai_text_generation_available' => function_exists('wp_ai_client_prompt') |
| 244 | && wp_ai_client_prompt('test')->is_supported_for_text_generation(), |
| 245 | ]; |
| 246 | if ($this->bridge->isMailpoetSendingServiceEnabled()) { |
| 247 | $inline_script_data['mailpoet_authorized_emails'] = $this->authorizedEmailsController->getAuthorizedEmailAddresses(); |
| 248 | $inline_script_data['mailpoet_verified_sender_domains'] = $this->senderDomainController->getFullyVerifiedSenderDomains(true); |
| 249 | $inline_script_data['mailpoet_partially_verified_sender_domains'] = $this->senderDomainController->getPartiallyVerifiedSenderDomains(true); |
| 250 | $inline_script_data['mailpoet_all_sender_domains'] = $this->senderDomainController->getAllSenderDomains(); |
| 251 | $inline_script_data['mailpoet_sender_restrictions'] = [ |
| 252 | 'lowerLimit' => AuthorizedSenderDomainController::LOWER_LIMIT, |
| 253 | 'isAuthorizedDomainRequiredForNewCampaigns' => $this->senderDomainController->isAuthorizedDomainRequiredForNewCampaigns(), |
| 254 | 'campaignTypes' => NewsletterEntity::CAMPAIGN_TYPES, |
| 255 | 'skipAuthorization' => $this->senderDomainController->shouldSkipAuthorization(), |
| 256 | ]; |
| 257 | } |
| 258 | $emailRegexScript = <<<'JS' |
| 259 | var mailpoet_email_regex = /(?=^[+a-zA-Z0-9_.!#$%&'*\/=?^`{|}~-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,63}$)(?=^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,})))/; |
| 260 | JS; |
| 261 | $inlineScript = implode('', array_map(function ($key) use ($inline_script_data) { |
| 262 | return sprintf("var %s=%s;", $key, wp_json_encode($inline_script_data[$key], JSON_HEX_TAG | JSON_UNESCAPED_SLASHES)); |
| 263 | }, array_keys($inline_script_data))); |
| 264 | $inlineScript = $emailRegexScript . $inlineScript; |
| 265 | $scriptHandles = [ |
| 266 | 'email_editor_integration', |
| 267 | 'mailpoet-powered-by-mailpoet-block', |
| 268 | ]; |
| 269 | foreach ($scriptHandles as $scriptHandle) { |
| 270 | $this->wp->wpAddInlineScript($scriptHandle, $inlineScript, 'before'); |
| 271 | } |
| 272 | |
| 273 | // Load CSS from Post Editor |
| 274 | $this->wp->wpEnqueueStyle('wp-edit-post'); |
| 275 | // Load CSS for the format library - used for example in popover |
| 276 | $this->wp->wpEnqueueStyle('wp-format-library'); |
| 277 | |
| 278 | // Enqueue media library scripts |
| 279 | $this->wp->wpEnqueueMedia(); |
| 280 | |
| 281 | $this->preloadRestApiData($post); |
| 282 | |
| 283 | require_once ABSPATH . 'wp-admin/admin-header.php'; |
| 284 | echo '<div id="mailpoet-email-editor" class="block-editor block-editor__container hide-if-no-js"></div>'; |
| 285 | } |
| 286 | |
| 287 | private function preloadRestApiData(\WP_Post $post): void { |
| 288 | $userThemePostId = $this->userTheme->get_user_theme_post()->ID; |
| 289 | $templateSlug = get_post_meta($post->ID, '_wp_page_template', true); |
| 290 | $routes = [ |
| 291 | '/wp/v2/mailpoet_email/' . intval($post->ID) . '?context=edit', |
| 292 | '/wp/v2/types/mailpoet_email?context=edit', |
| 293 | '/wp/v2/global-styles/' . intval($userThemePostId) . '?context=edit', // Global email styles |
| 294 | '/wp/v2/block-patterns/patterns', |
| 295 | '/wp/v2/templates?context=edit', |
| 296 | '/wp/v2/block-patterns/categories', |
| 297 | '/wp/v2/settings', |
| 298 | '/wp/v2/types?context=view', |
| 299 | '/wp/v2/taxonomies?context=view', |
| 300 | ]; |
| 301 | |
| 302 | if (is_string($templateSlug) && $templateSlug !== '') { |
| 303 | $routes[] = '/wp/v2/templates/lookup?slug=' . $templateSlug; |
| 304 | } else { |
| 305 | $routes[] = '/wp/v2/mailpoet_email?context=edit&per_page=30&status=publish,sent'; |
| 306 | } |
| 307 | |
| 308 | // Preload personalization tags for automation emails |
| 309 | // Note: The registry is already extended in render() before preloading. |
| 310 | // We include post_id to match the WooCommerce Email Editor's request URL. |
| 311 | $newsletter = $this->newslettersRepository->findOneBy(['wpPost' => $post->ID]); |
| 312 | if ($newsletter && ($newsletter->isAutomation() || $newsletter->isAutomationTransactional())) { |
| 313 | $routes[] = '/woocommerce-email-editor/v1/personalization_tags?context=view&per_page=-1&post_id=' . intval($post->ID); |
| 314 | } |
| 315 | |
| 316 | // Preload the data for the specified routes |
| 317 | $preloadData = array_reduce( |
| 318 | $routes, |
| 319 | 'rest_preload_api_request', |
| 320 | [] |
| 321 | ); |
| 322 | |
| 323 | // Add inline script to set up preloading middleware |
| 324 | wp_add_inline_script( |
| 325 | 'wp-blocks', |
| 326 | sprintf( |
| 327 | 'wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( %s ) );', |
| 328 | wp_json_encode($preloadData, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES) |
| 329 | ) |
| 330 | ); |
| 331 | } |
| 332 | |
| 333 | public function loadAnalyticsModule() { // phpcs:ignore -- MissingReturnStatement not required |
| 334 | $publicId = $this->analytics->getPublicId(); |
| 335 | $isPublicIdNew = $this->analytics->isPublicIdNew(); |
| 336 | // this is required here because of `analytics-event.js` and order of script load and use in `mailpoet-email-editor-integration/index.ts` |
| 337 | $libs3rdPartyEnabled = $this->mailpoetSettings->get('3rd_party_libs.enabled') === '1'; |
| 338 | |
| 339 | // we need to set this values because they are used in the analytics.html file |
| 340 | ?> |
| 341 | <script type="text/javascript"> <?php // phpcs:ignore ?> |
| 342 | window.mailpoet_analytics_enabled = true; |
| 343 | window.mailpoet_analytics_public_id = '<?php echo esc_js($publicId); ?>'; |
| 344 | window.mailpoet_analytics_new_public_id = <?php echo wp_json_encode($isPublicIdNew, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES); ?>; |
| 345 | window.mailpoet_3rd_party_libs_enabled = <?php echo wp_json_encode($libs3rdPartyEnabled, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES); ?>; |
| 346 | window.mailpoet_version = '<?php echo esc_js(MAILPOET_VERSION); ?>'; |
| 347 | window.mailpoet_premium_version = '<?php echo esc_js((defined('MAILPOET_PREMIUM_VERSION')) ? MAILPOET_PREMIUM_VERSION : ''); ?>'; |
| 348 | </script> |
| 349 | <?php |
| 350 | |
| 351 | include_once Env::$viewsPath . '/analytics.html'; |
| 352 | } |
| 353 | } |
| 354 |