= self::BATCH ) { wp_schedule_single_event( time() + 2 * MINUTE_IN_SECONDS, 'aeoora_suggestions_run' ); } return; } $today = wp_date( 'Y-m-d' ); $progress = get_option( 'aeoora_suggestions_progress', array() ); if ( ! is_array( $progress ) || ! isset( $progress['day'] ) || $today !== $progress['day'] ) { $progress = array( 'day' => $today, 'done' => 0, ); } $left = (int) $s['per_day'] - (int) $progress['done']; if ( $left <= 0 ) { return; } $summary = self::run( $left, (int) apply_filters( 'aeoora_suggestions_time_budget', 45 ) ); if ( ! empty( $summary['busy'] ) ) { wp_schedule_single_event( time() + 5 * MINUTE_IN_SECONDS, 'aeoora_suggestions_run' ); return; } $progress['done'] += (int) $summary['posts']; update_option( 'aeoora_suggestions_progress', $progress, false ); if ( ! empty( $summary['more'] ) && $progress['done'] < (int) $s['per_day'] ) { wp_schedule_single_event( time() + 2 * MINUTE_IN_SECONDS, 'aeoora_suggestions_run' ); } } /** * Delete suggestions that were applied or dismissed more than six months ago. */ public static function prune() { global $wpdb; if ( ! Aeoora_Install::ready() ) { return; } $table = self::table(); $quiet = $wpdb->suppress_errors( true ); $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE status IN ('applied','dismissed') AND updated_at < %s LIMIT 5000", $table, gmdate( 'Y-m-d H:i:s', time() - 180 * DAY_IN_SECONDS ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. $wpdb->suppress_errors( $quiet ); } /** * Table name. * * @return string */ private static function table() { return Aeoora_Install::table( Aeoora_Install::TABLE_SUGGESTIONS ); } /** * Run now (admin button, WP-CLI). * * @param int|null $limit Override number of posts. * @return array Summary. */ public static function run_daily( $limit = null ) { $s = Aeoora_Settings::get( 'suggestions' ); if ( empty( $s['enabled'] ) && null === $limit ) { return array( 'posts' => 0 ); } $limit = null === $limit ? (int) $s['per_day'] : (int) $limit; // In a browser request, stop after a minute rather than hit the host's time limit. $cli = defined( 'WP_CLI' ) && WP_CLI; return self::run( $limit, $cli ? 0 : 60 ); } /** * Create suggestions for up to $limit posts (one run at a time). * * @param int $limit Posts. * @param int $budget Seconds (0 = no limit). No new post is started after it. * @return array Summary (busy when another run holds the lock, more when time ran out). */ private static function run( $limit, $budget = 0 ) { if ( ! Aeoora_Util::lock( 'suggestions', 15 * MINUTE_IN_SECONDS ) ) { return array( 'busy' => true, 'posts' => 0, 'created' => 0, ); } try { return self::work( $limit, $budget ); } finally { Aeoora_Util::unlock( 'suggestions' ); } } /** * The run itself. * * @param int $limit Posts. * @param int $budget Seconds (0 = no limit). * @return array Summary. */ private static function work( $limit, $budget ) { $s = Aeoora_Settings::get( 'suggestions' ); $start = microtime( true ); $use_ai = ! empty( $s['use_ai'] ) && '' !== Aeoora_Ai::default_provider(); $done = 0; $created = 0; $errors = array(); $more = false; foreach ( self::pick_posts( $limit ) as $post ) { if ( $budget > 0 && microtime( true ) - $start > $budget ) { $more = true; break; } $audit = Aeoora_Audit::score_post( $post ); $done++; $created += self::rule_based( $post, $audit ); if ( $use_ai ) { $r = self::ai_based( $post, $audit ); if ( is_wp_error( $r ) ) { $errors[] = $r->get_error_message(); if ( in_array( $r->get_error_code(), array( 'aeoora_ai_limit', 'aeoora_ai_not_configured' ), true ) ) { $use_ai = false; } } else { $created += $r; } } update_post_meta( $post->ID, '_aeoora_suggested_at', time() ); } if ( ! $more && $use_ai && ! empty( $s['ideas'] ) && ! self::has_recent( 'idea', 7 ) ) { $ideas = Aeoora_Ai_Tasks::ideas( array( 'context' => 'daily' ) ); if ( ! is_wp_error( $ideas ) ) { foreach ( array_slice( (array) $ideas, 0, 6 ) as $idea ) { if ( empty( $idea['title'] ) ) { continue; } self::add( 0, 'idea', $idea['title'], '', wp_json_encode( $idea ), isset( $idea['why'] ) ? $idea['why'] : '', 'ai' ); $created++; } } } $summary = array( 'at' => time(), 'posts' => $done, 'created' => $created, 'ai' => $use_ai, 'errors' => array_slice( array_unique( $errors ), 0, 3 ), 'more' => $more, ); update_option( 'aeoora_suggestions_last', $summary, false ); return $summary; } /** * Posts with the most to gain: never scored or not recently suggested, lowest score first. * * @param int $limit Number. * @return WP_Post[] */ private static function pick_posts( $limit ) { if ( $limit <= 0 ) { return array(); } $types = (array) Aeoora_Settings::get( 'suggestions', 'post_types', array( 'post', 'page' ) ); $base = array( 'post_type' => $types, 'post_status' => 'publish', 'has_password' => false, 'posts_per_page' => $limit * 4, 'no_found_rows' => true, 'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery 'relation' => 'OR', array( 'key' => '_aeoora_suggested_at', 'compare' => 'NOT EXISTS', ), array( 'key' => '_aeoora_suggested_at', 'value' => time() - 30 * DAY_IN_SECONDS, 'compare' => '<', 'type' => 'NUMERIC', ), ), ); $unscored = $base; $unscored['meta_query'] = array( // phpcs:ignore WordPress.DB.SlowDBQuery 'relation' => 'AND', $base['meta_query'], array( 'key' => '_aeoora_score', 'compare' => 'NOT EXISTS', ), ); $unscored['orderby'] = 'date'; $posts = get_posts( $unscored ); $scored = $base; $scored['meta_key'] = '_aeoora_score'; // phpcs:ignore WordPress.DB.SlowDBQuery $scored['orderby'] = 'meta_value_num'; $scored['order'] = 'ASC'; $posts = array_merge( $posts, get_posts( $scored ) ); $out = array(); foreach ( $posts as $p ) { if ( isset( $out[ $p->ID ] ) || self::pending_count( $p->ID ) > 0 || ! Aeoora_Content::is_public( $p, 'audit' ) ) { continue; } $out[ $p->ID ] = $p; if ( count( $out ) >= $limit ) { break; } } return array_values( $out ); } /** * Rule-based suggestions from the audit (no AI needed). * * @param WP_Post $post Post. * @param array $audit Audit. * @return int Created. */ private static function rule_based( WP_Post $post, array $audit ) { $fixes = array(); foreach ( (array) $audit['checks'] as $c ) { if ( 'pass' !== $c['status'] && '' !== $c['fix'] ) { $fixes[] = array( 'check_id' => $c['id'], 'label' => $c['label'], 'problem' => $c['message'], 'fix' => $c['fix'], 'gain' => $c['max'] - $c['points'], 'ai' => $c['ai'], ); } } if ( ! $fixes ) { return 0; } usort( $fixes, static function ( $a, $b ) { return $b['gain'] <=> $a['gain']; } ); self::add( $post->ID, 'checklist', /* translators: %d: score. */ sprintf( __( 'AEO score %d/100 — top fixes', 'aeoora' ), $audit['score'] ), (string) $audit['score'], wp_json_encode( array_slice( $fixes, 0, 8 ) ), '', 'rules' ); return 1; } /** * AI suggestions for a post. * * @param WP_Post $post Post. * @param array $audit Audit. * @return int|WP_Error Created. */ private static function ai_based( WP_Post $post, array $audit ) { $data = Aeoora_Ai_Tasks::for_post( 'fixes', $post->ID, array( 'audit' => $audit, 'context' => 'daily', ) ); if ( is_wp_error( $data ) ) { return $data; } $source = isset( $data['_ai']['provider'] ) ? $data['_ai']['provider'] . ':' . $data['_ai']['model'] : 'ai'; $created = 0; $failed = array(); foreach ( (array) $audit['checks'] as $c ) { if ( 'pass' !== $c['status'] ) { $failed[ $c['id'] ] = true; } } // Titles and descriptions only where they can be written (no SEO plugin, or one we write to). $can_write = Aeoora_Seo::can_write(); if ( $can_write && ! empty( $data['meta_description'] ) && ( isset( $failed['meta_description'] ) || '' === Aeoora_Seo::get_description( $post->ID ) ) ) { $current = Aeoora_Seo::get_description( $post->ID ); $id = self::add( $post->ID, 'meta_description', __( 'New meta description', 'aeoora' ), $current, sanitize_text_field( $data['meta_description'] ), __( 'States the answer in 140–160 characters.', 'aeoora' ), $source ); $created++; if ( '' === $current && Aeoora_Settings::get( 'suggestions', 'auto_apply_meta', false ) ) { self::apply( $id ); } } if ( $can_write && ! empty( $data['meta_title'] ) && isset( $failed['meta_title'] ) ) { self::add( $post->ID, 'meta_title', __( 'New SEO title', 'aeoora' ), Aeoora_Seo::get_title( $post->ID ), sanitize_text_field( $data['meta_title'] ), '', $source ); $created++; } if ( ! empty( $data['intro'] ) && isset( $failed['answer_first'] ) ) { self::add( $post->ID, 'intro', __( 'Answer-first intro', 'aeoora' ), '', sanitize_textarea_field( $data['intro'] ), __( 'A 40–60 word opening that answers the main question.', 'aeoora' ), $source ); $created++; } if ( ! empty( $data['faq'] ) && is_array( $data['faq'] ) && ! Aeoora_Schema::get_faq( $post->ID ) ) { self::add( $post->ID, 'faq', __( 'FAQ section', 'aeoora' ), '', wp_json_encode( array_slice( $data['faq'], 0, 6 ) ), __( 'Adds visible questions and answers, plus FAQ structured data.', 'aeoora' ), $source ); $created++; } if ( ! empty( $data['fixes'] ) && is_array( $data['fixes'] ) ) { self::add( $post->ID, 'fixes', ! empty( $data['summary'] ) ? sanitize_text_field( $data['summary'] ) : __( 'AI editing suggestions', 'aeoora' ), '', wp_json_encode( array_slice( $data['fixes'], 0, 8 ) ), '', $source ); $created++; } return $created; } /** * Insert a suggestion (replacing an older pending one of the same type). * * @param int $post_id Post ID (0 = site-wide). * @param string $type Type. * @param string $title Title. * @param string $current Current value. * @param string $suggestion Suggestion. * @param string $rationale Rationale. * @param string $source Source. * @return int ID. */ public static function add( $post_id, $type, $title, $current, $suggestion, $rationale = '', $source = '' ) { global $wpdb; $table = self::table(); if ( $post_id ) { $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE post_id = %d AND type = %s AND status = 'pending'", $table, $post_id, $type ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. } $now = Aeoora_Util::now(); delete_transient( 'aeoora_pending' ); $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery $table, array( 'post_id' => (int) $post_id, 'type' => sanitize_key( $type ), 'status' => 'pending', 'title' => (string) $title, 'current' => (string) $current, 'suggestion' => (string) $suggestion, 'rationale' => (string) $rationale, 'source' => substr( (string) $source, 0, 64 ), 'created_at' => $now, 'updated_at' => $now, ), array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ); return (int) $wpdb->insert_id; } /** * List suggestions. * * @param array $args status, post_id, limit, offset. * @return array */ public static function query( array $args = array() ) { global $wpdb; $table = self::table(); // An empty filter matches everything: status '', post -1, author 0. $status = ! empty( $args['status'] ) ? sanitize_key( $args['status'] ) : ''; $post = isset( $args['post_id'] ) && '' !== $args['post_id'] && null !== $args['post_id'] ? (int) $args['post_id'] : -1; $author = ! empty( $args['author'] ) ? (int) $args['author'] : 0; // Site-wide ideas, plus suggestions for this author's own posts. $limit = isset( $args['limit'] ) ? max( 1, min( 200, (int) $args['limit'] ) ) : 50; $offset = isset( $args['offset'] ) ? max( 0, (int) $args['offset'] ) : 0; $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE ( %s = '' OR status = %s ) AND ( %d = -1 OR post_id = %d ) AND ( %d = 0 OR post_id = 0 OR post_id IN ( SELECT ID FROM %i WHERE post_author = %d ) ) ORDER BY created_at DESC, id DESC LIMIT %d OFFSET %d", $table, $status, $status, $post, $post, $author, $wpdb->posts, $author, $limit, $offset ), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. foreach ( $rows as &$r ) { $r['post_title'] = $r['post_id'] ? get_the_title( (int) $r['post_id'] ) : ''; $r['edit_url'] = $r['post_id'] ? get_edit_post_link( (int) $r['post_id'], 'raw' ) : ''; $r['view_url'] = $r['post_id'] ? get_permalink( (int) $r['post_id'] ) : ''; $r['score'] = $r['post_id'] ? get_post_meta( (int) $r['post_id'], '_aeoora_score', true ) : ''; $decoded = json_decode( (string) $r['suggestion'], true ); $r['data'] = is_array( $decoded ) ? $decoded : null; } return $rows; } /** * Pending count (optionally for one post, or for one author's posts). * * @param int|null $post_id Post. * @param int $author Count only this author's posts and site-wide ideas. * @return int */ public static function pending_count( $post_id = null, $author = 0 ) { global $wpdb; $table = self::table(); if ( null === $post_id && $author ) { return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE status = 'pending' AND ( post_id = 0 OR post_id IN ( SELECT ID FROM %i WHERE post_author = %d ) )", $table, $wpdb->posts, $author ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. } if ( null === $post_id ) { $cached = get_transient( 'aeoora_pending' ); if ( false !== $cached ) { return (int) $cached; } $n = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE status = 'pending'", $table ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. set_transient( 'aeoora_pending', $n, 10 * MINUTE_IN_SECONDS ); return $n; } return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE status = 'pending' AND post_id = %d", $table, $post_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. } /** * Any suggestion of a type in the last N days? * * @param string $type Type. * @param int $days Days. * @return bool */ private static function has_recent( $type, $days ) { global $wpdb; $table = self::table(); return (bool) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM %i WHERE type = %s AND created_at > %s LIMIT 1", $table, $type, gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. } /** * Get one. * * @param int $id ID. * @return array|null */ public static function get( $id ) { global $wpdb; $table = self::table(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE id = %d", $table, $id ), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. return $row ? $row : null; } /** * Set status. * * @param int $id ID. * @param string $status Status. */ public static function set_status( $id, $status ) { global $wpdb; delete_transient( 'aeoora_pending' ); $wpdb->update( self::table(), array( 'status' => $status, 'updated_at' => Aeoora_Util::now() ), array( 'id' => (int) $id ), array( '%s', '%s' ), array( '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } /** * Apply a suggestion. * * @param int $id ID. * @param string|null $override Edited value from the UI. * @return true|WP_Error */ public static function apply( $id, $override = null ) { $row = self::get( $id ); if ( ! $row ) { return new WP_Error( 'aeoora_not_found', __( 'Suggestion not found.', 'aeoora' ) ); } $post_id = (int) $row['post_id']; if ( $post_id && ! current_user_can( 'edit_post', $post_id ) && ! wp_doing_cron() ) { return new WP_Error( 'aeoora_forbidden', __( 'You cannot edit this post.', 'aeoora' ) ); } $value = null !== $override ? (string) $override : (string) $row['suggestion']; if ( in_array( $row['type'], array( 'meta_description', 'meta_title' ), true ) && ! Aeoora_Seo::can_write() ) { return new WP_Error( 'aeoora_seo_readonly', /* translators: %s: SEO plugin name. */ sprintf( __( '%s manages titles and descriptions on this site: copy the text into its fields.', 'aeoora' ), Aeoora_Seo::active_label() ) ); } switch ( $row['type'] ) { case 'meta_description': Aeoora_Seo::set_description( $post_id, $value ); break; case 'meta_title': Aeoora_Seo::set_title( $post_id, $value ); break; case 'faq': $items = json_decode( $value, true ); if ( ! is_array( $items ) ) { return new WP_Error( 'aeoora_bad_value', __( 'Invalid FAQ data.', 'aeoora' ) ); } Aeoora_Schema::set_faq( $post_id, array_merge( Aeoora_Schema::get_faq( $post_id ), $items ) ); break; case 'tldr': update_post_meta( $post_id, '_aeoora_tldr', sanitize_textarea_field( $value ) ); break; case 'intro': $r = self::insert_intro( $post_id, sanitize_textarea_field( $value ) ); if ( is_wp_error( $r ) ) { return $r; } break; default: // Checklists, AI fix lists and ideas are informational: mark done. break; } self::set_status( $id, 'applied' ); if ( $post_id ) { Aeoora_Markdown::flush_post( $post_id ); Aeoora_Audit::score_post( $post_id, 'content' ); } return true; } /** * Insert an intro paragraph at the top of the post content. * * @param int $post_id Post ID. * @param string $intro Text. * @return true|WP_Error */ private static function insert_intro( $post_id, $intro ) { $post = get_post( $post_id ); if ( ! $post || '' === $intro ) { return new WP_Error( 'aeoora_bad_value', __( 'Nothing to insert.', 'aeoora' ) ); } if ( Aeoora_Content::builder( $post_id ) ) { return new WP_Error( 'aeoora_builder', __( 'This page is built with a page builder: copy the intro into it manually.', 'aeoora' ) ); } $p = '
' . esc_html( $intro ) . '
'; $content = has_blocks( $post->post_content ) ? "\n" . $p . "\n\n\n" . $post->post_content : $p . "\n\n" . $post->post_content; $r = wp_update_post( array( 'ID' => $post_id, 'post_content' => $content, ), true ); return is_wp_error( $r ) ? $r : true; } }