generator = new ContentGeneratorService(); } /* ── GENERATE full article ───────────────────────── */ public function generate( \WP_REST_Request $request ): \WP_REST_Response { $word_count = absint( $request->get_param( 'word_count' ) ?: 1000 ); $topic = sanitize_text_field( $request->get_param( 'topic' ) ); $keywords = array_map( 'sanitize_text_field', $request->get_param( 'keywords' ) ?: array() ); $tone = sanitize_text_field( $request->get_param( 'tone' ) ?: 'professional' ); $language = sanitize_text_field( $request->get_param( 'language' ) ?: 'en' ); $outline = sanitize_textarea_field( $request->get_param( 'outline' ) ?: '' ); $serp_context = sanitize_textarea_field( $request->get_param( 'serp_context' ) ?: '' ); $include_table_of_contents = rest_sanitize_boolean( $request->get_param( 'include_table_of_contents' ) ); if ( $serp_context ) { $outline = trim( $outline . "\n\nSERP-aware brief context:\n" . $serp_context ); } if ( $include_table_of_contents ) { $outline = trim( $outline . "\n\nTable of contents requirement: Add a linked HTML table of contents near the top of the article before the first h2 section. Use a nav element with class \"aime-article-toc\", a short heading, and anchor links to the main h2 sections. Add matching id attributes to the h2 headings. Keep anchor ids readable, lowercase, and unique." ); } $post_type = sanitize_key( $request->get_param( 'post_type' ) ?: 'post' ); if ( ! post_type_exists( $post_type ) ) { $post_type = 'post'; } $brand_voice_id = absint( $request->get_param( 'brand_voice_id' ) ); // Load preset if specified. $preset_id = absint( $request->get_param( 'preset_id' ) ); $preset = null; if ( $preset_id ) { global $wpdb; $preset = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}aime_content_presets WHERE id = %d", $preset_id ) ); } $brand_voice_prompt = WorkflowController::get_brand_voice_prompt( $brand_voice_id ); if ( $brand_voice_prompt ) { if ( ! $preset ) { $preset = (object) array( 'prompt_template' => '', 'system_instructions' => '' ); } $preset->system_instructions = trim( ( $preset->system_instructions ?? '' ) . "\n\n" . $brand_voice_prompt ); } // In-body stock images (site setting): the AI embeds placeholders, // which are swapped for imported stock photos after generation. $cg_settings = get_option( 'aime_content-generator_settings', array() ); $inline_images = min( 3, absint( $cg_settings['inline_images'] ?? 0 ) ); if ( $inline_images > 0 && ! \WPSpace\AiMarketingExpert\Modules\ContentGenerator\Services\StockImageService::is_configured() ) { $inline_images = 0; } $include_quick_answer = $request->get_param( 'include_quick_answer' ); $include_quick_answer = null === $include_quick_answer ? true : (bool) $include_quick_answer; $include_faq = $request->get_param( 'include_faq' ); $include_faq = null === $include_faq ? true : (bool) $include_faq; $result = $this->generator->generate_article( $topic, $keywords, $tone, $word_count, $language, $outline, $preset, $include_table_of_contents, $inline_images, 0, $include_quick_answer, $include_faq ); if ( ! $result['success'] ) { return new \WP_REST_Response( array( 'message' => __( 'AI generation failed.', 'ai-marketing-expert' ), 'error' => $result['error'] ?? '', ), 500 ); } // Save as article. global $wpdb; $p = $wpdb->prefix; $now = current_time( 'mysql', true ); $content = $result['content']; $generated = $result['parsed'] ?? array(); $article_title = $generated['title'] ?? $topic; $article_body = $generated['body'] ?? $content; $excerpt = $generated['excerpt'] ?? ''; // Clean up the body: remove any residual JSON wrapper and convert literal \n to real newlines. $article_body = self::clean_ai_body( $article_body, sanitize_text_field( (string) $article_title ) ); // Swap AI image placeholders for stock photos (fail-soft; also strips // any leftover placeholders when the feature is off). $stock_service = new \WPSpace\AiMarketingExpert\Modules\ContentGenerator\Services\StockImageService(); $article_body = $stock_service->embed_inline_images( (string) $article_body, $inline_images, $topic ); if ( empty( $keywords ) && ! empty( $generated['focus_keyword'] ) ) { $keywords = array( sanitize_text_field( (string) $generated['focus_keyword'] ) ); } // Load automation settings. $settings = get_option( 'aime_content-generator_settings', array() ); $auto_meta = (bool) ( $settings['auto_generate_meta'] ?? true ); $auto_excerpt = (bool) ( $settings['auto_generate_excerpt'] ?? true ); $auto_seo = (bool) ( $settings['auto_seo_optimize'] ?? true ); $initial_meta_title = $auto_meta ? sanitize_text_field( $article_title ) : ''; $initial_meta_desc = $auto_meta ? sanitize_textarea_field( $excerpt ) : ''; $initial_excerpt = $auto_excerpt ? sanitize_textarea_field( $excerpt ) : ''; $inserted = $wpdb->insert( "{$p}aime_content_articles", array( 'title' => sanitize_text_field( $article_title ), 'slug' => sanitize_title( $article_title ), 'content' => aime_kses_article( $article_body ), 'excerpt' => $initial_excerpt, 'status' => 'ready', 'post_type' => $post_type, 'topic' => $topic, 'keywords' => wp_json_encode( $keywords ), 'tone' => $tone, 'word_count_target' => $word_count, 'actual_word_count' => function_exists( 'aime_count_words' ) ? aime_count_words( $article_body ) : str_word_count( wp_strip_all_tags( $article_body ) ), 'meta_title' => $initial_meta_title, 'meta_description' => $initial_meta_desc, 'language' => $language, 'ai_provider' => $result['provider'] ?? '', 'ai_model' => $result['model'] ?? '', 'outline' => wp_json_encode( $generated['outline'] ?? array() ), 'category_ids' => wp_json_encode( array_map( 'absint', (array) ( $request->get_param( 'category_ids' ) ?: array() ) ) ), 'tag_ids' => wp_json_encode( array_map( 'sanitize_text_field', (array) ( $request->get_param( 'tag_ids' ) ?: array() ) ) ), 'preset_id' => $preset_id ?: null, 'brand_voice_id' => $brand_voice_id ?: null, 'created_at' => $now, 'updated_at' => $now, ) ); // A failed insert must not fall through: the AI cost was already paid, // but returning id:0 would create a phantom history row and a broken // 201 response. Surface the failure instead. if ( false === $inserted || 0 === (int) $wpdb->insert_id ) { return new \WP_REST_Response( array( 'message' => __( 'The article was generated but could not be saved: ', 'ai-marketing-expert' ) . ( $wpdb->last_error ?: __( 'unknown database error.', 'ai-marketing-expert' ) ), ), 500 ); } $article_id = (int) $wpdb->insert_id; WorkflowController::save_article_version( $article_id, 'Generated' ); // Auto-generate meta title + description (if enabled in automation settings). if ( $auto_meta ) { try { $meta_result = $this->generator->generate_meta( sanitize_text_field( $article_title ), aime_kses_article( $article_body ), $keywords ); if ( ! empty( $meta_result['success'] ) && ! empty( $meta_result['meta'] ) ) { $meta_title = sanitize_text_field( $meta_result['meta']['meta_title'] ?? '' ); $meta_desc = sanitize_text_field( $meta_result['meta']['meta_description'] ?? '' ); if ( $meta_title || $meta_desc ) { $wpdb->update( "{$p}aime_content_articles", array_filter( array( 'meta_title' => $meta_title, 'meta_description' => $meta_desc, ) ), array( 'id' => $article_id ) ); } else { aime_log( 'Auto-generate meta: AI returned response but no meta_title/meta_description could be parsed. Raw: ' . wp_json_encode( $meta_result['meta'] ), 'warning', 'content-generator' ); } } else { aime_log( 'Auto-generate meta failed for article #' . $article_id . ': ' . ( $meta_result['error'] ?? 'Unknown error' ), 'warning', 'content-generator' ); } } catch ( \Throwable $e ) { aime_log( 'Auto-generate meta failed for article #' . $article_id . ': ' . $e->getMessage(), 'error', 'content-generator' ); } } // Auto-generate excerpt (always when enabled, overrides article-level excerpt). if ( $auto_excerpt ) { try { $excerpt_result = $this->generator->generate_excerpt( sanitize_text_field( $article_title ), aime_kses_article( $article_body ) ); if ( ! empty( $excerpt_result['success'] ) && ! empty( $excerpt_result['excerpt'] ) ) { $excerpt = sanitize_textarea_field( $excerpt_result['excerpt'] ); $wpdb->update( "{$p}aime_content_articles", array( 'excerpt' => $excerpt ), array( 'id' => $article_id ) ); } else { aime_log( 'Auto-generate excerpt failed for article #' . $article_id . ': ' . ( $excerpt_result['error'] ?? 'AI returned empty excerpt' ), 'warning', 'content-generator' ); } } catch ( \Throwable $e ) { aime_log( 'Auto-generate excerpt failed for article #' . $article_id . ': ' . $e->getMessage(), 'error', 'content-generator' ); } } // Log. $wpdb->insert( "{$p}aime_content_history", array( 'article_id' => $article_id, 'action' => 'generated', 'details' => wp_json_encode( array( 'topic' => $topic, 'provider' => $result['provider'] ?? '', 'model' => $result['model'] ?? '', 'providers' => $result['providers'] ?? array(), 'continued' => (int) ( $result['continued'] ?? 0 ), 'partial' => ! empty( $result['truncated'] ), 'words' => function_exists( 'aime_count_words' ) ? aime_count_words( $article_body ) : str_word_count( wp_strip_all_tags( $article_body ) ), ) ), 'created_at' => $now, ) ); // Auto SEO score: calculate baseline quick score so article has accurate initial SEO metrics. $seo = new SeoAnalyzerService(); $seo->quick_score( $article_id ); $article = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$p}aime_content_articles WHERE id = %d", $article_id ) ); $continued = (int) ( $result['continued'] ?? 0 ); $partial = ! empty( $result['truncated'] ); if ( $continued > 0 ) { aime_log( sprintf( 'Article #%d completed across %d provider(s) after the first one stopped early.', $article_id, count( $result['providers'] ?? array() ) ), 'info', 'content-generator' ); } if ( $partial ) { $message = __( 'Article saved, but the AI providers ran out of capacity before finishing it. Review the ending in the editor and use Improve Content to extend it.', 'ai-marketing-expert' ); } elseif ( $continued > 0 ) { $message = __( 'Article generated successfully (finished by a second AI provider after the first hit its limit).', 'ai-marketing-expert' ); } else { $message = __( 'Article generated successfully.', 'ai-marketing-expert' ); } return new \WP_REST_Response( array( 'id' => $article_id, 'article' => $article, 'provider' => $result['provider'] ?? '', 'model' => $result['model'] ?? '', 'providers' => $result['providers'] ?? array(), 'continued' => $continued, 'partial' => $partial, 'image_search' => sanitize_text_field( (string) ( $generated['image_search'] ?? '' ) ), 'message' => $message, ), 201 ); } /* ── GENERATE outline only ───────────────────────── */ public function generate_outline( \WP_REST_Request $request ): \WP_REST_Response { $topic = sanitize_text_field( $request->get_param( 'topic' ) ); $keywords = array_map( 'sanitize_text_field', $request->get_param( 'keywords' ) ?: array() ); $tone = sanitize_text_field( $request->get_param( 'tone' ) ?: 'professional' ); $style = sanitize_text_field( $request->get_param( 'style' ) ?: 'blog_post' ); $serp_context = sanitize_textarea_field( $request->get_param( 'serp_context' ) ?: '' ); if ( $serp_context ) { $topic .= "\n\nSERP-aware brief context:\n" . $serp_context; } $result = $this->generator->generate_outline( $topic, $keywords, $tone, $style ); if ( ! $result['success'] ) { return new \WP_REST_Response( array( 'message' => __( 'AI generation failed.', 'ai-marketing-expert' ) ), 500 ); } return new \WP_REST_Response( $result ); } /* ── GENERATE single section ─────────────────────── */ public function generate_section( \WP_REST_Request $request ): \WP_REST_Response { $topic = sanitize_text_field( $request->get_param( 'topic' ) ); $section_title = sanitize_text_field( $request->get_param( 'section_title' ) ); $context = sanitize_textarea_field( $request->get_param( 'context' ) ?: '' ); $tone = sanitize_text_field( $request->get_param( 'tone' ) ?: 'professional' ); $result = $this->generator->generate_section( $topic, $section_title, $context, $tone ); if ( ! $result['success'] ) { return new \WP_REST_Response( array( 'message' => __( 'AI generation failed.', 'ai-marketing-expert' ) ), 500 ); } return new \WP_REST_Response( $result ); } /* ── IMPROVE existing content ────────────────────── */ public function improve_content( \WP_REST_Request $request ): \WP_REST_Response { $content = aime_kses_article( $request->get_param( 'content' ) ); $instruction = sanitize_text_field( $request->get_param( 'instruction' ) ); $tone = sanitize_text_field( $request->get_param( 'tone' ) ?: 'professional' ); $article_id = absint( $request->get_param( 'article_id' ) ); if ( $article_id > 0 ) { WorkflowController::save_article_version( $article_id, __( 'Before Humanize', 'ai-marketing-expert' ) ); } $result = $this->generator->improve_content( $content, $instruction, $tone ); if ( ! $result['success'] ) { return new \WP_REST_Response( array( 'message' => __( 'AI generation failed.', 'ai-marketing-expert' ) ), 500 ); } return new \WP_REST_Response( $result ); } /* ── SEO OPTIMIZE ────────────────────────────────── */ public function seo_optimize( \WP_REST_Request $request ): \WP_REST_Response { $content = aime_kses_article( $request->get_param( 'content' ) ); $keywords = array_map( 'sanitize_text_field', $request->get_param( 'keywords' ) ?: array() ); $title = sanitize_text_field( $request->get_param( 'title' ) ?: '' ); $article_id = absint( $request->get_param( 'article_id' ) ); $seo = new SeoAnalyzerService(); $result = $seo->analyze_and_optimize( $content, $keywords, $title ); if ( ! $result['success'] ) { return new \WP_REST_Response( array( 'message' => __( 'AI analysis failed.', 'ai-marketing-expert' ) ), 500 ); } if ( $article_id > 0 && ! empty( $result['analysis'] ) && is_array( $result['analysis'] ) ) { global $wpdb; $update = array(); if ( isset( $result['analysis']['seo_score'] ) ) { $update['seo_score'] = absint( $result['analysis']['seo_score'] ); } if ( isset( $result['analysis']['readability_score'] ) ) { $update['readability_score'] = absint( $result['analysis']['readability_score'] ); } if ( ! empty( $update ) ) { $update['updated_at'] = current_time( 'mysql', true ); $wpdb->update( $wpdb->prefix . 'aime_content_articles', $update, array( 'id' => $article_id ) ); } } return new \WP_REST_Response( $result ); } /* ── GENERATE META (title + description) ─────────── */ public function generate_meta( \WP_REST_Request $request ): \WP_REST_Response { $title = sanitize_text_field( $request->get_param( 'title' ) ); $content = aime_kses_article( $request->get_param( 'content' ) ?: '' ); $keywords = array_map( 'sanitize_text_field', $request->get_param( 'keywords' ) ?: array() ); $result = $this->generator->generate_meta( $title, $content, $keywords ); if ( ! $result['success'] ) { return new \WP_REST_Response( array( 'message' => __( 'AI generation failed.', 'ai-marketing-expert' ) ), 500 ); } return new \WP_REST_Response( $result ); } /* ── GENERATE IMAGE PROMPT ───────────────────────── */ public function generate_image_prompt( \WP_REST_Request $request ): \WP_REST_Response { $title = sanitize_text_field( $request->get_param( 'title' ) ); $content = aime_kses_article( $request->get_param( 'content' ) ?: '' ); $result = $this->generator->generate_image_prompt( $title, $content ); if ( ! $result['success'] ) { return new \WP_REST_Response( array( 'message' => __( 'AI generation failed.', 'ai-marketing-expert' ) ), 500 ); } return new \WP_REST_Response( $result ); } /** * Clean up AI-generated body content. * * Strips leftover JSON wrappers, converts literal \n to real newlines, * removes blank lines, strips AI safety-classification lines (e.g. * "User Safety: safe"), drops a duplicate title heading (theme already * renders H1), and ensures proper HTML. * * @param string $body Raw body HTML. * @param string $title Optional article title for duplicate-H1 stripping. */ public static function clean_ai_body( string $body, string $title = '' ): string { $body = trim( $body ); // Remove Markdown code fences such as ```json ... ``` before JSON cleanup. $body = preg_replace( '/^\s*```(?:json|html)?\s*/i', '', $body ); $body = preg_replace( '/\s*```\s*$/', '', $body ); $decoded = json_decode( $body, true ); if ( is_array( $decoded ) && ! empty( $decoded['body'] ) ) { $body = (string) $decoded['body']; } // If body starts with JSON-like prefix, strip it. $body = preg_replace( '/^\s*\{\s*"title"\s*:\s*"(?:[^"\\\\]|\\\\.)*"\s*,\s*"body"\s*:\s*"/si', '', $body ); $body = preg_replace( '/^\s*\{\s*"[^"]*"\s*:\s*"(?:[^"\\\\]|\\\\.)*"\s*,\s*"body"\s*:\s*"/si', '', $body ); // Remove trailing JSON closure. $body = preg_replace( '/"\s*,\s*"(excerpt|outline)"\s*:.*$/si', '', $body ); $body = preg_replace( '/"\s*\}\s*$/s', '', $body ); $body = preg_replace( '/\s*```\s*$/', '', $body ); // Replace literal \n sequences with real newlines, then normalize. $body = str_replace( array( '\\n', '\n' ), "\n", $body ); $body = stripcslashes( $body ); // Strip Google Translate injected divs. $body = preg_replace( '/