$signal['code'], 'p' => (int) $signal['points'], ); if ( ! empty( $signal['args'] ) ) { $entry['a'] = $signal['args']; } $compact[] = $entry; } $row['signals'] = wp_json_encode( $compact ); } if ( array_key_exists( 'total', $row ) && null === $row['total'] ) { unset( $row['total'] ); } if ( array_key_exists( 'report_email', $row ) && ( null === $row['report_email'] || '' === $row['report_email'] ) ) { unset( $row['report_email'] ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Custom table. $ok = $wpdb->insert( Schema::table( 'events' ), $row ); return $ok ? (int) $wpdb->insert_id : 0; } /** * Changes fields of one event. * * @param int $id Event id. * @param array $fields Column => value. */ public static function update( $id, array $fields ) { global $wpdb; if ( $id > 0 && ! empty( $fields ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Custom table. $wpdb->update( Schema::table( 'events' ), $fields, array( 'id' => (int) $id ) ); } } /** * One event. * * @param int $id Event id. * @return array|null */ public static function get( $id ) { global $wpdb; $table = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, (int) $id ), ARRAY_A ); return $row ? $row : null; } /** * The most recent event for an order. * * @param int $order_id Order id. * @return array|null */ public static function latest_for_order( $order_id ) { global $wpdb; $table = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE order_id = %d ORDER BY id DESC LIMIT 1', $table, (int) $order_id ), ARRAY_A ); return $row ? $row : null; } /** * How many different emails and billing names one address used since a time. * * @param string $ip Address. * @param int $since Unix time. * @return array{emails:string[],names:string[]} */ public static function identities_for_ip( $ip, $since ) { global $wpdb; $out = array( 'emails' => array(), 'names' => array(), ); if ( '' === $ip ) { return $out; } $table = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT DISTINCT email_hash, addr_hash FROM %i WHERE ip = %s AND ts >= %d LIMIT 40', $table, $ip, (int) $since ), ARRAY_A ); foreach ( (array) $rows as $row ) { if ( '' !== $row['email_hash'] ) { $out['emails'][ $row['email_hash'] ] = true; } if ( '' !== $row['addr_hash'] ) { $out['names'][ $row['addr_hash'] ] = true; } } $out['emails'] = array_keys( $out['emails'] ); $out['names'] = array_keys( $out['names'] ); return $out; } /** * The values for the event list's filter, in the order its placeholders come: * * (%s = '' OR decision = %s) * AND (%d = 0 OR email_hash = %s OR ip LIKE %s OR order_id = %d OR id = %d * OR country REGEXP %s OR reasons REGEXP %s) * * The filter is written out in full in each query that uses it, so the SQL is always the same * text and only these values change. A part of the search that does not apply gets a value * that can match nothing. * * @param string $decision allow, challenge, block or ''. * @param string $search What the merchant typed. * @return array{decision:string,searching:int,email:string,ip:string,order:int,id:int,country:string,reasons:string} */ private static function filter_values( $decision, $search ) { global $wpdb; $decision = in_array( $decision, array( 'allow', 'challenge', 'block' ), true ) ? $decision : ''; $nothing = '^-$'; // No country code and no list of reasons is a single dash. $values = array( 'decision' => $decision, 'searching' => 0, 'email' => '-', 'ip' => '-', 'order' => -1, 'id' => -1, 'country' => $nothing, 'reasons' => $nothing, ); $search = trim( (string) $search ); if ( '' === $search ) { return $values; } $values['searching'] = 1; if ( false !== strpos( $search, '@' ) ) { $hash = Settings::email_hash( $search ); if ( '' !== $hash ) { $values['email'] = $hash; } } elseif ( preg_match( '/^[0-9a-f:.]+$/i', $search ) && ( false !== strpos( $search, '.' ) || false !== strpos( $search, ':' ) ) ) { $values['ip'] = $wpdb->esc_like( strtolower( $search ) ) . '%'; } elseif ( preg_match( '/^#?(\d+)$/', $search, $m ) ) { $values['order'] = (int) $m[1]; $values['id'] = (int) $m[1]; } $lower = static function ( $text ) { return function_exists( 'mb_strtolower' ) ? mb_strtolower( (string) $text ) : strtolower( (string) $text ); }; $needle = $lower( $search ); $countries = array(); $reasons = array(); if ( 2 === strlen( $search ) && ctype_alpha( $search ) ) { $countries[] = strtoupper( $search ); } if ( strlen( $search ) >= 3 && function_exists( 'WC' ) && WC()->countries ) { foreach ( WC()->countries->get_countries() as $code => $name ) { if ( count( $countries ) < 20 && preg_match( '/^[A-Z]{2}$/', (string) $code ) && false !== strpos( $lower( html_entity_decode( (string) $name, ENT_QUOTES, 'UTF-8' ) ), $needle ) ) { $countries[] = (string) $code; } } // Words from a reason, e.g. "rented server". foreach ( self::known_codes() as $code ) { if ( false !== strpos( $lower( Signals::general_label( $code ) ), $needle ) ) { $reasons[] = $code; } } } // Country codes are two capital letters and reason codes are lower-case words, so both lists // are safe to join into a pattern. if ( ! empty( $countries ) ) { $values['country'] = '^(' . implode( '|', array_unique( $countries ) ) . ')$'; } if ( ! empty( $reasons ) ) { $values['reasons'] = ',(' . implode( '|', $reasons ) . '),'; } return $values; } /** * Signal codes that can be a "main reason". * * @return string[] */ public static function known_codes() { return array( 'honeypot', 'manual_block', 'no_token', 'token_reused', 'network_listed', 'headless', 'unknown_origin', 'many_emails', 'fast_submit', 'hosting', 'small_basket', 'recent_decline', 'disposable_email', 'country_mismatch', 'velocity_ip_attempts', 'velocity_ip_declines', 'velocity_prefix_declines', 'velocity_email_declines', 'velocity_device_declines', 'order_locked', 'lockdown_min_total', 'lockdown_guest', 'strict_guest', 'paid_device', 'account_age', 'trusted_staff', 'trusted_customer', 'trusted_allowlist', 'normal_shopper' ); } /** * A page of the event list, newest first. * * @param string $decision allow, challenge, block or ''. * @param string $search What the merchant typed. * @param int $page Page number from 1. * @param int $per_page Rows per page. * @return array{rows:array,total:int,counts:array} */ public static function query( $decision, $search, $page, $per_page ) { global $wpdb; $table = Schema::table( 'events' ); $offset = max( 0, ( (int) $page - 1 ) * (int) $per_page ); $f = self::filter_values( $decision, $search ); // phpcs:disable WordPress.DB.DirectDatabaseQuery -- The plugin's own table; the list changes with every checkout attempt. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, ts, decision, score, reasons, signals, country, route FROM %i WHERE (%s = '' OR decision = %s) AND (%d = 0 OR email_hash = %s OR ip LIKE %s OR order_id = %d OR id = %d OR country REGEXP %s OR reasons REGEXP %s) ORDER BY id DESC LIMIT %d OFFSET %d", $table, $f['decision'], $f['decision'], $f['searching'], $f['email'], $f['ip'], $f['order'], $f['id'], $f['country'], $f['reasons'], (int) $per_page, $offset ), ARRAY_A ); // The filter tabs show how many events match the search, per decision. $grouped = $wpdb->get_results( $wpdb->prepare( "SELECT decision, COUNT(*) AS n FROM %i WHERE (%s = '' OR decision = %s) AND (%d = 0 OR email_hash = %s OR ip LIKE %s OR order_id = %d OR id = %d OR country REGEXP %s OR reasons REGEXP %s) GROUP BY decision", $table, '', '', $f['searching'], $f['email'], $f['ip'], $f['order'], $f['id'], $f['country'], $f['reasons'] ), ARRAY_A ); // phpcs:enable $counts = array( 'all' => 0, 'block' => 0, 'challenge' => 0, 'allow' => 0, ); foreach ( (array) $grouped as $group ) { if ( isset( $counts[ $group['decision'] ] ) ) { $counts[ $group['decision'] ] = (int) $group['n']; $counts['all'] += (int) $group['n']; } } $total = in_array( $decision, array( 'allow', 'challenge', 'block' ), true ) ? $counts[ $decision ] : $counts['all']; return array( 'rows' => array_map( array( __CLASS__, 'to_row' ), (array) $rows ), 'total' => $total, 'counts' => $counts, ); } /** * The newest events. * * @param int $limit How many. * @param int $since Only events at or after this unix time. * @return array EventRow[]. */ public static function recent( $limit, $since = 0 ) { global $wpdb; $table = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT id, ts, decision, score, reasons, signals, country, route FROM %i WHERE ts >= %d ORDER BY id DESC LIMIT %d', $table, (int) $since, (int) $limit ), ARRAY_A ); return array_map( array( __CLASS__, 'to_row' ), (array) $rows ); } /** * Rows for the CSV export, newest first. * * @param string $decision allow, challenge, block or ''. * @param string $search What the merchant typed. * @param int $limit Most rows to return. * @return array */ public static function export_rows( $decision, $search, $limit = 20000 ) { global $wpdb; $table = Schema::table( 'events' ); $f = self::filter_values( $decision, $search ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table, read once for a file download. return (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, ts, decision, score, reasons, signals, country, route, ip, order_id, outcome FROM %i WHERE (%s = '' OR decision = %s) AND (%d = 0 OR email_hash = %s OR ip LIKE %s OR order_id = %d OR id = %d OR country REGEXP %s OR reasons REGEXP %s) ORDER BY id DESC LIMIT %d", $table, $f['decision'], $f['decision'], $f['searching'], $f['email'], $f['ip'], $f['order'], $f['id'], $f['country'], $f['reasons'], (int) $limit ), ARRAY_A ); } /** * Decodes the signals stored with an event. * * @param array $row Database row. * @return array */ public static function signals( array $row ) { $signals = isset( $row['signals'] ) ? json_decode( (string) $row['signals'], true ) : array(); return is_array( $signals ) ? $signals : array(); } /** * The top reason of an event, in plain English. * * @param array $row Database row. * @return string */ public static function reason_label( array $row ) { $codes = array_values( array_filter( explode( ',', isset( $row['reasons'] ) ? (string) $row['reasons'] : '' ) ) ); $top = isset( $codes[0] ) ? $codes[0] : 'normal_shopper'; foreach ( self::signals( $row ) as $signal ) { if ( isset( $signal['c'] ) && $signal['c'] === $top ) { return Signals::label( $top, isset( $signal['a'] ) ? (array) $signal['a'] : array() ); } } return Signals::label( $top ); } /** * A database row as an EventRow. * * @param array $row Database row. * @return array */ public static function to_row( array $row ) { return array( 'id' => (int) $row['id'], 'time' => Util::iso( (int) $row['ts'] ), 'decision' => (string) $row['decision'], 'score' => (int) $row['score'], 'reason' => self::reason_label( $row ), 'country' => Geo::name( (string) $row['country'] ), 'countryCode' => (string) $row['country'], 'route' => (string) $row['route'], ); } /** * A database row as an EventDetail. * * @param array $row Database row. * @return array */ public static function to_detail( array $row ) { $order_id = (int) $row['order_id']; $edit_url = null; if ( $order_id > 0 ) { $order = wc_get_order( $order_id ); if ( $order ) { $edit_url = $order->get_edit_order_url(); } } $outcome = (string) $row['outcome']; if ( ! in_array( $outcome, array( 'paid', 'declined', 'blocked', 'challenge_passed', 'challenge_failed' ), true ) ) { $outcome = 'unknown'; } $marks = Blocks::marks_for_event( (int) $row['id'] ); return array_merge( self::to_row( $row ), array( 'signals' => Signals::to_rest( self::signals( $row ) ), 'routeLabel' => Signals::route_label( (string) $row['route'] ), 'ipMasked' => Ip::mask( (string) $row['ip'] ), 'orderId' => $order_id > 0 ? $order_id : null, 'orderEditUrl' => $edit_url, 'outcome' => $outcome, 'attackId' => (int) $row['attack_id'] > 0 ? (int) $row['attack_id'] : null, 'markedReal' => $marks['markedReal'], 'alwaysBlocked' => $marks['alwaysBlocked'], ) ); } /** * Counts per hour and decision, for the charts. * * @param int $from Unix time. * @param int $to Unix time. * @return array */ public static function hourly( $from, $to ) { global $wpdb; $table = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. return (array) $wpdb->get_results( $wpdb->prepare( "SELECT FLOOR(ts / 3600) AS h, decision, COUNT(*) AS n, SUM(passed = 1 AND outcome = 'paid') AS paid_passed FROM %i WHERE ts >= %d AND ts < %d GROUP BY h, decision", $table, (int) $from, (int) $to ), ARRAY_A ); } /** * Totals for a time window. * * @param int $from Unix time. * @param int $to Unix time. * @return array{attempts:int,allowed:int,challenged:int,blocked:int,declined:int,unique_ips:int,unique_devices:int,network:int} */ public static function totals( $from, $to ) { global $wpdb; $table = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $row = $wpdb->get_row( $wpdb->prepare( "SELECT COUNT(*) AS attempts, SUM(decision = 'allow') AS allowed, SUM(decision = 'challenge') AS challenged, SUM(decision = 'block') AS blocked, SUM(outcome = 'declined') AS declined, COUNT(DISTINCT ip) AS unique_ips, COUNT(DISTINCT NULLIF(device_hash, '')) AS unique_devices, SUM(network = 1 AND decision <> 'allow') AS network FROM %i WHERE ts >= %d AND ts <= %d", $table, (int) $from, (int) $to ), ARRAY_A ); $out = array(); foreach ( array( 'attempts', 'allowed', 'challenged', 'blocked', 'declined', 'unique_ips', 'unique_devices', 'network' ) as $key ) { $out[ $key ] = isset( $row[ $key ] ) ? (int) $row[ $key ] : 0; } return $out; } /** * How often each combination of reasons stopped an attempt. * * @param int $from Unix time. * @param int $to Unix time. * @return array */ public static function stopped_reasons( $from, $to ) { global $wpdb; $table = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. return (array) $wpdb->get_results( $wpdb->prepare( "SELECT reasons, COUNT(*) AS n FROM %i WHERE ts >= %d AND ts <= %d AND decision IN ('block','challenge') AND policy = 0 GROUP BY reasons", $table, (int) $from, (int) $to ), ARRAY_A ); } /** * Attempts and declines per minute. * * @param int $from Unix time. * @param int $to Unix time. * @return array */ public static function per_minute( $from, $to ) { global $wpdb; $table = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. return (array) $wpdb->get_results( $wpdb->prepare( "SELECT FLOOR(ts / 60) AS m, COUNT(*) AS attempts, SUM(outcome = 'declined') AS declines FROM %i WHERE ts >= %d AND ts <= %d GROUP BY m", $table, (int) $from, (int) $to ), ARRAY_A ); } /** * Where a window's suspicious attempts came from: by country and kind of connection. * * @param int $from Unix time. * @param int $to Unix time. * @return array */ public static function sources( $from, $to ) { global $wpdb; $table = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. return (array) $wpdb->get_results( $wpdb->prepare( "SELECT country, (hosting <> '') AS rented, COUNT(*) AS n FROM %i WHERE ts >= %d AND ts <= %d AND (decision <> 'allow' OR outcome = 'declined') GROUP BY country, rented ORDER BY n DESC LIMIT 8", $table, (int) $from, (int) $to ), ARRAY_A ); } /** * The hosting companies behind a window's suspicious attempts. * * @param int $from Unix time. * @param int $to Unix time. * @return array */ public static function networks( $from, $to ) { global $wpdb; $table = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. return (array) $wpdb->get_results( $wpdb->prepare( "SELECT hosting, COUNT(*) AS n FROM %i WHERE ts >= %d AND ts <= %d AND (decision <> 'allow' OR outcome = 'declined') GROUP BY hosting ORDER BY n DESC LIMIT 5", $table, (int) $from, (int) $to ), ARRAY_A ); } /** * Time of the first suspicious event (stopped or declined) in a window. * * @param int $from Unix time. * @param int $to Unix time. * @return int Unix time, 0 when there was none. */ public static function first_suspicious( $from, $to ) { global $wpdb; $table = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. return (int) $wpdb->get_var( $wpdb->prepare( "SELECT MIN(ts) FROM %i WHERE ts >= %d AND ts <= %d AND ((decision <> 'allow' AND policy = 0) OR outcome = 'declined')", $table, (int) $from, (int) $to ) ); } /** * Ids of orders the log marked as declined or blocked, among a set of orders. * * @param int[] $order_ids Order ids. * @return array Order id => 'declined' or 'blocked'. */ public static function flagged_orders( array $order_ids ) { global $wpdb; $out = array(); $table = Schema::table( 'events' ); $order_ids = array_values( array_unique( array_filter( array_map( 'intval', $order_ids ) ) ) ); foreach ( array_chunk( $order_ids, 500 ) as $chunk ) { $places = implode( ',', array_fill( 0, count( $chunk ), '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- One placeholder per id is built above. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT order_id, outcome FROM %i WHERE order_id IN ({$places}) AND outcome IN ('declined','blocked')", array_merge( array( $table ), $chunk ) ), ARRAY_A ); foreach ( (array) $rows as $row ) { $out[ (int) $row['order_id'] ] = (string) $row['outcome']; } } return $out; } /** * Deletes events older than a time (retention), in bounded steps. * * @param int $before Unix time. */ public static function prune( $before ) { global $wpdb; $table = Schema::table( 'events' ); for ( $i = 0; $i < 20; $i++ ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $deleted = $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE ts < %d LIMIT 5000', $table, (int) $before ) ); if ( ! $deleted || $deleted < 5000 ) { break; } } } }