keywords = new ABDS_SEO_Keyword_Extractor(); $this->readability = new ABDS_SEO_Readability_Checker(); $this->block_recommendations = new ABDS_SEO_Block_Recommendations( $this->keywords ); } /** * Analyzes a post's content against a focus keyword and persists the * resulting content score to wp_abds_seo_page_scores. * * @param int $post_id Post ID to analyze. * @param string $focus_keyword Focus keyword (or phrase). * @return array{post_id:int, focus_keyword:string, content_score:int, keyword_density:float, checks:array, readability:array, recommendations:array, block_recommendations:array} */ public function analyze( int $post_id, string $focus_keyword ): array { $post = get_post( $post_id ); if ( ! $post ) { return $this->empty_result( $post_id, $focus_keyword ); } $focus_keyword = trim( $focus_keyword ); if ( '' === $focus_keyword ) { return $this->empty_result( $post_id, $focus_keyword ); } $title = get_post_meta( $post_id, '_abds_seo_title', true ); $title = '' !== $title ? $title : get_the_title( $post_id ); $description = (string) get_post_meta( $post_id, '_abds_seo_description', true ); $slug = (string) $post->post_name; $content = (string) $post->post_content; $plain = wp_strip_all_tags( $content ); $first_100 = $this->keywords->first_words( $plain, 100 ); $checks = array( 'title' => $this->keywords->contains( (string) $title, $focus_keyword ), 'h1' => $this->check_heading_group( $content, $focus_keyword, array( 'h1' ) ), 'first_100_words' => $this->keywords->contains( $first_100, $focus_keyword ), 'subheadings' => $this->check_heading_group( $content, $focus_keyword, array( 'h2', 'h3', 'h4', 'h5', 'h6' ) ), 'slug' => $this->keywords->slug_contains_keyword( $slug, $focus_keyword ), 'meta_description' => $this->keywords->contains( $description, $focus_keyword ), ); $density = $this->keywords->density( $plain, $focus_keyword ); $readability = $this->readability->analyze( $content ); $recommendations = $this->build_recommendations( $checks, $density, $content ); $score = $this->calculate_score( $checks, $density, $readability['score'] ); $block_recommendations = array_map( array( $this, 'translate_block_recommendation' ), $this->block_recommendations->analyze( parse_blocks( $content ), $focus_keyword ) ); $result = array( 'post_id' => $post_id, 'focus_keyword' => $focus_keyword, 'content_score' => $score, 'keyword_density' => $density, 'checks' => $checks, 'readability' => $readability, 'recommendations' => $recommendations, 'block_recommendations' => $block_recommendations, ); $this->persist_result( $post_id, $score, $recommendations ); return $result; } /** * Builds the zero-value result returned when the post doesn't exist or * no focus keyword was supplied. * * @param int $post_id Post ID. * @param string $focus_keyword Focus keyword as passed in (possibly empty). * @return array{post_id:int, focus_keyword:string, content_score:int, keyword_density:float, checks:array, readability:array, recommendations:array, block_recommendations:array} */ protected function empty_result( int $post_id, string $focus_keyword ): array { return array( 'post_id' => $post_id, 'focus_keyword' => $focus_keyword, 'content_score' => 0, 'keyword_density' => 0.0, 'checks' => array(), 'readability' => array(), 'recommendations' => array(), 'block_recommendations' => array(), ); } /** * Whether the keyword appears inside any heading matching the given tags. * * @param string $content Post content HTML. * @param string $keyword Focus keyword (or phrase). * @param string[] $tags Heading tag names to check, e.g. ['h1'] or ['h2'..'h6']. * @return bool True if found in at least one matching heading. */ protected function check_heading_group( string $content, string $keyword, array $tags ): bool { $pattern = '/<(?:' . implode( '|', $tags ) . ')[^>]*>(.*?)<\/(?:' . implode( '|', $tags ) . ')>/is'; if ( ! preg_match_all( $pattern, $content, $matches ) ) { return false; } foreach ( $matches[1] as $heading_html ) { if ( $this->keywords->contains( wp_strip_all_tags( $heading_html ), $keyword ) ) { return true; } } return false; } /** * Builds the add/adapt/remove recommendation list from the check * results and keyword density, then ties each to a Gutenberg block. * * @param array $checks Placement check results, keyed by check name. * @param float $density Keyword density percentage. * @param string $content Post content HTML. * @return array */ protected function build_recommendations( array $checks, float $density, string $content ): array { $recommendations = array(); if ( ! $checks['title'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADAPT, 'title', __( 'Add the focus keyword to the page title.', 'abds-seo' ) ); } if ( ! $checks['h1'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADD, 'h1', __( 'Add the focus keyword to the H1 heading.', 'abds-seo' ) ); } if ( ! $checks['first_100_words'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADAPT, 'first_paragraph', __( 'Mention the keyword in the first 100 words of the text.', 'abds-seo' ) ); } if ( ! $checks['subheadings'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADD, 'subheading', __( 'Add a subheading (H2–H6) with the keyword or a variation of it.', 'abds-seo' ) ); } if ( ! $checks['meta_description'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADD, 'meta_description', __( 'Add a meta description containing the keyword.', 'abds-seo' ) ); } if ( ! $checks['slug'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADAPT, 'slug', __( 'Consider adding the keyword to the URL slug.', 'abds-seo' ) ); } if ( $density > self::DENSITY_MAX ) { $recommendations[] = $this->recommendation( self::ACTION_REMOVE, 'content', sprintf( /* translators: %s: keyword density percentage. */ __( 'Keyword over-stuffing (density %s%%) — remove some repetitions.', 'abds-seo' ), $density ) ); } elseif ( $density < self::DENSITY_MIN ) { $recommendations[] = $this->recommendation( self::ACTION_ADAPT, 'content', sprintf( /* translators: %s: keyword density percentage. */ __( 'Keyword density is too low (%s%%) — add a few natural mentions in the text.', 'abds-seo' ), $density ) ); } return $this->attach_block_references( $recommendations, $content ); } /** * Builds a single recommendation entry. * * @param string $action One of the ACTION_* constants. * @param string $target Recommendation target, e.g. "title", "h1", "content". * @param string $message Human-readable, translated message. * @return array{action:string, target:string, message:string, block_client_id:?string, block_position:?int} */ protected function recommendation( string $action, string $target, string $message ): array { return array( 'action' => $action, 'target' => $target, 'message' => $message, 'block_client_id' => null, 'block_position' => null, ); } /** * Ties a recommendation to the Gutenberg block it applies to. Server-side * parse_blocks() does not expose the editor's runtime clientId, so the * block's position in the post is used as the fallback identifier — the * REST layer can be called from the editor with the live clientId when * a richer match is available (see includes/api/class-abds-seo-rest-controller.php). * * @param array $recommendations Recommendations to annotate. * @param string $content Post content HTML. * @return array */ protected function attach_block_references( array $recommendations, string $content ): array { if ( ! function_exists( 'parse_blocks' ) ) { return $recommendations; } $blocks = parse_blocks( $content ); $block_map = array( 'h1' => 'core/heading', 'subheading' => 'core/heading', 'first_paragraph' => 'core/paragraph', ); foreach ( $recommendations as &$recommendation ) { $wanted_block_name = $block_map[ $recommendation['target'] ] ?? null; if ( ! $wanted_block_name ) { continue; } foreach ( $blocks as $position => $block ) { if ( ( $block['blockName'] ?? null ) === $wanted_block_name ) { $recommendation['block_position'] = $position; break; } } } unset( $recommendation ); return $recommendations; } /** * Maps a single ABDS_SEO_Block_Recommendations entry's machine-readable * "issue" code to a translated "suggestion" message. Kept here, in the * WP-dependent orchestrator, rather than in ABDS_SEO_Block_Recommendations * itself, because that class calls zero WordPress functions (including * __()) so it stays unit testable without bootstrapping WP. * * @param array{block_path:int[], block_type:string, content_snippet:string, issue:string, severity:string} $recommendation Entry from ABDS_SEO_Block_Recommendations::analyze(). * @return array{block_path:int[], block_type:string, content_snippet:string, issue:string, suggestion:string, severity:string} */ protected function translate_block_recommendation( array $recommendation ): array { $messages = array( 'heading_missing_keyword' => __( 'Add the focus keyword to this subheading.', 'abds-seo' ), 'first_paragraph_missing_keyword' => __( 'The first paragraph does not contain the focus keyword.', 'abds-seo' ), 'paragraph_too_long' => __( 'This paragraph is too long — split it for better readability.', 'abds-seo' ), 'image_missing_alt' => __( 'This image has no alt text.', 'abds-seo' ), 'list_empty' => __( 'This list is empty.', 'abds-seo' ), ); $recommendation['suggestion'] = $messages[ $recommendation['issue'] ] ?? ''; return $recommendation; } /** * Categorizes a content_score into good/ok/poor/not_analyzed — the one * place this plugin decides what those words mean, reused everywhere * a score needs a traffic-light-style label (currently: reports, see * ABDS_SEO_Reports) rather than each caller re-deriving its own * boundaries. Deliberately reuses abds_seo_prepublish_threshold (see * ABDS_SEO_Rest_Controller::get_content_analysis()) as the poor/ok * boundary instead of a second constant, so "below the pre-publish * warning threshold" and "poor" always mean the same score, not two * numbers that could drift apart. * * @param ?int $score Content score, 0-100, or null if never analyzed. * @return string 'good', 'ok', 'poor', or 'not_analyzed'. */ public static function categorize_score( ?int $score ): string { if ( null === $score ) { return 'not_analyzed'; } /** This filter is documented in includes/api/class-abds-seo-rest-controller.php. */ $poor_threshold = (int) apply_filters( 'abds_seo_prepublish_threshold', 60 ); /** * Filters the content_score at/above which a page is categorized * "good" rather than "ok". Like abds_seo_prepublish_threshold, a * starting heuristic meant to be recalibrated once real usage data * exists. * * @param int $threshold Minimum content_score (0-100) for "good". Default 80. */ $good_threshold = (int) apply_filters( 'abds_seo_good_score_threshold', 80 ); if ( $score >= $good_threshold ) { return 'good'; } if ( $score >= $poor_threshold ) { return 'ok'; } return 'poor'; } /** * Combines check pass-rate, density fit, and readability into a 0-100 * content score. * * @param array $checks Placement check results, keyed by check name. * @param float $density Keyword density percentage. * @param int $readability_score Readability sub-score, 0-100. * @return int Content score, 0-100. */ protected function calculate_score( array $checks, float $density, int $readability_score ): int { $checks_total = count( $checks ); $checks_passed = count( array_filter( $checks ) ); $checks_score = $checks_total ? ( $checks_passed / $checks_total ) * 60 : 0; $density_score = ( $density >= self::DENSITY_MIN && $density <= self::DENSITY_MAX ) ? 20 : 10; $readability_weighted = ( $readability_score / 100 ) * 20; return (int) round( $checks_score + $density_score + $readability_weighted ); } /** * Upserts the content score and recommendations into wp_abds_seo_page_scores. * * @param int $post_id Post ID. * @param int $score Content score, 0-100. * @param array $recommendations Recommendations to store. */ protected function persist_result( int $post_id, int $score, array $recommendations ): void { global $wpdb; $table = $wpdb->prefix . 'abds_seo_page_scores'; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table is built only from $wpdb->prefix plus a hardcoded literal, never user input; $post_id is passed through $wpdb->prepare(). Runs once per editor keystroke-debounced analysis request, not a cacheable read path. $existing_id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE post_id = %d", $post_id ) ); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table is built only from $wpdb->prefix plus a hardcoded literal, never user input; $wpdb->update()/insert() safely escape their values via the format array. Runs once per editor keystroke-debounced analysis request, not a cacheable read path. if ( $existing_id ) { $wpdb->update( $table, array( 'content_score' => $score, 'last_scanned' => current_time( 'mysql' ), ), array( 'id' => $existing_id ), array( '%f', '%s' ), array( '%d' ) ); } else { $wpdb->insert( $table, array( 'post_id' => $post_id, 'content_score' => $score, 'issues_json' => wp_json_encode( array( 'content_recommendations' => $recommendations ) ), 'last_scanned' => current_time( 'mysql' ), ), array( '%d', '%f', '%s', '%s' ) ); } // phpcs:enable } }