woocommerce
/
src
/
Internal
/
EmailEditor
/
WCTransactionalEmails
/
WCTransactionalEmailPostsGenerator.php
WCTransactionalEmailPostsGenerator.php
| 1 | <?php |
| 2 | |
| 3 | declare( strict_types=1 ); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Internal\EmailEditor\WCTransactionalEmails; |
| 6 | |
| 7 | use Automattic\WooCommerce\Internal\EmailEditor\Integration; |
| 8 | use Automattic\WooCommerce\Internal\EmailEditor\EmailTemplates\WooEmailTemplate; |
| 9 | use Automattic\WooCommerce\Utilities\StringUtil; |
| 10 | |
| 11 | /** |
| 12 | * Class WCTransactionalEmailPostsGenerator |
| 13 | * |
| 14 | * Handles the generation of WooCommerce transactional email templates. |
| 15 | * This class is responsible for initializing and managing default email templates, |
| 16 | * as well as generating new templates when required. |
| 17 | * |
| 18 | * @package Automattic\WooCommerce\Internal\EmailEditor\WCTransactionalEmails |
| 19 | */ |
| 20 | class WCTransactionalEmailPostsGenerator { |
| 21 | /** |
| 22 | * Resolve the block template name for the given email. |
| 23 | * |
| 24 | * Returns `$email->template_block` when set, otherwise derives it from |
| 25 | * `$email->template_plain` by replacing the `plain` segment with `block` |
| 26 | * (e.g. `emails/plain/customer-invoice.php` becomes `emails/block/customer-invoice.php`). |
| 27 | * |
| 28 | * @param \WC_Email $email The email object. |
| 29 | * @return string The block template name, or an empty string if none can be resolved. |
| 30 | * |
| 31 | * @since 10.8.0 |
| 32 | */ |
| 33 | public static function resolve_block_template_name( $email ): string { |
| 34 | if ( ! empty( $email->template_block ) ) { |
| 35 | return (string) $email->template_block; |
| 36 | } |
| 37 | |
| 38 | $template_plain = (string) $email->template_plain; |
| 39 | if ( '' === $template_plain ) { |
| 40 | return ''; |
| 41 | } |
| 42 | |
| 43 | return str_replace( 'plain', 'block', $template_plain ); |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * Resolve the absolute path of the block template for the given email. |
| 48 | * |
| 49 | * Uses {@see self::resolve_block_template_name()} for name resolution and then |
| 50 | * delegates to `wc_locate_template()` so theme overrides are honored. |
| 51 | * |
| 52 | * @param \WC_Email $email The email object. |
| 53 | * @return string The absolute template path, or an empty string if none can be resolved. |
| 54 | * |
| 55 | * @since 10.8.0 |
| 56 | */ |
| 57 | public static function resolve_block_template_path( $email ): string { |
| 58 | $template_name = self::resolve_block_template_name( $email ); |
| 59 | if ( '' === $template_name ) { |
| 60 | return ''; |
| 61 | } |
| 62 | |
| 63 | return (string) wc_locate_template( |
| 64 | $template_name, |
| 65 | '', |
| 66 | (string) $email->template_base |
| 67 | ); |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Get the email template for the given email. |
| 72 | * |
| 73 | * Looks for the initial email block content in plugins/woocommerce/templates/emails/block. |
| 74 | * |
| 75 | * @param \WC_Email $email The email object. |
| 76 | * @return string The email template. |
| 77 | */ |
| 78 | public function get_email_template( $email ) { |
| 79 | return self::render_block_template_html( $email ); |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * Render the block template HTML for a given email. |
| 84 | * |
| 85 | * Resolves the block template (honouring theme overrides), falls back to the |
| 86 | * default block content on failure, and applies the |
| 87 | * `woocommerce_email_block_template_html` filter. Stateless so both the |
| 88 | * generator (via {@see self::get_email_template()}) and the divergence |
| 89 | * detector observe an identical rendering pipeline. |
| 90 | * |
| 91 | * @param \WC_Email $email The email object. |
| 92 | * @return string The rendered template HTML. |
| 93 | * |
| 94 | * @since 10.8.0 |
| 95 | */ |
| 96 | public static function render_block_template_html( $email ): string { |
| 97 | $template_name = self::resolve_block_template_name( $email ); |
| 98 | |
| 99 | try { |
| 100 | $template_html = wc_get_template_html( |
| 101 | $template_name, |
| 102 | array(), |
| 103 | '', |
| 104 | (string) $email->template_base |
| 105 | ); |
| 106 | } catch ( \Exception $e ) { |
| 107 | // wc_get_template_html() uses ob_start(), so we need to clean the output buffer if an exception is thrown. |
| 108 | if ( ob_get_level() > 0 ) { |
| 109 | ob_end_clean(); |
| 110 | } |
| 111 | $template_html = ''; |
| 112 | } |
| 113 | |
| 114 | // wc_get_template_html does not throw an error when the template is not found. |
| 115 | // We need to check if the template is not found by checking the template_html content. |
| 116 | $has_template_error = |
| 117 | StringUtil::contains( $template_html, 'No such file or directory', false ) || |
| 118 | StringUtil::contains( $template_html, 'Failed to open stream', false ) || |
| 119 | StringUtil::contains( $template_html, 'Warning: include', false ); |
| 120 | |
| 121 | if ( is_wp_error( $template_html ) || empty( $template_html ) || $has_template_error ) { |
| 122 | $default_template_name = 'emails/block/default-block-content.php'; |
| 123 | $template_html = wc_get_template_html( |
| 124 | $default_template_name, |
| 125 | array() |
| 126 | ); |
| 127 | } |
| 128 | |
| 129 | /** |
| 130 | * Filter the email template HTML. |
| 131 | * |
| 132 | * Runs wherever the file template is rendered: in admin (post creation, |
| 133 | * divergence detection) and on the email send path (file-first |
| 134 | * rendering) — including front-end, cron, and CLI requests. Callbacks |
| 135 | * must not assume admin context. |
| 136 | * |
| 137 | * @param string $template_html The email template HTML. |
| 138 | * @param \WC_Email $email The email object. |
| 139 | * @since 10.7.0 |
| 140 | */ |
| 141 | $filtered_template_html = apply_filters( 'woocommerce_email_block_template_html', $template_html, $email ); |
| 142 | |
| 143 | return is_string( $filtered_template_html ) ? $filtered_template_html : $template_html; |
| 144 | } |
| 145 | |
| 146 | /** |
| 147 | * Build the `wp_insert_post()` payload for a given email and apply the |
| 148 | * `woocommerce_email_content_post_data` filter. |
| 149 | * |
| 150 | * Extracted so the generator and the divergence detector observe the exact |
| 151 | * same pre-insert post payload, guaranteeing by construction that the hash |
| 152 | * stamped in {@see self::create_draft()} and the hash recomputed |
| 153 | * in `WCEmailTemplateDivergenceDetector` hash identical input. |
| 154 | * |
| 155 | * Note: a `post_status` returned by the filter is not honored on the |
| 156 | * creation path — {@see self::create_draft()} forces `draft` |
| 157 | * because the status is system-owned (only published posts are rendered). |
| 158 | * |
| 159 | * @param string $email_type The email type identifier (e.g. `customer_processing_order`). |
| 160 | * @param \WC_Email $email The transactional email instance. |
| 161 | * @return array The post data array after the `woocommerce_email_content_post_data` filter runs. |
| 162 | * |
| 163 | * @since 10.8.0 |
| 164 | */ |
| 165 | public static function build_filtered_post_data( string $email_type, $email ): array { |
| 166 | $post_data = array( |
| 167 | 'post_type' => Integration::EMAIL_POST_TYPE, |
| 168 | 'post_status' => 'publish', |
| 169 | 'post_name' => $email_type, |
| 170 | 'post_title' => $email->get_title(), |
| 171 | 'post_excerpt' => $email->get_description(), |
| 172 | 'post_content' => self::render_block_template_html( $email ), |
| 173 | 'meta_input' => array( |
| 174 | '_wp_page_template' => ( new WooEmailTemplate() )->get_slug(), |
| 175 | ), |
| 176 | ); |
| 177 | |
| 178 | /** |
| 179 | * Filter the email content post data before creating the post. |
| 180 | * |
| 181 | * Allows third-party integrators to modify the post data (title, content, meta, etc.) |
| 182 | * before the email content post is created. |
| 183 | * |
| 184 | * Besides post creation, this also runs whenever the canonical file |
| 185 | * template content is computed — including the email send path |
| 186 | * (front-end, cron, CLI), where only `post_content` from the filtered |
| 187 | * array is used. On the creation path `post_status` is system-owned |
| 188 | * and not honored. Callbacks must not assume admin context. |
| 189 | * |
| 190 | * @since 10.5.0 |
| 191 | * @param array $post_data The post data array to be used for wp_insert_post(). |
| 192 | * @param string $email_type The email type identifier (e.g., 'customer_processing_order'). |
| 193 | * @param \WC_Email $email The WooCommerce email object. |
| 194 | */ |
| 195 | $filtered_post_data = apply_filters( 'woocommerce_email_content_post_data', $post_data, $email_type, $email ); |
| 196 | |
| 197 | return is_array( $filtered_post_data ) ? $filtered_post_data : $post_data; |
| 198 | } |
| 199 | |
| 200 | /** |
| 201 | * Compute the canonical `post_content` for a given email. |
| 202 | * |
| 203 | * Returns the `post_content` value that the generator would persist for this |
| 204 | * email after the `woocommerce_email_content_post_data` filter runs, i.e. |
| 205 | * the exact string whose sha1 is stamped into `_wc_email_template_source_hash`. |
| 206 | * |
| 207 | * Callers can hash the return value to obtain `currentCoreHash` for |
| 208 | * divergence detection. |
| 209 | * |
| 210 | * @param \WC_Email $email The transactional email instance. |
| 211 | * @return string The canonical post content. |
| 212 | * |
| 213 | * @since 10.8.0 |
| 214 | */ |
| 215 | public static function compute_canonical_post_content( $email ): string { |
| 216 | $post_data = self::build_filtered_post_data( (string) $email->id, $email ); |
| 217 | return (string) ( $post_data['post_content'] ?? '' ); |
| 218 | } |
| 219 | |
| 220 | /** |
| 221 | * Create a draft email post for the given email. |
| 222 | * |
| 223 | * The draft is the editing scratchpad created when a user opens the |
| 224 | * email editor for an email type that has no saved post yet. It stays |
| 225 | * invisible to rendering (only published posts are used) and links to its |
| 226 | * email type solely via the `_wc_email_type` meta — the option mapping is |
| 227 | * written when the post is published, see |
| 228 | * `Integration::save_email_mapping_on_publish()`. |
| 229 | * |
| 230 | * @param \WC_Email $email The transactional email instance. |
| 231 | * @return int The post ID of the created draft. |
| 232 | * @throws \Exception When post creation fails. |
| 233 | * |
| 234 | * @since 11.1.0 |
| 235 | */ |
| 236 | public function create_draft( \WC_Email $email ): int { |
| 237 | $email_type = (string) $email->id; |
| 238 | $post_data = self::build_filtered_post_data( $email_type, $email ); |
| 239 | |
| 240 | // The status is system-owned: it must stay `draft` so the post is |
| 241 | // ignored by rendering until published, regardless of what the |
| 242 | // `woocommerce_email_content_post_data` filter returns. A regular draft |
| 243 | // is used instead of an auto-draft because the editor treats auto-draft |
| 244 | // titles as placeholders and blanks them. |
| 245 | $post_data['post_status'] = 'draft'; |
| 246 | |
| 247 | if ( ! isset( $post_data['meta_input'] ) || ! is_array( $post_data['meta_input'] ) ) { |
| 248 | $post_data['meta_input'] = array(); |
| 249 | } |
| 250 | $post_data['meta_input'][ WCTransactionalEmailPostsManager::EMAIL_TYPE_META_KEY ] = $email_type; |
| 251 | |
| 252 | // Version + last-synced meta only apply to emails participating in |
| 253 | // template update propagation. Their values don't depend on what |
| 254 | // WordPress persists, so they can be written as part of the insert |
| 255 | // (unlike the source hash below, which must match the saved content). |
| 256 | $sync_config = WCEmailTemplateSyncRegistry::get_email_sync_config( $email_type ); |
| 257 | if ( null !== $sync_config ) { |
| 258 | $post_data['meta_input'][ WCEmailTemplateDivergenceDetector::VERSION_META_KEY ] = (string) $sync_config['version']; |
| 259 | $post_data['meta_input'][ WCEmailTemplateDivergenceDetector::LAST_SYNCED_AT_META_KEY ] = gmdate( 'Y-m-d H:i:s' ); |
| 260 | $post_data['meta_input'][ WCEmailTemplateDivergenceDetector::LAST_CORE_RENDER_META_KEY ] = (string) ( $post_data['post_content'] ?? '' ); |
| 261 | } |
| 262 | |
| 263 | $post_id = wp_insert_post( $post_data, true ); |
| 264 | |
| 265 | if ( is_wp_error( $post_id ) ) { |
| 266 | throw new \Exception( esc_html( $post_id->get_error_message() ) ); |
| 267 | } |
| 268 | |
| 269 | // The source hash is stamped for every draft — also for emails outside |
| 270 | // the sync registry — because `was_never_edited()` checks rely on it; |
| 271 | // the timestamp fallback breaks once a refresh or autosave touches |
| 272 | // `post_modified`. It must reflect the post_content WordPress actually |
| 273 | // persisted (post-`content_save_pre` filter chain), so it is stamped |
| 274 | // after the insert returns, hashing the saved content. |
| 275 | $saved_post = get_post( $post_id ); |
| 276 | $saved_body = $saved_post instanceof \WP_Post ? (string) $saved_post->post_content : (string) ( $post_data['post_content'] ?? '' ); |
| 277 | update_post_meta( |
| 278 | (int) $post_id, |
| 279 | WCEmailTemplateDivergenceDetector::SOURCE_HASH_META_KEY, |
| 280 | sha1( $saved_body ) |
| 281 | ); |
| 282 | // Freshly created posts match canonical core by construction. |
| 283 | update_post_meta( |
| 284 | (int) $post_id, |
| 285 | WCEmailTemplateDivergenceDetector::STATUS_META_KEY, |
| 286 | WCEmailTemplateDivergenceDetector::STATUS_IN_SYNC |
| 287 | ); |
| 288 | |
| 289 | return (int) $post_id; |
| 290 | } |
| 291 | |
| 292 | /** |
| 293 | * Initialize the email template generator. |
| 294 | * |
| 295 | * @deprecated 11.1.0 Email posts are created lazily when the user opens the editor; there is no initialization step anymore. No-op, will be removed in a future version. |
| 296 | * @return void |
| 297 | */ |
| 298 | public function initialize() { |
| 299 | wc_deprecated_function( __METHOD__, '11.1.0' ); |
| 300 | } |
| 301 | |
| 302 | /** |
| 303 | * Initialize the default WooCommerce Transactional Emails. |
| 304 | * |
| 305 | * @deprecated 11.1.0 Email posts are created lazily when the user opens the editor; default templates are no longer pre-loaded. No-op, will be removed in a future version. |
| 306 | * @return void |
| 307 | */ |
| 308 | public function init_default_transactional_emails() { |
| 309 | wc_deprecated_function( __METHOD__, '11.1.0' ); |
| 310 | } |
| 311 | |
| 312 | /** |
| 313 | * Generate initial email templates. |
| 314 | * |
| 315 | * @deprecated 11.1.0 Email posts are no longer bulk-generated; file templates are the rendering source until an email is customized and saved. No-op, will be removed in a future version. |
| 316 | * @return bool Always false. |
| 317 | */ |
| 318 | public function generate_initial_email_templates() { |
| 319 | wc_deprecated_function( __METHOD__, '11.1.0' ); |
| 320 | return false; |
| 321 | } |
| 322 | |
| 323 | /** |
| 324 | * Generate email templates. |
| 325 | * |
| 326 | * @deprecated 11.1.0 Email posts are no longer bulk-generated; file templates are the rendering source until an email is customized and saved. No-op, will be removed in a future version. |
| 327 | * @param array $templates_to_generate The email types to generate. |
| 328 | * @return bool Always false. |
| 329 | */ |
| 330 | public function generate_email_templates( $templates_to_generate ) { |
| 331 | unset( $templates_to_generate ); |
| 332 | wc_deprecated_function( __METHOD__, '11.1.0' ); |
| 333 | return false; |
| 334 | } |
| 335 | |
| 336 | /** |
| 337 | * Generate email template if it doesn't exist. |
| 338 | * |
| 339 | * @deprecated 11.1.0 Email posts are created lazily as drafts when the user opens the editor and become the rendering source when published. This method now creates a published post directly and will be removed in a future version. |
| 340 | * @param string $email_type The email type. |
| 341 | * @return int|false The post ID, or false when the email type is not registered or the post could not be created or published. |
| 342 | */ |
| 343 | public function generate_email_template_if_not_exists( $email_type ) { |
| 344 | wc_deprecated_function( __METHOD__, '11.1.0' ); |
| 345 | |
| 346 | $post_manager = WCTransactionalEmailPostsManager::get_instance(); |
| 347 | |
| 348 | // Reuse the mapped post only when it still exists and isn't trashed — |
| 349 | // a stale mapping (post deleted or trashed out-of-band) must fall |
| 350 | // through to creating a fresh post, mirroring the recreate endpoint. |
| 351 | $existing_post = $post_manager->get_email_post( $email_type ); |
| 352 | if ( $existing_post && 'trash' !== $existing_post->post_status ) { |
| 353 | return $existing_post->ID; |
| 354 | } |
| 355 | |
| 356 | $email = $post_manager->get_email_by_id( (string) $email_type ); |
| 357 | if ( ! $email ) { |
| 358 | return false; |
| 359 | } |
| 360 | |
| 361 | // Preserve the method's original int|false contract: it never threw, |
| 362 | // so a post-creation failure must surface as false, not an exception. |
| 363 | try { |
| 364 | $post_id = $this->create_draft( $email ); |
| 365 | } catch ( \Exception $e ) { |
| 366 | return false; |
| 367 | } |
| 368 | |
| 369 | $updated = wp_update_post( |
| 370 | array( |
| 371 | 'ID' => $post_id, |
| 372 | 'post_status' => 'publish', |
| 373 | // An empty value makes core skip page template handling, |
| 374 | // leaving the meta as created. Omitting the key would not |
| 375 | // help: wp_update_post() fills it from the stored meta and |
| 376 | // then fails validation when the email template is not |
| 377 | // registered in the current request. |
| 378 | 'page_template' => '', |
| 379 | ), |
| 380 | true |
| 381 | ); |
| 382 | |
| 383 | // Callers expect a published, mapped, render-ready post. When |
| 384 | // publishing fails, don't map the leftover draft (the renderer |
| 385 | // ignores unpublished posts); the editor flow reuses it as the |
| 386 | // scratchpad for this email type when the user opens the editor. |
| 387 | if ( is_wp_error( $updated ) || 0 === $updated ) { |
| 388 | return false; |
| 389 | } |
| 390 | |
| 391 | $post_manager->save_email_template_post_id( $email_type, $post_id ); |
| 392 | |
| 393 | return $post_id; |
| 394 | } |
| 395 | } |
| 396 |