woocommerce
/
src
/
Internal
/
EmailEditor
/
WCTransactionalEmails
/
WCTransactionalEmailPostsGenerator.php
WCEmailTemplateAutoApplier.php
1 month ago
WCEmailTemplateChangeSummary.php
1 month ago
WCEmailTemplateDivergenceDetector.php
1 month ago
WCEmailTemplateSelectiveApplier.php
1 month ago
WCEmailTemplateSyncBackfill.php
1 month ago
WCEmailTemplateSyncRegistry.php
2 months ago
WCEmailTemplateSyncTracker.php
1 month ago
WCTransactionalEmailPostsGenerator.php
1 month ago
WCTransactionalEmailPostsManager.php
2 months ago
WCTransactionalEmails.php
1 month ago
WCTransactionalEmailPostsGenerator.php
443 lines
| 1 | <?php |
| 2 | |
| 3 | declare( strict_types=1 ); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Internal\EmailEditor\WCTransactionalEmails; |
| 6 | |
| 7 | use Automattic\Jetpack\Constants; |
| 8 | use Automattic\WooCommerce\Internal\EmailEditor\Integration; |
| 9 | use Automattic\WooCommerce\Internal\EmailEditor\EmailTemplates\WooEmailTemplate; |
| 10 | use Automattic\WooCommerce\Utilities\StringUtil; |
| 11 | |
| 12 | /** |
| 13 | * Class WCTransactionalEmailPostsGenerator |
| 14 | * |
| 15 | * Handles the generation of WooCommerce transactional email templates. |
| 16 | * This class is responsible for initializing and managing default email templates, |
| 17 | * as well as generating new templates when required. |
| 18 | * |
| 19 | * @package Automattic\WooCommerce\Internal\EmailEditor\WCTransactionalEmails |
| 20 | */ |
| 21 | class WCTransactionalEmailPostsGenerator { |
| 22 | /** |
| 23 | * WooCommerce Email Template Manager instance. |
| 24 | * |
| 25 | * @var WCTransactionalEmailPostsManager |
| 26 | */ |
| 27 | private $template_manager; |
| 28 | |
| 29 | /** |
| 30 | * Default templates. |
| 31 | * |
| 32 | * @var array<string, \WC_Email> |
| 33 | */ |
| 34 | private $default_templates = array(); |
| 35 | |
| 36 | /** |
| 37 | * Transient name. |
| 38 | * |
| 39 | * @var string |
| 40 | */ |
| 41 | private $transient_name = 'wc_email_editor_initial_templates_generated'; |
| 42 | |
| 43 | /** |
| 44 | * Constructor. |
| 45 | * |
| 46 | * Initializes the WCTransactionalEmailPostsGenerator by setting up the template manager. |
| 47 | */ |
| 48 | public function __construct() { |
| 49 | $this->template_manager = WCTransactionalEmailPostsManager::get_instance(); |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Initialize the email template generator. |
| 54 | * |
| 55 | * This function initializes the email template generator by loading the default templates |
| 56 | * and generating initial email templates if needed. |
| 57 | * |
| 58 | * @internal |
| 59 | */ |
| 60 | public function initialize() { |
| 61 | if ( Constants::get_constant( 'WC_VERSION' ) === get_transient( $this->transient_name ) ) { |
| 62 | // if templates are already generated, we don't need to run this function again. |
| 63 | return true; |
| 64 | } |
| 65 | |
| 66 | $this->init_default_transactional_emails(); |
| 67 | $this->generate_initial_email_templates(); |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Initialize the default WooCommerce Transactional Emails. |
| 72 | * |
| 73 | * This function initializes the default templates for the core transactional emails. |
| 74 | * It fetches all the emails from WooCommerce and filters them to include only the core transactional emails. |
| 75 | */ |
| 76 | public function init_default_transactional_emails() { |
| 77 | if ( ! empty( $this->default_templates ) ) { |
| 78 | // If the default templates are already initialized, we don't need to run this function again. |
| 79 | return; |
| 80 | } |
| 81 | |
| 82 | $core_transactional_emails = WCTransactionalEmails::get_transactional_emails(); |
| 83 | |
| 84 | $wc_emails = \WC_Emails::instance(); |
| 85 | /** |
| 86 | * WooCommerce Transactional Emails instance. |
| 87 | * |
| 88 | * @var \WC_Email[] |
| 89 | */ |
| 90 | $email_types = $wc_emails->get_emails(); |
| 91 | |
| 92 | // Filter the emails to include only the core transactional emails. |
| 93 | $email_types = array_filter( |
| 94 | $email_types, |
| 95 | function ( $email ) use ( $core_transactional_emails ) { |
| 96 | return in_array( $email->id, $core_transactional_emails, true ); |
| 97 | } |
| 98 | ); |
| 99 | |
| 100 | $this->default_templates = array_reduce( |
| 101 | $email_types, |
| 102 | function ( $acc, $email ) { |
| 103 | $acc[ $email->id ] = $email; |
| 104 | return $acc; |
| 105 | }, |
| 106 | array() |
| 107 | ); |
| 108 | } |
| 109 | |
| 110 | /** |
| 111 | * Resolve the block template name for the given email. |
| 112 | * |
| 113 | * Returns `$email->template_block` when set, otherwise derives it from |
| 114 | * `$email->template_plain` by replacing the `plain` segment with `block` |
| 115 | * (e.g. `emails/plain/customer-invoice.php` becomes `emails/block/customer-invoice.php`). |
| 116 | * |
| 117 | * @param \WC_Email $email The email object. |
| 118 | * @return string The block template name, or an empty string if none can be resolved. |
| 119 | * |
| 120 | * @since 10.8.0 |
| 121 | */ |
| 122 | public static function resolve_block_template_name( $email ): string { |
| 123 | if ( ! empty( $email->template_block ) ) { |
| 124 | return (string) $email->template_block; |
| 125 | } |
| 126 | |
| 127 | $template_plain = (string) $email->template_plain; |
| 128 | if ( '' === $template_plain ) { |
| 129 | return ''; |
| 130 | } |
| 131 | |
| 132 | return str_replace( 'plain', 'block', $template_plain ); |
| 133 | } |
| 134 | |
| 135 | /** |
| 136 | * Resolve the absolute path of the block template for the given email. |
| 137 | * |
| 138 | * Uses {@see self::resolve_block_template_name()} for name resolution and then |
| 139 | * delegates to `wc_locate_template()` so theme overrides are honored. |
| 140 | * |
| 141 | * @param \WC_Email $email The email object. |
| 142 | * @return string The absolute template path, or an empty string if none can be resolved. |
| 143 | * |
| 144 | * @since 10.8.0 |
| 145 | */ |
| 146 | public static function resolve_block_template_path( $email ): string { |
| 147 | $template_name = self::resolve_block_template_name( $email ); |
| 148 | if ( '' === $template_name ) { |
| 149 | return ''; |
| 150 | } |
| 151 | |
| 152 | return (string) wc_locate_template( |
| 153 | $template_name, |
| 154 | '', |
| 155 | (string) $email->template_base |
| 156 | ); |
| 157 | } |
| 158 | |
| 159 | /** |
| 160 | * Get the email template for the given email. |
| 161 | * |
| 162 | * Looks for the initial email block content in plugins/woocommerce/templates/emails/block. |
| 163 | * |
| 164 | * @param \WC_Email $email The email object. |
| 165 | * @return string The email template. |
| 166 | */ |
| 167 | public function get_email_template( $email ) { |
| 168 | return self::render_block_template_html( $email ); |
| 169 | } |
| 170 | |
| 171 | /** |
| 172 | * Render the block template HTML for a given email. |
| 173 | * |
| 174 | * Resolves the block template (honouring theme overrides), falls back to the |
| 175 | * default block content on failure, and applies the |
| 176 | * `woocommerce_email_block_template_html` filter. Stateless so both the |
| 177 | * generator (via {@see self::get_email_template()}) and the divergence |
| 178 | * detector observe an identical rendering pipeline. |
| 179 | * |
| 180 | * @param \WC_Email $email The email object. |
| 181 | * @return string The rendered template HTML. |
| 182 | * |
| 183 | * @since 10.8.0 |
| 184 | */ |
| 185 | public static function render_block_template_html( $email ): string { |
| 186 | $template_name = self::resolve_block_template_name( $email ); |
| 187 | |
| 188 | try { |
| 189 | $template_html = wc_get_template_html( |
| 190 | $template_name, |
| 191 | array(), |
| 192 | '', |
| 193 | (string) $email->template_base |
| 194 | ); |
| 195 | } catch ( \Exception $e ) { |
| 196 | // wc_get_template_html() uses ob_start(), so we need to clean the output buffer if an exception is thrown. |
| 197 | if ( ob_get_level() > 0 ) { |
| 198 | ob_end_clean(); |
| 199 | } |
| 200 | $template_html = ''; |
| 201 | } |
| 202 | |
| 203 | // wc_get_template_html does not throw an error when the template is not found. |
| 204 | // We need to check if the template is not found by checking the template_html content. |
| 205 | $has_template_error = |
| 206 | StringUtil::contains( $template_html, 'No such file or directory', false ) || |
| 207 | StringUtil::contains( $template_html, 'Failed to open stream', false ) || |
| 208 | StringUtil::contains( $template_html, 'Warning: include', false ); |
| 209 | |
| 210 | if ( is_wp_error( $template_html ) || empty( $template_html ) || $has_template_error ) { |
| 211 | $default_template_name = 'emails/block/default-block-content.php'; |
| 212 | $template_html = wc_get_template_html( |
| 213 | $default_template_name, |
| 214 | array() |
| 215 | ); |
| 216 | } |
| 217 | |
| 218 | /** |
| 219 | * Filter the email template HTML. |
| 220 | * |
| 221 | * @param string $template_html The email template HTML. |
| 222 | * @param \WC_Email $email The email object. |
| 223 | * @since 10.7.0 |
| 224 | */ |
| 225 | $filtered_template_html = apply_filters( 'woocommerce_email_block_template_html', $template_html, $email ); |
| 226 | |
| 227 | return is_string( $filtered_template_html ) ? $filtered_template_html : $template_html; |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Generate initial email templates. |
| 232 | * |
| 233 | * This function generates the initial email templates for the core transactional emails. |
| 234 | * It checks if the templates are already generated and if not, it generates them. |
| 235 | * |
| 236 | * @return bool True if the templates are generated, false otherwise. |
| 237 | */ |
| 238 | public function generate_initial_email_templates() { |
| 239 | $core_transactional_emails = WCTransactionalEmails::get_transactional_emails(); |
| 240 | |
| 241 | $templates_to_generate = array(); |
| 242 | foreach ( $core_transactional_emails as $email_type ) { |
| 243 | if ( empty( $this->template_manager->get_email_template_post_id( $email_type ) ) ) { |
| 244 | $templates_to_generate[] = $email_type; |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | if ( empty( $templates_to_generate ) ) { |
| 249 | return; |
| 250 | } |
| 251 | |
| 252 | $result = $this->generate_email_templates( $templates_to_generate ); |
| 253 | |
| 254 | if ( is_wp_error( $result ) ) { |
| 255 | return false; |
| 256 | } |
| 257 | |
| 258 | set_transient( $this->transient_name, Constants::get_constant( 'WC_VERSION' ), WEEK_IN_SECONDS ); |
| 259 | |
| 260 | // Flush rewrite rules to ensure the new templates are loaded. |
| 261 | flush_rewrite_rules(); |
| 262 | |
| 263 | return true; |
| 264 | } |
| 265 | |
| 266 | /** |
| 267 | * Generate email template if it doesn't exist. |
| 268 | * |
| 269 | * This function generates an email template if it doesn't exist. |
| 270 | * |
| 271 | * @param string $email_type The email type. |
| 272 | * @return int The post ID of the generated template. |
| 273 | * @throws \Exception When post creation fails. |
| 274 | */ |
| 275 | public function generate_email_template_if_not_exists( $email_type ) { |
| 276 | $email_data = $this->default_templates[ $email_type ]; |
| 277 | |
| 278 | if ( $this->template_manager->get_email_template_post_id( $email_type ) || empty( $email_data ) ) { |
| 279 | return $this->template_manager->get_email_template_post_id( $email_type ); |
| 280 | } |
| 281 | |
| 282 | return $this->generate_single_template( $email_type, $email_data ); |
| 283 | } |
| 284 | |
| 285 | /** |
| 286 | * Generate email templates. |
| 287 | * |
| 288 | * This function generates the email templates for the given email types. |
| 289 | * |
| 290 | * @param array $templates_to_generate The email types to generate. |
| 291 | */ |
| 292 | public function generate_email_templates( $templates_to_generate ) { |
| 293 | global $wpdb; |
| 294 | |
| 295 | $core_emails = array_filter( |
| 296 | $this->default_templates, |
| 297 | function ( $email_id ) use ( $templates_to_generate ) { |
| 298 | return in_array( $email_id, $templates_to_generate, true ); |
| 299 | }, |
| 300 | ARRAY_FILTER_USE_KEY |
| 301 | ); |
| 302 | |
| 303 | if ( empty( $core_emails ) ) { |
| 304 | return false; |
| 305 | } |
| 306 | |
| 307 | // Start transaction. |
| 308 | $wpdb->query( 'START TRANSACTION' ); |
| 309 | |
| 310 | try { |
| 311 | foreach ( $core_emails as $email_type => $email_data ) { |
| 312 | $this->generate_single_template( $email_type, $email_data ); |
| 313 | } |
| 314 | |
| 315 | $wpdb->query( 'COMMIT' ); |
| 316 | return true; |
| 317 | |
| 318 | } catch ( \Exception $e ) { |
| 319 | $wpdb->query( 'ROLLBACK' ); |
| 320 | return new \WP_Error( 'email_generation_failed', $e->getMessage() ); |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | /** |
| 325 | * Build the `wp_insert_post()` payload for a given email and apply the |
| 326 | * `woocommerce_email_content_post_data` filter. |
| 327 | * |
| 328 | * Extracted so the generator and the divergence detector observe the exact |
| 329 | * same pre-insert post payload, guaranteeing by construction that the hash |
| 330 | * stamped in {@see self::generate_single_template()} and the hash recomputed |
| 331 | * in `WCEmailTemplateDivergenceDetector` hash identical input. |
| 332 | * |
| 333 | * @param string $email_type The email type identifier (e.g. `customer_processing_order`). |
| 334 | * @param \WC_Email $email The transactional email instance. |
| 335 | * @return array The post data array after the `woocommerce_email_content_post_data` filter runs. |
| 336 | * |
| 337 | * @since 10.8.0 |
| 338 | */ |
| 339 | public static function build_filtered_post_data( string $email_type, $email ): array { |
| 340 | $post_data = array( |
| 341 | 'post_type' => Integration::EMAIL_POST_TYPE, |
| 342 | 'post_status' => 'publish', |
| 343 | 'post_name' => $email_type, |
| 344 | 'post_title' => $email->get_title(), |
| 345 | 'post_excerpt' => $email->get_description(), |
| 346 | 'post_content' => self::render_block_template_html( $email ), |
| 347 | 'meta_input' => array( |
| 348 | '_wp_page_template' => ( new WooEmailTemplate() )->get_slug(), |
| 349 | ), |
| 350 | ); |
| 351 | |
| 352 | /** |
| 353 | * Filter the email content post data before creating the post. |
| 354 | * |
| 355 | * Allows third-party integrators to modify the post data (title, content, meta, etc.) |
| 356 | * before the email content post is created. |
| 357 | * |
| 358 | * @since 10.5.0 |
| 359 | * @param array $post_data The post data array to be used for wp_insert_post(). |
| 360 | * @param string $email_type The email type identifier (e.g., 'customer_processing_order'). |
| 361 | * @param \WC_Email $email The WooCommerce email object. |
| 362 | */ |
| 363 | $filtered_post_data = apply_filters( 'woocommerce_email_content_post_data', $post_data, $email_type, $email ); |
| 364 | |
| 365 | return is_array( $filtered_post_data ) ? $filtered_post_data : $post_data; |
| 366 | } |
| 367 | |
| 368 | /** |
| 369 | * Compute the canonical `post_content` for a given email. |
| 370 | * |
| 371 | * Returns the `post_content` value that the generator would persist for this |
| 372 | * email after the `woocommerce_email_content_post_data` filter runs, i.e. |
| 373 | * the exact string whose sha1 is stamped into `_wc_email_template_source_hash`. |
| 374 | * |
| 375 | * Callers can hash the return value to obtain `currentCoreHash` for |
| 376 | * divergence detection. |
| 377 | * |
| 378 | * @param \WC_Email $email The transactional email instance. |
| 379 | * @return string The canonical post content. |
| 380 | * |
| 381 | * @since 10.8.0 |
| 382 | */ |
| 383 | public static function compute_canonical_post_content( $email ): string { |
| 384 | $post_data = self::build_filtered_post_data( (string) $email->id, $email ); |
| 385 | return (string) ( $post_data['post_content'] ?? '' ); |
| 386 | } |
| 387 | |
| 388 | /** |
| 389 | * Generate a single email template. |
| 390 | * |
| 391 | * This function generates a single email template post and sets its postmeta association. |
| 392 | * |
| 393 | * @param string $email_type The email type. |
| 394 | * @param \WC_Email $email_data The transactional email data. |
| 395 | * @return int The post ID of the generated template. |
| 396 | * @throws \Exception When post creation fails. |
| 397 | */ |
| 398 | private function generate_single_template( $email_type, $email_data ) { |
| 399 | $post_data = self::build_filtered_post_data( (string) $email_type, $email_data ); |
| 400 | |
| 401 | // Sync meta stamp for emails participating in template update propagation. |
| 402 | // VERSION + LAST_SYNCED_AT are filter-independent and can ride on `meta_input` |
| 403 | // during the insert. SOURCE_HASH must reflect the post_content WordPress |
| 404 | // actually persisted (post-`content_save_pre` filter chain), so we stamp it |
| 405 | // after the insert returns and re-fetch the post to hash its saved content. |
| 406 | $sync_config = WCEmailTemplateSyncRegistry::get_email_sync_config( (string) $email_data->id ); |
| 407 | if ( null !== $sync_config ) { |
| 408 | if ( ! isset( $post_data['meta_input'] ) || ! is_array( $post_data['meta_input'] ) ) { |
| 409 | $post_data['meta_input'] = array(); |
| 410 | } |
| 411 | $post_data['meta_input'][ WCEmailTemplateDivergenceDetector::VERSION_META_KEY ] = (string) $sync_config['version']; |
| 412 | $post_data['meta_input'][ WCEmailTemplateDivergenceDetector::LAST_SYNCED_AT_META_KEY ] = gmdate( 'Y-m-d H:i:s' ); |
| 413 | $post_data['meta_input'][ WCEmailTemplateDivergenceDetector::LAST_CORE_RENDER_META_KEY ] = (string) ( $post_data['post_content'] ?? '' ); |
| 414 | } |
| 415 | |
| 416 | $post_id = wp_insert_post( $post_data, true ); |
| 417 | |
| 418 | if ( is_wp_error( $post_id ) ) { |
| 419 | throw new \Exception( esc_html( $post_id->get_error_message() ) ); |
| 420 | } |
| 421 | |
| 422 | if ( null !== $sync_config ) { |
| 423 | $saved_post = get_post( $post_id ); |
| 424 | $saved_body = $saved_post instanceof \WP_Post ? (string) $saved_post->post_content : (string) ( $post_data['post_content'] ?? '' ); |
| 425 | update_post_meta( |
| 426 | (int) $post_id, |
| 427 | WCEmailTemplateDivergenceDetector::SOURCE_HASH_META_KEY, |
| 428 | sha1( $saved_body ) |
| 429 | ); |
| 430 | // Freshly generated posts match canonical core by construction. |
| 431 | update_post_meta( |
| 432 | (int) $post_id, |
| 433 | WCEmailTemplateDivergenceDetector::STATUS_META_KEY, |
| 434 | WCEmailTemplateDivergenceDetector::STATUS_IN_SYNC |
| 435 | ); |
| 436 | } |
| 437 | |
| 438 | $this->template_manager->save_email_template_post_id( $email_type, $post_id ); |
| 439 | |
| 440 | return $post_id; |
| 441 | } |
| 442 | } |
| 443 |