prepare(). * * @package Nodebook */ // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom tables owned by this plugin. defined( 'ABSPATH' ) || exit; final class Nodebook_Contacts { /** Columns that may be written directly. */ const COLUMNS = array( 'email', 'first_name', 'last_name', 'phone', 'job_title', 'company_id', 'status', 'source', 'website', 'address', 'city', 'state', 'postcode', 'country', 'description', 'meta', 'wp_user_id', 'orders_count', 'total_spent', 'visits_count', 'first_seen', 'last_seen', 'first_source', 'first_medium', 'first_campaign', 'first_referrer', 'landing_page', 'first_touch_at', 'watched', 'last_intent_at', 'last_alert_at', 'followed_up_at', 'owner_id', 'remind_at', 'status_at', 'pinned', 'last_inquiry_at', 'other_spent' ); public static function table() { return Nodebook_Install::table( 'contacts' ); } public static function get( $id ) { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', self::table(), $id ), ARRAY_A ); return $row ? self::hydrate( $row ) : null; } public static function find_by_email( $email ) { global $wpdb; $email = strtolower( sanitize_email( $email ) ); if ( ! $email ) { return null; } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE email = %s', self::table(), $email ), ARRAY_A ); if ( ! $row ) { // Former addresses of merged contacts keep pointing at the surviving contact. $row = $wpdb->get_row( $wpdb->prepare( 'SELECT c.* FROM %i c INNER JOIN %i a ON a.contact_id = c.id WHERE a.email = %s', self::table(), Nodebook_Install::table( 'aliases' ), $email ), ARRAY_A ); } return $row ? self::hydrate( $row ) : null; } /** All email addresses of a contact: primary first, then former (merged) addresses. */ public static function emails( $id ) { global $wpdb; $c = self::get( $id ); $out = $c && $c['email'] ? array( $c['email'] ) : array(); foreach ( (array) $wpdb->get_col( $wpdb->prepare( 'SELECT email FROM %i WHERE contact_id = %d ORDER BY created_at ASC', Nodebook_Install::table( 'aliases' ), $id ) ) as $e ) { if ( ! in_array( $e, $out, true ) ) { $out[] = $e; } } return $out; } public static function add_alias( $email, $contact_id ) { global $wpdb; $email = strtolower( sanitize_email( $email ) ); if ( ! is_email( $email ) ) { return; } $wpdb->query( $wpdb->prepare( 'REPLACE INTO %i (email, contact_id, created_at) VALUES (%s, %d, %s)', Nodebook_Install::table( 'aliases' ), $email, $contact_id, current_time( 'mysql', true ) ) ); } public static function find_by_phone( $phone ) { global $wpdb; $phone = sanitize_text_field( $phone ); if ( strlen( preg_replace( '/\D/', '', $phone ) ) < 6 ) { return null; } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE phone = %s AND email IS NULL ORDER BY id ASC LIMIT 1', self::table(), $phone ), ARRAY_A ); return $row ? self::hydrate( $row ) : null; } public static function find_by_user( $user_id ) { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE wp_user_id = %d ORDER BY id ASC LIMIT 1', self::table(), $user_id ), ARRAY_A ); return $row ? self::hydrate( $row ) : null; } public static function hydrate( array $row ) { $meta = json_decode( (string) $row['meta'], true ); $row['meta'] = is_array( $meta ) ? $meta : array(); $row['id'] = (int) $row['id']; return $row; } public static function display_name( array $c ) { $name = Nodebook_Fields::name_case( trim( $c['first_name'] . ' ' . $c['last_name'] ) ); if ( '' !== $name ) { return $name; } if ( ! empty( $c['email'] ) ) { return $c['email']; } return $c['phone'] ? $c['phone'] : sprintf( /* translators: %d: contact ID */ __( 'Contact #%d', 'nodebook' ), $c['id'] ); } /** * Clean an incoming data array to writable columns. */ public static function prepare( array $data ) { $defs = Nodebook_Fields::contact(); $out = array(); foreach ( $data as $key => $value ) { if ( ! in_array( $key, self::COLUMNS, true ) ) { continue; } if ( 'meta' === $key ) { $out['meta'] = wp_json_encode( self::clean_meta( (array) $value ) ); } elseif ( in_array( $key, array( 'company_id', 'wp_user_id', 'orders_count', 'visits_count', 'watched', 'owner_id' ), true ) ) { $out[ $key ] = absint( $value ); } elseif ( 'total_spent' === $key ) { $out[ $key ] = round( (float) $value, 4 ); } elseif ( in_array( $key, array( 'first_seen', 'last_seen', 'first_touch_at', 'last_intent_at', 'last_alert_at', 'followed_up_at', 'remind_at', 'status_at', 'last_inquiry_at' ), true ) ) { $out[ $key ] = $value ? gmdate( 'Y-m-d H:i:s', strtotime( (string) $value ) ) : null; } elseif ( 'other_spent' === $key ) { $out[ $key ] = is_array( $value ) ? (string) wp_json_encode( array_map( 'floatval', $value ) ) : mb_substr( (string) $value, 0, 255 ); } elseif ( 'pinned' === $key ) { $out[ $key ] = mb_substr( sanitize_textarea_field( (string) $value ), 0, 500 ); } elseif ( isset( $defs[ $key ] ) ) { $out[ $key ] = Nodebook_Fields::clean( $key, $value, $defs[ $key ] ); } } if ( array_key_exists( 'email', $out ) ) { $out['email'] = is_email( $out['email'] ) ? $out['email'] : null; } foreach ( array( 'first_name', 'last_name', 'city' ) as $k ) { if ( isset( $out[ $k ] ) && is_string( $out[ $k ] ) ) { $out[ $k ] = Nodebook_Fields::name_case( $out[ $k ] ); } } if ( isset( $out['status'] ) && '' === $out['status'] ) { unset( $out['status'] ); } return $out; } /** * Custom fields: label => scalar, capped so a hostile form cannot bloat a row. */ public static function clean_meta( array $meta ) { $clean = array(); foreach ( $meta as $k => $v ) { if ( count( $clean ) >= 60 ) { break; } $k = sanitize_text_field( (string) $k ); if ( '' === $k ) { continue; } if ( is_array( $v ) ) { $v = implode( ', ', array_map( 'strval', array_filter( $v, 'is_scalar' ) ) ); } $v = sanitize_textarea_field( (string) $v ); if ( '' === $v ) { continue; } $clean[ mb_substr( $k, 0, 80 ) ] = mb_substr( $v, 0, 2000 ); } return $clean; } public static function insert( array $data ) { global $wpdb; $row = self::prepare( $data ); if ( empty( $row['status'] ) ) { $row['status'] = Nodebook_Settings::get( 'default_status' ); } $now = current_time( 'mysql', true ); $row['created_at'] = $now; $row['updated_at'] = $now; $row['status_at'] = $now; if ( ! isset( $row['meta'] ) ) { $row['meta'] = '{}'; } if ( false === $wpdb->insert( self::table(), $row ) ) { return 0; } $id = (int) $wpdb->insert_id; /** * Fires after a contact is created. * * @param int $id Contact ID. * @param array $row Stored values. */ do_action( 'nodebook_contact_created', $id, $row ); return $id; } public static function update( $id, array $data ) { global $wpdb; $row = self::prepare( $data ); if ( ! $row ) { return true; } $row['updated_at'] = current_time( 'mysql', true ); if ( isset( $row['status'] ) && ! isset( $row['status_at'] ) ) { // When the status really changes, remember when: "no movement in 30 days" is measured from here. $wpdb->query( $wpdb->prepare( 'UPDATE %i SET status_at = %s WHERE id = %d AND status <> %s', self::table(), $row['updated_at'], (int) $id, $row['status'] ) ); } $ok = false !== $wpdb->update( self::table(), $row, array( 'id' => (int) $id ) ); if ( $ok ) { do_action( 'nodebook_contact_updated', (int) $id, $row ); } return $ok; } /** * Create or update by email (or by phone when there is no email). * * @param array $data Contact columns plus optional 'company' (name) and 'meta' (custom fields). * @param string $policy 'fill' = only fill empty fields, 'overwrite' = incoming values win. * @return array{id:int,created:bool} */ public static function upsert( array $data, $policy = 'fill' ) { $existing = null; if ( ! empty( $data['email'] ) ) { $existing = self::find_by_email( $data['email'] ); } if ( ! $existing && ! empty( $data['phone'] ) ) { // Stitch: a phone-only contact who now gives an email is the same person. $existing = self::find_by_phone( $data['phone'] ); if ( $existing && ! empty( $data['email'] ) ) { self::update( $existing['id'], array( 'email' => $data['email'] ) ); $existing['email'] = strtolower( $data['email'] ); } } $company_name = isset( $data['company'] ) ? trim( (string) $data['company'] ) : ''; unset( $data['company'] ); if ( ! $existing ) { if ( empty( $data['company_id'] ) ) { $data['company_id'] = Nodebook_Companies::resolve( $company_name, isset( $data['email'] ) ? $data['email'] : '' ); } $id = self::insert( $data ); return array( 'id' => $id, 'created' => true ); } $changes = array(); foreach ( $data as $key => $value ) { if ( 'meta' === $key ) { $merged = 'overwrite' === $policy ? array_merge( $existing['meta'], (array) $value ) : array_merge( (array) $value, $existing['meta'] ); if ( $merged !== $existing['meta'] ) { $changes['meta'] = $merged; } continue; } if ( ! in_array( $key, self::COLUMNS, true ) || '' === $value || null === $value ) { continue; } $current = isset( $existing[ $key ] ) ? $existing[ $key ] : ''; if ( 'overwrite' === $policy || '' === (string) $current || '0' === (string) $current ) { if ( (string) $current !== (string) $value ) { $changes[ $key ] = $value; } } } if ( empty( $existing['company_id'] ) && empty( $changes['company_id'] ) ) { $cid = Nodebook_Companies::resolve( $company_name, $existing['email'] ? $existing['email'] : ( $data['email'] ?? '' ) ); if ( $cid ) { $changes['company_id'] = $cid; } } elseif ( 'overwrite' === $policy && '' !== $company_name ) { $cid = Nodebook_Companies::resolve( $company_name, '' ); if ( $cid && (int) $cid !== (int) $existing['company_id'] ) { $changes['company_id'] = $cid; } } if ( $changes ) { self::update( $existing['id'], $changes ); } return array( 'id' => (int) $existing['id'], 'created' => false ); } public static function delete( array $ids ) { global $wpdb; $ids = array_filter( array_map( 'absint', $ids ) ); foreach ( $ids as $id ) { do_action( 'nodebook_contact_before_delete', $id ); $wpdb->delete( self::table(), array( 'id' => $id ) ); $wpdb->delete( Nodebook_Install::table( 'activities' ), array( 'contact_id' => $id ) ); $wpdb->delete( Nodebook_Install::table( 'segment_contacts' ), array( 'contact_id' => $id ) ); $wpdb->delete( Nodebook_Install::table( 'visitors' ), array( 'contact_id' => $id ) ); $wpdb->delete( Nodebook_Install::table( 'aliases' ), array( 'contact_id' => $id ) ); } if ( $ids ) { Nodebook_Props::delete_for( 'contact', $ids ); self::flush_caches(); } return count( $ids ); } /** * Forget every stored number that counts contacts (segment sizes, duplicates, follow-up badges, * report snapshots), so a delete or merge never leaves stale figures on screen. */ public static function flush_caches() { global $wpdb; delete_transient( 'nodebook_dupe_count' ); foreach ( (array) $wpdb->get_col( $wpdb->prepare( 'SELECT id FROM %i', Nodebook_Install::table( 'segments' ) ) ) as $sid ) { delete_transient( 'nodebook_segcount_' . (int) $sid ); } foreach ( array_keys( Nodebook_Team::users() + array( 0 => '' ) ) as $uid ) { delete_transient( 'nodebook_due_' . (int) $uid . '_0' ); delete_transient( 'nodebook_due_' . (int) $uid . '_' . (int) $uid ); } foreach ( array( 0, 7, 30, 90, 365 ) as $days ) { $data = get_option( 'nodebook_report_' . $days ); if ( is_array( $data ) && ! empty( $data['built'] ) ) { // Keep showing it, but rebuild on the next visit to Journeys. $data['built'] = 1; update_option( 'nodebook_report_' . $days, $data, false ); } } } public static function count_all() { global $wpdb; return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', self::table() ) ); } /** * Query contacts for lists and exports. * * @param array $args search, status, segment, company_id, ids, orderby, order, per_page, page. * @return array{rows:array,total:int} */ public static function query( array $args = array() ) { global $wpdb; $args = wp_parse_args( $args, array( 'search' => '', 'status' => '', 'segment' => 0, 'email_status' => null, 'company_id' => 0, 'owner' => 0, 'mine' => 0, 'ids' => array(), 'orderby' => 'created_at', 'order' => 'DESC', 'per_page' => 25, 'page' => 1, ) ); list( $where, $params ) = self::where( $args ); $sortable = array( 'created_at', 'last_seen', 'first_name', 'last_name', 'email', 'status', 'orders_count', 'total_spent', 'visits_count', 'company', 'first_source', 'last_intent_at', 'score' ); $orderby = in_array( $args['orderby'], $sortable, true ) ? $args['orderby'] : 'created_at'; $sort = 'company' === $orderby ? array( 'co', 'name' ) : array( 'c', $orderby ); // Fixed SQL only; the sort column goes in as %i identifiers. $tail = 'ASC' === strtoupper( $args['order'] ) ? ' ORDER BY %i.%i ASC, c.id ASC' : ' ORDER BY %i.%i DESC, c.id DESC'; $tables = array( self::table(), Nodebook_Companies::table() ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $where and $tail are fixed SQL with placeholders; every value is passed to prepare(). $total = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i c LEFT JOIN %i co ON co.id = c.company_id WHERE ' . $where, array_merge( $tables, $params ) ) ); if ( $args['per_page'] > 0 ) { $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT c.*, co.name AS company FROM %i c LEFT JOIN %i co ON co.id = c.company_id WHERE ' . $where . $tail . ' LIMIT %d OFFSET %d', array_merge( $tables, $params, $sort, array( (int) $args['per_page'], max( 0, ( (int) $args['page'] - 1 ) * (int) $args['per_page'] ) ) ) ), ARRAY_A ); } else { $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT c.*, co.name AS company FROM %i c LEFT JOIN %i co ON co.id = c.company_id WHERE ' . $where . $tail, array_merge( $tables, $params, $sort ) ), ARRAY_A ); } // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return array( 'rows' => array_map( array( __CLASS__, 'hydrate' ), (array) $rows ), 'total' => $total, ); } /** * Contacts per status for the same filters (one query instead of one per status). * * @param array $args Filters as for query(); status is ignored. * @return array{all:int,by:array} */ public static function status_counts( array $args = array() ) { global $wpdb; $args = wp_parse_args( $args, array( 'segment' => 0 ) ); $args['status'] = ''; list( $where, $params ) = self::where( $args ); $sql = 'SELECT c.status, COUNT(*) AS n FROM %i c LEFT JOIN %i co ON co.id = c.company_id WHERE ' . $where . ' GROUP BY c.status'; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $sql is fixed SQL with placeholders; every value is passed to prepare(). $rows = $wpdb->get_results( $wpdb->prepare( $sql, array_merge( array( self::table(), Nodebook_Companies::table() ), $params ) ), ARRAY_A ); $by = array(); foreach ( (array) $rows as $r ) { $by[ (string) $r['status'] ] = (int) $r['n']; } return array( 'all' => array_sum( $by ), 'by' => $by, ); } /** * The WHERE condition for list filters (aliases c = contacts, co = companies), see Nodebook_Sql. * * @return array{0:string,1:array} Fixed SQL with placeholders, and their values. */ public static function where( array $args ) { global $wpdb; $parts = array(); if ( '' !== (string) ( $args['search'] ?? '' ) ) { $like = '%' . $wpdb->esc_like( $args['search'] ) . '%'; $parts[] = array( 'c.email LIKE %s OR c.first_name LIKE %s OR c.last_name LIKE %s OR c.phone LIKE %s OR co.name LIKE %s OR CONCAT(c.first_name, %s, c.last_name) LIKE %s', array( $like, $like, $like, $like, $like, ' ', $like ) ); } if ( ! empty( $args['status'] ) ) { $parts[] = array( 'c.status = %s', array( (string) $args['status'] ) ); } if ( ! empty( $args['company_id'] ) ) { $parts[] = array( 'c.company_id = %d', array( (int) $args['company_id'] ) ); } if ( isset( $args['email_status'] ) && null !== $args['email_status'] && '' !== $args['email_status'] ) { $parts[] = array( 'c.email_status = %s', array( 'none' === $args['email_status'] ? '' : (string) $args['email_status'] ) ); } if ( ! empty( $args['owner'] ) ) { // -1 = unassigned. $parts[] = array( 'c.owner_id = %d', array( max( 0, (int) $args['owner'] ) ) ); } if ( ! empty( $args['mine'] ) ) { // Mine = assigned to me, or nobody's yet (same rule as Follow up today). $parts[] = array( 'c.owner_id IN (0, %d)', array( (int) $args['mine'] ) ); } if ( ! empty( $args['ids'] ) ) { $parts[] = Nodebook_Sql::in_ids( 'c.id', array_map( 'absint', (array) $args['ids'] ) ); } // Users who see only their own contacts never get anyone else's, whatever the filters. if ( ! isset( $args['scope'] ) || false !== $args['scope'] ) { $parts[] = Nodebook_Team::scope_where( 'c.owner_id' ); } if ( ! empty( $args['segment'] ) ) { $parts[] = Nodebook_Segments::where( (int) $args['segment'] ); } // Drill-down from Journeys: kind (new, buyers, back, source), period, source/medium. $j = isset( $args['journey'] ) && is_array( $args['journey'] ) ? $args['journey'] : array(); if ( $j ) { $since = Nodebook_Report::since( (int) $j['days'] ); if ( 'back' === $j['kind'] ) { $parts[] = array( 'c.last_seen >= %s AND c.visits_count > 0', array( $since ) ); } else { $parts[] = array( 'c.created_at >= %s', array( $since ) ); } if ( 'buyers' === $j['kind'] ) { $parts[] = array( 'c.orders_count > 0', array() ); } if ( 'source' === $j['kind'] ) { $parts[] = array( 'c.first_source = %s AND c.first_medium = %s', array( (string) $j['source'], (string) $j['medium'] ) ); } } return Nodebook_Sql::join( $parts ); } /** * Recalculate visit counters for a contact from its activities. */ public static function recount_visits( $id ) { global $wpdb; $a = Nodebook_Install::table( 'activities' ); $stats = $wpdb->get_row( $wpdb->prepare( "SELECT COUNT(*) AS visits, MIN(created_at) AS first_seen, MAX(created_at) AS last_seen FROM %i WHERE contact_id = %d AND type IN ('visit','pageview')", $a, $id ), ARRAY_A ); $count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE contact_id = %d AND type = 'visit'", $a, $id ) ); $wpdb->update( self::table(), array( 'visits_count' => $count, 'first_seen' => $stats && $stats['first_seen'] ? $stats['first_seen'] : null, 'last_seen' => $stats && $stats['last_seen'] ? $stats['last_seen'] : null, ), array( 'id' => (int) $id ) ); } }