[ done|skip, time ].
/** User agents of AI crawlers and assistants: pattern => name shown. */
const AI_BOTS = array(
'GPTBot' => 'ChatGPT',
'ChatGPT-User' => 'ChatGPT',
'OAI-SearchBot' => 'ChatGPT',
'ClaudeBot' => 'Claude',
'Claude-User' => 'Claude',
'Claude-SearchBot' => 'Claude',
'anthropic-ai' => 'Claude',
'PerplexityBot' => 'Perplexity',
'Perplexity-User' => 'Perplexity',
'Google-CloudVertexBot' => 'Gemini',
'Gemini-Deep-Research' => 'Gemini',
'meta-externalagent' => 'Meta AI',
'meta-externalfetcher' => 'Meta AI',
'Applebot' => 'Apple',
'Amazonbot' => 'Amazon',
'DuckAssistBot' => 'DuckDuckGo',
'MistralAI-User' => 'Mistral',
'cohere-ai' => 'Cohere',
'Bytespider' => 'ByteDance',
'CCBot' => 'Common Crawl',
'YouBot' => 'You.com',
);
/** Crawlers that matter for AI answers; robots.txt blocking them hides you from those answers. */
const AI_ROBOTS = array( 'GPTBot', 'OAI-SearchBot', 'ChatGPT-User', 'ClaudeBot', 'Claude-SearchBot', 'PerplexityBot', 'Google-Extended', 'Applebot-Extended' );
const STATS = 'nodebook_content_stats';
public static function init() {
add_action( 'template_redirect', array( __CLASS__, 'observe' ), 1 );
add_action( Nodebook_Cron::HOOK, array( __CLASS__, 'daily' ), 20 );
// The content checks are cached; editing posts, pages or images makes them fresh again.
add_action( 'save_post', array( __CLASS__, 'content_changed' ), 10, 2 );
add_action( 'deleted_post', array( __CLASS__, 'content_changed' ), 10, 2 );
foreach ( array( 'added_post_meta', 'updated_post_meta', 'deleted_post_meta' ) as $hook ) {
add_action( $hook, array( __CLASS__, 'meta_changed' ), 10, 3 );
}
}
/**
* Forget the cached content checks when a post, page or image changes.
*
* @param int $post_id Post ID.
* @param WP_Post|null $post Post.
*/
public static function content_changed( $post_id, $post = null ) {
$type = $post instanceof WP_Post ? $post->post_type : get_post_type( $post_id );
if ( in_array( $type, array( 'post', 'page', 'attachment' ), true ) ) {
delete_transient( self::STATS );
}
}
/**
* Forget the cached content checks when a featured image or alt text changes.
*
* @param int|int[] $meta_id Meta ID(s).
* @param int $post_id Post ID.
* @param string $meta_key Meta key.
*/
public static function meta_changed( $meta_id, $post_id, $meta_key ) {
if ( in_array( $meta_key, array( '_thumbnail_id', '_wp_attachment_image_alt' ), true ) ) {
delete_transient( self::STATS );
}
}
public static function on() {
return (bool) Nodebook_Settings::get( 'node_growth' ) && ! Nodebook_Crm_Only::on();
}
/* ------------------------------------------------------------------ *
* Watching: AI crawlers and missing pages
* ------------------------------------------------------------------ */
/** Which AI is this user agent? '' if none. */
public static function ai_bot( $ua ) {
foreach ( self::AI_BOTS as $needle => $name ) {
if ( false !== stripos( (string) $ua, $needle ) ) {
return $name;
}
}
return '';
}
/** Front-end requests: note AI crawler visits and pages people could not find. */
public static function observe() {
if ( is_admin() || wp_doing_ajax() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
return;
}
$ua = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
$path = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_parse_url( sanitize_url( wp_unslash( $_SERVER['REQUEST_URI'] ) ), PHP_URL_PATH ) : '/';
$path = '' === $path ? '/' : $path;
$bot = self::ai_bot( $ua );
if ( $bot ) {
self::record( 'aibot', $bot, $path, 'Nodebook-AI:' . $bot . ':' . $path );
return;
}
if ( is_404() && '' !== $ua && ! preg_match( '/bot|crawl|spider|slurp|curl|wget|python|scan|http|java|go-http|headless/i', $ua ) && ! self::noise( $path ) ) {
self::record( 'notfound', '', $path, 'Nodebook-404:' . $path );
}
}
/** Paths scanners try (.env, wp-config, …): not people looking for a page. */
private static function noise( $path ) {
return (bool) preg_match( '#(\.php|\.env|\.git|\.sql|\.bak|\.zip|xmlrpc|/wp-(admin|includes|content)/|/cgi-bin|/\.well-known/|favicon|apple-touch-icon|\.map$)#i', $path );
}
/** One row per bot (or 404 path) per path per hour, so a busy crawler does not flood the table. */
private static function record( $type, $who, $path, $lock ) {
$key = 'nodebook_g_' . md5( $lock );
if ( get_transient( $key ) ) {
return;
}
set_transient( $key, 1, HOUR_IN_SECONDS );
Nodebook_Activities::add(
0,
$type,
'' !== $who ? $who : $path,
array(
'url' => home_url( $path ),
'visitor_id' => '' !== $who ? sanitize_key( $who ) : '',
'user_id' => 0,
)
);
}
/**
* AI crawler visits in the last N days.
*
* @return array total, bots (name => count), pages (path => count), last (GMT)
*/
public static function ai_visits( $days = 30 ) {
global $wpdb;
$a = Nodebook_Activities::table();
$since = gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS );
$rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT title, url, created_at FROM %i WHERE type = 'aibot' AND contact_id = 0 AND created_at >= %s ORDER BY id DESC LIMIT 5000", $a, $since ), ARRAY_A );
$bots = array();
$pages = array();
foreach ( $rows as $r ) {
$bots[ $r['title'] ] = ( $bots[ $r['title'] ] ?? 0 ) + 1;
$p = Nodebook_Report::path( $r['url'] );
$pages[ $p ] = ( $pages[ $p ] ?? 0 ) + 1;
}
arsort( $bots );
arsort( $pages );
return array(
'total' => count( $rows ),
'bots' => $bots,
'pages' => array_slice( $pages, 0, 8, true ),
'last' => $rows ? $rows[0]['created_at'] : '',
);
}
/** Pages people asked for that do not exist, last N days: path => count. */
public static function missing( $days = 30 ) {
global $wpdb;
$rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT title AS path, COUNT(*) AS n FROM %i WHERE type = 'notfound' AND contact_id = 0 AND created_at >= %s GROUP BY title ORDER BY n DESC LIMIT 10", Nodebook_Activities::table(), gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ) ), ARRAY_A );
$out = array();
foreach ( $rows as $r ) {
$out[ $r['path'] ] = (int) $r['n'];
}
// Redirection plugin keeps its own 404 log: use it when it has more.
if ( self::table_exists( 'redirection_404' ) ) {
$rp = (array) $wpdb->get_results( $wpdb->prepare( 'SELECT url AS path, COUNT(*) AS n FROM %i WHERE created >= %s GROUP BY url ORDER BY n DESC LIMIT 10', $wpdb->prefix . 'redirection_404', gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ) ), ARRAY_A );
foreach ( $rp as $r ) {
if ( ! self::noise( (string) $r['path'] ) ) {
$out[ $r['path'] ] = max( $out[ $r['path'] ] ?? 0, (int) $r['n'] );
}
}
arsort( $out );
}
return array_slice( $out, 0, 10, true );
}
private static function table_exists( $name ) {
global $wpdb;
static $cache = array();
if ( ! isset( $cache[ $name ] ) ) {
// Ask the table itself (works on MySQL, MariaDB and SQLite); a missing table is not an error worth logging.
$quiet = $wpdb->suppress_errors( true );
$wpdb->get_var( $wpdb->prepare( 'SELECT 1 FROM %i LIMIT 1', $wpdb->prefix . $name ) );
$cache[ $name ] = '' === (string) $wpdb->last_error;
$wpdb->suppress_errors( $quiet );
}
return $cache[ $name ];
}
/* ------------------------------------------------------------------ *
* Looking at the site from outside
* ------------------------------------------------------------------ */
public static function daily() {
if ( self::on() ) {
self::probe();
}
}
/** Last look at the site, or an empty result. */
public static function last_probe() {
$p = get_option( self::PROBE );
return is_array( $p ) ? $p : array( 'time' => 0 );
}
public static function stale() {
$p = self::last_probe();
return empty( $p['time'] ) || $p['time'] < time() - 12 * HOUR_IN_SECONDS;
}
private static function fetch( $url ) {
$r = wp_remote_get(
$url,
array(
'timeout' => 8,
'redirection' => 3,
'sslverify' => apply_filters( 'https_local_ssl_verify', false ), // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress core filter for loopback requests.
'user-agent' => 'Mozilla/5.0 (compatible; Nodebook-Check/1.0; +' . home_url( '/' ) . ')',
'headers' => array( 'Cache-Control' => 'no-cache' ),
)
);
if ( is_wp_error( $r ) ) {
return null;
}
return array(
'code' => (int) wp_remote_retrieve_response_code( $r ),
'type' => (string) wp_remote_retrieve_header( $r, 'content-type' ),
'body' => (string) wp_remote_retrieve_body( $r ),
);
}
/** Read the tags on a page that matter for search, sharing and AI. */
public static function read_page( $html ) {
$out = array(
'title' => '',
'description' => '',
'og_image' => false,
'canonical' => false,
'noindex' => false,
'viewport' => false,
'schema' => array(),
'analytics' => false,
'gtm' => false,
'meta_pixel' => false,
'gsc_meta' => false,
'h1' => 0,
);
if ( preg_match( '#
]*>(.*?)#is', $html, $m ) ) {
$out['title'] = trim( html_entity_decode( wp_strip_all_tags( $m[1] ), ENT_QUOTES ) );
}
if ( preg_match( '#]+name=["\']description["\'][^>]*content=["\']([^"\']*)#i', $html, $m ) || preg_match( '#]+content=["\']([^"\']*)["\'][^>]*name=["\']description["\']#i', $html, $m ) ) {
$out['description'] = trim( html_entity_decode( $m[1], ENT_QUOTES ) );
}
$out['og_image'] = (bool) preg_match( '#]+property=["\']og:image["\']#i', $html );
$out['canonical'] = (bool) preg_match( '#]+rel=["\']canonical["\']#i', $html );
$out['noindex'] = (bool) preg_match( '#]+name=["\']robots["\'][^>]*content=["\'][^"\']*noindex#i', $html );
$out['viewport'] = (bool) preg_match( '#]+name=["\']viewport["\']#i', $html );
$out['analytics'] = (bool) preg_match( '#googletagmanager\.com/gtag/js|gtag\(\s*["\']config["\']\s*,\s*["\']G-|google-analytics\.com/analytics\.js#i', $html );
$out['gtm'] = (bool) preg_match( '#googletagmanager\.com/gtm\.js|GTM-[A-Z0-9]{4,}#', $html );
$out['meta_pixel'] = (bool) preg_match( '#connect\.facebook\.net/[^"\']*/fbevents\.js|fbq\(\s*["\']init#i', $html );
$out['gsc_meta'] = (bool) preg_match( '#]+name=["\']google-site-verification["\']#i', $html );
$out['h1'] = (int) preg_match_all( '#]#i', $html );
if ( preg_match_all( '##is', $html, $all ) ) {
foreach ( $all[1] as $json ) {
$data = json_decode( trim( $json ), true );
if ( is_array( $data ) ) {
self::schema_types( $data, $out['schema'] );
}
}
$out['schema'] = array_values( array_unique( $out['schema'] ) );
}
return $out;
}
private static function schema_types( $node, array &$types, $depth = 0 ) {
if ( $depth > 6 || ! is_array( $node ) ) {
return;
}
if ( isset( $node['@type'] ) ) {
foreach ( (array) $node['@type'] as $t ) {
if ( is_string( $t ) ) {
$types[] = $t;
}
}
}
foreach ( $node as $v ) {
if ( is_array( $v ) ) {
self::schema_types( $v, $types, $depth + 1 );
}
}
}
/** Which AI crawlers robots.txt shuts out completely (Disallow: /). */
public static function blocked_bots( $robots ) {
$blocked = array();
$groups = array();
$agents = array();
$fresh = true;
foreach ( preg_split( '/\r\n|\r|\n/', (string) $robots ) as $line ) {
$line = trim( preg_replace( '/#.*$/', '', $line ) );
if ( '' === $line ) {
continue;
}
if ( preg_match( '/^user-agent\s*:\s*(.+)$/i', $line, $m ) ) {
if ( ! $fresh ) {
$agents = array();
}
$agents[] = strtolower( trim( $m[1] ) );
$fresh = true;
continue;
}
$fresh = false;
if ( preg_match( '/^disallow\s*:\s*(\S*)$/i', $line, $m ) && '/' === $m[1] ) {
foreach ( $agents as $a ) {
$groups[ $a ] = true;
}
}
}
foreach ( self::AI_ROBOTS as $bot ) {
if ( isset( $groups[ strtolower( $bot ) ] ) || isset( $groups['*'] ) ) {
$blocked[] = $bot;
}
}
return $blocked;
}
/** Look at the site from outside and keep what we saw. */
public static function probe() {
$home = home_url( '/' );
$res = array(
'time' => time(),
'ok' => false,
'pages' => array(),
'robots' => null,
'blocked' => array(),
'llms' => false,
'sitemap' => '',
);
$urls = array( 'home' => $home );
$post = get_posts(
array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'fields' => 'ids',
)
);
if ( $post ) {
$urls['post'] = get_permalink( $post[0] );
}
if ( post_type_exists( 'product' ) ) {
$prod = get_posts(
array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 1,
'fields' => 'ids',
)
);
if ( $prod ) {
$urls['product'] = get_permalink( $prod[0] );
}
}
foreach ( $urls as $k => $u ) {
$r = self::fetch( $u );
if ( $r && $r['code'] >= 200 && $r['code'] < 400 ) {
$res['ok'] = true;
$res['pages'][ $k ] = array_merge( array( 'url' => $u ), self::read_page( $r['body'] ) );
}
}
if ( $res['ok'] ) {
$r = self::fetch( home_url( '/robots.txt' ) );
if ( $r && 200 === $r['code'] ) {
$res['robots'] = substr( $r['body'], 0, 20000 );
$res['blocked'] = self::blocked_bots( $r['body'] );
if ( preg_match( '/^sitemap\s*:\s*(\S+)/im', $r['body'], $m ) ) {
$res['sitemap'] = esc_url_raw( $m[1] );
}
}
$r = self::fetch( home_url( '/llms.txt' ) );
$res['llms'] = $r && 200 === $r['code'] && false === stripos( $r['type'], 'html' ) && strlen( trim( $r['body'] ) ) > 20;
if ( '' === $res['sitemap'] ) {
foreach ( array( '/sitemap_index.xml', '/wp-sitemap.xml', '/sitemap.xml' ) as $p ) {
$r = self::fetch( home_url( $p ) );
if ( $r && 200 === $r['code'] && false !== stripos( $r['body'], ' array( __( 'Get found on Google', 'nodebook' ), 'search' ),
'ai' => array( __( 'Show up in AI answers', 'nodebook' ), 'smile' ),
'content' => array( __( 'Content', 'nodebook' ), 'file-text' ),
'sell' => self::sell_group(),
'reach' => array( __( 'Stay in touch', 'nodebook' ), 'mail' ),
'site' => array( __( 'Site basics', 'nodebook' ), 'shield' ),
);
}
private static function sell_group() {
$n = Nodebook_Niche::current();
if ( 'shop' === $n ) {
return array( __( 'Sell more', 'nodebook' ), 'target' );
}
if ( in_array( $n, array( 'rentals', 'services' ), true ) ) {
return array( __( 'Get more bookings', 'nodebook' ), 'calendar' );
}
return array( __( 'Win more customers', 'nodebook' ), 'target' );
}
public static function marks() {
$m = get_option( self::MARKS );
return is_array( $m ) ? $m : array();
}
public static function mark( $key, $how ) {
$m = self::marks();
if ( 'undo' === $how ) {
unset( $m[ $key ] );
} elseif ( in_array( $how, array( 'done', 'skip' ), true ) ) {
$m[ sanitize_key( $key ) ] = array( $how, time() );
}
update_option( self::MARKS, $m, false );
Nodebook_Node::flush();
}
private static function plugin_on( $file ) {
if ( in_array( $file, (array) get_option( 'active_plugins', array() ), true ) ) {
return true;
}
return is_multisite() && isset( ( (array) get_site_option( 'active_sitewide_plugins', array() ) )[ $file ] );
}
private static function install_url( $slug ) {
return admin_url( 'plugin-install.php?tab=plugin-information&plugin=' . rawurlencode( $slug ) . '&TB_iframe=true' );
}
private static function search_install( $term ) {
return admin_url( 'plugin-install.php?s=' . rawurlencode( $term ) . '&tab=search&type=term' );
}
/** Which SEO plugin is in charge, if any: [ name, settings url ]. */
public static function seo_plugin() {
if ( defined( 'WPSEO_VERSION' ) ) {
return array( 'Yoast SEO', admin_url( 'admin.php?page=wpseo_dashboard' ) );
}
if ( class_exists( 'RankMath' ) || defined( 'RANK_MATH_VERSION' ) ) {
return array( 'Rank Math', admin_url( 'admin.php?page=rank-math' ) );
}
if ( defined( 'AIOSEO_VERSION' ) || function_exists( 'aioseo' ) ) {
return array( 'All in One SEO', admin_url( 'admin.php?page=aioseo' ) );
}
if ( defined( 'SEOPRESS_VERSION' ) ) {
return array( 'SEOPress', admin_url( 'admin.php?page=seopress-option' ) );
}
if ( defined( 'THE_SEO_FRAMEWORK_VERSION' ) ) {
return array( 'The SEO Framework', admin_url( 'admin.php?page=theseoframework-settings' ) );
}
return null;
}
private static function opt( $name, $key ) {
$o = get_option( $name );
return is_array( $o ) && isset( $o[ $key ] ) ? $o[ $key ] : null;
}
/** Search Console looks connected: Site Kit property, Rank Math analytics, or a verification tag on the home page. */
private static function search_console( array $home ) {
if ( '' !== (string) self::opt( 'googlesitekit_search-console_settings', 'propertyID' ) ) {
return 'Site Kit';
}
if ( get_option( 'rank_math_google_analytic_profile' ) ) {
return 'Rank Math';
}
if ( ! empty( $home['gsc_meta'] ) ) {
return __( 'verification tag', 'nodebook' );
}
if ( '' !== (string) self::opt( 'wpseo', 'googleverify' ) ) {
return 'Yoast SEO';
}
return '';
}
/** Posts and pages: counts and the newest date. */
private static function content_stats() {
global $wpdb;
$cached = get_transient( self::STATS );
if ( is_array( $cached ) ) {
return $cached;
}
$p = $wpdb->posts;
$stats = array(
'posts' => (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE post_type = 'post' AND post_status = 'publish'", $p ) ),
'last_post' => (string) $wpdb->get_var( $wpdb->prepare( "SELECT MAX(post_date_gmt) FROM %i WHERE post_type = 'post' AND post_status = 'publish'", $p ) ),
'no_image' => (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i p LEFT JOIN %i m ON m.post_id = p.ID AND m.meta_key = '_thumbnail_id' WHERE p.post_type = 'post' AND p.post_status = 'publish' AND m.meta_id IS NULL", $p, $wpdb->postmeta ) ),
'thin' => self::thin_pages(),
'alt_empty' => (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i a LEFT JOIN %i m ON m.post_id = a.ID AND m.meta_key = '_wp_attachment_image_alt' WHERE a.post_type = 'attachment' AND a.post_mime_type LIKE %s AND a.post_parent > 0 AND ( m.meta_value IS NULL OR m.meta_value = '' )", $p, $wpdb->postmeta, 'image/%' ) ),
);
set_transient( self::STATS, $stats, 6 * HOUR_IN_SECONDS );
return $stats;
}
/**
* Published pages and posts with fewer than ~120 words of their own text. Pages that a plugin fills in
* (shortcodes, shop and account pages, plugin blocks) are left out: their text is not in the editor.
*
* @return array[] ID, post_title, post_type
*/
public static function thin_pages() {
global $wpdb;
$skip = array( (int) get_option( 'wp_page_for_privacy_policy' ), (int) get_option( 'page_for_posts' ) );
if ( function_exists( 'wc_get_page_id' ) ) {
foreach ( array( 'shop', 'cart', 'checkout', 'myaccount', 'terms' ) as $wc ) {
$skip[] = (int) wc_get_page_id( $wc );
}
}
$rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title, post_type, post_content FROM %i WHERE post_type IN ('page','post') AND post_status = 'publish' AND CHAR_LENGTH(post_content) < 4000 ORDER BY post_type = 'page' DESC, menu_order ASC, ID ASC LIMIT 200", $wpdb->posts ), ARRAY_A );
$out = array();
foreach ( $rows as $r ) {
$html = (string) $r['post_content'];
if ( in_array( (int) $r['ID'], $skip, true ) || preg_match( '/\[[a-z][a-z0-9_-]*[\s\]]/i', $html ) || preg_match( '#