array( 'email', 'first_name', 'last_name', 'phone', 'status' ), 'company' => array( 'name', 'domain' ), 'deal' => array(), ); public static function init() { add_action( self::JOB_HOOK, array( __CLASS__, 'run_jobs' ) ); } public static function table() { return Nodebook_Install::table( 'values' ); } public static function objects() { return array( 'contact', 'company', 'deal' ); } public static function types() { return array( 'text' => __( 'Text', 'nodebook' ), 'textarea' => __( 'Long text', 'nodebook' ), 'number' => __( 'Number', 'nodebook' ), 'money' => __( 'Amount', 'nodebook' ), 'date' => __( 'Date', 'nodebook' ), 'select' => __( 'Choice', 'nodebook' ), 'checkbox' => __( 'Yes / no', 'nodebook' ), 'url' => __( 'Link', 'nodebook' ), ); } /* ------------------------------------------------------------------ * * Definitions * ------------------------------------------------------------------ */ /** * Custom fields of an object, in display order: key => [ label, type, options[], aliases[] ]. */ public static function defs( $object = 'contact' ) { $all = get_option( self::OPTION, array() ); $defs = is_array( $all ) && isset( $all[ $object ] ) && is_array( $all[ $object ] ) ? $all[ $object ] : array(); uasort( $defs, static function ( $a, $b ) { return (int) ( $a['order'] ?? 0 ) <=> (int) ( $b['order'] ?? 0 ); } ); return $defs; } public static function get( $object, $key ) { $defs = self::defs( $object ); return isset( $defs[ $key ] ) ? $defs[ $key ] : null; } public static function is_key( $key ) { return is_string( $key ) && 0 === strpos( $key, 'cf_' ); } private static function store( $object, array $defs ) { $all = get_option( self::OPTION, array() ); $all = is_array( $all ) ? $all : array(); $all[ $object ] = $defs; update_option( self::OPTION, $all, true ); } /** "Check-in date" → "checkindate": how labels and form names are compared. */ public static function norm( $label ) { $label = remove_accents( strtolower( wp_strip_all_tags( (string) $label ) ) ); return (string) preg_replace( '/[^a-z0-9]+/', '', $label ); } /** Options of a choice field from text: one per line or comma-separated. */ public static function parse_options( $raw ) { $list = is_array( $raw ) ? $raw : preg_split( '/[\r\n,]+/', (string) $raw ); $out = array(); foreach ( $list as $o ) { $o = mb_substr( trim( sanitize_text_field( (string) $o ) ), 0, 100 ); if ( '' !== $o && ! in_array( $o, $out, true ) ) { $out[] = $o; } if ( count( $out ) >= 50 ) { break; } } return $out; } /** * Create or update a field. Returns its key, or '' when invalid (no label, too many fields, * or a label that is already taken). * * @param string $object contact|company. * @param array $in label, type, options, aliases. * @param string $key Existing key to update. */ public static function save_def( $object, array $in, $key = '' ) { if ( ! in_array( $object, self::objects(), true ) ) { return ''; } $defs = self::defs( $object ); $label = mb_substr( trim( sanitize_text_field( (string) ( $in['label'] ?? '' ) ) ), 0, 80 ); if ( '' === $label ) { return ''; } foreach ( $defs as $k => $d ) { if ( $k !== $key && self::norm( $d['label'] ) === self::norm( $label ) ) { return ''; } } if ( $key && ! isset( $defs[ $key ] ) ) { return ''; } if ( ! $key ) { if ( count( $defs ) >= self::MAX ) { return ''; } $base = 'cf_' . substr( (string) preg_replace( '/[^a-z0-9]+/', '_', remove_accents( strtolower( $label ) ) ), 0, 40 ); $base = rtrim( $base, '_' ); $base = 'cf_' === $base || 'cf' === $base ? 'cf_field' : $base; $key = $base; for ( $i = 2; isset( $defs[ $key ] ); $i++ ) { $key = $base . '_' . $i; } $type = isset( self::types()[ $in['type'] ?? '' ] ) ? $in['type'] : 'text'; $order = 1; foreach ( $defs as $d ) { $order = max( $order, (int) ( $d['order'] ?? 0 ) + 1 ); } } else { // The type of an existing field never changes: its stored values were converted for it. $type = $defs[ $key ]['type']; $order = isset( $in['order'] ) ? (int) $in['order'] : (int) ( $defs[ $key ]['order'] ?? 0 ); } $old = isset( $defs[ $key ]['label'] ) ? array( $defs[ $key ]['label'] ) : array(); // A renamed field still catches forms using its old name. $aliases = array_values( array_unique( array_filter( array_map( array( __CLASS__, 'norm' ), array_merge( (array) ( $defs[ $key ]['aliases'] ?? array() ), (array) ( $in['aliases'] ?? array() ), $old ) ) ) ) ); $card_was = ! empty( $defs[ $key ]['card'] ); $defs[ $key ] = array( 'label' => $label, 'type' => $type, 'options' => 'select' === $type ? self::parse_options( $in['options'] ?? ( $defs[ $key ]['options'] ?? array() ) ) : array(), 'aliases' => array_slice( $aliases, 0, 30 ), 'order' => $order, ); // Deal fields can be shown on the cards of the deals board. if ( 'deal' === $object && ( isset( $in['card'] ) ? ! empty( $in['card'] ) : $card_was ) ) { $defs[ $key ]['card'] = true; } // A name belongs to one field: the field that is called this now takes it over from older aliases. $mine = self::norm( $label ); foreach ( $defs as $k => $d ) { if ( $k !== $key && ! empty( $d['aliases'] ) ) { $defs[ $k ]['aliases'] = array_values( array_diff( $d['aliases'], array( $mine ) ) ); } } $defs[ $key ]['aliases'] = array_values( array_diff( $defs[ $key ]['aliases'], array_map( array( __CLASS__, 'norm' ), wp_list_pluck( array_diff_key( $defs, array( $key => 1 ) ), 'label' ) ) ) ); self::store( $object, $defs ); return $key; } /** Remove a field and all of its values. */ public static function delete_def( $object, $key ) { global $wpdb; $defs = self::defs( $object ); if ( ! isset( $defs[ $key ] ) ) { return false; } unset( $defs[ $key ] ); self::store( $object, $defs ); $wpdb->delete( self::table(), array( 'object_type' => $object, 'field_key' => $key, ) ); return true; } /* ------------------------------------------------------------------ * * Built-in fields: rename and hide * ------------------------------------------------------------------ */ public static function builtin( $object ) { $all = get_option( self::BUILTIN, array() ); return is_array( $all ) && isset( $all[ $object ] ) && is_array( $all[ $object ] ) ? $all[ $object ] : array(); } /** * @param array $in key => [ label, hidden ]. */ public static function save_builtin( $object, array $in, array $defaults ) { $out = array(); foreach ( $in as $key => $o ) { if ( ! isset( $defaults[ $key ] ) || ! empty( $defaults[ $key ]['readonly'] ) ) { continue; } $label = mb_substr( trim( sanitize_text_field( (string) ( $o['label'] ?? '' ) ) ), 0, 80 ); $hidden = ! empty( $o['hidden'] ) && ! in_array( $key, self::LOCKED[ $object ], true ); $row = array(); $orig = $defaults[ $key ]['default_label'] ?? $defaults[ $key ]['label']; if ( '' !== $label && $label !== $orig ) { $row['label'] = $label; } if ( $hidden ) { $row['hidden'] = true; } if ( $row ) { $out[ $key ] = $row; } } $all = get_option( self::BUILTIN, array() ); $all = is_array( $all ) ? $all : array(); $all[ $object ] = $out; update_option( self::BUILTIN, $all, true ); } /** Apply renames and hidden flags to a built-in definition list (used by Nodebook_Fields). */ public static function apply_builtin( $object, array $fields ) { foreach ( self::builtin( $object ) as $key => $o ) { if ( ! isset( $fields[ $key ] ) ) { continue; } if ( ! empty( $o['label'] ) ) { $fields[ $key ]['default_label'] = $fields[ $key ]['label']; $fields[ $key ]['label'] = $o['label']; } if ( ! empty( $o['hidden'] ) && ! in_array( $key, self::LOCKED[ $object ], true ) ) { $fields[ $key ]['hidden'] = true; } } return $fields; } public static function hidden( $object, $key ) { $o = self::builtin( $object ); return ! empty( $o[ $key ]['hidden'] ) && ! in_array( $key, self::LOCKED[ $object ], true ); } /* ------------------------------------------------------------------ * * Values * ------------------------------------------------------------------ */ /** Yes / no from what people type in forms and spreadsheets. */ public static function truthy( $v ) { $v = strtolower( trim( (string) $v ) ); if ( in_array( $v, array( '1', 'yes', 'y', 'true', 'on', 'checked', 'ja', 'si', 'sí', 'oui', 'x', '✓' ), true ) ) { return true; } if ( in_array( $v, array( '0', 'no', 'n', 'false', 'off', 'nee', 'nein', 'non' ), true ) ) { return false; } return null; } /** "1.250,50", "1,250.50", "€ 300k" → float, or null. */ public static function to_number( $v ) { $s = strtolower( trim( (string) $v ) ); $m = 1; if ( preg_match( '/^(.*\d)\s*(k|m)$/', $s, $x ) ) { $s = $x[1]; $m = 'k' === $x[2] ? 1000 : 1000000; } $s = preg_replace( '/[^0-9,.\-]/', '', $s ); if ( '' === $s || '-' === $s ) { return null; } $dot = strrpos( $s, '.' ); $comma = strrpos( $s, ',' ); if ( false !== $dot && false !== $comma ) { // The last separator is the decimal one. $s = $dot > $comma ? str_replace( ',', '', $s ) : str_replace( array( '.', ',' ), array( '', '.' ), $s ); } elseif ( false !== $comma ) { // "1,250" is a thousand; "12,5" is twelve and a half. $s = preg_match( '/^-?\d{1,3}(,\d{3})+$/', $s ) ? str_replace( ',', '', $s ) : str_replace( ',', '.', $s ); } elseif ( preg_match( '/^-?\d{1,3}(\.\d{3})+$/', $s ) ) { // "300.000" / "2.500.000": dots as thousands separators (a decimal never has exactly three digits here). $s = str_replace( '.', '', $s ); } return is_numeric( $s ) ? (float) $s * $m : null; } /** Dates as people write them → Y-m-d, or ''. */ public static function to_date( $v ) { $v = trim( (string) $v ); if ( '' === $v ) { return ''; } if ( preg_match( '/^(\d{4})-(\d{1,2})-(\d{1,2})/', $v, $m ) ) { return checkdate( (int) $m[2], (int) $m[3], (int) $m[1] ) ? sprintf( '%04d-%02d-%02d', $m[1], $m[2], $m[3] ) : ''; } if ( preg_match( '#^(\d{1,2})[/.\-](\d{1,2})[/.\-](\d{2,4})$#', $v, $m ) ) { $a = (int) $m[1]; $b = (int) $m[2]; $y = (int) $m[3]; $y = $y < 100 ? 2000 + $y : $y; // Month first only when it must be (day > 12) or the site writes dates that way. $us = $b > 12 || ( $a <= 12 && preg_match( '/^[mnFM]/', (string) get_option( 'date_format', 'Y-m-d' ) ) ); list( $mo, $d ) = $us ? array( $a, $b ) : array( $b, $a ); return checkdate( $mo, $d, $y ) ? sprintf( '%04d-%02d-%02d', $y, $mo, $d ) : ''; } $ts = strtotime( $v ); return $ts ? gmdate( 'Y-m-d', $ts ) : ''; } /** * Normalise a value for a field: [ text, num, date ] or null when empty / not valid. */ public static function convert( array $def, $value ) { if ( is_array( $value ) ) { $value = implode( ', ', array_map( 'strval', array_filter( $value, 'is_scalar' ) ) ); } $value = 'textarea' === $def['type'] ? sanitize_textarea_field( (string) $value ) : sanitize_text_field( (string) $value ); $value = trim( $value ); if ( '' === $value ) { return null; } switch ( $def['type'] ) { case 'number': case 'money': $n = self::to_number( $value ); if ( null === $n ) { return null; } $n = round( $n, 'money' === $def['type'] ? 2 : 4 ); return array( rtrim( rtrim( number_format( $n, 4, '.', '' ), '0' ), '.' ), $n, null ); case 'date': $d = self::to_date( $value ); return $d ? array( $d, null, $d ) : null; case 'checkbox': $b = self::truthy( $value ); return null === $b ? null : array( $b ? '1' : '0', $b ? 1 : 0, null ); case 'select': foreach ( (array) $def['options'] as $o ) { if ( self::norm( $o ) === self::norm( $value ) ) { return array( $o, null, null ); } } // Not one of the choices (an old form option, a typo): keep it rather than lose it. return array( mb_substr( $value, 0, 100 ), null, null ); case 'url': if ( ! preg_match( '#^https?://#i', $value ) ) { $value = 'https://' . $value; } $value = esc_url_raw( $value ); return '' === $value ? null : array( mb_substr( $value, 0, self::TEXT_MAX ), null, null ); } return array( mb_substr( $value, 0, self::TEXT_MAX ), null, null ); } /** * Stored values for one record: key => text. */ public static function values( $object, $id ) { $all = self::values_for( $object, array( $id ) ); return isset( $all[ (int) $id ] ) ? $all[ (int) $id ] : array(); } /** * Stored values for many records in one query: id => [ key => text ]. */ public static function values_for( $object, array $ids ) { global $wpdb; $ids = array_values( array_unique( array_filter( array_map( 'absint', $ids ) ) ) ); if ( ! $ids || ! self::defs( $object ) ) { return array(); } $out = array(); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- one %d placeholder per ID. $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT object_id, field_key, value_text FROM %i WHERE object_type = %s AND object_id IN (' . Nodebook_Sql::list_of( count( $ids ) ) . ')', array_merge( array( self::table(), (string) $object ), $ids ) ), ARRAY_A ); foreach ( (array) $rows as $r ) { $out[ (int) $r['object_id'] ][ $r['field_key'] ] = (string) $r['value_text']; } return $out; } /** * Save values for a record. * * @param string $object contact|company. * @param int $id Record ID. * @param array $vals key => raw value. Unknown keys are ignored. * @param string $policy overwrite (empty clears) | overwrite_nonempty (new values win, empty ones are ignored) * | fill (only fills fields that have no value). * @return int Number of fields written or cleared. */ public static function set( $object, $id, array $vals, $policy = 'overwrite' ) { global $wpdb; $id = absint( $id ); $defs = self::defs( $object ); if ( ! $id || ! $defs || ! $vals ) { return 0; } $have = 'fill' === $policy ? self::values( $object, $id ) : array(); $n = 0; foreach ( $vals as $key => $raw ) { if ( ! isset( $defs[ $key ] ) ) { continue; } $v = self::convert( $defs[ $key ], $raw ); if ( null === $v ) { if ( 'overwrite' === $policy ) { $n += (int) $wpdb->delete( self::table(), array( 'object_type' => $object, 'object_id' => $id, 'field_key' => $key, ) ); } continue; } if ( 'fill' === $policy && isset( $have[ $key ] ) && '' !== $have[ $key ] ) { continue; } $wpdb->replace( self::table(), array( 'object_type' => $object, 'object_id' => $id, 'field_key' => $key, 'value_text' => $v[0], 'value_num' => $v[1], 'value_date' => $v[2], ) ); ++$n; } return $n; } /** Remove every value of deleted records. */ public static function delete_for( $object, array $ids ) { global $wpdb; $ids = array_values( array_filter( array_map( 'absint', $ids ) ) ); if ( $ids ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- one %d placeholder per ID. $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE object_type = %s AND object_id IN (' . Nodebook_Sql::list_of( count( $ids ) ) . ')', array_merge( array( self::table(), (string) $object ), $ids ) ) ); } } /** Merge: the kept record keeps its values; fields it lacks are filled from the other one. */ public static function merge( $object, $keep, $merge ) { global $wpdb; $t = self::table(); $keys = $wpdb->get_col( $wpdb->prepare( 'SELECT field_key FROM %i WHERE object_type = %s AND object_id = %d', $t, $object, $keep ) ); foreach ( (array) $keys as $k ) { $wpdb->delete( $t, array( 'object_type' => $object, 'object_id' => (int) $merge, 'field_key' => $k, ) ); } $wpdb->update( $t, array( 'object_id' => (int) $keep ), array( 'object_type' => $object, 'object_id' => (int) $merge, ) ); } /** How a stored value reads on screen. */ public static function display( array $def, $text ) { $text = (string) $text; switch ( $def['type'] ) { case 'checkbox': return '1' === $text ? __( 'Yes', 'nodebook' ) : __( 'No', 'nodebook' ); case 'money': return Nodebook_Report::money( (float) $text ); case 'number': return is_numeric( $text ) ? number_format_i18n( (float) $text, floor( (float) $text ) == (float) $text ? 0 : 2 ) : $text; // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- comparing a float with its whole part. case 'date': $ts = strtotime( $text . ' 12:00:00 UTC' ); return $ts ? wp_date( (string) get_option( 'date_format', 'Y-m-d' ), $ts ) : $text; } return $text; } /* ------------------------------------------------------------------ * * Matching incoming data to fields * ------------------------------------------------------------------ */ /** * The field a form field / CSV column / custom-field name belongs to, or ''. * Matches the field's label and every name it was created from. */ public static function match( $object, $label, $key = '' ) { $cands = array_filter( array( self::norm( $label ), self::norm( $key ) ) ); if ( ! $cands ) { return ''; } foreach ( self::defs( $object ) as $k => $d ) { $names = (array) ( $d['aliases'] ?? array() ); $names[] = self::norm( $d['label'] ); if ( array_intersect( $cands, $names ) ) { return $k; } } return ''; } /** * Split free-form custom fields into defined fields and the rest. * * @return array{0:array,1:array} [ props key => value, remaining meta ]. */ public static function split_meta( $object, array $meta ) { $props = array(); $rest = array(); foreach ( $meta as $label => $value ) { $k = self::match( $object, $label ); if ( $k ) { if ( ! isset( $props[ $k ] ) || '' === trim( (string) $props[ $k ] ) ) { $props[ $k ] = $value; } } else { $rest[ $label ] = $value; } } return array( $props, $rest ); } /* ------------------------------------------------------------------ * * Ready-made fields per business type * ------------------------------------------------------------------ */ /** label => [ type, options, aliases ]. */ public static function presets( $niche = '' ) { $niche = $niche ? $niche : Nodebook_Niche::current(); $sets = array( 'rentals' => array( __( 'Check-in', 'nodebook' ) => array( 'date', array(), array( 'arrival', 'arrival date', 'check in date', 'llegada', 'aankomst', 'from' ) ), __( 'Check-out', 'nodebook' ) => array( 'date', array(), array( 'departure', 'departure date', 'check out date', 'salida', 'vertrek', 'to' ) ), __( 'Guests', 'nodebook' ) => array( 'number', array(), array( 'number of guests', 'adults', 'people', 'huespedes', 'personas', 'gasten', 'party size' ) ), __( 'Budget', 'nodebook' ) => array( 'money', array(), array( 'presupuesto', 'price range' ) ), ), 'realestate' => array( __( 'Looking to', 'nodebook' ) => array( 'select', array( __( 'Buy', 'nodebook' ), __( 'Rent', 'nodebook' ), __( 'Sell', 'nodebook' ) ), array( 'buy or rent', 'interested in', 'operation', 'operacion', 'tipo de operacion' ) ), __( 'Budget', 'nodebook' ) => array( 'money', array(), array( 'presupuesto', 'price range', 'max price', 'maximum price' ) ), __( 'Bedrooms', 'nodebook' ) => array( 'number', array(), array( 'beds', 'rooms', 'habitaciones', 'recamaras', 'slaapkamers' ) ), __( 'Move-in date', 'nodebook' ) => array( 'date', array(), array( 'move in', 'when', 'timeline date' ) ), ), 'services' => array( __( 'Preferred date', 'nodebook' ) => array( 'date', array(), array( 'date', 'appointment date', 'fecha', 'datum' ) ), __( 'Budget', 'nodebook' ) => array( 'money', array(), array( 'presupuesto' ) ), __( 'How did you hear about us', 'nodebook' ) => array( 'text', array(), array( 'referral', 'how did you find us', 'heard about us', 'como nos conocio' ) ), ), 'retreats' => array( __( 'Retreat of interest', 'nodebook' ) => array( 'text', array(), array( 'retreat', 'which retreat', 'event', 'program', 'programme', 'retiro', 'which event' ) ), __( 'Preferred dates', 'nodebook' ) => array( 'text', array(), array( 'dates', 'when', 'preferred date', 'fechas', 'travel dates' ) ), __( 'Group size', 'nodebook' ) => array( 'number', array(), array( 'number of people', 'people', 'guests', 'how many', 'personas', 'party size' ) ), __( 'Room preference', 'nodebook' ) => array( 'select', array( __( 'Private', 'nodebook' ), __( 'Shared', 'nodebook' ), __( 'No preference', 'nodebook' ) ), array( 'room', 'room type', 'accommodation', 'habitacion' ) ), __( 'Dietary preferences', 'nodebook' ) => array( 'text', array(), array( 'diet', 'dietary', 'food preferences', 'dieta' ) ), __( 'How did you hear about us', 'nodebook' ) => array( 'text', array(), array( 'referral', 'how did you find us', 'heard about us', 'como nos conocio' ) ), ), 'b2b' => array( __( 'Team size', 'nodebook' ) => array( 'select', array( '1–10', '11–50', '51–200', '201–1000', '1000+' ), array( 'employees', 'company size', 'number of employees' ) ), __( 'Timeline', 'nodebook' ) => array( 'select', array( __( 'Now', 'nodebook' ), __( 'This quarter', 'nodebook' ), __( 'This year', 'nodebook' ), __( 'Just looking', 'nodebook' ) ), array( 'when', 'timeframe', 'time frame' ) ), __( 'Budget', 'nodebook' ) => array( 'money', array(), array( 'project budget', 'presupuesto' ) ), ), 'shop' => array( __( 'Birthday', 'nodebook' ) => array( 'date', array(), array( 'date of birth', 'birth date', 'dob', 'cumpleanos', 'verjaardag' ) ), __( 'Newsletter consent', 'nodebook' ) => array( 'checkbox', array(), array( 'newsletter', 'subscribe', 'marketing consent', 'opt in' ) ), ), 'general' => array( __( 'Budget', 'nodebook' ) => array( 'money', array(), array( 'presupuesto' ) ), __( 'Timeline', 'nodebook' ) => array( 'text', array(), array( 'when', 'timeframe' ) ), ), ); return (array) apply_filters( 'nodebook_field_presets', $sets[ $niche ] ?? $sets['general'], $niche ); } /** Presets not added yet. */ public static function missing_presets() { $out = array(); foreach ( self::presets() as $label => $p ) { if ( ! self::match( 'contact', $label ) ) { $out[ $label ] = $p; } } return $out; } /** Add all missing presets; returns the keys created. */ public static function add_presets() { $keys = array(); foreach ( self::missing_presets() as $label => $p ) { $k = self::save_def( 'contact', array( 'label' => $label, 'type' => $p[0], 'options' => $p[1], 'aliases' => $p[2], ) ); if ( $k ) { $keys[] = $k; self::queue( 'contact', $k, array_merge( array( $label ), $p[2] ) ); } } return $keys; } /* ------------------------------------------------------------------ * * Turning captured custom fields into real fields * ------------------------------------------------------------------ */ /** * Custom-field names found on contacts (most recent 20,000 with any), grouped by how they read. * * @return array[] [ names[], count, example ] sorted by count. */ public static function discovered( $fresh = false ) { global $wpdb; $cached = $fresh ? false : get_transient( 'nodebook_found_fields' ); if ( is_array( $cached ) ) { return $cached; } $groups = array(); $last = PHP_INT_MAX; $seen = 0; while ( $seen < 20000 ) { $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, meta FROM %i WHERE id < %d AND meta IS NOT NULL AND meta <> '' AND meta <> '{}' AND meta <> '[]' ORDER BY id DESC LIMIT 2000", Nodebook_Contacts::table(), $last ), ARRAY_A ); if ( ! $rows ) { break; } foreach ( $rows as $r ) { $last = (int) $r['id']; $meta = json_decode( (string) $r['meta'], true ); foreach ( is_array( $meta ) ? $meta : array() as $name => $value ) { $n = self::norm( $name ); if ( '' === $n ) { continue; } if ( ! isset( $groups[ $n ] ) ) { $groups[ $n ] = array( 'key' => $n, 'names' => array(), 'count' => 0, 'example' => '', ); } $groups[ $n ]['names'][ (string) $name ] = true; ++$groups[ $n ]['count']; if ( '' === $groups[ $n ]['example'] && is_scalar( $value ) ) { $groups[ $n ]['example'] = mb_substr( (string) $value, 0, 60 ); } } } $seen += count( $rows ); if ( count( $rows ) < 2000 ) { break; } } foreach ( $groups as &$g ) { $g['names'] = array_slice( array_keys( $g['names'] ), 0, 10 ); } unset( $g ); usort( $groups, static function ( $a, $b ) { return $b['count'] <=> $a['count']; } ); $groups = array_slice( $groups, 0, 100 ); set_transient( 'nodebook_found_fields', $groups, HOUR_IN_SECONDS ); return $groups; } /** A field name as it is stored inside the JSON column, for LIKE searches. */ private static function json_needle( $name ) { return (string) wp_json_encode( (string) $name ) . ':'; } /** * Queue moving custom-field data (any of $names) into a field. Runs right away for a while, * then continues in the background. */ public static function queue( $object, $key, array $names ) { if ( 'contact' !== $object || ! self::get( $object, $key ) ) { return; } $names = array_values( array_unique( array_filter( array_map( 'strval', $names ), 'strlen' ) ) ); // Store every spelling we can see too ("Budget", "budget", "BUDGET"), since the JSON is matched literally. foreach ( self::discovered() as $g ) { foreach ( $names as $n ) { if ( self::norm( $n ) === $g['key'] ) { $names = array_merge( $names, $g['names'] ); } } } $names = array_slice( array_values( array_unique( $names ) ), 0, 40 ); if ( ! $names ) { return; } $jobs = get_option( self::JOBS, array() ); $jobs = is_array( $jobs ) ? $jobs : array(); $jobs[] = array( 'object' => $object, 'key' => $key, 'names' => $names, 'cursor' => 0, 'moved' => 0, ); update_option( self::JOBS, $jobs, false ); self::run_jobs( 4 ); } public static function pending() { $jobs = get_option( self::JOBS, array() ); return is_array( $jobs ) ? $jobs : array(); } /** * Work through queued moves for up to $seconds; schedules itself again when not finished. * * @return int Contacts updated in this run. */ public static function run_jobs( $seconds = 20 ) { global $wpdb; $start = microtime( true ); $jobs = self::pending(); $done = 0; $t = Nodebook_Contacts::table(); while ( $jobs && microtime( true ) - $start < (float) $seconds ) { $job = $jobs[0]; $def = self::get( $job['object'], $job['key'] ); if ( ! $def ) { array_shift( $jobs ); continue; } $names = array_values( (array) $job['names'] ); if ( ! $names ) { array_shift( $jobs ); continue; } $args = array( $t, (int) $job['cursor'] ); foreach ( $names as $n ) { $args[] = '%' . $wpdb->esc_like( self::json_needle( $n ) ) . '%'; } // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- one "meta LIKE %s" per name. $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT id, meta FROM %i WHERE id > %d AND ( ' . implode( ' OR ', array_fill( 0, count( $names ), 'meta LIKE %s' ) ) . ' ) ORDER BY id ASC LIMIT 500', $args ), ARRAY_A ); $inserts = array(); foreach ( (array) $rows as $r ) { $meta = json_decode( (string) $r['meta'], true ); $meta = is_array( $meta ) ? $meta : array(); $value = ''; foreach ( $job['names'] as $n ) { if ( array_key_exists( $n, $meta ) ) { if ( '' === $value && '' !== trim( (string) $meta[ $n ] ) ) { $value = $meta[ $n ]; } unset( $meta[ $n ] ); } } $job['cursor'] = (int) $r['id']; $converted = '' !== $value ? self::convert( $def, $value ) : null; if ( '' !== $value && null === $converted ) { // Could not be read as this type (e.g. "next summer" for a date): keep it as it was. continue; } if ( null !== $converted ) { // One row: text, then number and date ('' becomes NULL in the query). $inserts[] = array( (string) $job['object'], (int) $r['id'], (string) $job['key'], (string) $converted[0], null === $converted[1] ? '' : (string) wp_json_encode( (float) $converted[1] ), null === $converted[2] ? '' : (string) $converted[2] ); } $wpdb->update( $t, array( 'meta' => wp_json_encode( $meta ) ), array( 'id' => (int) $r['id'] ) ); ++$job['moved']; ++$done; } if ( $inserts ) { // INSERT IGNORE = "fill": a value someone already entered in the field is kept. // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- one fixed row of placeholders per value set. $wpdb->query( $wpdb->prepare( 'INSERT IGNORE INTO %i (object_type, object_id, field_key, value_text, value_num, value_date) VALUES ' . implode( ',', array_fill( 0, count( $inserts ), "(%s, %d, %s, %s, NULLIF(%s, ''), NULLIF(%s, ''))" ) ), array_merge( array( self::table() ), ...$inserts ) ) ); } if ( ! $rows || count( $rows ) < 500 ) { array_shift( $jobs ); } else { $jobs[0] = $job; } } update_option( self::JOBS, $jobs, false ); delete_transient( 'nodebook_found_fields' ); if ( $jobs && ! wp_next_scheduled( self::JOB_HOOK ) ) { wp_schedule_single_event( time() + 30, self::JOB_HOOK ); } return $done; } }