api = new AI_SEO_Article_Generator_API(); } /** * Debug logging helper function */ private function debug_log($message, $data = null) { if (get_option('ai_seo_article_generator_debug_logging', 0)) { $log_message = 'AI SEO Article Generator Generator: ' . $message; if ($data !== null && is_array($data)) { $log_message .= ' - ' . wp_json_encode($data); } elseif ($data !== null) { $log_message .= ' - ' . $data; } if (function_exists('error_log')) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Conditional debug logging error_log($log_message); } } } public function create_wordpress_post($title, $content, $main_keyword, $sub_keywords = '') { // Validate and fix content structure $validation = $this->validate_content_structure($content); if (!$validation['valid']) { $this->debug_log('AI SEO Generator: Content validation issues found: ' . implode(', ', $validation['issues'])); } // Remove any H1 tags from content to prevent duplicates (WordPress post title becomes H1) $content = $this->remove_h1_tags($content); // Detect if content is Hebrew $is_hebrew = $this->detect_hebrew_content($content); $post_data = array( 'post_title' => $title, 'post_content' => $content, 'post_status' => 'draft', 'post_type' => 'post', 'meta_input' => array( 'ai_seo_article_generator_main_keyword' => $main_keyword, 'ai_seo_article_generator_sub_keywords' => $sub_keywords, 'ai_seo_article_generator_generated' => true, 'ai_seo_article_generator_generated_date' => current_time('mysql'), 'ai_seo_article_generator_is_hebrew' => $is_hebrew, 'ai_seo_article_generator_content_validation' => $validation ) ); $post_id = wp_insert_post($post_data); if (is_wp_error($post_id)) { return array('success' => false, 'message' => $post_id->get_error_message()); } $this->set_seo_metadata($post_id, $title, $content, $main_keyword, $sub_keywords); return array( 'success' => true, 'post_id' => $post_id, 'is_hebrew' => $is_hebrew, 'validation' => $validation ); } public function generate_meta_description($content, $main_keyword, $max_length = 160) { $stripped_content = wp_strip_all_tags($content); $sentences = preg_split('/[.!?]+/', $stripped_content); $description = ''; foreach ($sentences as $sentence) { $sentence = trim($sentence); if (empty($sentence)) continue; if (stripos($sentence, $main_keyword) !== false) { $description = $sentence; break; } if (empty($description) && strlen($sentence) > 50) { $description = $sentence; } } if (empty($description)) { $description = substr($stripped_content, 0, $max_length); } if (strlen($description) > $max_length) { $description = substr($description, 0, strrpos(substr($description, 0, $max_length), ' ')) . '...'; } return $description; } public function extract_headings($content) { $headings = array(); preg_match_all('/]*>(.*?)<\/h[1-6]>/i', $content, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $level = intval($match[1]); $text = wp_strip_all_tags($match[2]); $id = sanitize_title($text); $headings[] = array( 'level' => $level, 'text' => $text, 'id' => $id ); } return $headings; } public function generate_table_of_contents($headings, $style = 'numbered', $is_hebrew = false) { if (empty($headings)) { return ''; } // Filter out H1 (should only be main title) $filtered_headings = array_filter($headings, function($h) { return $h['level'] > 1; }); if (empty($filtered_headings)) { return ''; } // Set language-specific texts $toc_title = $is_hebrew ? '馃搵 转讜讻谉 注谞讬讬谞讬诐' : '馃搵 Table of Contents'; $toggle_text = $is_hebrew ? '讛爪讙/讛住转专' : 'Show/Hide'; $toc_classes = 'ai-seo-article-generator-toc ai-seo-article-generator-toc-' . $style; $toc = '
'; $toc .= '
'; $toc .= '

' . $toc_title . '

'; $toc .= ''; $toc .= '
'; $toc .= '
'; if ($style === 'numbered') { $toc .= '
    '; } else { $toc .= '
      '; } $current_level = 2; $counter = 1; foreach ($filtered_headings as $heading) { $level = $heading['level']; $text = $heading['text']; $id = $heading['id']; // Handle nested levels if ($level > $current_level) { // Open sublists for ($i = $current_level; $i < $level; $i++) { $toc .= $style === 'numbered' ? '
        ' : '
          '; } } elseif ($level < $current_level) { // Close sublists for ($i = $current_level; $i > $level; $i--) { $toc .= $style === 'numbered' ? '
      ' : '
    '; } } $level_class = 'toc-level-' . $level; $toc .= '
  1. '; $toc .= ''; if ($style === 'numbered' && $level === 2) { $toc .= '' . $counter . '. '; $counter++; } $toc .= esc_html($text); $toc .= '
  2. '; $current_level = $level; } // Close any remaining open lists for ($i = $current_level; $i > 2; $i--) { $toc .= $style === 'numbered' ? '
' : ''; } $toc .= $style === 'numbered' ? '' : ''; $toc .= '
'; $toc .= '
'; return $toc; } public function insert_table_of_contents($content, $position = 'auto', $is_hebrew = null) { // Detect if content is Hebrew if not specified if ($is_hebrew === null) { $is_hebrew = $this->detect_hebrew_content($content); } // First, add IDs to headings $content_with_ids = $this->add_heading_ids($content); // Extract headings from the content $headings = $this->extract_headings($content_with_ids); // Only create TOC if we have sufficient headings for SEO value if (count($headings) < 3) { $this->debug_log('Postinor TOC: Not enough headings for TOC (' . count($headings) . ' found, need at least 3)'); return $content_with_ids; } // Generate TOC with language support $toc = $this->generate_table_of_contents($headings, 'numbered', $is_hebrew); if (empty($toc)) { return $content_with_ids; } // Determine optimal insertion position for SEO if ($position === 'auto') { // Strategy 1: Insert after introduction (first 1-2 paragraphs) $paragraph_matches = array(); preg_match_all('/<\/p>/', $content_with_ids, $paragraph_matches, PREG_OFFSET_CAPTURE); if (count($paragraph_matches[0]) >= 2) { // Insert after second paragraph if we have enough content $insert_pos = $paragraph_matches[0][1][1] + strlen($paragraph_matches[0][1][0]); $before = substr($content_with_ids, 0, $insert_pos); $after = substr($content_with_ids, $insert_pos); $this->debug_log('Postinor TOC: Inserted after second paragraph for better user experience'); return $before . "\n\n" . $toc . "\n\n" . $after; } elseif (count($paragraph_matches[0]) >= 1) { // Insert after first paragraph $insert_pos = $paragraph_matches[0][0][1] + strlen($paragraph_matches[0][0][0]); $before = substr($content_with_ids, 0, $insert_pos); $after = substr($content_with_ids, $insert_pos); $this->debug_log('Postinor TOC: Inserted after first paragraph'); return $before . "\n\n" . $toc . "\n\n" . $after; } // Strategy 2: Insert before first H2 for better structure if (preg_match('/

debug_log('Postinor TOC: Inserted before first H2'); return $before . $toc . "\n\n" . $after; } } // Fallback: insert at the beginning after H1 if it exists if (preg_match('/<\/h1>/i', $content_with_ids, $matches, PREG_OFFSET_CAPTURE)) { $insert_pos = $matches[0][1] + strlen($matches[0][0]); $before = substr($content_with_ids, 0, $insert_pos); $after = substr($content_with_ids, $insert_pos); $this->debug_log('Postinor TOC: Inserted after H1 as fallback'); return $before . "\n\n" . $toc . "\n\n" . $after; } // Final fallback: insert at the beginning $this->debug_log('Postinor TOC: Inserted at beginning as final fallback'); return $toc . "\n\n" . $content_with_ids; } public function add_heading_ids($content) { return preg_replace_callback( '/]*)>(.*?)<\/h[1-6]>/i', function($matches) { $level = $matches[1]; $attributes = $matches[2]; $text = $matches[3]; $id = sanitize_title(wp_strip_all_tags($text)); if (strpos($attributes, 'id=') === false) { $attributes .= ' id="' . $id . '"'; } return '' . $text . ''; }, $content ); } public function optimize_images($content, $main_keyword) { return preg_replace_callback( '/]+)>/i', function($matches) use ($main_keyword) { $img_tag = $matches[0]; $attributes = $matches[1]; if (strpos($attributes, 'alt=') === false) { $alt_text = '转诪讜谞讛 讛拽砖讜专讛 诇' . $main_keyword; $img_tag = str_replace('>', ' alt="' . esc_attr($alt_text) . '">', $img_tag); } if (strpos($attributes, 'loading=') === false) { $img_tag = str_replace('>', ' loading="lazy">', $img_tag); } return $img_tag; }, $content ); } public function add_schema_markup($post_id, $content, $main_keyword) { $post = get_post($post_id); $headings = $this->extract_headings($content); $schema = array( '@context' => 'https://schema.org', '@type' => 'Article', 'headline' => $post->post_title, 'description' => $this->generate_meta_description($content, $main_keyword), 'author' => array( '@type' => 'Person', 'name' => get_the_author_meta('display_name', $post->post_author) ), 'datePublished' => get_the_date('c', $post_id), 'dateModified' => get_the_modified_date('c', $post_id), 'publisher' => array( '@type' => 'Organization', 'name' => get_bloginfo('name'), 'url' => home_url() ), 'mainEntityOfPage' => array( '@type' => 'WebPage', '@id' => get_permalink($post_id) ), 'keywords' => $main_keyword ); if (!empty($headings)) { $schema['articleSection'] = array_map(function($h) { return $h['text']; }, $headings); } $featured_image = get_the_post_thumbnail_url($post_id, 'full'); if ($featured_image) { $schema['image'] = array( '@type' => 'ImageObject', 'url' => $featured_image, 'width' => 1200, 'height' => 630 ); } update_post_meta($post_id, 'ai_seo_article_generator_schema_markup', json_encode($schema, JSON_UNESCAPED_UNICODE)); return $schema; } public function analyze_keyword_density($content, $keywords) { $text = wp_strip_all_tags($content); $text = preg_replace('/\s+/', ' ', $text); $word_count = str_word_count($text, 0, '讗讘讙讚讛讜讝讞讟讬讻诇诪谞住注驻爪拽专砖转讱诐谉祝抓'); $keyword_analysis = array(); $keywords_array = is_array($keywords) ? $keywords : array($keywords); foreach ($keywords_array as $keyword) { $keyword = trim($keyword); if (empty($keyword)) continue; $occurrences = substr_count(mb_strtolower($text), mb_strtolower($keyword)); $density = $word_count > 0 ? ($occurrences / $word_count) * 100 : 0; $keyword_analysis[] = array( 'keyword' => $keyword, 'occurrences' => $occurrences, 'density' => round($density, 2) ); } return $keyword_analysis; } public function generate_readability_score($content) { $text = wp_strip_all_tags($content); $sentences = preg_split('/[.!?]+/', $text); $sentences = array_filter($sentences, function($s) { return !empty(trim($s)); }); $words = str_word_count($text, 1, '讗讘讙讚讛讜讝讞讟讬讻诇诪谞住注驻爪拽专砖转讱诐谉祝抓'); $syllables = 0; foreach ($words as $word) { $syllables += max(1, preg_match_all('/[讗讗值讗址讗指讗植注直注 指讜 旨讜 只讜 值讬执 址讬讬只讬 职讬 值讜 指讜 止讜 旨讜 只讗 职讗直讗指讗 植讗注指注直注值注侄注]/', $word)); } $sentence_count = count($sentences); $word_count = count($words); if ($sentence_count == 0 || $word_count == 0) { return array('score' => 0, 'level' => '诇讗 谞讬转谉 诇讞讬砖讜讘'); } $avg_sentence_length = $word_count / $sentence_count; $avg_syllables_per_word = $syllables / $word_count; $flesch_score = 206.835 - (1.015 * $avg_sentence_length) - (84.6 * $avg_syllables_per_word); $flesch_score = max(0, min(100, $flesch_score)); $level = '拽砖讛'; if ($flesch_score >= 90) $level = '拽诇 诪讗讜讚'; elseif ($flesch_score >= 80) $level = '拽诇'; elseif ($flesch_score >= 70) $level = '拽诇 诇诪讚讬'; elseif ($flesch_score >= 60) $level = '住讟谞讚专讟讬'; elseif ($flesch_score >= 50) $level = '拽砖讛 诇诪讚讬'; return array( 'score' => round($flesch_score, 1), 'level' => $level, 'sentences' => $sentence_count, 'words' => $word_count, 'avg_sentence_length' => round($avg_sentence_length, 1) ); } private function set_seo_metadata($post_id, $title, $content, $main_keyword, $sub_keywords) { $meta_description = $this->generate_meta_description($content, $main_keyword); update_post_meta($post_id, '_yoast_wpseo_title', $title); update_post_meta($post_id, '_yoast_wpseo_metadesc', $meta_description); update_post_meta($post_id, '_yoast_wpseo_focuskw', $main_keyword); update_post_meta($post_id, '_aioseo_title', $title); update_post_meta($post_id, '_aioseo_description', $meta_description); update_post_meta($post_id, '_aioseo_keywords', $main_keyword . ($sub_keywords ? ', ' . $sub_keywords : '')); $keyword_analysis = $this->analyze_keyword_density($content, array_merge(array($main_keyword), explode(',', $sub_keywords))); $readability = $this->generate_readability_score($content); update_post_meta($post_id, 'ai_seo_article_generator_keyword_analysis', $keyword_analysis); update_post_meta($post_id, 'ai_seo_article_generator_readability_score', $readability); $this->add_schema_markup($post_id, $content, $main_keyword); } public function save_draft($title, $main_keyword, $sub_keywords, $target_words, $structure_data = '', $content = '', $status = 'draft') { global $wpdb; $table_name = $wpdb->prefix . 'ai_seo_article_generator_article_drafts'; $data = array( 'title' => $title, 'main_keyword' => $main_keyword, 'sub_keywords' => $sub_keywords, 'target_words' => $target_words, 'structure_data' => $structure_data, 'content' => $content, 'status' => $status ); $result = $wpdb->insert($table_name, $data); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table insert if ($result === false) { return array('success' => false, 'message' => '砖讙讬讗讛 讘砖诪讬专转 讛讟讬讜讟讛'); } return array('success' => true, 'draft_id' => $wpdb->insert_id); } public function get_draft($draft_id) { global $wpdb; $table_name = $wpdb->prefix . 'ai_seo_article_generator_article_drafts'; $table_name = $wpdb->prefix . 'ai_seo_article_generator_article_drafts'; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query $draft = $wpdb->get_row($wpdb->prepare("SELECT * FROM `$table_name` WHERE id = %d", $draft_id)); if (!$draft) { return array('success' => false, 'message' => '讟讬讜讟讛 诇讗 谞诪爪讗讛'); } return array('success' => true, 'draft' => $draft); } public function update_draft($draft_id, $data) { global $wpdb; $table_name = $wpdb->prefix . 'ai_seo_article_generator_article_drafts'; $result = $wpdb->update($table_name, $data, array('id' => $draft_id)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table update if ($result === false) { return array('success' => false, 'message' => '砖讙讬讗讛 讘注讚讻讜谉 讛讟讬讜讟讛'); } return array('success' => true); } public function delete_draft($draft_id) { global $wpdb; $table_name = $wpdb->prefix . 'ai_seo_article_generator_article_drafts'; $result = $wpdb->delete($table_name, array('id' => $draft_id)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table delete if ($result === false) { return array('success' => false, 'message' => '砖讙讬讗讛 讘诪讞讬拽转 讛讟讬讜讟讛'); } return array('success' => true); } /** * Remove H1 tags from content to prevent duplicate titles * WordPress post title automatically becomes H1, so content shouldn't contain H1s */ public function remove_h1_tags($content) { // Remove H1 tags but preserve their content, converting them to H2 $content = preg_replace('/]*)>(.*?)<\/h1>/i', '$2

', $content); // Log the action for debugging if (preg_match('/

debug_log('Postinor: H1 tags found and converted to H2 to prevent duplicate titles'); } return $content; } /** * Detect if content contains Hebrew text */ public function detect_hebrew_content($content) { // Strip HTML tags first $text = wp_strip_all_tags($content); // Check for Hebrew characters (Unicode range for Hebrew) return preg_match('/[\x{0590}-\x{05FF}]/u', $text) ? true : false; } /** * Enhanced content validation to ensure proper structure */ public function validate_content_structure($content) { $issues = array(); // Check for H1 tags if (preg_match_all('/

extract_headings($content); $previous_level = 1; // Start after H1 (which should be post title) foreach ($headings as $heading) { if ($heading['level'] > $previous_level + 1) { $issues[] = 'Heading hierarchy skip detected: H' . $previous_level . ' to H' . $heading['level']; } $previous_level = $heading['level']; } return array( 'valid' => empty($issues), 'issues' => $issues, 'headings_count' => count($headings) ); } }