0 ) { return $uid; } $fallback = (int) $fallback_user_id; if ( $fallback > 0 ) { return $fallback; } // Last resort: any administrator with AI configured. Scans the first // 20 admins to avoid a full table scan on large sites. return desktop_mode_ai_find_enabled_user(); } /** * Returns the first administrator user ID that has AI features enabled. * * Used as a last-resort fallback for anonymous comments, WP-CLI imports, * and other contexts where no user session is available. * * @since 0.14.0 * * @return int User ID, or 0 if none found. */ function desktop_mode_ai_find_enabled_user() { $admin_ids = get_users( array( 'role' => 'administrator', 'number' => 20, 'fields' => 'ID', ) ); foreach ( $admin_ids as $uid ) { if ( desktop_mode_ai_is_enabled( (int) $uid ) ) { return (int) $uid; } } return 0; } // --------------------------------------------------------------------------- // Comments // --------------------------------------------------------------------------- /** * Shared handler for new and edited comments. * * @since 0.14.0 * * @param int $comment_id The comment ID. */ function desktop_mode_ai_on_comment_change( $comment_id ) { $comment = get_comment( $comment_id ); if ( ! $comment instanceof WP_Comment ) { return; } // Skip pingbacks and trackbacks — only analyze real human comments. if ( '' !== $comment->comment_type && 'comment' !== $comment->comment_type ) { return; } // Resolve the user: comment author user_id if logged-in, otherwise // fall back to any admin who has AI configured. We use the comment's // own user_id first since the commenter may have AI enabled; then // fall back to current_user (moderator context), then to 0 (rejected). $user_id = (int) $comment->user_id; if ( $user_id <= 0 ) { $user_id = desktop_mode_ai_resolve_user_id(); } if ( $user_id <= 0 ) { return; } if ( ! desktop_mode_ai_is_enabled( $user_id ) ) { return; } desktop_mode_ai_schedule_job( 'desktop_mode_ai_analyze_comment', array( $comment_id, $user_id ), 'comment_' . $comment_id ); } // `wp_insert_comment` fires after a new comment is inserted into the DB. add_action( 'wp_insert_comment', 'desktop_mode_ai_on_comment_change', 20, 1 ); // `edit_comment` fires after an existing comment is updated. add_action( 'edit_comment', 'desktop_mode_ai_on_comment_change', 20, 1 );