0, 'subscriber' => 1, 'lead' => 2, 'prospect' => 3, 'customer' => 4 ) ); return isset( $order[ $status ] ) ? $order[ $status ] : 1; } /* ------------------------------------------------------------------ * * Detection * ------------------------------------------------------------------ */ /** Last 8 digits of a phone number: ignores formatting and country/area prefixes (a review hint, not proof). */ public static function phone_key( $phone ) { $d = preg_replace( '/\D/', '', (string) $phone ); return strlen( $d ) >= 7 ? substr( $d, -8 ) : ''; } /** Gmail ignores dots and +tags: a.b+x@gmail.com is ab@gmail.com. */ public static function email_key( $email ) { $email = strtolower( (string) $email ); if ( false === strpos( $email, '@' ) ) { return ''; } list( $local, $domain ) = explode( '@', $email, 2 ); $local = preg_replace( '/\+.*$/', '', $local ); if ( in_array( $domain, array( 'gmail.com', 'googlemail.com' ), true ) ) { $local = str_replace( '.', '', $local ); $domain = 'gmail.com'; } return $local . '@' . $domain; } private static function name_key( array $c ) { $n = strtolower( trim( remove_accents( $c['first_name'] . ' ' . $c['last_name'] ) ) ); $n = preg_replace( '/[^a-z0-9 ]/', '', $n ); return ( strlen( $n ) >= 5 && false !== strpos( $n, ' ' ) ) ? $n : ''; } private static function pair_key( $a, $b ) { return min( $a, $b ) . '-' . max( $a, $b ); } public static function dismissed() { $d = get_option( self::DISMISSED, array() ); return is_array( $d ) ? $d : array(); } public static function dismiss( $a, $b ) { $d = self::dismissed(); $d[ self::pair_key( $a, $b ) ] = 1; if ( count( $d ) > 5000 ) { $d = array_slice( $d, -5000, null, true ); } update_option( self::DISMISSED, $d, false ); } /** * Likely duplicate pairs, strongest first. * * @param int $limit Max pairs. * @return array[] { a: contact, b: contact, reasons: string[], score: int } */ public static function find( $limit = 50 ) { global $wpdb; // Pass 1: stream every contact in chunks (no cap) and keep only the match keys → IDs. $buckets = array( 'email' => array(), 'phone' => array(), 'name' => array(), 'user' => array(), ); $last = 0; do { $chunk = (array) $wpdb->get_results( $wpdb->prepare( 'SELECT id, email, first_name, last_name, phone, wp_user_id FROM %i WHERE id > %d ORDER BY id ASC LIMIT 20000', Nodebook_Contacts::table(), $last ), ARRAY_A ); foreach ( $chunk as $r ) { $id = (int) $r['id']; $last = $id; $ek = $r['email'] ? self::email_key( $r['email'] ) : ''; $pk = self::phone_key( $r['phone'] ); $nk = self::name_key( $r ); if ( $ek ) { $buckets['email'][ $ek ][] = $id; } if ( $pk ) { $buckets['phone'][ $pk ][] = $id; } if ( $nk ) { $buckets['name'][ $nk ][] = $id; } if ( (int) $r['wp_user_id'] && ! Nodebook_Repair::is_staff( (int) $r['wp_user_id'] ) ) { $buckets['user'][ (int) $r['wp_user_id'] ][] = $id; } } $n = count( $chunk ); unset( $chunk ); } while ( 20000 === $n ); foreach ( $buckets as $kind => $groups ) { $buckets[ $kind ] = array_filter( $groups, static function ( $ids ) { return count( $ids ) > 1; } ); } $labels = array( 'email' => __( 'Same email (ignoring dots and +tags)', 'nodebook' ), 'user' => __( 'Same WordPress user', 'nodebook' ), 'phone' => __( 'Same phone number', 'nodebook' ), 'name' => __( 'Same full name', 'nodebook' ), ); $weight = array( 'email' => 60, 'user' => 60, 'phone' => 45, 'name' => 25, ); $dismissed = self::dismissed(); $pairs = array(); foreach ( $buckets as $kind => $groups ) { foreach ( $groups as $ids ) { $n = count( $ids ); if ( $n < 2 || $n > 25 ) { // Very large groups are shared numbers/names, not people. continue; } for ( $i = 0; $i < $n; $i++ ) { for ( $j = $i + 1; $j < $n; $j++ ) { $key = self::pair_key( $ids[ $i ], $ids[ $j ] ); if ( isset( $dismissed[ $key ] ) ) { continue; } if ( ! isset( $pairs[ $key ] ) ) { $pairs[ $key ] = array( 'a' => min( $ids[ $i ], $ids[ $j ] ), 'b' => max( $ids[ $i ], $ids[ $j ] ), 'reasons' => array(), 'score' => 0, ); } $pairs[ $key ]['reasons'][] = $labels[ $kind ]; $pairs[ $key ]['score'] += $weight[ $kind ]; } } } } // Pass 2: load full rows only for contacts that appear in a candidate pair. $need = array(); foreach ( $pairs as $p ) { $need[ $p['a'] ] = true; $need[ $p['b'] ] = true; } $by_id = array(); foreach ( array_chunk( array_keys( $need ), 1000 ) as $ids ) { $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT id, email, first_name, last_name, phone, company_id, wp_user_id, status, source, created_at, last_seen, orders_count, visits_count FROM %i WHERE id IN (' . implode( ',', array_fill( 0, count( $ids ), '%d' ) ) . ')', array_merge( array( Nodebook_Contacts::table() ), $ids ) ), ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQL.NotPrepared -- placeholders generated per ID. foreach ( (array) $rows as $r ) { $r['id'] = (int) $r['id']; $by_id[ $r['id'] ] = $r; } } foreach ( $pairs as $key => $p ) { if ( ! isset( $by_id[ $p['a'] ], $by_id[ $p['b'] ] ) ) { unset( $pairs[ $key ] ); continue; } $pairs[ $key ]['a'] = $by_id[ $p['a'] ]; $pairs[ $key ]['b'] = $by_id[ $p['b'] ]; } // Same name only counts as a duplicate signal with something else in common. foreach ( $pairs as $key => $p ) { if ( array( $labels['name'] ) === $p['reasons'] ) { $same_company = $p['a']['company_id'] && (int) $p['a']['company_id'] === (int) $p['b']['company_id']; $one_blank = ! $p['a']['email'] || ! $p['b']['email']; if ( $same_company ) { $pairs[ $key ]['reasons'][] = __( 'same company', 'nodebook' ); $pairs[ $key ]['score'] += 25; } elseif ( $one_blank ) { $pairs[ $key ]['reasons'][] = __( 'one has no email', 'nodebook' ); $pairs[ $key ]['score'] += 10; } else { unset( $pairs[ $key ] ); } } } uasort( $pairs, static function ( $x, $y ) { return $y['score'] <=> $x['score']; } ); return array_slice( array_values( $pairs ), 0, $limit ); } /* ------------------------------------------------------------------ * * Merge * ------------------------------------------------------------------ */ /** * Merge $merge_id into $keep_id. The kept contact's values win; its blanks are filled from the other. * * @return bool */ public static function merge( $keep_id, $merge_id ) { global $wpdb; $keep_id = absint( $keep_id ); $merge_id = absint( $merge_id ); if ( ! $keep_id || ! $merge_id || $keep_id === $merge_id ) { return false; } $k = Nodebook_Contacts::get( $keep_id ); $m = Nodebook_Contacts::get( $merge_id ); if ( ! $k || ! $m ) { return false; } do_action( 'nodebook_before_merge', $k, $m ); $data = array(); foreach ( array( 'first_name', 'last_name', 'phone', 'job_title', 'company_id', 'source', 'website', 'address', 'city', 'state', 'postcode', 'country', 'description', 'wp_user_id' ) as $f ) { if ( ( '' === (string) $k[ $f ] || '0' === (string) $k[ $f ] ) && '' !== (string) $m[ $f ] && '0' !== (string) $m[ $f ] ) { $data[ $f ] = $m[ $f ]; } } if ( ! $k['email'] && $m['email'] ) { $data['email'] = $m['email']; } // Earliest first touch wins: that is where the relationship really started. $k_touch = $k['first_touch_at'] ? $k['first_touch_at'] : ( $k['first_source'] ? $k['created_at'] : null ); $m_touch = $m['first_touch_at'] ? $m['first_touch_at'] : ( $m['first_source'] ? $m['created_at'] : null ); if ( $m['first_source'] && ( ! $k['first_source'] || ( $m_touch && $k_touch && $m_touch < $k_touch ) ) ) { foreach ( array( 'first_source', 'first_medium', 'first_campaign', 'first_referrer', 'landing_page', 'first_touch_at' ) as $f ) { $data[ $f ] = $m[ $f ]; } } if ( self::rank( $m['status'] ) > self::rank( $k['status'] ) ) { $data['status'] = $m['status']; } $data['meta'] = array_merge( $m['meta'], $k['meta'] ); $data['watched'] = max( (int) $k['watched'], (int) $m['watched'] ); foreach ( array( 'last_intent_at', 'last_seen', 'last_inquiry_at' ) as $f ) { if ( $m[ $f ] && ( ! $k[ $f ] || $m[ $f ] > $k[ $f ] ) ) { $data[ $f ] = $m[ $f ]; } } if ( $m['first_seen'] && ( ! $k['first_seen'] || $m['first_seen'] < $k['first_seen'] ) ) { $data['first_seen'] = $m['first_seen']; } $kp = trim( (string) ( $k['pinned'] ?? '' ) ); $mp = trim( (string) ( $m['pinned'] ?? '' ) ); if ( '' !== $mp && $mp !== $kp ) { $data['pinned'] = '' === $kp ? $mp : $kp . "\n" . $mp; } if ( $m['description'] && $k['description'] && $m['description'] !== $k['description'] ) { $data['description'] = $k['description'] . "\n\n" . $m['description']; } $a = Nodebook_Install::table( 'activities' ); $v = Nodebook_Install::table( 'visitors' ); $sc = Nodebook_Install::table( 'segment_contacts' ); $al = Nodebook_Install::table( 'aliases' ); // Move history and identity. $wpdb->update( $a, array( 'contact_id' => $keep_id ), array( 'contact_id' => $merge_id ) ); $wpdb->update( $v, array( 'contact_id' => $keep_id ), array( 'contact_id' => $merge_id ) ); $wpdb->query( $wpdb->prepare( 'INSERT IGNORE INTO %i (segment_id, contact_id, added_at) SELECT segment_id, %d, added_at FROM %i WHERE contact_id = %d', $sc, $keep_id, $sc, $merge_id ) ); $wpdb->delete( $sc, array( 'contact_id' => $merge_id ) ); $wpdb->update( $al, array( 'contact_id' => $keep_id ), array( 'contact_id' => $merge_id ) ); Nodebook_Props::merge( 'contact', $keep_id, $merge_id ); // Remove the merged row first so its email is free, then remember that email as an alias. $wpdb->delete( Nodebook_Contacts::table(), array( 'id' => $merge_id ) ); Nodebook_Contacts::update( $keep_id, $data ); $email_status = Nodebook_Subscription::merged( $k['email_status'] ?? '', $m['email_status'] ?? '' ); if ( $email_status !== (string) ( $k['email_status'] ?? '' ) ) { $wpdb->update( Nodebook_Contacts::table(), array( 'email_status' => $email_status, 'email_status_at' => $m['email_status_at'], 'consent_source' => $m['consent_source'], ), array( 'id' => $keep_id ) ); } $kept_email = isset( $data['email'] ) ? $data['email'] : $k['email']; if ( $m['email'] && strtolower( $m['email'] ) !== strtolower( (string) $kept_email ) ) { Nodebook_Contacts::add_alias( $m['email'], $keep_id ); } // Recalculate counters. Nodebook_Contacts::recount_visits( $keep_id ); if ( Nodebook_Woocommerce::active() ) { Nodebook_Woocommerce::recalculate( $keep_id, (string) $kept_email ); } else { Nodebook_Contacts::update( $keep_id, array( 'orders_count' => (int) $k['orders_count'] + (int) $m['orders_count'], 'total_spent' => (float) $k['total_spent'] + (float) $m['total_spent'], ) ); } Nodebook_Activities::add( $keep_id, 'merge', /* translators: %s: name or email of the merged contact */ sprintf( __( 'Merged with %s', 'nodebook' ), Nodebook_Contacts::display_name( $m ) . ( $m['email'] && $m['email'] !== $kept_email ? ' (' . $m['email'] . ')' : '' ) ), array( 'data' => array( 'merged_id' => $merge_id, 'email' => $m['email'], 'phone' => $m['phone'], ), ) ); /** * Fires after two contacts were merged. * * @param int $keep_id Surviving contact. * @param int $merge_id Removed contact. * @param array $m The removed contact as it was. */ do_action( 'nodebook_contacts_merged', $keep_id, $merge_id, $m ); Nodebook_Contacts::flush_caches(); return true; } /** * Merge several contacts into one. Keeps the given ID, or the oldest when 0. * * @return int Surviving contact ID (0 on failure). */ public static function merge_many( array $ids, $keep_id = 0 ) { $ids = array_values( array_unique( array_filter( array_map( 'absint', $ids ) ) ) ); if ( count( $ids ) < 2 ) { return 0; } sort( $ids ); $keep = $keep_id && in_array( (int) $keep_id, $ids, true ) ? (int) $keep_id : $ids[0]; foreach ( $ids as $id ) { if ( $id !== $keep ) { self::merge( $keep, $id ); } } return $keep; } }