mailpoet
/
lib
/
EmailEditor
/
Integrations
/
MailPoet
/
Endpoints
/
GenerateSubjectSuggestionsEndpoint.php
GenerateSubjectSuggestionsEndpoint.php
256 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\EmailEditor\Integrations\MailPoet\Endpoints; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use Automattic\WooCommerce\EmailEditor\Email_Editor_Container; |
| 9 | use Automattic\WooCommerce\EmailEditor\Engine\PersonalizationTags\Personalization_Tags_Registry; |
| 10 | use MailPoet\API\REST\Endpoint; |
| 11 | use MailPoet\API\REST\ErrorResponse; |
| 12 | use MailPoet\API\REST\Request; |
| 13 | use MailPoet\API\REST\Response; |
| 14 | use MailPoet\EmailEditor\Integrations\MailPoet\EmailEditor; |
| 15 | use MailPoet\Logging\LoggerFactory; |
| 16 | use MailPoet\Validator\Builder; |
| 17 | use MailPoet\Validator\Schema; |
| 18 | use MailPoet\WP\Functions as WPFunctions; |
| 19 | |
| 20 | class GenerateSubjectSuggestionsEndpoint extends Endpoint { |
| 21 | private WPFunctions $wp; |
| 22 | |
| 23 | private const TAG_CATEGORIES_FOR_SUBJECT = ['Subscriber', 'Site', 'Customer', 'Order']; |
| 24 | |
| 25 | private const SUBJECT_MAX_LENGTH = 60; |
| 26 | private const PREHEADER_MAX_LENGTH = 150; |
| 27 | |
| 28 | public function __construct( |
| 29 | WPFunctions $wp |
| 30 | ) { |
| 31 | $this->wp = $wp; |
| 32 | } |
| 33 | |
| 34 | public function handle(Request $request): Response { |
| 35 | /** @var int $postId validated by schema */ |
| 36 | $postId = $request->getParam('post_id'); |
| 37 | |
| 38 | if (!function_exists('wp_ai_client_prompt')) { |
| 39 | return new ErrorResponse( |
| 40 | 503, |
| 41 | __('AI text generation is not available.', 'mailpoet'), |
| 42 | 'mailpoet_ai_unavailable' |
| 43 | ); |
| 44 | } |
| 45 | |
| 46 | $post = $this->wp->getPost($postId); |
| 47 | if (!$post instanceof \WP_Post || $post->post_type !== 'mailpoet_email') { // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps |
| 48 | return new ErrorResponse( |
| 49 | 404, |
| 50 | __('Email not found.', 'mailpoet'), |
| 51 | 'mailpoet_ai_email_not_found' |
| 52 | ); |
| 53 | } |
| 54 | |
| 55 | if (!current_user_can('edit_post', $postId)) { |
| 56 | return new ErrorResponse( |
| 57 | 403, |
| 58 | __('You are not allowed to generate suggestions for this email.', 'mailpoet'), |
| 59 | 'mailpoet_ai_forbidden' |
| 60 | ); |
| 61 | } |
| 62 | |
| 63 | $html = do_blocks($post->post_content); // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps |
| 64 | $bodyText = $this->wp->wpStripAllTags($html); |
| 65 | $bodyText = (string)preg_replace('/\s+/', ' ', trim($bodyText)); |
| 66 | |
| 67 | if ($bodyText === '') { |
| 68 | return new ErrorResponse( |
| 69 | 400, |
| 70 | __('Email body is empty. Add content before generating suggestions.', 'mailpoet'), |
| 71 | 'mailpoet_ai_empty_content' |
| 72 | ); |
| 73 | } |
| 74 | |
| 75 | $personalizationTags = $this->getAvailablePersonalizationTags(); |
| 76 | $tagsInstruction = ''; |
| 77 | if (!empty($personalizationTags)) { |
| 78 | $tagsList = implode(', ', array_map(function ($tag) { |
| 79 | return $tag['token'] . ' (' . $tag['name'] . ')'; |
| 80 | }, $personalizationTags)); |
| 81 | $tagsInstruction = 'You may use these personalization tags in the subject lines and preview text to make them more personal: ' |
| 82 | . $tagsList . '. Use them sparingly — not every suggestion needs a tag. Insert the tag token exactly as shown (e.g. [mailpoet/subscriber-firstname]). '; |
| 83 | } |
| 84 | |
| 85 | $systemInstruction = 'You are an expert email marketer. Generate subject lines and preview text for marketing emails. ' |
| 86 | . 'Match the tone and style of the email body — if it\'s a business email, keep it professional; ' |
| 87 | . 'if it\'s fun or casual, feel free to use emojis. ' |
| 88 | . 'IMPORTANT: Generate suggestions in the same language as the email body content. ' |
| 89 | . $tagsInstruction |
| 90 | . 'Subject lines must be under 60 characters. Preview text must be under 150 characters and complement the subject line. ' |
| 91 | . 'Respond ONLY with valid JSON (no markdown, no code fences) in this exact format: ' |
| 92 | . '{"suggestions":[{"subject":"...","preheader":"..."},{"subject":"...","preheader":"..."},{"subject":"...","preheader":"..."},{"subject":"...","preheader":"..."}]}'; |
| 93 | |
| 94 | $prompt = "Based on the following email body content, generate 4 different subject line and preview text pairs:\n\n" . $bodyText; |
| 95 | |
| 96 | $promptBuilder = wp_ai_client_prompt($prompt) |
| 97 | ->using_system_instruction($systemInstruction) |
| 98 | ->using_model_preference( |
| 99 | ['anthropic', 'claude-sonnet-4-6'], |
| 100 | ['google', 'gemini-3-flash-preview'], |
| 101 | ['google', 'gemini-2.5-flash'], |
| 102 | ['openai', 'gpt-5.4-mini'], |
| 103 | ['openai', 'gpt-4.1-mini'] |
| 104 | ) |
| 105 | ->as_json_response(); |
| 106 | |
| 107 | $logger = LoggerFactory::getInstance()->getLogger(LoggerFactory::TOPIC_EMAIL_EDITOR); |
| 108 | |
| 109 | if (!$promptBuilder->is_supported_for_text_generation()) { |
| 110 | return new ErrorResponse( |
| 111 | 503, |
| 112 | __('AI text generation is not available. Please check your AI provider configuration.', 'mailpoet'), |
| 113 | 'mailpoet_ai_unavailable' |
| 114 | ); |
| 115 | } |
| 116 | |
| 117 | $result = $promptBuilder->generate_text(); |
| 118 | |
| 119 | if (is_wp_error($result)) { |
| 120 | $logger->error('AI subject generation failed', [ |
| 121 | 'error_code' => $result->get_error_code(), |
| 122 | 'error_message' => $result->get_error_message(), |
| 123 | 'post_id' => $postId, |
| 124 | ]); |
| 125 | return new ErrorResponse( |
| 126 | 502, |
| 127 | __('Failed to generate suggestions. Please check your AI provider configuration and try again.', 'mailpoet'), |
| 128 | 'mailpoet_ai_generation_failed' |
| 129 | ); |
| 130 | } |
| 131 | |
| 132 | $decoded = $this->parseAiResponse($result); |
| 133 | if ($decoded === null) { |
| 134 | $logger->error('AI subject generation returned invalid JSON', [ |
| 135 | 'response_type' => gettype($result), |
| 136 | 'response_length' => is_string($result) ? mb_strlen($result) : null, |
| 137 | 'response_preview' => is_string($result) ? mb_substr($result, 0, 200) : null, |
| 138 | 'post_id' => $postId, |
| 139 | ]); |
| 140 | return new ErrorResponse( |
| 141 | 502, |
| 142 | __('AI returned an unexpected response.', 'mailpoet'), |
| 143 | 'mailpoet_ai_invalid_response' |
| 144 | ); |
| 145 | } |
| 146 | |
| 147 | $validSuggestions = []; |
| 148 | foreach ($decoded['suggestions'] as $suggestion) { |
| 149 | if ( |
| 150 | !is_array($suggestion) |
| 151 | || !isset($suggestion['subject'], $suggestion['preheader']) |
| 152 | || !is_string($suggestion['subject']) |
| 153 | || !is_string($suggestion['preheader']) |
| 154 | || mb_strlen($suggestion['subject']) > self::SUBJECT_MAX_LENGTH |
| 155 | || mb_strlen($suggestion['preheader']) > self::PREHEADER_MAX_LENGTH |
| 156 | ) { |
| 157 | $logger->info('AI subject suggestion filtered out', [ |
| 158 | 'suggestion_type' => gettype($suggestion), |
| 159 | 'suggestion_keys' => is_array($suggestion) ? array_keys($suggestion) : [], |
| 160 | 'subject_length' => is_array($suggestion) && isset($suggestion['subject']) && is_string($suggestion['subject']) ? mb_strlen($suggestion['subject']) : null, |
| 161 | 'preheader_length' => is_array($suggestion) && isset($suggestion['preheader']) && is_string($suggestion['preheader']) ? mb_strlen($suggestion['preheader']) : null, |
| 162 | 'post_id' => $postId, |
| 163 | ]); |
| 164 | continue; |
| 165 | } |
| 166 | $validSuggestions[] = [ |
| 167 | 'subject' => $suggestion['subject'], |
| 168 | 'preheader' => $suggestion['preheader'], |
| 169 | ]; |
| 170 | } |
| 171 | |
| 172 | if (empty($validSuggestions)) { |
| 173 | $logger->error('AI subject generation returned no valid suggestions', [ |
| 174 | 'suggestion_count' => count($decoded['suggestions']), |
| 175 | 'post_id' => $postId, |
| 176 | ]); |
| 177 | return new ErrorResponse( |
| 178 | 502, |
| 179 | __('AI did not return any valid suggestions. Please try again.', 'mailpoet'), |
| 180 | 'mailpoet_ai_no_valid_suggestions' |
| 181 | ); |
| 182 | } |
| 183 | |
| 184 | return new Response(['suggestions' => $validSuggestions]); |
| 185 | } |
| 186 | |
| 187 | /** |
| 188 | * @return array{suggestions: array<int, mixed>}|null |
| 189 | */ |
| 190 | private function parseAiResponse(string $result): ?array { |
| 191 | $json = preg_replace('/^```(?:json)?\s*|```\s*$/i', '', trim($result)) ?? trim($result); |
| 192 | $json = trim($json); |
| 193 | |
| 194 | $decoded = json_decode($json, true); |
| 195 | |
| 196 | if (is_array($decoded) && isset($decoded['suggestions']) && is_array($decoded['suggestions'])) { |
| 197 | return ['suggestions' => array_values($decoded['suggestions'])]; |
| 198 | } |
| 199 | |
| 200 | if (is_array($decoded) && !isset($decoded['suggestions']) && isset($decoded[0])) { |
| 201 | return ['suggestions' => array_values($decoded)]; |
| 202 | } |
| 203 | |
| 204 | return null; |
| 205 | } |
| 206 | |
| 207 | /** |
| 208 | * @return array<int, array{name: string, token: string}> |
| 209 | */ |
| 210 | private function getAvailablePersonalizationTags(): array { |
| 211 | if (!class_exists(Email_Editor_Container::class)) { |
| 212 | return []; |
| 213 | } |
| 214 | $registry = Email_Editor_Container::container()->get(Personalization_Tags_Registry::class); |
| 215 | $tags = []; |
| 216 | $urlKeywords = ['url', 'link']; |
| 217 | foreach ($registry->get_all() as $tag) { |
| 218 | $postTypes = $tag->get_post_types(); |
| 219 | if (!empty($postTypes) && !in_array(EmailEditor::MAILPOET_EMAIL_POST_TYPE, $postTypes, true)) { |
| 220 | continue; |
| 221 | } |
| 222 | if (!in_array($tag->get_category(), self::TAG_CATEGORIES_FOR_SUBJECT, true)) { |
| 223 | continue; |
| 224 | } |
| 225 | $token = $tag->get_token(); |
| 226 | $tokenLower = strtolower($token); |
| 227 | $isUrl = false; |
| 228 | foreach ($urlKeywords as $keyword) { |
| 229 | if (strpos($tokenLower, $keyword) !== false) { |
| 230 | $isUrl = true; |
| 231 | break; |
| 232 | } |
| 233 | } |
| 234 | if ($isUrl) { |
| 235 | continue; |
| 236 | } |
| 237 | $tags[] = [ |
| 238 | 'name' => $tag->get_name(), |
| 239 | 'token' => $token, |
| 240 | ]; |
| 241 | } |
| 242 | return $tags; |
| 243 | } |
| 244 | |
| 245 | public function checkPermissions(): bool { |
| 246 | return current_user_can('edit_posts'); |
| 247 | } |
| 248 | |
| 249 | /** @return array<string, Schema> */ |
| 250 | public static function getRequestSchema(): array { |
| 251 | return [ |
| 252 | 'post_id' => Builder::integer()->required(), |
| 253 | ]; |
| 254 | } |
| 255 | } |
| 256 |