get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', self::table(), $id ), ARRAY_A ); return $row ? self::hydrate( $row ) : null; } private 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 find_by_name( $name ) { global $wpdb; $name = trim( sanitize_text_field( $name ) ); if ( '' === $name ) { return null; } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE LOWER(name) = LOWER(%s) ORDER BY id ASC LIMIT 1', self::table(), $name ), ARRAY_A ); return $row ? self::hydrate( $row ) : null; } public static function find_by_domain( $domain ) { global $wpdb; $domain = self::normalize_domain( $domain ); if ( '' === $domain ) { return null; } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE domain = %s', self::table(), $domain ), ARRAY_A ); return $row ? self::hydrate( $row ) : null; } public static function normalize_domain( $value ) { $value = strtolower( trim( (string) $value ) ); if ( false !== strpos( $value, '@' ) ) { $value = substr( strrchr( $value, '@' ), 1 ); } $host = wp_parse_url( preg_match( '#^https?://#', $value ) ? $value : 'http://' . $value, PHP_URL_HOST ); $host = $host ? preg_replace( '/^www\./', '', $host ) : ''; return preg_match( '/^[a-z0-9.-]+\.[a-z]{2,}$/', $host ) ? substr( $host, 0, 190 ) : ''; } public static function is_free_mail( $domain ) { return in_array( self::normalize_domain( $domain ), apply_filters( 'nodebook_free_mail_domains', self::FREE_MAIL ), true ); } public static function prepare( array $data ) { $defs = Nodebook_Fields::company(); $out = array(); foreach ( $data as $key => $value ) { if ( ! in_array( $key, self::COLUMNS, true ) ) { continue; } if ( 'meta' === $key ) { $out['meta'] = wp_json_encode( Nodebook_Contacts::clean_meta( (array) $value ) ); } elseif ( 'domain' === $key ) { $d = self::normalize_domain( $value ); $out['domain'] = '' === $d ? null : $d; } elseif ( isset( $defs[ $key ] ) ) { $out[ $key ] = Nodebook_Fields::clean( $key, $value, $defs[ $key ] ); } } if ( empty( $out['domain'] ) && ! empty( $out['website'] ) && ! array_key_exists( 'domain', $data ) ) { $d = self::normalize_domain( $out['website'] ); if ( $d && ! self::find_by_domain( $d ) ) { $out['domain'] = $d; } } return $out; } public static function insert( array $data ) { global $wpdb; $row = self::prepare( $data ); if ( empty( $row['name'] ) ) { return 0; } $now = current_time( 'mysql', true ); $row['created_at'] = $now; $row['updated_at'] = $now; if ( ! isset( $row['meta'] ) ) { $row['meta'] = '{}'; } if ( false === $wpdb->insert( self::table(), $row ) ) { return 0; } $id = (int) $wpdb->insert_id; do_action( 'nodebook_company_created', $id, $row ); return $id; } public static function update( $id, array $data ) { global $wpdb; $row = self::prepare( $data ); if ( ! $row ) { return true; } if ( array_key_exists( 'name', $row ) && '' === $row['name'] ) { unset( $row['name'] ); } $row['updated_at'] = current_time( 'mysql', true ); $ok = false !== $wpdb->update( self::table(), $row, array( 'id' => (int) $id ) ); if ( $ok ) { do_action( 'nodebook_company_updated', (int) $id, $row ); } return $ok; } /** * Find or create a company from a name and/or an email address. * * @return int Company ID or 0. */ public static function resolve( $name, $email = '' ) { $name = trim( (string) $name ); if ( '' !== $name ) { $found = self::find_by_name( $name ); if ( $found ) { return $found['id']; } $domain = ( $email && ! self::is_free_mail( $email ) ) ? self::normalize_domain( $email ) : ''; if ( $domain ) { $by_domain = self::find_by_domain( $domain ); if ( $by_domain ) { return $by_domain['id']; } } return self::insert( array( 'name' => $name, 'domain' => $domain, ) ); } if ( $email && Nodebook_Settings::get( 'auto_company' ) && ! self::is_free_mail( $email ) ) { $domain = self::normalize_domain( $email ); if ( ! $domain ) { return 0; } $found = self::find_by_domain( $domain ); if ( $found ) { return $found['id']; } $label = explode( '.', $domain ); return self::insert( array( 'name' => ucwords( str_replace( '-', ' ', $label[0] ) ), 'domain' => $domain, 'website' => 'https://' . $domain, ) ); } return 0; } /** * Create or update by domain, then by name (used by CSV import). */ public static function upsert( array $data, $policy = 'overwrite' ) { $existing = null; if ( ! empty( $data['domain'] ) ) { $existing = self::find_by_domain( $data['domain'] ); } if ( ! $existing && ! empty( $data['name'] ) ) { $existing = self::find_by_name( $data['name'] ); } if ( ! $existing ) { return array( 'id' => self::insert( $data ), 'created' => true ); } if ( 'fill' === $policy ) { foreach ( $data as $k => $v ) { if ( isset( $existing[ $k ] ) && '' !== (string) $existing[ $k ] ) { unset( $data[ $k ] ); } } } $data = array_filter( $data, static function ( $v ) { return '' !== $v && null !== $v; } ); self::update( $existing['id'], $data ); return array( 'id' => $existing['id'], 'created' => false ); } public static function delete( array $ids ) { global $wpdb; $ids = array_filter( array_map( 'absint', $ids ) ); foreach ( $ids as $id ) { $wpdb->delete( self::table(), array( 'id' => $id ) ); $wpdb->update( Nodebook_Contacts::table(), array( 'company_id' => 0 ), array( 'company_id' => $id ) ); $wpdb->update( Nodebook_Deals::table(), array( 'company_id' => 0 ), array( 'company_id' => $id ) ); } Nodebook_Props::delete_for( 'company', $ids ); return count( $ids ); } public static function query( array $args = array() ) { global $wpdb; $args = wp_parse_args( $args, array( 'search' => '', 'orderby' => 'name', 'order' => 'ASC', 'per_page' => 25, 'page' => 1, 'ids' => array(), ) ); $parts = array(); if ( '' !== $args['search'] ) { $like = '%' . $wpdb->esc_like( $args['search'] ) . '%'; $parts[] = array( 'co.name LIKE %s OR co.domain LIKE %s OR co.city LIKE %s', array( $like, $like, $like ) ); } if ( $args['ids'] ) { $parts[] = Nodebook_Sql::in_ids( 'co.id', array_map( 'absint', (array) $args['ids'] ) ); } list( $where, $params ) = Nodebook_Sql::join( $parts ); $sortable = array( 'name', 'domain', 'city', 'country', 'created_at', 'contacts' ); $orderby = in_array( $args['orderby'], $sortable, true ) ? $args['orderby'] : 'name'; $desc = 'DESC' === strtoupper( $args['order'] ); // Fixed SQL only: sort by the contact count, or by a company column given as an %i identifier. if ( 'contacts' === $orderby ) { $tail = $desc ? ' ORDER BY contacts DESC, co.id ASC' : ' ORDER BY contacts ASC, co.id ASC'; $sort = array(); } else { $tail = $desc ? ' ORDER BY %i.%i DESC, co.id ASC' : ' ORDER BY %i.%i ASC, co.id ASC'; $sort = array( 'co', $orderby ); } $page = $args['per_page'] > 0 ? array( (int) $args['per_page'], max( 0, ( (int) $args['page'] - 1 ) * (int) $args['per_page'] ) ) : array( PHP_INT_MAX, 0 ); // 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 co WHERE ' . $where, array_merge( array( self::table() ), $params ) ) ); $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT co.*, (SELECT COUNT(*) FROM %i c WHERE c.company_id = co.id) AS contacts FROM %i co WHERE ' . $where . $tail . ' LIMIT %d OFFSET %d', array_merge( array( Nodebook_Contacts::table(), self::table() ), $params, $sort, $page ) ), 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, ); } public static function all_names() { global $wpdb; return $wpdb->get_results( $wpdb->prepare( 'SELECT id, name FROM %i ORDER BY name ASC LIMIT 2000', self::table() ), ARRAY_A ); } }