[ source, medium ]. First match wins, so order matters. */ public static function referrer_map() { return apply_filters( 'nodebook_referrer_map', array( 'mail.google.' => array( 'gmail', 'email' ), 'outlook.live.' => array( 'outlook', 'email' ), 'outlook.office' => array( 'outlook', 'email' ), 'mail.yahoo.' => array( 'yahoo-mail', 'email' ), 'gemini.google.' => array( 'gemini', 'ai' ), 'chatgpt.com' => array( 'chatgpt', 'ai' ), 'chat.openai.com' => array( 'chatgpt', 'ai' ), 'perplexity.ai' => array( 'perplexity', 'ai' ), 'copilot.microsoft.' => array( 'copilot', 'ai' ), 'google.' => array( 'google', 'organic' ), 'bing.com' => array( 'bing', 'organic' ), 'duckduckgo.com' => array( 'duckduckgo', 'organic' ), 'search.yahoo.' => array( 'yahoo', 'organic' ), 'ecosia.org' => array( 'ecosia', 'organic' ), 'search.brave.com' => array( 'brave', 'organic' ), 'yandex.' => array( 'yandex', 'organic' ), 'baidu.com' => array( 'baidu', 'organic' ), 'startpage.com' => array( 'startpage', 'organic' ), 'facebook.com' => array( 'facebook', 'social' ), 'fb.com' => array( 'facebook', 'social' ), 'instagram.com' => array( 'instagram', 'social' ), 'linkedin.com' => array( 'linkedin', 'social' ), 'lnkd.in' => array( 'linkedin', 'social' ), 't.co' => array( 'x', 'social' ), 'twitter.com' => array( 'x', 'social' ), 'x.com' => array( 'x', 'social' ), 'threads.net' => array( 'threads', 'social' ), 'pinterest.' => array( 'pinterest', 'social' ), 'youtube.com' => array( 'youtube', 'social' ), 'youtu.be' => array( 'youtube', 'social' ), 'tiktok.com' => array( 'tiktok', 'social' ), 'reddit.com' => array( 'reddit', 'social' ), 'wa.me' => array( 'whatsapp', 'social' ), 'whatsapp.com' => array( 'whatsapp', 'social' ), 'news.ycombinator.com' => array( 'hacker-news', 'social' ), ) ); } /** Ad click IDs => [ source, medium ]. */ public static function click_ids() { return array( 'gclid' => array( 'google', 'cpc' ), 'gbraid' => array( 'google', 'cpc' ), 'wbraid' => array( 'google', 'cpc' ), 'msclkid' => array( 'bing', 'cpc' ), 'fbclid' => array( 'facebook', 'social' ), 'ttclid' => array( 'tiktok', 'cpc' ), 'li_fat_id' => array( 'linkedin', 'cpc' ), ); } /** Human label for a source/medium pair, e.g. "Google · organic". */ public static function label( $source, $medium = '' ) { if ( '' === (string) $source ) { return __( 'Unknown', 'nodebook' ); } $names = array( 'google' => 'Google', 'bing' => 'Bing', 'facebook' => 'Facebook', 'instagram' => 'Instagram', 'linkedin' => 'LinkedIn', 'x' => 'X', 'youtube' => 'YouTube', 'tiktok' => 'TikTok', 'chatgpt' => 'ChatGPT', 'perplexity' => 'Perplexity', 'gemini' => 'Gemini', 'copilot' => 'Copilot', 'duckduckgo' => 'DuckDuckGo', 'whatsapp' => 'WhatsApp', 'gmail' => 'Gmail', 'hacker-news' => 'Hacker News', '(direct)' => __( 'Direct', 'nodebook' ), ); $name = isset( $names[ $source ] ) ? $names[ $source ] : $source; $mediums = array( 'cpc' => __( 'paid', 'nodebook' ), 'organic' => __( 'search', 'nodebook' ), 'social' => __( 'social', 'nodebook' ), 'email' => __( 'email', 'nodebook' ), 'referral' => __( 'referral', 'nodebook' ), 'ai' => __( 'AI assistant', 'nodebook' ), ); if ( '' === (string) $medium || '(none)' === $medium ) { return $name; } return $name . ' · ' . ( isset( $mediums[ $medium ] ) ? $mediums[ $medium ] : $medium ); } private static function clean( $v, $max = 150 ) { return mb_substr( sanitize_text_field( (string) $v ), 0, $max ); } /** * Classify raw arrival data. * * @param array $raw Keys: utm_source, utm_medium, utm_campaign, gclid…, r (referrer URL), l (landing path+query), t (unix time). * @return array source, medium, campaign, referrer, landing, at (GMT) — or empty array when nothing usable. */ public static function classify( array $raw ) { $home = (string) wp_parse_url( home_url(), PHP_URL_HOST ); $referrer = isset( $raw['r'] ) ? esc_url_raw( (string) $raw['r'] ) : ''; $ref_host = $referrer ? strtolower( (string) wp_parse_url( $referrer, PHP_URL_HOST ) ) : ''; if ( $ref_host && preg_replace( '/^www\./', '', $ref_host ) === preg_replace( '/^www\./', '', strtolower( $home ) ) ) { $referrer = ''; $ref_host = ''; } $landing = isset( $raw['l'] ) ? self::clean( $raw['l'], 255 ) : ''; // Landing URL query wins over separately sent params when both exist. if ( $landing && false !== strpos( $landing, '?' ) ) { parse_str( (string) wp_parse_url( 'https://x.invalid' . $landing, PHP_URL_QUERY ), $q ); $raw = array_merge( $q, $raw ); } $out = array( 'source' => '', 'medium' => '', 'campaign' => isset( $raw['utm_campaign'] ) ? self::clean( $raw['utm_campaign'] ) : '', 'referrer' => mb_substr( $referrer, 0, 255 ), 'landing' => $landing, 'at' => ( isset( $raw['t'] ) && (int) $raw['t'] > 946684800 && (int) $raw['t'] <= time() + 300 ) ? gmdate( 'Y-m-d H:i:s', (int) $raw['t'] ) : current_time( 'mysql', true ), ); if ( ! empty( $raw['utm_source'] ) ) { $out['source'] = strtolower( self::clean( $raw['utm_source'], 100 ) ); $out['medium'] = ! empty( $raw['utm_medium'] ) ? strtolower( self::clean( $raw['utm_medium'], 100 ) ) : '(not set)'; } else { foreach ( self::click_ids() as $param => $pair ) { if ( ! empty( $raw[ $param ] ) ) { list( $out['source'], $out['medium'] ) = $pair; break; } } } if ( '' === $out['source'] && $ref_host ) { $host = preg_replace( '/^(www|m|l|lm|mobile)\./', '', $ref_host ); foreach ( self::referrer_map() as $needle => $pair ) { if ( 0 === strpos( $host, $needle ) || false !== strpos( '.' . $host, '.' . $needle ) ) { list( $out['source'], $out['medium'] ) = $pair; break; } } if ( '' === $out['source'] ) { $out['source'] = mb_substr( $host, 0, 100 ); $out['medium'] = 'referral'; } } if ( '' === $out['source'] ) { $out['source'] = '(direct)'; $out['medium'] = '(none)'; } return apply_filters( 'nodebook_attribution', $out, $raw ); } /** Raw arrival data from the cookie, or null. */ public static function from_cookie() { if ( empty( $_COOKIE[ self::COOKIE ] ) ) { return null; } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON: decoded below, then only known keys are kept and every value is sanitized. $raw = json_decode( wp_unslash( $_COOKIE[ self::COOKIE ] ), true ); if ( ! is_array( $raw ) ) { return null; } $allowed = array_merge( array( 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'r', 'l', 't' ), array_keys( self::click_ids() ) ); $out = array(); foreach ( array_intersect_key( $raw, array_flip( $allowed ) ) as $key => $value ) { if ( ! is_scalar( $value ) ) { continue; } if ( 'r' === $key ) { $out[ $key ] = sanitize_url( (string) $value ); // Referrer: a URL. } elseif ( 't' === $key ) { $out[ $key ] = absint( $value ); // Arrival time (Unix timestamp). } else { $out[ $key ] = mb_substr( sanitize_text_field( (string) $value ), 0, 255 ); } } return $out; } /** * Save first-touch data on a contact if it has none yet. * Uses the cookie, else the contact's earliest recorded visit. */ public static function apply( $contact_id ) { $c = Nodebook_Contacts::get( $contact_id ); if ( ! $c || '' !== (string) $c['first_source'] ) { return; } $data = null; $raw = Nodebook_Settings::get( 'attribution' ) ? self::from_cookie() : null; if ( $raw ) { $data = self::classify( $raw ); } else { $data = self::from_history( $contact_id ); } if ( ! $data ) { return; } Nodebook_Contacts::update( $contact_id, array( 'first_source' => $data['source'], 'first_medium' => $data['medium'], 'first_campaign' => $data['campaign'], 'first_referrer' => $data['referrer'], 'landing_page' => $data['landing'], 'first_touch_at' => $data['at'], ) ); } /** * Fallback: WooCommerce's built-in order attribution (last-click, per order). * Only used when the contact has no first touch yet. */ public static function apply_wc_order( $contact_id, $order ) { $c = Nodebook_Contacts::get( $contact_id ); if ( ! $c || '' !== (string) $c['first_source'] || ! is_object( $order ) || ! method_exists( $order, 'get_meta' ) ) { return false; } $type = (string) $order->get_meta( '_wc_order_attribution_source_type' ); if ( '' === $type ) { return false; } $src = strtolower( (string) $order->get_meta( '_wc_order_attribution_utm_source' ) ); $med = strtolower( (string) $order->get_meta( '_wc_order_attribution_utm_medium' ) ); $ref = (string) $order->get_meta( '_wc_order_attribution_referrer' ); switch ( $type ) { case 'utm': $medium = $med ? $med : '(not set)'; break; case 'organic': $medium = 'organic'; break; case 'referral': $data = self::classify( array( 'r' => $ref ) ); $src = $data['source']; $medium = $data['medium']; break; case 'typein': $src = '(direct)'; $medium = '(none)'; break; default: return false; } if ( '' === $src ) { return false; } $entry = (string) $order->get_meta( '_wc_order_attribution_session_entry' ); $path = $entry ? (string) wp_parse_url( $entry, PHP_URL_PATH ) : ''; $created = method_exists( $order, 'get_date_created' ) ? $order->get_date_created() : null; Nodebook_Contacts::update( $contact_id, array( 'first_source' => mb_substr( sanitize_text_field( $src ), 0, 100 ), 'first_medium' => mb_substr( sanitize_text_field( $medium ), 0, 100 ), 'first_campaign' => mb_substr( sanitize_text_field( (string) $order->get_meta( '_wc_order_attribution_utm_campaign' ) ), 0, 150 ), 'first_referrer' => mb_substr( esc_url_raw( $ref ), 0, 255 ), 'landing_page' => mb_substr( $path, 0, 255 ), 'first_touch_at' => $created ? gmdate( 'Y-m-d H:i:s', $created->getTimestamp() ) : current_time( 'mysql', true ), ) ); return true; } /** First touch from the earliest stored visit (when anonymous history was claimed). */ public static function from_history( $contact_id ) { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( "SELECT url, data, created_at FROM %i WHERE contact_id = %d AND type = 'visit' ORDER BY created_at ASC, id ASC LIMIT 1", Nodebook_Activities::table(), $contact_id ), ARRAY_A ); if ( ! $row ) { return null; } $d = json_decode( (string) $row['data'], true ); $d = is_array( $d ) ? $d : array(); $path = (string) wp_parse_url( (string) $row['url'], PHP_URL_PATH ); $q = (string) wp_parse_url( (string) $row['url'], PHP_URL_QUERY ); $out = self::classify( array( 'r' => isset( $d['referrer'] ) ? $d['referrer'] : '', 'l' => ( $path ? $path : '/' ) . ( $q ? '?' . $q : '' ), ) ); $out['at'] = $row['created_at']; return $out; } }