*/ public static function checks(): array { $checks = array( /* -------------------------------------------------- Indexability */ 'noindex_page' => array( 'label' => __( 'Page is set to noindex', 'ai-rank-suite' ), 'severity' => 'critical', 'group' => 'indexability', 'weight' => 6, 'fix' => __( 'Remove the noindex directive unless this page is genuinely private.', 'ai-rank-suite' ), ), 'canonical_foreign' => array( 'label' => __( 'Canonical points at another page', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'indexability', 'weight' => 4, 'fix' => __( 'A canonical to a different URL tells Google not to index this page. Confirm that is intended.', 'ai-rank-suite' ), ), 'orphan' => array( 'label' => __( 'No internal links point here', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'indexability', 'weight' => 3, 'fix' => __( 'Link to this page from a related article or a menu — orphans are crawled last and cited least.', 'ai-rank-suite' ), ), /* --------------------------------------------------- Duplication */ 'dup_title' => array( 'label' => __( 'Duplicate title', 'ai-rank-suite' ), 'severity' => 'critical', 'group' => 'duplication', 'weight' => 5, 'fix' => __( 'Two or more pages share this exact title. Search engines pick one and drop the rest.', 'ai-rank-suite' ), ), 'dup_desc' => array( 'label' => __( 'Duplicate meta description', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'duplication', 'weight' => 3, 'fix' => __( 'Give each page its own description — a shared one wastes the snippet.', 'ai-rank-suite' ), ), 'dup_h1' => array( 'label' => __( 'Duplicate H1', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'duplication', 'weight' => 2, 'fix' => __( 'The H1 is the strongest on-page topic signal. Repeating it merges two topics into one.', 'ai-rank-suite' ), ), /* ------------------------------------------------------- Content */ 'no_desc' => array( 'label' => __( 'No meta description', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'content', 'weight' => 3, 'fix' => __( 'Write one, or generate it with AI in bulk. It feeds the snippet, the social card and llms.txt.', 'ai-rank-suite' ), ), 'title_length' => array( 'label' => __( 'Title too short or too long', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'content', 'weight' => 1, 'fix' => __( 'Aim for 30–60 characters so it neither truncates nor wastes space.', 'ai-rank-suite' ), ), 'thin' => array( 'label' => __( 'Thin content', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'content', 'weight' => 3, 'fix' => __( 'Under 300 words rarely answers a question well enough to be quoted by an assistant.', 'ai-rank-suite' ), ), 'many_h1' => array( 'label' => __( 'Extra H1 inside the content', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'content', 'weight' => 1, 'fix' => __( 'Your theme already renders the page title as the H1. An H1 in the content competes with it — demote it to H2.', 'ai-rank-suite' ), ), 'no_headings' => array( 'label' => __( 'No headings at all', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'content', 'weight' => 2, 'fix' => __( 'Assistants quote sections, not pages. Break the text up with H2s that read like questions.', 'ai-rank-suite' ), ), 'no_alt' => array( 'label' => __( 'Images without alt text', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'content', 'weight' => 1, 'fix' => __( 'Alt text is read by screen readers, image search and multimodal assistants alike.', 'ai-rank-suite' ), ), 'desc_length' => array( 'label' => __( 'Meta description too short or too long', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'content', 'weight' => 1, 'fix' => __( 'Aim for 70 to 160 characters: shorter wastes the snippet, longer is cut mid-sentence.', 'ai-rank-suite' ), ), 'no_keyword' => array( 'label' => __( 'No focus keyword', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'content', 'weight' => 1, 'fix' => __( 'Without a keyword the page has no target and the SEO score has nothing to measure. Set one in the editor sidebar or let the AI suggest it.', 'ai-rank-suite' ), ), 'keyword_not_in_title' => array( 'label' => __( 'Focus keyword missing from the title', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'content', 'weight' => 3, 'fix' => __( 'The title is the strongest place for the keyword. Put it in, near the front.', 'ai-rank-suite' ), ), 'slug_long' => array( 'label' => __( 'URL slug is very long', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'indexability', 'weight' => 1, 'fix' => __( 'Over 75 characters. Keep the words that carry meaning and drop the rest; add a redirect from the old slug.', 'ai-rank-suite' ), ), 'no_featured_image' => array( 'label' => __( 'Post without a featured image', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'content', 'weight' => 1, 'fix' => __( 'The featured image becomes the social card and the thumbnail in Discover and in assistants that show sources.', 'ai-rank-suite' ), ), 'no_links_out' => array( 'label' => __( 'No internal links out', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'indexability', 'weight' => 2, 'fix' => __( 'A page that links to nothing is a dead end for the crawler and for the reader. Link to two or three related pages.', 'ai-rank-suite' ), ), 'oversized_image' => array( 'label' => __( 'Featured image is oversized', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'content', 'weight' => 1, 'fix' => __( 'Wider than 2500 pixels. Resize it before upload; the page loads faster and image search prefers it.', 'ai-rank-suite' ), ), /* ------------------------------------------------------------ GEO */ 'no_faq' => array( 'label' => __( 'Long page with no FAQ', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'geo', 'weight' => 1, 'fix' => __( 'Question-and-answer pairs are the single most quotable format for an assistant. Generate them in the Content panel.', 'ai-rank-suite' ), ), 'site_no_schema' => array( 'label' => __( 'Structured data is switched off', 'ai-rank-suite' ), 'severity' => 'critical', 'group' => 'site', 'weight' => 6, 'fix' => __( 'Without JSON-LD an assistant has to guess what kind of thing each page is. Switch the Schema module on.', 'ai-rank-suite' ), ), 'not_in_llms' => array( 'label' => __( 'Excluded from llms.txt', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'geo', 'weight' => 1, 'fix' => __( 'If this page should be quotable, include it in llms.txt.', 'ai-rank-suite' ), ), 'stale' => array( 'label' => __( 'Not updated in over two years', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'geo', 'weight' => 1, 'fix' => __( 'Assistants weight freshness heavily. Review the facts and republish.', 'ai-rank-suite' ), ), /* ----------------------------------------------------- Commerce */ 'product_no_image' => array( 'label' => __( 'Product without an image', 'ai-rank-suite' ), 'severity' => 'critical', 'group' => 'commerce', 'weight' => 5, 'fix' => __( 'Google Merchant and shopping surfaces reject product listings without an image.', 'ai-rank-suite' ), ), 'product_no_price' => array( 'label' => __( 'Product without a price', 'ai-rank-suite' ), 'severity' => 'critical', 'group' => 'commerce', 'weight' => 5, 'fix' => __( 'A Product without an offer price cannot produce a rich result.', 'ai-rank-suite' ), ), 'product_no_gtin' => array( 'label' => __( 'Product without GTIN, MPN or SKU', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'commerce', 'weight' => 3, 'fix' => __( 'Merchant listings match your product to the wider catalogue by identifier. Without one you compete alone.', 'ai-rank-suite' ), ), 'product_no_brand' => array( 'label' => __( 'Product without a brand', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'commerce', 'weight' => 2, 'fix' => __( 'Brand is a required merchant-listing property and a strong entity signal for assistants.', 'ai-rank-suite' ), ), 'product_no_desc' => array( 'label' => __( 'Product with no description', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'commerce', 'weight' => 3, 'fix' => __( 'An assistant asked to recommend a product reads the description. An empty one is never recommended.', 'ai-rank-suite' ), ), 'product_oos' => array( 'label' => __( 'Out of stock but indexable', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'commerce', 'weight' => 1, 'fix' => __( 'Keep it indexed if it is coming back; otherwise redirect it to the category.', 'ai-rank-suite' ), ), /* -------------------------------------------------------- Site */ 'site_private' => array( 'label' => __( 'Search engines are discouraged', 'ai-rank-suite' ), 'severity' => 'critical', 'group' => 'site', 'weight' => 10, 'fix' => __( 'Settings → Reading has "Discourage search engines" switched on. Nothing else matters until it is off.', 'ai-rank-suite' ), ), 'site_permalinks' => array( 'label' => __( 'Plain permalinks', 'ai-rank-suite' ), 'severity' => 'critical', 'group' => 'site', 'weight' => 6, 'fix' => __( 'Settings → Permalinks: choose Post name. ?p=123 URLs carry no keywords and break sitemaps.', 'ai-rank-suite' ), ), 'site_no_ssl' => array( 'label' => __( 'Site is not served over HTTPS', 'ai-rank-suite' ), 'severity' => 'critical', 'group' => 'site', 'weight' => 6, 'fix' => __( 'Install a certificate. HTTPS has been a ranking signal for a decade.', 'ai-rank-suite' ), ), 'site_no_sitemap' => array( 'label' => __( 'No XML sitemap', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'site', 'weight' => 4, 'fix' => __( 'Switch the sitemap module on so crawlers find every page.', 'ai-rank-suite' ), ), 'site_no_llms' => array( 'label' => __( 'No llms.txt', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'site', 'weight' => 4, 'fix' => __( 'llms.txt is how you tell an assistant which pages to read first. This is the GEO equivalent of a sitemap.', 'ai-rank-suite' ), ), 'site_no_identity' => array( 'label' => __( 'No Organization or LocalBusiness identity', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'site', 'weight' => 4, 'fix' => __( 'Without an identity node an assistant cannot tell who is answering. Fill in Local SEO or Schema → Identity.', 'ai-rank-suite' ), ), 'site_no_tagline' => array( 'label' => __( 'Default tagline still in place', 'ai-rank-suite' ), 'severity' => 'notice', 'group' => 'site', 'weight' => 1, 'fix' => __( '"Just another WordPress site" appears in your schema and your llms.txt.', 'ai-rank-suite' ), ), 'site_404s' => array( 'label' => __( 'Frequently hit 404s', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'site', 'weight' => 3, 'fix' => __( 'Redirect the URLs visitors and crawlers keep asking for.', 'ai-rank-suite' ), ), 'site_broken_links' => array( 'label' => __( 'Broken links found', 'ai-rank-suite' ), 'severity' => 'warning', 'group' => 'site', 'weight' => 3, 'fix' => __( 'Fix or remove them — a dead link is a trust signal in the wrong direction.', 'ai-rank-suite' ), ), ); /** * Filter the site-audit rule set — reprice a weight, soften a severity, rewrite a fix, or drop a rule so its findings disappear from the report and the score. * * The detectors are the plugin's own: a rule added here changes grouping and pricing but does not invent a new walker. * * @param array $checks Rule definitions keyed by check id. */ return (array) apply_filters( 'airanksuite/audit/checks', $checks ); } /** * Check groups, in report order. * * @return array */ public static function groups(): array { return array( 'site' => __( 'Site foundations', 'ai-rank-suite' ), 'indexability' => __( 'Indexability', 'ai-rank-suite' ), 'duplication' => __( 'Duplicate content', 'ai-rank-suite' ), 'content' => __( 'Content quality', 'ai-rank-suite' ), 'geo' => __( 'AI readiness', 'ai-rank-suite' ), 'commerce' => __( 'Shop & products', 'ai-rank-suite' ), ); } /* ------------------------------------------------------------------ run */ /** * Queue a run. * * @param list $post_types Restrict to these, or empty for all public. * @return array */ public function start( array $post_types = array(), int $limit = 5000 ): array { global $wpdb; $types = ! empty( $post_types ) ? array_values( array_intersect( $post_types, \AiRankSuite\Support\Inventory::eligible_types() ) ) : \AiRankSuite\Support\Inventory::eligible_types(); $limit = max( 1, min( 50000, $limit ) ); $total = min( $limit, $this->count_pages( $types ) ); $run = 'r' . substr( (string) time(), -9 ) . wp_rand( 100, 999 ); // Clear the previous run's duplicate stamps so the GROUP BY at the end // only ever sees this run. foreach ( array( self::META_TITLE, self::META_DESC, self::META_H1 ) as $key ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->delete( $wpdb->postmeta, array( 'meta_key' => $key ) ); } update_option( self::OPTION, array( 'run_id' => $run, 'types' => $types, 'cursor' => 0, 'limit' => $limit, 'total' => $total, 'done' => 0, 'issues' => 0, 'phase' => 'pages', 'state' => 'running', 'started' => time(), ), false ); return $this->status(); } /** * Pages that exist to transact, not to rank. * * Cart, Checkout and My account are noindexed on purpose by every shop that * knows what it is doing — reporting them as thin, description-less and * orphaned is three false alarms per page, on every run, forever. * * @return list */ private static function excluded_ids(): array { $ids = array(); foreach ( array( 'woocommerce_cart_page_id', 'woocommerce_checkout_page_id', 'woocommerce_myaccount_page_id', 'woocommerce_terms_page_id', 'wp_page_for_privacy_policy' ) as $option ) { $id = (int) get_option( $option ); if ( $id > 0 ) { $ids[] = $id; } } /** * Filter the pages the site audit skips entirely. * * @param list $ids Post IDs. */ return array_values( array_unique( array_map( 'intval', (array) apply_filters( 'airanksuite/audit/excluded', $ids ) ) ) ); } /** * Process one slice. Returns the job status. * * @return array */ public function tick(): array { $job = get_option( self::OPTION ); if ( ! is_array( $job ) || 'running' !== ( $job['state'] ?? '' ) ) { return $this->status(); } if ( 'pages' === $job['phase'] ) { // Jobs created before 0.99.26 carried every ID in one autoloaded // option. Finish those safely, while new jobs keep only a cursor. if ( isset( $job['pending'] ) && is_array( $job['pending'] ) ) { $batch = array_splice( $job['pending'], 0, \AiRankSuite\Support\Job::batch_size( self::SLICE ) ); } else { $remaining = max( 0, (int) $job['total'] - (int) $job['done'] ); $batch = $this->page_batch( (array) $job['types'], (int) ( $job['cursor'] ?? 0 ), min( \AiRankSuite\Support\Job::batch_size( self::SLICE ), $remaining ) ); } foreach ( $batch as $post_id ) { $job['cursor'] = max( (int) ( $job['cursor'] ?? 0 ), (int) $post_id ); $post = get_post( (int) $post_id ); if ( ! $post instanceof WP_Post ) { continue; } try { $job['issues'] += $this->audit_post( $post, (string) $job['run_id'] ); } catch ( \Throwable $e ) { // One bad page must never end the run. unset( $e ); } ++$job['done']; // A slice that is running out of memory stops here; the cursor // is already advanced, so the next tick picks up where it left. if ( \AiRankSuite\Support\Job::memory_tight() ) { break; } } if ( ( isset( $job['pending'] ) && empty( $job['pending'] ) ) || ( ! isset( $job['pending'] ) && ( empty( $batch ) || (int) $job['done'] >= (int) $job['total'] ) ) ) { $job['phase'] = 'duplicates'; } } elseif ( 'duplicates' === $job['phase'] ) { $job['issues'] += $this->find_duplicates( (string) $job['run_id'] ); $job['phase'] = 'site'; } elseif ( 'site' === $job['phase'] ) { $job['issues'] += $this->audit_site( (string) $job['run_id'] ); $job['phase'] = 'done'; $job['state'] = 'done'; $job['ended'] = time(); update_option( 'airanksuite_audit_last', $job['run_id'], false ); self::forget_summary( (string) $job['run_id'] ); delete_transient( 'airanksuite_auditdelta_' . md5( (string) $job['run_id'] ) ); // The dashboard findings chart is cached separately from the audit // report. Publishing a completed run must make that new point visible // on the very next dashboard request. delete_transient( 'airanksuite_dashboard_trends' ); // The "Open findings" tile reads the same run from the KPI payload, // which has its own five-minute cache. Left alone, the chart under // the tile showed the new run while the tile kept the old count. delete_transient( 'airanksuite_kpis' ); $report = $this->report( '', '', 1, 1 ); \AiRankSuite\Support\Events::emit( 'audit.finished', array( 'run_id' => (string) $job['run_id'], 'score' => $report['score'] ?? null, 'totals' => $report['totals'] ?? array(), 'checked' => (int) ( $job['done'] ?? 0 ), 'issues' => (int) $job['issues'], ) ); } update_option( self::OPTION, $job, false ); return $this->status(); } public function cancel(): array { $job = get_option( self::OPTION ); if ( is_array( $job ) ) { $job['state'] = 'cancelled'; unset( $job['pending'] ); update_option( self::OPTION, $job, false ); } return $this->status(); } /** @param list $types */ private function count_pages( array $types ): int { global $wpdb; if ( empty( $types ) ) { return 0; } // No post has the id 0, so an empty exclusion list excludes that: the // statement keeps one shape and only the %s / %d lists are generated. $excluded = self::excluded_ids(); $excluded = empty( $excluded ) ? array( 0 ) : $excluded; $placeholders = implode( ',', array_fill( 0, count( $types ), '%s' ) ); $not_in = implode( ',', array_fill( 0, count( $excluded ), '%d' ) ); $args = array_merge( $types, $excluded ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type IN ({$placeholders}) AND ID NOT IN ({$not_in})", ...$args ) ); } /** @param list $types @return list */ private function page_batch( array $types, int $cursor, int $size ): array { global $wpdb; if ( empty( $types ) || $size < 1 ) { return array(); } // As in count_pages(): an empty exclusion list excludes the id 0. $excluded = self::excluded_ids(); $excluded = empty( $excluded ) ? array( 0 ) : $excluded; $placeholders = implode( ',', array_fill( 0, count( $types ), '%s' ) ); $not_in = implode( ',', array_fill( 0, count( $excluded ), '%d' ) ); $args = array_merge( array( $cursor ), $types, $excluded, array( $size ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE ID > %d AND post_status = 'publish' AND post_type IN ({$placeholders}) AND ID NOT IN ({$not_in}) ORDER BY ID ASC LIMIT %d", ...$args ) ) ); } /** @return array */ public function status(): array { $job = get_option( self::OPTION ); if ( ! is_array( $job ) ) { return array( 'state' => 'idle', 'last' => (string) get_option( 'airanksuite_audit_last', '' ), ); } $total = max( 1, (int) $job['total'] ); return array( 'state' => (string) $job['state'], 'phase' => (string) $job['phase'], 'run_id' => (string) $job['run_id'], 'total' => (int) $job['total'], 'done' => (int) $job['done'], 'issues' => (int) $job['issues'], 'percent' => 'done' === $job['state'] ? 100 : (int) round( ( (int) $job['done'] / $total ) * 100 ), 'started' => (int) $job['started'], 'ended' => (int) ( $job['ended'] ?? 0 ), 'last' => (string) get_option( 'airanksuite_audit_last', '' ), ); } /* -------------------------------------------------------------- checks */ /** * Everything one page can be wrong about. Returns the number of issues found. */ private function audit_post( WP_Post $post, string $run ): int { $found = 0; $html = Html::rendered( $post ); $words = Html::word_count( $html ); $heads = Html::headings( $html ); // Html::headings() returns [level, text] pairs, not an associative map. $h1 = array_values( array_filter( $heads, static fn( array $h ): bool => 1 === (int) ( $h[0] ?? 0 ) ) ); $title = \AiRankSuite\Modules\Seo\SeoModule::resolve_title( $post ); $desc = \AiRankSuite\Modules\Seo\SeoModule::resolve_description( $post ); $robots = (array) get_post_meta( $post->ID, '_airanksuite_robots', true ); if ( in_array( 'noindex', $robots, true ) ) { // One finding, then stop. A page you have chosen not to index does // not also need to be told its description is missing — the whole // point is that nothing reads it. return $this->record( $run, 'noindex_page', $post ); } $canonical = trim( (string) get_post_meta( $post->ID, \AiRankSuite\Support\PostSeo::CANONICAL, true ) ); if ( '' !== $canonical && untrailingslashit( $canonical ) !== untrailingslashit( (string) get_permalink( $post ) ) ) { $found += $this->record( $run, 'canonical_foreign', $post, $canonical ); } if ( '' === trim( $desc ) ) { $found += $this->record( $run, 'no_desc', $post ); } $len = mb_strlen( $title ); if ( $len > 0 && ( $len < 30 || $len > 60 ) ) { $found += $this->record( $run, 'title_length', $post, /* translators: %d: character count. */ sprintf( __( '%d characters', 'ai-rank-suite' ), $len ) ); } if ( $words < 300 ) { $found += $this->record( $run, 'thin', $post, /* translators: %d: word count. */ sprintf( __( '%d words', 'ai-rank-suite' ), $words ) ); } // Themes render the post title as the page H1, so an H1 *inside* the // content is the anomaly — the absence of one is the norm. Flagging // "no H1" here would fire on every page of every site, and a report // that is wrong everywhere teaches the customer to ignore it. if ( ! empty( $h1 ) ) { $found += $this->record( $run, 'many_h1', $post, /* translators: %d: heading count. */ sprintf( _n( '%d H1 in the content', '%d H1s in the content', count( $h1 ), 'ai-rank-suite' ), count( $h1 ) ) ); } elseif ( empty( $heads ) && $words > 150 ) { $found += $this->record( $run, 'no_headings', $post ); } $dlen = mb_strlen( trim( $desc ) ); if ( $dlen > 0 && ( $dlen < 70 || $dlen > 160 ) ) { $found += $this->record( $run, 'desc_length', $post, /* translators: %d: character count. */ sprintf( __( '%d characters', 'ai-rank-suite' ), $dlen ) ); } // The focus keyword: absent, or present but not in the title. $keywords = class_exists( \AiRankSuite\Modules\ContentAnalyzer\Services\KeywordAnalyzer::class ) ? \AiRankSuite\Modules\ContentAnalyzer\Services\KeywordAnalyzer::get( $post->ID ) : array(); $keyword = trim( (string) ( $keywords['shorttail'][0] ?? '' ) ); if ( '' === $keyword ) { $found += $this->record( $run, 'no_keyword', $post ); } elseif ( false === mb_stripos( $title, $keyword ) ) { $found += $this->record( $run, 'keyword_not_in_title', $post, $keyword ); } if ( mb_strlen( (string) $post->post_name ) > 75 ) { $found += $this->record( $run, 'slug_long', $post, /* translators: %d: character count. */ sprintf( __( '%d characters', 'ai-rank-suite' ), mb_strlen( (string) $post->post_name ) ) ); } $thumb = (int) get_post_thumbnail_id( $post ); if ( 'post' === $post->post_type && 0 === $thumb ) { $found += $this->record( $run, 'no_featured_image', $post ); } elseif ( $thumb > 0 ) { $meta = wp_get_attachment_metadata( $thumb ); if ( is_array( $meta ) && (int) ( $meta['width'] ?? 0 ) > 2500 ) { $found += $this->record( $run, 'oversized_image', $post, /* translators: 1: width, 2: height in pixels. */ sprintf( __( '%1$d × %2$d px', 'ai-rank-suite' ), (int) $meta['width'], (int) ( $meta['height'] ?? 0 ) ) ); } } list( $links_in_body ) = Html::links( $html ); if ( $words >= 300 && 0 === $links_in_body ) { $found += $this->record( $run, 'no_links_out', $post ); } list( , $miss ) = Html::images_alt( $html ); if ( $miss > 0 ) { $found += $this->record( $run, 'no_alt', $post, /* translators: %d: image count. */ sprintf( __( '%d images', 'ai-rank-suite' ), $miss ) ); } // The schema module generates a graph for every page automatically, so // "no structured data" is a site-level setting, not a per-page fault. // A long page with no Q&A, on the other hand, is a missed citation. if ( $words >= 600 && empty( \AiRankSuite\Support\StoredReads::faq_items( $post->ID ) ) ) { $found += $this->record( $run, 'no_faq', $post ); } if ( ! empty( get_post_meta( $post->ID, '_airanksuite_exclude', true ) ) ) { $found += $this->record( $run, 'not_in_llms', $post ); } $age = time() - (int) get_post_modified_time( 'U', true, $post ); if ( $age > 2 * YEAR_IN_SECONDS ) { $found += $this->record( $run, 'stale', $post, /* translators: %d: number of years. */ sprintf( __( 'last touched %d years ago', 'ai-rank-suite' ), (int) floor( $age / YEAR_IN_SECONDS ) ) ); } if ( 'product' === $post->post_type && function_exists( 'wc_get_product' ) ) { $found += $this->audit_product( $post, $run ); } // Stamp the duplicate fingerprints for the SQL pass. $this->stamp( $post->ID, self::META_TITLE, $run, $title ); $this->stamp( $post->ID, self::META_DESC, $run, $desc ); $this->stamp( $post->ID, self::META_H1, $run, (string) ( $h1[0][1] ?? '' ) ); return $found; } /** * WooCommerce-specific checks. Everything here is a merchant-listing * requirement, not an opinion — a product missing these is either rejected * by Google Merchant or ineligible for a rich result. */ private function audit_product( WP_Post $post, string $run ): int { $found = 0; $product = wc_get_product( $post->ID ); if ( ! $product ) { return 0; } if ( ! $product->get_image_id() ) { $found += $this->record( $run, 'product_no_image', $post ); } if ( '' === (string) $product->get_price() ) { $found += $this->record( $run, 'product_no_price', $post ); } $identifier = trim( (string) $product->get_sku() ) . trim( (string) $product->get_meta( '_airanksuite_gtin' ) ) . trim( (string) $product->get_meta( '_airanksuite_mpn' ) ) . trim( (string) $product->get_meta( '_gtin' ) ); if ( '' === $identifier ) { $found += $this->record( $run, 'product_no_gtin', $post ); } if ( '' === trim( (string) $product->get_description() ) && '' === trim( (string) $product->get_short_description() ) ) { $found += $this->record( $run, 'product_no_desc', $post ); } if ( ! $product->is_in_stock() ) { $found += $this->record( $run, 'product_oos', $post ); } $brand = ''; foreach ( array( 'product_brand', 'pwb-brand', 'yith_product_brand' ) as $taxonomy ) { if ( taxonomy_exists( $taxonomy ) ) { $terms = wp_get_post_terms( $post->ID, $taxonomy, array( 'fields' => 'names' ) ); if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) { $brand = (string) $terms[0]; break; } } } if ( '' === $brand && '' === trim( (string) $product->get_attribute( 'brand' ) ) ) { $found += $this->record( $run, 'product_no_brand', $post ); } return $found; } /** * How the finding count moved across the last audit runs. * * Every run stamps its rows with a run_id, so the history is already in the * table — nothing extra is stored for this. One point per run, split by * severity, oldest first, so a chart reads left to right. * * @param int $limit How many runs to look back over. * @return array> */ public function trend( int $limit = 20 ): array { global $wpdb; $table = Database::audit(); $limit = max( 2, min( 60, $limit ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( "SELECT run_id, MIN(created_at) AS ran_at, COUNT(*) AS total, SUM(severity = 'critical') AS critical, SUM(severity = 'warning') AS warning, SUM(severity = 'notice') AS notice FROM {$table} GROUP BY run_id ORDER BY MIN(created_at) DESC LIMIT %d", $limit ) ); $out = array(); foreach ( array_reverse( (array) $rows ) as $row ) { $out[] = array( 'run' => (string) $row->run_id, 'date' => (string) mysql2date( 'M j', (string) $row->ran_at ), 'value' => (int) $row->total, 'critical' => (int) $row->critical, 'warning' => (int) $row->warning, 'notice' => (int) $row->notice, ); } return $out; } /** * Duplicates, resolved by the database rather than by PHP memory. */ private function find_duplicates( string $run ): int { global $wpdb; $found = 0; $map = array( self::META_TITLE => 'dup_title', self::META_DESC => 'dup_desc', self::META_H1 => 'dup_h1', ); foreach ( $map as $meta_key => $check ) { // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared $rows = $wpdb->get_results( $wpdb->prepare( "SELECT meta_value, GROUP_CONCAT(post_id) AS ids, COUNT(*) AS n FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value LIKE %s GROUP BY meta_value HAVING n > 1 LIMIT 500", $meta_key, $wpdb->esc_like( $run . ':' ) . '%' ) ); // phpcs:enable foreach ( (array) $rows as $row ) { $ids = array_map( 'intval', explode( ',', (string) $row->ids ) ); foreach ( $ids as $post_id ) { $post = get_post( $post_id ); if ( ! $post instanceof WP_Post ) { continue; } $found += $this->record( $run, $check, $post, /* translators: %d: number of pages sharing the value. */ sprintf( __( 'shared with %d other pages', 'ai-rank-suite' ), count( $ids ) - 1 ) ); } } } // Orphans: published pages nothing links to. Only meaningful once the // internal link index has actually been built. $links = Database::links(); // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared $indexed = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i", $links ) ); if ( $indexed > 0 ) { $orphans = $wpdb->get_col( $wpdb->prepare( "SELECT p.ID FROM %i p WHERE p.post_status = 'publish' AND p.post_type IN ('post','page') AND NOT EXISTS (SELECT 1 FROM %i l WHERE l.target_post_id = p.ID) LIMIT 200", $wpdb->posts, $links ) ); foreach ( (array) $orphans as $post_id ) { $post = get_post( (int) $post_id ); if ( $post instanceof WP_Post ) { $found += $this->record( $run, 'orphan', $post ); } } } // phpcs:enable return $found; } /** * Site-wide settings that no per-page check can see. */ private function audit_site( string $run ): int { global $wpdb; $found = 0; if ( '0' === (string) get_option( 'blog_public' ) ) { $found += $this->record_site( $run, 'site_private' ); } if ( '' === (string) get_option( 'permalink_structure' ) ) { $found += $this->record_site( $run, 'site_permalinks' ); } if ( 0 !== strpos( (string) home_url(), 'https://' ) ) { $found += $this->record_site( $run, 'site_no_ssl' ); } $sitemap = $this->options->get( 'sitemap', array( 'enabled' => true ) ); if ( empty( $sitemap['enabled'] ) ) { $found += $this->record_site( $run, 'site_no_sitemap' ); } $schema = $this->options->get( 'schema', array( 'enabled' => true ) ); if ( isset( $schema['enabled'] ) && empty( $schema['enabled'] ) ) { $found += $this->record_site( $run, 'site_no_schema' ); } $llms = $this->options->get( 'llms_txt', array( 'enabled' => true ) ); if ( empty( $llms['enabled'] ) ) { $found += $this->record_site( $run, 'site_no_llms' ); } $local = $this->options->get( 'local_seo', array() ); if ( empty( $local['name'] ) && empty( $schema['org_name'] ) ) { $found += $this->record_site( $run, 'site_no_identity' ); } $tagline = (string) get_bloginfo( 'description' ); if ( '' === trim( $tagline ) || 'Just another WordPress site' === $tagline ) { $found += $this->record_site( $run, 'site_no_tagline' ); } $not_found = Database::not_found(); // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared $hot404 = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE hits >= 5", $not_found ) ); if ( $hot404 > 0 ) { $found += $this->record_site( $run, 'site_404s', /* translators: %d: number of URLs. */ sprintf( __( '%d URLs hit five times or more', 'ai-rank-suite' ), $hot404 ) ); } $found_links = Database::found_links(); // Published scan only; with none published the flag is 0 and nothing matches. $link_scope = \AiRankSuite\Support\StoredReads::linkscan_scope(); $broken = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE ( %d = 1 AND run_id = %s ) AND ok = 0 AND status >= 400', $found_links, $link_scope[0], $link_scope[1] ) ); // phpcs:enable if ( $broken > 0 ) { $found += $this->record_site( $run, 'site_broken_links', /* translators: %d: number of links. */ sprintf( __( '%d links return an error', 'ai-rank-suite' ), $broken ) ); } return $found; } /* ------------------------------------------------------------- storage */ private function stamp( int $post_id, string $key, string $run, string $value ): void { $value = trim( $value ); if ( '' === $value ) { return; } update_post_meta( $post_id, $key, $run . ':' . md5( mb_strtolower( $value ) ) ); } /** * Write one finding, unless the customer marked it as accepted. * * @return int 1 when stored, 0 when ignored. */ /** * Every finding of the last completed run as CSV rows. * * @return array> */ public function export_rows(): array { global $wpdb; $run = (string) get_option( 'airanksuite_audit_last', '' ); if ( '' === $run ) { return array(); } $checks = self::checks(); $out = array( array( 'severity', 'rule', 'group', 'page', 'url', 'detail', 'fix' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT check_id, severity, post_id, label, detail FROM %i WHERE run_id = %s ORDER BY FIELD(severity, %s, %s, %s), check_id, label', Database::audit(), $run, 'critical', 'warning', 'notice' ), ARRAY_A ); foreach ( (array) $rows as $row ) { $def = $checks[ $row['check_id'] ] ?? array(); $out[] = array( (string) $row['severity'], (string) ( $def['label'] ?? $row['check_id'] ), (string) ( $def['group'] ?? '' ), (string) $row['label'], $row['post_id'] ? (string) get_permalink( (int) $row['post_id'] ) : home_url( '/' ), (string) $row['detail'], (string) ( $def['fix'] ?? '' ), ); } return $out; } private function record( string $run, string $check, WP_Post $post, string $detail = '' ): int { return $this->write( $run, $check, 'post', $post->ID, get_the_title( $post ), $detail ); } private function record_site( string $run, string $check, string $detail = '' ): int { return $this->write( $run, $check, 'site', 0, get_bloginfo( 'name' ), $detail ); } private function write( string $run, string $check, string $type, int $post_id, string $label, string $detail ): int { global $wpdb; $def = self::checks()[ $check ] ?? null; if ( null === $def ) { return 0; } if ( in_array( $check, $this->ignored_rules(), true ) ) { return 0; } $fingerprint = md5( $check . '|' . $type . '|' . $post_id ); if ( in_array( $fingerprint, $this->ignored(), true ) ) { return 0; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->insert( Database::audit(), array( 'run_id' => $run, 'object_type' => $type, 'post_id' => $post_id, 'check_id' => $check, 'severity' => (string) $def['severity'], 'label' => mb_substr( $label, 0, 180 ), 'detail' => $detail, 'fingerprint' => $fingerprint, 'created_at' => current_time( 'mysql', true ), ), array( '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s' ) ); return 1; } /** @return list */ public function ignored(): array { $list = get_option( self::IGNORED, array() ); return is_array( $list ) ? array_values( array_map( 'strval', $list ) ) : array(); } /** * Rules accepted wholesale — a small list of check ids, never a list of * fingerprints. "We know our category pages are thin, stop telling us" is * one entry, however many pages it covers. * * @return array */ public function ignored_rules(): array { $list = get_option( self::IGNORED . '_rules', array() ); return is_array( $list ) ? array_values( array_map( 'strval', $list ) ) : array(); } /** * Accept (or un-accept) every finding of one rule, now and in future runs. * * @return array The rules currently accepted. */ public function ignore_rule( string $check, bool $on = true ): array { global $wpdb; $list = $this->ignored_rules(); if ( $on ) { if ( isset( self::checks()[ $check ] ) ) { $list[] = $check; // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->delete( Database::audit(), array( 'check_id' => $check ), array( '%s' ) ); } } else { $list = array_values( array_diff( $list, array( $check ) ) ); } $list = array_values( array_unique( $list ) ); update_option( self::IGNORED . '_rules', $list, false ); // Findings were deleted: the cached roll-up would still count them. self::forget_summary(); return $list; } public function ignore( string $fingerprint, bool $on = true ): array { global $wpdb; $list = $this->ignored(); if ( $on ) { $list[] = $fingerprint; // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->delete( Database::audit(), array( 'fingerprint' => $fingerprint ), array( '%s' ) ); } else { $list = array_values( array_diff( $list, array( $fingerprint ) ) ); } $list = array_values( array_unique( $list ) ); update_option( self::IGNORED, $list, false ); self::forget_summary(); return $list; } /** Drop the cached roll-up of a run (or of the current one). */ public static function forget_summary( string $run = '' ): void { $run = '' !== $run ? $run : (string) get_option( 'airanksuite_audit_last', '' ); delete_transient( 'airanksuite_auditsummary_' . md5( $run ) ); } /* -------------------------------------------------------------- report */ /** * The audit report: score, counts by severity, and findings grouped by check. * * @return array */ public function report( string $group = '', string $severity = '', int $page = 1, int $per_page = 50, string $lang = '', string $check = '', string $type = '' ): array { global $wpdb; $table = Database::audit(); $run = (string) get_option( 'airanksuite_audit_last', '' ); if ( '' === $run ) { return array( 'run_id' => '', 'score' => null, 'totals' => array( 'critical' => 0, 'warning' => 0, 'notice' => 0, ), 'groups' => array(), 'items' => array(), 'total' => 0, 'checked' => 0, ); } $checks = self::checks(); // The roll-up is a GROUP BY over every finding of the run — a hundred // thousand rows on a large site, on every page of the findings list and // every filter change. A completed run's counts cannot change, so they // are computed once and cached under the run id (cleared when a run // finishes, when a rule is ignored, and when a finding is deleted). $summary_key = 'airanksuite_auditsummary_' . md5( $run ); $rows = get_transient( $summary_key ); if ( ! is_array( $rows ) ) { // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared $rows = $wpdb->get_results( $wpdb->prepare( "SELECT check_id, severity, COUNT(*) AS n FROM {$table} WHERE run_id = %s GROUP BY check_id, severity", $run ), ARRAY_A ); // phpcs:enable set_transient( $summary_key, $rows, DAY_IN_SECONDS ); } $rows = array_map( static fn( $r ) => (object) $r, (array) $rows ); $totals = array( 'critical' => 0, 'warning' => 0, 'notice' => 0, ); $by_group = array(); $by_check = array(); $penalty = 0; foreach ( (array) $rows as $row ) { $def = $checks[ $row->check_id ] ?? null; if ( null === $def ) { continue; } $n = (int) $row->n; $totals[ (string) $row->severity ] = ( $totals[ (string) $row->severity ] ?? 0 ) + $n; $g = (string) $def['group']; $by_group[ $g ] = ( $by_group[ $g ] ?? 0 ) + $n; $by_check[] = array( 'id' => (string) $row->check_id, 'label' => (string) $def['label'], 'fix' => (string) $def['fix'], 'severity' => (string) $def['severity'], 'group' => $g, 'count' => $n, ); // A check that fires on many pages should not sink the score more // than one that fires everywhere — dampen by log, not by count. $penalty += (int) $def['weight'] * ( 1 + (int) floor( log( max( 1, $n ), 4 ) ) ); } usort( $by_check, static function ( array $a, array $b ) use ( $checks ): int { $rank = array( 'critical' => 0, 'warning' => 1, 'notice' => 2, ); $cmp = ( $rank[ $a['severity'] ] ?? 3 ) <=> ( $rank[ $b['severity'] ] ?? 3 ); return 0 !== $cmp ? $cmp : $b['count'] <=> $a['count']; } ); // Findings list, filtered. The statement is a constant: a filter that // is not in use is switched off by its own flag rather than left out of // the text, and only the placeholder list of a group's checks is // generated. $ids = array( '__none__' ); if ( '' !== $group ) { $ids = array_keys( array_filter( $checks, static fn( array $c ): bool => $c['group'] === $group ) ); if ( empty( $ids ) ) { $ids = array( '__none__' ); } } $ids_ph = implode( ',', array_fill( 0, count( $ids ), '%s' ) ); // One rule, one post type: the two filters an SEO reaches for on a // large site ("show me every thin-content page among the products"). $by_check_id = '' !== $check && isset( $checks[ $check ] ); $by_type = '' !== $type && in_array( $type, \AiRankSuite\Support\Inventory::eligible_types(), true ); // One language, looked up rather than collected: an IN list of every post // id in a language stops scaling at exactly the size this has to work at. $scope = \AiRankSuite\Support\Multilingual::sql_scope_args( $lang ); $params = array_merge( array( $table, $run, '' !== $severity ? 1 : 0, $severity, '' !== $group ? 1 : 0 ), $ids, array( $by_check_id ? 1 : 0, $check, $by_type ? 1 : 0, $type ), $scope['args'] ); $per_page = max( 1, min( 200, $per_page ) ); $offset = max( 0, ( $page - 1 ) * $per_page ); // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- only the generated %s list is interpolated. $total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i a WHERE a.run_id = %s AND ( %d = 0 OR a.severity = %s ) AND ( %d = 0 OR a.check_id IN ({$ids_ph}) ) AND ( %d = 0 OR a.check_id = %s ) AND ( %d = 0 OR EXISTS ( SELECT 1 FROM {$wpdb->posts} pt WHERE pt.ID = a.post_id AND pt.post_type = %s ) ) AND ( %d = 0 OR EXISTS ( SELECT 1 FROM %i airanksuite_x WHERE airanksuite_x.%i = a.post_id AND airanksuite_x.%i = %s AND airanksuite_x.%i LIKE %s ) ) AND ( %d = 0 OR EXISTS ( SELECT 1 FROM {$wpdb->term_relationships} airanksuite_lr INNER JOIN {$wpdb->term_taxonomy} airanksuite_lt ON airanksuite_lt.term_taxonomy_id = airanksuite_lr.term_taxonomy_id AND airanksuite_lt.taxonomy = 'language' INNER JOIN {$wpdb->terms} airanksuite_lg ON airanksuite_lg.term_id = airanksuite_lt.term_id WHERE airanksuite_lr.object_id = a.post_id AND airanksuite_lg.slug = %s ) )", ...$params ) ); $items = $wpdb->get_results( $wpdb->prepare( "SELECT a.id, a.object_type, a.post_id, a.check_id, a.severity, a.label, a.detail, a.fingerprint FROM %i a WHERE a.run_id = %s AND ( %d = 0 OR a.severity = %s ) AND ( %d = 0 OR a.check_id IN ({$ids_ph}) ) AND ( %d = 0 OR a.check_id = %s ) AND ( %d = 0 OR EXISTS ( SELECT 1 FROM {$wpdb->posts} pt WHERE pt.ID = a.post_id AND pt.post_type = %s ) ) AND ( %d = 0 OR EXISTS ( SELECT 1 FROM %i airanksuite_x WHERE airanksuite_x.%i = a.post_id AND airanksuite_x.%i = %s AND airanksuite_x.%i LIKE %s ) ) AND ( %d = 0 OR EXISTS ( SELECT 1 FROM {$wpdb->term_relationships} airanksuite_lr INNER JOIN {$wpdb->term_taxonomy} airanksuite_lt ON airanksuite_lt.term_taxonomy_id = airanksuite_lr.term_taxonomy_id AND airanksuite_lt.taxonomy = 'language' INNER JOIN {$wpdb->terms} airanksuite_lg ON airanksuite_lg.term_id = airanksuite_lt.term_id WHERE airanksuite_lr.object_id = a.post_id AND airanksuite_lg.slug = %s ) ) ORDER BY FIELD(a.severity,'critical','warning','notice'), a.check_id, a.id LIMIT %d OFFSET %d", ...array_merge( $params, array( $per_page, $offset ) ) ) ); // phpcs:enable $out = array(); foreach ( (array) $items as $row ) { $def = $checks[ $row->check_id ] ?? array(); $out[] = array( 'id' => (int) $row->id, 'check' => (string) $row->check_id, 'check_label' => (string) ( $def['label'] ?? $row->check_id ), 'fix' => (string) ( $def['fix'] ?? '' ), 'group' => (string) ( $def['group'] ?? 'site' ), 'severity' => (string) $row->severity, 'label' => (string) $row->label, 'detail' => (string) $row->detail, 'post_id' => (int) $row->post_id, 'fingerprint' => (string) $row->fingerprint, 'url' => $row->post_id ? (string) get_permalink( (int) $row->post_id ) : (string) home_url( '/' ), 'edit_url' => $row->post_id ? (string) get_edit_post_link( (int) $row->post_id, '' ) : '', 'post_id' => (int) $row->post_id, ); } $groups = array(); foreach ( self::groups() as $id => $label ) { $groups[] = array( 'id' => $id, 'label' => $label, 'count' => (int) ( $by_group[ $id ] ?? 0 ), ); } $job = get_option( self::OPTION ); return array( 'run_id' => $run, 'score' => max( 0, 100 - min( 100, $penalty ) ), 'totals' => $totals, 'groups' => $groups, 'checks' => $by_check, 'items' => $out, 'total' => $total, 'page' => $page, 'per_page' => $per_page, 'checked' => is_array( $job ) ? (int) $job['done'] : 0, 'ended' => is_array( $job ) ? (int) ( $job['ended'] ?? 0 ) : 0, /* * How many rules there are, from the catalogue rather than from a * number typed into the screen. The audit screen carried `const * RULES = 30`, which was right on the day it was written and * silently wrong the first time a rule was added. */ 'rules_total' => count( self::checks() ), 'ignored' => count( $this->ignored() ), 'ignored_rules' => $this->ignored_rules(), 'delta' => $this->delta( $run ), ); } /** * This run against the one before it: what is new, what was fixed, what * is still there. Three COUNTs on the fingerprint index — no rows are * loaded — so it costs the same on 500 findings and on 100,000. * * @return array{previous: string, new: int, fixed: int, recurring: int}|null */ public function delta( string $run ): ?array { global $wpdb; $table = Database::audit(); // Three anti-joins across two complete runs — a fifth of a second at a // hundred thousand findings, on every request that renders the audit // header. Two finished runs cannot change, so this is computed once. $key = 'airanksuite_auditdelta_' . md5( $run ); $cached = get_transient( $key ); if ( is_array( $cached ) ) { return $cached; } // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared $prev = (string) $wpdb->get_var( $wpdb->prepare( "SELECT run_id FROM {$table} WHERE run_id <> %s GROUP BY run_id ORDER BY MIN(created_at) DESC LIMIT 1", $run ) ); if ( '' === $prev ) { return null; } $new = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$table} a WHERE a.run_id = %s AND NOT EXISTS (SELECT 1 FROM {$table} b WHERE b.run_id = %s AND b.fingerprint = a.fingerprint)", $run, $prev ) ); $fixed = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$table} b WHERE b.run_id = %s AND NOT EXISTS (SELECT 1 FROM {$table} a WHERE a.run_id = %s AND a.fingerprint = b.fingerprint)", $prev, $run ) ); $recurring = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$table} a WHERE a.run_id = %s AND EXISTS (SELECT 1 FROM {$table} b WHERE b.run_id = %s AND b.fingerprint = a.fingerprint)", $run, $prev ) ); // phpcs:enable $out = array( 'previous' => $prev, 'new' => $new, 'fixed' => $fixed, 'recurring' => $recurring, ); set_transient( $key, $out, DAY_IN_SECONDS ); return $out; } }