roles, array_merge( (array) Nodebook_Settings::get( 'exclude_roles' ), array( Nodebook_Team::ROLE ) ) ); } public static function enqueue() { $attribution = (bool) Nodebook_Settings::get( 'attribution' ); $forms = Nodebook_Anyform::enabled(); if ( ( 'off' === self::mode() && ! $attribution && ! $forms ) || self::excluded_user() || is_customize_preview() ) { return; } $min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min'; wp_register_script( 'nodebook-tracker', NODEBOOK_URL . "assets/js/tracker{$min}.js", array(), NODEBOOK_VERSION, array( 'in_footer' => true, 'strategy' => 'defer', ) ); $item = 0; if ( is_singular() && ! is_front_page() ) { $qid = (int) get_queried_object_id(); if ( $qid && Nodebook_Interests::is_item( $qid ) ) { $item = $qid; } } $cfg = array( 'endpoint' => esc_url_raw( rest_url( 'nodebook/v1/hit' ) ), 'item' => $item, 'clicks' => (bool) Nodebook_Settings::get( 'clicks' ), 'forms' => $forms, 'mode' => self::mode(), 'consent' => (bool) Nodebook_Settings::get( 'require_consent' ), 'cookie' => self::COOKIE, 'src' => $attribution ? Nodebook_Attribution::COOKIE : '', 'secure' => is_ssl(), ); wp_add_inline_script( 'nodebook-tracker', 'window.nodebookTracker=' . wp_json_encode( $cfg ) . ';', 'before' ); wp_enqueue_script( 'nodebook-tracker' ); } public static function routes() { register_rest_route( 'nodebook/v1', '/hit', array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'hit' ), // Public by design: anonymous visitors report their own page views. Input is validated and // writes are limited to known visitor IDs (mode "known") and rate-limited per visitor. 'permission_callback' => '__return_true', ) ); } private static function is_bot() { $ua = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : ''; return '' === $ua || (bool) preg_match( '/bot|crawl|spider|slurp|facebookexternalhit|preview|headless|lighthouse|pingdom|uptime|monitor|curl|wget|python|java\//i', $ua ); } /** * Sanitize a decoded hit: addresses as URLs, everything else as plain text (form fields included). * * @param mixed $body Decoded JSON. * @return array|null */ public static function clean_body( $body ) { if ( ! is_array( $body ) ) { return null; } $out = array(); foreach ( $body as $k => $v ) { $k = sanitize_key( (string) $k ); if ( is_array( $v ) ) { $out[ $k ] = map_deep( $v, static function ( $x ) { return is_scalar( $x ) ? sanitize_text_field( (string) $x ) : ''; } ); } elseif ( is_scalar( $v ) ) { $out[ $k ] = in_array( $k, array( 'u', 'r', 'h' ), true ) ? sanitize_url( (string) $v ) : sanitize_text_field( (string) $v ); } } return $out; } /** * Beacon endpoint. Body (text/plain JSON): { v: visitorId, u: url, t: title, r: referrer }. */ public static function hit( WP_REST_Request $request ) { $mode = self::mode(); $body = self::clean_body( json_decode( (string) $request->get_body(), true ) ); if ( is_array( $body ) && ! empty( $body['ping'] ) ) { // Health check from Settings: proves the endpoint is reachable through caches, firewalls and security plugins. return new WP_REST_Response( array( 'nodebook' => NODEBOOK_VERSION ), 200 ); } if ( is_array( $body ) && isset( $body['e'] ) && 'form' === $body['e'] ) { // "Any other form" works in every tracking mode: the visitor typed and sent the data themselves. if ( ! self::is_bot() && ! self::excluded_user() ) { Nodebook_Anyform::handle( $body ); } return new WP_REST_Response( null, 204 ); } if ( 'off' === $mode || ! is_array( $body ) || self::is_bot() || self::excluded_user() ) { return new WP_REST_Response( null, 204 ); } $vid = isset( $body['v'] ) ? (string) $body['v'] : ''; $url = isset( $body['u'] ) ? esc_url_raw( (string) $body['u'] ) : ''; if ( ! self::valid_id( $vid ) || ! $url ) { return new WP_REST_Response( null, 204 ); } if ( wp_parse_url( $url, PHP_URL_HOST ) !== wp_parse_url( home_url(), PHP_URL_HOST ) ) { return new WP_REST_Response( null, 204 ); } if ( Nodebook_Settings::get( 'require_consent' ) && empty( $body['c'] ) ) { return new WP_REST_Response( null, 204 ); } $item = isset( $body['o'] ) ? absint( $body['o'] ) : 0; if ( $item ) { if ( ! Nodebook_Interests::is_item( $item ) ) { $item = 0; } } if ( isset( $body['e'] ) && 'click' === $body['e'] ) { if ( Nodebook_Settings::get( 'clicks' ) ) { self::record_click( $vid, $url, isset( $body['k'] ) ? (string) $body['k'] : '', isset( $body['h'] ) ? (string) $body['h'] : '', isset( $body['x'] ) ? (string) $body['x'] : '', $item ); } return new WP_REST_Response( null, 204 ); } self::record( $vid, $url, isset( $body['t'] ) ? (string) $body['t'] : '', isset( $body['r'] ) ? (string) $body['r'] : '', $item ); return new WP_REST_Response( null, 204 ); } /** * Store a page view (and a visit when a new session starts). */ public static function record( $vid, $url, $title = '', $referrer = '', $item = 0 ) { global $wpdb; $vt = Nodebook_Install::table( 'visitors' ); $now = time(); $now_sql = gmdate( 'Y-m-d H:i:s', $now ); $visitor = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE visitor_id = %s', $vt, $vid ), ARRAY_A ); // No logged-in identity yet? Attach the visitor to the user's contact if there is one. if ( ( ! $visitor || ! (int) $visitor['contact_id'] ) && is_user_logged_in() ) { $c = Nodebook_Contacts::find_by_user( get_current_user_id() ); if ( $c ) { self::link( $vid, $c['id'] ); $visitor = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE visitor_id = %s', $vt, $vid ), ARRAY_A ); } } if ( 'known' === self::mode() && ( ! $visitor || ! (int) $visitor['contact_id'] ) ) { return false; } $path = wp_parse_url( $url, PHP_URL_PATH ); $path = ( $path ? $path : '/' ) . ( wp_parse_url( $url, PHP_URL_QUERY ) ? '?' . wp_parse_url( $url, PHP_URL_QUERY ) : '' ); if ( $visitor ) { $last = strtotime( $visitor['last_seen'] . ' UTC' ); // Drop reloads / double beacons of the same page within 10 seconds. if ( $now - $last < 10 && (string) $visitor['last_url'] === $url ) { return false; } $new_visit = ( $now - $last ) > self::SESSION_GAP; $wpdb->update( $vt, array( 'last_seen' => $now_sql, 'last_url' => $url, ), array( 'visitor_id' => $vid ) ); $contact_id = (int) $visitor['contact_id']; } else { $new_visit = true; $wpdb->insert( $vt, array( 'visitor_id' => $vid, 'contact_id' => 0, 'last_url' => $url, 'created_at' => $now_sql, 'last_seen' => $now_sql, ) ); $contact_id = 0; } $ref_host = $referrer ? wp_parse_url( $referrer, PHP_URL_HOST ) : ''; $external = $ref_host && wp_parse_url( home_url(), PHP_URL_HOST ) !== $ref_host; $intent = Nodebook_Alerts::is_intent( $url ) && ! Nodebook_Alerts::is_after_conversion( $url, $title ); if ( $new_visit ) { $src = Nodebook_Attribution::classify( array( 'r' => $external ? $referrer : '', 'l' => $path, ) ); Nodebook_Activities::add( $contact_id, 'visit', '(direct)' !== $src['source'] /* translators: %s: traffic source, e.g. "Google ยท search" */ ? sprintf( __( 'Visited the website from %s', 'nodebook' ), Nodebook_Attribution::label( $src['source'], $src['medium'] ) ) : __( 'Visited the website', 'nodebook' ), array( 'visitor_id' => $vid, 'url' => $url, 'user_id' => 0, 'created_at' => $now_sql, 'data' => array( 'referrer' => $external ? esc_url_raw( $referrer ) : '', 'landing' => $path, 'source' => $src['source'], 'medium' => $src['medium'], 'campaign' => $src['campaign'], ), ) ); } $pv_data = array( 'path' => $path ); if ( $intent ) { $pv_data['intent'] = true; } $dates = Nodebook_Interests::dates_from_url( $url ); if ( $dates ) { $pv_data['dates'] = $dates; } Nodebook_Activities::add( $contact_id, 'pageview', $title ? wp_strip_all_tags( $title ) : $path, array( 'visitor_id' => $vid, 'object_id' => absint( $item ), 'url' => $url, 'user_id' => 0, 'created_at' => $now_sql, 'data' => $pv_data, ) ); if ( $contact_id ) { global $wpdb; $ct = Nodebook_Contacts::table(); if ( $new_visit ) { $wpdb->query( $wpdb->prepare( 'UPDATE %i SET visits_count = visits_count + 1, last_seen = %s, first_seen = IFNULL(first_seen, %s) WHERE id = %d', $ct, $now_sql, $now_sql, $contact_id ) ); } else { $wpdb->query( $wpdb->prepare( 'UPDATE %i SET last_seen = %s, first_seen = IFNULL(first_seen, %s) WHERE id = %d', $ct, $now_sql, $now_sql, $contact_id ) ); } if ( $intent ) { $wpdb->update( $ct, array( 'last_intent_at' => $now_sql ), array( 'id' => $contact_id ) ); } do_action( 'nodebook_contact_visit', $contact_id, $url, $new_visit ); Nodebook_Alerts::on_pageview( $contact_id, $url, $title, $new_visit, $intent ); } return true; } /** Click kinds: label, and whether they signal buying intent. */ public static function click_kinds() { return apply_filters( 'nodebook_click_kinds', array( 'call' => array( __( 'Tapped to call', 'nodebook' ), true ), 'whatsapp' => array( __( 'Opened WhatsApp', 'nodebook' ), true ), 'email' => array( __( 'Clicked an email address', 'nodebook' ), false ), 'booking' => array( __( 'Clicked a booking link', 'nodebook' ), true ), 'directions' => array( __( 'Asked for directions', 'nodebook' ), true ), 'download' => array( __( 'Downloaded', 'nodebook' ), 'b2b' === Nodebook_Niche::current() ), ) ); } /** * Store a click signal (known visitors; anonymous too in "track everyone" mode). */ public static function record_click( $vid, $url, $kind, $href, $text = '', $item = 0 ) { global $wpdb; $kinds = self::click_kinds(); $kind = sanitize_key( $kind ); if ( ! isset( $kinds[ $kind ] ) ) { return false; } $vt = Nodebook_Install::table( 'visitors' ); $visitor = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE visitor_id = %s', $vt, $vid ), ARRAY_A ); $cid = $visitor ? (int) $visitor['contact_id'] : 0; if ( ! $cid && 'all' !== self::mode() ) { return false; } $href = mb_substr( sanitize_text_field( $href ), 0, 255 ); $text = mb_substr( sanitize_text_field( $text ), 0, 80 ); $label = $kinds[ $kind ][0]; if ( 'download' === $kind ) { $file = basename( (string) wp_parse_url( $href, PHP_URL_PATH ) ); $label = sprintf( '%s %s', $label, $file ? $file : $text ); } elseif ( 'booking' === $kind ) { $host = (string) wp_parse_url( $href, PHP_URL_HOST ); $label = $host ? sprintf( '%s (%s)', $label, preg_replace( '/^www\./', '', $host ) ) : $label; } if ( $item ) { /* translators: 1: action, 2: item title */ $label = sprintf( __( '%1$s on %2$s', 'nodebook' ), $label, get_the_title( $item ) ); } // Ignore double clicks: same kind and target within 30 seconds. $recent = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE visitor_id = %s AND type = 'click' AND title = %s AND created_at >= %s", Nodebook_Activities::table(), $vid, mb_substr( $label, 0, 255 ), gmdate( 'Y-m-d H:i:s', time() - 30 ) ) ); if ( (int) $recent ) { return false; } $intent = (bool) $kinds[ $kind ][1]; Nodebook_Activities::add( $cid, 'click', $label, array( 'visitor_id' => $vid, 'object_id' => absint( $item ), 'url' => $url, 'user_id' => 0, 'data' => array( 'kind' => $kind, 'target' => $href, 'text' => $text, 'intent' => $intent, ), ) ); if ( $cid ) { $now = current_time( 'mysql', true ); $wpdb->update( Nodebook_Contacts::table(), array_merge( array( 'last_seen' => $now ), $intent ? array( 'last_intent_at' => $now ) : array() ), array( 'id' => $cid ) ); if ( $intent ) { Nodebook_Alerts::on_pageview( $cid, $url, $label, false, true, $label ); } } return true; } /** * Attach a visitor ID to a contact and claim its anonymous history. */ public static function link( $vid, $contact_id ) { global $wpdb; if ( ! self::valid_id( $vid ) || ! $contact_id ) { return; } $vt = Nodebook_Install::table( 'visitors' ); $now = current_time( 'mysql', true ); // A freshly linked visitor gets an old last_seen so their next page view opens a visit. $wpdb->query( $wpdb->prepare( 'INSERT INTO %i (visitor_id, contact_id, created_at, last_seen) VALUES (%s, %d, %s, %s) ON DUPLICATE KEY UPDATE contact_id = VALUES(contact_id)', $vt, $vid, $contact_id, $now, '1970-01-01 00:00:01' ) ); $claimed = $wpdb->query( $wpdb->prepare( 'UPDATE %i SET contact_id = %d WHERE visitor_id = %s AND contact_id = 0', Nodebook_Activities::table(), $contact_id, $vid ) ); if ( $claimed ) { Nodebook_Contacts::recount_visits( $contact_id ); } Nodebook_Attribution::apply( $contact_id ); } /** * Called whenever a person identifies (form, order, registration, login). * Links the existing cookie, or sets one so their next visits are recognised. */ public static function identify( $contact_id ) { if ( 'off' === self::mode() || ! self::has_consent() ) { if ( self::has_consent() ) { Nodebook_Attribution::apply( $contact_id ); } return; } $vid = self::current_visitor_id(); if ( ! $vid ) { $vid = wp_generate_uuid4(); if ( ! headers_sent() ) { setcookie( self::COOKIE, $vid, array( 'expires' => time() + YEAR_IN_SECONDS, 'path' => COOKIEPATH ? COOKIEPATH : '/', 'domain' => COOKIE_DOMAIN, 'secure' => is_ssl(), 'httponly' => false, // The beacon script reads it. 'samesite' => 'Lax', ) ); $_COOKIE[ self::COOKIE ] = $vid; } else { Nodebook_Attribution::apply( $contact_id ); return; } } self::link( $vid, $contact_id ); } public static function on_login( $login, $user ) { $c = Nodebook_Contacts::find_by_user( $user->ID ); if ( ! $c && $user->user_email ) { $c = Nodebook_Contacts::find_by_email( $user->user_email ); if ( $c && ! $c['wp_user_id'] ) { Nodebook_Contacts::update( $c['id'], array( 'wp_user_id' => $user->ID ) ); } } if ( $c && ! array_intersect( (array) $user->roles, (array) Nodebook_Settings::get( 'exclude_roles' ) ) ) { self::identify( $c['id'] ); } } }