get_var( $wpdb->prepare( "SELECT MAX(score) FROM %i WHERE expires > %d AND ((ntype = 'ip' AND nvalue = %s) OR (ntype = 'prefix' AND nvalue = %s) OR (ntype = 'device' AND nvalue = %s))", $table, null === $now ? time() : (int) $now, $ip, $prefix, $device ) ); return min( 100, max( 0, (int) $score ) ); } /** * Asks the service whether an email is listed. Gives up after 300 ms and allows. * * @param string $email Normalised email. * @return int 0–100; 0 when not listed or when the service did not answer in time. */ public static function email_check( $email ) { try { $answer = Api_Client::request( 'POST', '/email-check', array( 'email' => $email ), 0.3 ); if ( $answer['ok'] && ! empty( $answer['data']['listed'] ) ) { return min( 100, max( 1, isset( $answer['data']['score'] ) ? (int) $answer['data']['score'] : 100 ) ); } } catch ( \Throwable $error ) { unset( $error ); // Fail open. } return 0; } /** * Downloads the changes since the last download. * * @return bool Whether the list is up to date afterwards. */ public static function sync() { global $wpdb; $table = Schema::table( 'network' ); $etag = (string) get_option( self::ETAG_OPTION, '' ); $path = '/blocklist' . ( '' !== $etag ? '?since=' . rawurlencode( $etag ) : '' ); $res = Api_Client::request( 'GET', $path, null, 10 ); $now = time(); if ( ! $res['ok'] ) { update_option( self::SYNC_OPTION, array_merge( self::sync_state(), array( 'ok' => false, 'triedAt' => $now, ) ), false ); return false; } if ( 304 !== $res['status'] && is_array( $res['data'] ) ) { $data = $res['data']; if ( ! empty( $data['full'] ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $wpdb->query( $wpdb->prepare( 'DELETE FROM %i', $table ) ); } foreach ( isset( $data['remove'] ) && is_array( $data['remove'] ) ? $data['remove'] : array() as $entry ) { if ( isset( $entry['type'], $entry['value'] ) && self::valid_type( $entry['type'] ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Custom table. $wpdb->delete( $table, array( 'ntype' => $entry['type'], 'nvalue' => substr( strtolower( (string) $entry['value'] ), 0, 64 ), ) ); } } $rows = array(); foreach ( isset( $data['add'] ) && is_array( $data['add'] ) ? $data['add'] : array() as $entry ) { if ( ! isset( $entry['type'], $entry['value'] ) || ! self::valid_type( $entry['type'] ) || ! is_string( $entry['value'] ) || '' === $entry['value'] || strlen( $entry['value'] ) > 64 ) { continue; } $expires = isset( $entry['expiresAt'] ) ? Util::from_iso( $entry['expiresAt'] ) : 0; if ( $expires <= $now ) { continue; } $rows[] = array( $entry['type'], strtolower( $entry['value'] ), min( 100, max( 0, isset( $entry['score'] ) ? (int) $entry['score'] : 0 ) ), $expires ); } // One statement per entry, 500 to a transaction so a long list is still written quickly. // phpcs:disable WordPress.DB.DirectDatabaseQuery -- The plugin's own table, written by a background job. foreach ( array_chunk( $rows, 500 ) as $chunk ) { $wpdb->query( 'START TRANSACTION' ); foreach ( $chunk as $row ) { $wpdb->query( $wpdb->prepare( 'INSERT INTO %i (ntype,nvalue,score,expires) VALUES (%s,%s,%d,%d) ON DUPLICATE KEY UPDATE score = %d, expires = %d', $table, $row[0], $row[1], $row[2], $row[3], $row[2], $row[3] ) ); } $wpdb->query( 'COMMIT' ); } // phpcs:enable if ( isset( $data['etag'] ) && is_string( $data['etag'] ) ) { update_option( self::ETAG_OPTION, substr( sanitize_text_field( $data['etag'] ), 0, 190 ), false ); } self::handle_campaigns( isset( $data['campaigns'] ) && is_array( $data['campaigns'] ) ? $data['campaigns'] : array() ); } self::prune(); update_option( self::SYNC_OPTION, array( 'ok' => true, 'triedAt' => $now, 'okAt' => $now, ), false ); return true; } /** * Whether a list type is one we know. * * @param mixed $type Type. * @return bool */ private static function valid_type( $type ) { return in_array( $type, array( 'ip', 'prefix', 'device' ), true ); } /** * A campaign is a coordinated attack moving from store to store. When one is aimed at the * kind of checkout this store has, the administrator is told: a notice on the Overview and, * if they asked for attack alerts, an email. That is all. The store's settings and its mode * stay exactly as they are; whether to start lockdown is the administrator's decision, * made with the button on the Overview. * * @param array $campaigns Campaigns from the service. */ private static function handle_campaigns( array $campaigns ) { if ( empty( $campaigns ) ) { return; } $seen = get_option( self::CAMPAIGNS_OPTION, array() ); $seen = is_array( $seen ) ? $seen : array(); $gateways = array(); foreach ( WC()->payment_gateways()->payment_gateways() as $gateway ) { if ( 'yes' === $gateway->enabled ) { $gateways[ (string) $gateway->id ] = wp_strip_all_tags( (string) $gateway->get_title() ); } } $warning = null; foreach ( $campaigns as $campaign ) { if ( ! isset( $campaign['id'] ) || ! is_string( $campaign['id'] ) ) { continue; } $id = substr( sanitize_text_field( $campaign['id'] ), 0, 64 ); if ( '' === $id || in_array( $id, $seen, true ) ) { continue; } $seen[] = $id; $route = isset( $campaign['route'] ) ? (string) $campaign['route'] : ''; $gateway = isset( $campaign['gateway'] ) && is_string( $campaign['gateway'] ) ? $campaign['gateway'] : ''; if ( in_array( $route, Context::ROUTES, true ) && ( '' === $gateway || isset( $gateways[ $gateway ] ) ) ) { $warning = array( 'id' => $id, 'gateway' => '' !== $gateway ? $gateways[ $gateway ] : '', 'at' => time(), ); } } update_option( self::CAMPAIGNS_OPTION, array_slice( $seen, -100 ), false ); if ( null !== $warning ) { update_option( self::WARNING_OPTION, $warning, false ); // No email when the store is already locked down: there is nothing left to decide. if ( ! Lockdown::is_on() ) { Alerts::network_warning( $warning['gateway'] ); } } } /** * The warning to show on the Overview, if there is one: at most a day old, not dismissed, and * only while the store is not in lockdown already. * * @return array{id:string,gateway:string,since:string}|null */ public static function warning() { $stored = get_option( self::WARNING_OPTION, array() ); if ( ! is_array( $stored ) || empty( $stored['id'] ) || empty( $stored['at'] ) ) { return null; } if ( time() - (int) $stored['at'] >= self::WARNING_SECONDS ) { delete_option( self::WARNING_OPTION ); return null; } if ( Lockdown::is_on() || ! Licence::service_on() ) { return null; } return array( 'id' => (string) $stored['id'], 'gateway' => isset( $stored['gateway'] ) ? (string) $stored['gateway'] : '', 'since' => (string) Util::iso( (int) $stored['at'] ), ); } /** * Puts the warning away (the administrator pressed "Dismiss"). */ public static function dismiss_warning() { delete_option( self::WARNING_OPTION ); } /** * The last download. * * @return array{ok:bool,triedAt:int,okAt:int} */ public static function sync_state() { $state = get_option( self::SYNC_OPTION, array() ); $state = is_array( $state ) ? $state : array(); return array( 'ok' => ! empty( $state['ok'] ), 'triedAt' => isset( $state['triedAt'] ) ? (int) $state['triedAt'] : 0, 'okAt' => isset( $state['okAt'] ) ? (int) $state['okAt'] : 0, ); } /** * The shared list as the admin screens read it. * * @return array NetworkState. */ public static function to_rest() { $licence = Licence::stored(); $sync = self::sync_state(); if ( '' === $licence['key'] || in_array( $licence['status'], array( 'none', 'invalid' ), true ) ) { $state = 'off_free'; } elseif ( 'expired' === $licence['status'] ) { $state = 'off_expired'; } elseif ( Licence::service_on() && $sync['ok'] ) { $state = 'on'; } else { $state = 'error'; } $entries = (int) get_option( self::COUNT_OPTION, 0 ); $blocked = 0; if ( $entries > 0 ) { $today = new \DateTimeImmutable( 'today', wp_timezone() ); $totals = Events::totals( $today->getTimestamp(), time() ); $blocked = $totals['network']; } return array( 'state' => $state, 'updatedAt' => Util::iso( $sync['okAt'] ), 'blockedToday' => $blocked, 'entries' => $entries, 'warning' => self::warning(), ); } /** * Drops expired entries and refreshes the entry count. */ public static function prune() { global $wpdb; $table = Schema::table( 'network' ); // phpcs:disable WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE expires <= %d', $table, time() ) ); $count = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $table ) ); // phpcs:enable update_option( self::COUNT_OPTION, $count, true ); } /** * Empties the list (licence removed, reset, uninstall). */ public static function clear() { global $wpdb; $table = Schema::table( 'network' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $wpdb->query( $wpdb->prepare( 'DELETE FROM %i', $table ) ); delete_option( self::ETAG_OPTION ); delete_option( self::SYNC_OPTION ); delete_option( self::CAMPAIGNS_OPTION ); delete_option( self::WARNING_OPTION ); update_option( self::COUNT_OPTION, 0, true ); } }