get_row( $wpdb->prepare( 'SELECT * FROM ' . self::table() . ' WHERE id = %d', $id ), ARRAY_A ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. } public static function normalize_phone( $phone ) { return preg_replace( '/[^\d+]/', '', (string) $phone ); } /** * Find a guest by email, falling back to phone. */ public static function find( $email, $phone = '' ) { global $wpdb; $email = strtolower( trim( (string) $email ) ); if ( $email ) { $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::table() . ' WHERE email = %s ORDER BY id ASC LIMIT 1', $email ), ARRAY_A ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. if ( $row ) { return $row; } } $phone = self::normalize_phone( $phone ); if ( strlen( preg_replace( '/\D/', '', $phone ) ) >= 6 ) { // Only match phone-only guests, so two people sharing a number keep separate email records. return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::table() . " WHERE phone = %s AND email = '' ORDER BY id ASC LIMIT 1", $phone ), ARRAY_A ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. } return null; } /** * Find or create the guest for a reservation row. Returns the guest id (0 if no identity). */ public static function resolve( array $row ) { global $wpdb; $email = strtolower( trim( (string) ( $row['email'] ?? '' ) ) ); $phone = self::normalize_phone( $row['phone'] ?? '' ); if ( ! $email && strlen( preg_replace( '/\D/', '', $phone ) ) < 6 ) { return 0; } $guest = self::find( $email, $phone ); $now = current_time( 'mysql', true ); if ( $guest ) { // Keep contact details current without erasing known values. $update = array(); if ( ! empty( $row['name'] ) && $row['name'] !== $guest['name'] ) { $update['name'] = $row['name']; } if ( $phone && $phone !== $guest['phone'] ) { $update['phone'] = $phone; } if ( $email && ! $guest['email'] ) { $update['email'] = $email; } if ( ! empty( $row['marketing_optin'] ) && ! (int) $guest['marketing_optin'] ) { $update['marketing_optin'] = 1; } if ( $update ) { $update['updated_gmt'] = $now; $wpdb->update( self::table(), $update, array( 'id' => (int) $guest['id'] ) ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. } return (int) $guest['id']; } $data = apply_filters( 'tableengine_guest_insert_data', array( 'name' => (string) ( $row['name'] ?? '' ), 'email' => $email, 'phone' => $phone, 'marketing_optin' => empty( $row['marketing_optin'] ) ? 0 : 1, 'user_id' => email_exists( $email ) ? (int) email_exists( $email ) : 0, 'created_gmt' => $now, 'updated_gmt' => $now, ), $row ); $wpdb->insert( self::table(), $data ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. $id = (int) $wpdb->insert_id; if ( $id ) { do_action( 'tableengine_guest_created', $id, $row ); } return $id; } /** * Recalculate a guest's statistics from their reservations. */ public static function refresh_stats( $guest_id ) { global $wpdb; $guest_id = (int) $guest_id; if ( ! $guest_id ) { return; } $res = self::res_table(); // Fixed status slugs, escaped and quoted for the IN () lists below. $visited = "'" . implode( "','", array_map( 'esc_sql', self::VISITED ) ) . "'"; $skip = "'" . implode( "','", array_map( 'esc_sql', Reservations::non_booking_statuses() ) ) . "'"; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Only the internal table name and the escaped status lists above are interpolated. $stats = $wpdb->get_row( // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. $wpdb->prepare( "SELECT SUM( status NOT IN ({$skip}) ) AS bookings, SUM( status IN ({$visited}) ) AS visits, SUM( IF( status IN ({$visited}), party_size, 0 ) ) AS covers, SUM( status = 'cancelled' ) AS cancellations, SUM( status = 'no_show' ) AS no_shows, SUM( IF( payment_status IN ('paid','partially_refunded'), amount, 0 ) ) AS spent, MIN( IF( status IN ({$visited}), start_at, NULL ) ) AS first_visit, MAX( IF( status IN ({$visited}), start_at, NULL ) ) AS last_visit FROM {$res} WHERE guest_id = %d", $guest_id ), ARRAY_A ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( ! $stats ) { return; } $wpdb->update( // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. self::table(), array( 'bookings' => (int) $stats['bookings'], 'visits' => (int) $stats['visits'], 'covers' => (int) $stats['covers'], 'cancellations' => (int) $stats['cancellations'], 'no_shows' => (int) $stats['no_shows'], 'spent' => (int) $stats['spent'], 'first_visit' => $stats['first_visit'], 'last_visit' => $stats['last_visit'], 'updated_gmt' => current_time( 'mysql', true ), ), array( 'id' => $guest_id ) ); do_action( 'tableengine_guest_stats_refreshed', $guest_id ); } /** * Compact summary for the admin dashboard. */ public static function summary( $guest_id ) { $g = $guest_id ? self::get( $guest_id ) : null; if ( ! $g ) { return null; } return apply_filters( 'tableengine_guest_summary', array( 'id' => (int) $g['id'], 'bookings' => (int) $g['bookings'], 'visits' => (int) $g['visits'], 'cancellations' => (int) $g['cancellations'], 'no_shows' => (int) $g['no_shows'], 'last_visit' => $g['last_visit'] ? substr( $g['last_visit'], 0, 10 ) : '', 'tags' => array_values( array_filter( array_map( 'trim', explode( ',', $g['tags'] ) ) ) ), ), $g ); } /** * Update editable guest columns: name, phone, tags (array or comma list), notes, marketing_optin, user_id. */ public static function update( $id, array $data ) { global $wpdb; $clean = array(); if ( isset( $data['name'] ) ) { $clean['name'] = mb_substr( sanitize_text_field( $data['name'] ), 0, 190 ); } if ( isset( $data['phone'] ) ) { $clean['phone'] = self::normalize_phone( $data['phone'] ); } if ( isset( $data['tags'] ) ) { $clean['tags'] = implode( ',', self::clean_tags( $data['tags'] ) ); } if ( isset( $data['notes'] ) ) { $clean['notes'] = sanitize_textarea_field( $data['notes'] ); } foreach ( array( 'marketing_optin', 'user_id' ) as $int ) { if ( isset( $data[ $int ] ) ) { $clean[ $int ] = (int) $data[ $int ]; } } if ( $clean ) { $clean['updated_gmt'] = current_time( 'mysql', true ); $wpdb->update( self::table(), $clean, array( 'id' => (int) $id ) ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. do_action( 'tableengine_guest_updated', (int) $id, $clean ); } return self::get( $id ); } /** * Normalise tags: trimmed, de-duplicated case-insensitively, no commas, max 20 × 30 chars. * * @param string|string[] $tags * @return string[] */ public static function clean_tags( $tags ) { $out = array(); foreach ( is_array( $tags ) ? $tags : explode( ',', (string) $tags ) as $tag ) { $tag = mb_substr( trim( str_replace( ',', ' ', sanitize_text_field( (string) $tag ) ) ), 0, 30 ); if ( '' !== $tag && ! isset( $out[ mb_strtolower( $tag ) ] ) ) { $out[ mb_strtolower( $tag ) ] = $tag; } } return array_slice( array_values( $out ), 0, 20 ); } public static function get_meta( $guest_id, $key = '', $single = true ) { return get_metadata( 'tableengine_guest', (int) $guest_id, $key, $single ); } public static function update_meta( $guest_id, $key, $value ) { return update_metadata( 'tableengine_guest', (int) $guest_id, $key, $value ); } public static function delete_meta( $guest_id, $key ) { return delete_metadata( 'tableengine_guest', (int) $guest_id, $key ); } /** * Link existing reservations to guests (runs on upgrade). Works in batches and * reschedules itself so large booking histories don't time out a request. */ public static function backfill() { global $wpdb; $res = self::res_table(); $deadline = microtime( true ) + 15; $cursor = (int) get_option( 'tableengine_guest_backfill_cursor', 0 ); $touched = array(); $done = false; while ( microtime( true ) < $deadline ) { $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, name, email, phone, marketing_optin FROM {$res} WHERE guest_id = 0 AND id > %d ORDER BY id ASC LIMIT 200", $cursor ), ARRAY_A ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. foreach ( $rows as $row ) { $cursor = (int) $row['id']; $gid = self::resolve( $row ); if ( $gid ) { $wpdb->update( $res, array( 'guest_id' => $gid ), array( 'id' => $cursor ) ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. $touched[ $gid ] = true; } } if ( count( $rows ) < 200 ) { $done = true; break; } } foreach ( array_keys( $touched ) as $gid ) { self::refresh_stats( $gid ); } if ( $done ) { delete_option( 'tableengine_guest_backfill_cursor' ); } else { update_option( 'tableengine_guest_backfill_cursor', $cursor, false ); wp_schedule_single_event( time() + 60, 'tableengine_backfill_guests' ); } } }