*/ private static $selected = array(); /** * The attack a cleanup is about: the one asked for, or the latest one from the last 7 days. * * @param int $attack_id Attack id, or 0 to pick. * @return array|null Attack row, or null for a plain 7-day sweep. */ public static function target( $attack_id = 0 ) { if ( $attack_id > 0 ) { return Attacks::get( $attack_id ); } // The latest attack that still has junk orders waiting (or is still running). foreach ( Attacks::all( 20, time() - Cleanup_Rules::MANUAL_WINDOW ) as $attack ) { $running = 0 === (int) $attack['ended'] && 'manual' !== $attack['trigger_name']; if ( $running || (int) $attack['junk_orders'] > (int) $attack['junk_cleaned'] ) { return $attack; } } return null; } /** * The time window a cleanup covers. * * @param array|null $attack Attack row or null. * @return array{0:int,1:int} */ private static function window( $attack ) { return Cleanup_Rules::window( $attack ? array( 'started' => (int) $attack['started'], 'ended' => (int) $attack['ended'], ) : null, time() ); } /** * Works out which orders in the window are junk. * * @param array|null $attack Attack row or null. * @return array{junk:array,kept:int} Junk order id => reason; number of real orders kept. */ public static function select( $attack ) { list( $from, $to ) = self::window( $attack ); $cache_key = $from . '-' . intdiv( $to, 30 ); if ( isset( self::$selected[ $cache_key ] ) ) { return self::$selected[ $cache_key ]; } $now = time(); /** * Filters the most orders one cleanup looks at. * * @param int $limit Default 5000. */ $limit = max( 100, (int) apply_filters( 'brickmoat_cleanup_max_orders', 5000 ) ); $orders = wc_get_orders( array( 'type' => 'shop_order', 'status' => array( 'wc-failed', 'wc-pending' ), 'date_created' => $from . '...' . $to, 'limit' => $limit, 'orderby' => 'date', 'order' => 'ASC', ) ); $ids = array(); foreach ( $orders as $order ) { $ids[] = $order->get_id(); } $flagged = Events::flagged_orders( $ids ); // Orders a staff member added a note to are never touched. $noted = array(); if ( ! empty( $flagged ) ) { foreach ( array_chunk( array_keys( $flagged ), 200 ) as $chunk ) { $notes = wc_get_order_notes( array( 'order__in' => $chunk, 'limit' => 2000, ) ); foreach ( (array) $notes as $note ) { if ( isset( $note->added_by ) && 'system' !== $note->added_by ) { $noted[ (int) $note->order_id ] = true; } } } } $junk = array(); $email_seen = array(); foreach ( $orders as $order ) { $id = $order->get_id(); if ( ! isset( $flagged[ $id ] ) ) { continue; } $email = strtolower( (string) $order->get_billing_email() ); $completed = false; if ( '' !== $email ) { if ( ! isset( $email_seen[ $email ] ) ) { $email_seen[ $email ] = ! empty( wc_get_orders( array( 'billing_email' => $email, 'status' => array( 'wc-completed' ), 'limit' => 1, 'return' => 'ids', ) ) ); } $completed = $email_seen[ $email ]; } $created = $order->get_date_created(); list( $is_junk, $reason ) = Cleanup_Rules::classify( array( 'status' => $order->get_status(), 'created' => $created ? $created->getTimestamp() : 0, 'paid' => null !== $order->get_date_paid() || '' !== (string) $order->get_transaction_id(), 'flagged' => true, 'email_has_completed' => $completed, 'staff_note' => isset( $noted[ $id ] ), ), $from, $to, $now ); if ( $is_junk ) { $junk[ $id ] = 'blocked' === $flagged[ $id ] ? 'stopped' : $reason; } } // Everything else placed in the window is "kept". $all = wc_get_orders( array( 'type' => 'shop_order', 'status' => array_keys( wc_get_order_statuses() ), 'date_created' => $from . '...' . $to, 'limit' => 1, 'paginate' => true, 'return' => 'ids', ) ); $kept = max( 0, ( isset( $all->total ) ? (int) $all->total : 0 ) - count( $junk ) ); self::$selected[ $cache_key ] = array( 'junk' => $junk, 'kept' => $kept, ); return self::$selected[ $cache_key ]; } /** * How many junk orders an attack left. * * @param array|null $attack Attack row or null. * @return int */ public static function count_junk( $attack ) { try { $selection = self::select( $attack ); return count( $selection['junk'] ); } catch ( \Throwable $error ) { Util::log_error( 'Counting junk orders failed', $error ); return 0; } } /** * Junk orders waiting for cleanup, for the menu badge. Counted at most every few minutes. * * @return int */ public static function pending_count() { $cached = get_transient( 'brickmoat_cleanup_pending' ); if ( false !== $cached ) { return (int) $cached; } $count = self::count_junk( self::target() ); set_transient( 'brickmoat_cleanup_pending', $count, Lockdown::attack_id() > 0 ? MINUTE_IN_SECONDS : 5 * MINUTE_IN_SECONDS ); return $count; } /** * The stored job. * * @return array */ private static function job() { $job = get_option( self::JOB_OPTION, array() ); return is_array( $job ) ? $job : array(); } /** * The job as the admin screen reads it. * * @return array{status:string,batchId:?string,done:int,total:int,finishedAt:?string,canUndo:bool} */ public static function job_to_rest() { $job = self::job(); if ( empty( $job['batchId'] ) ) { return array( 'status' => 'idle', 'batchId' => null, 'done' => 0, 'total' => 0, 'finishedAt' => null, 'canUndo' => false, ); } $running = 'running' === $job['status']; $finished = isset( $job['finishedAt'] ) ? (int) $job['finishedAt'] : 0; $trash = defined( 'EMPTY_TRASH_DAYS' ) ? (int) EMPTY_TRASH_DAYS : 30; return array( 'status' => $running ? 'running' : 'done', 'batchId' => (string) $job['batchId'], 'done' => (int) $job['done'], 'total' => (int) $job['total'], 'finishedAt' => $running ? null : Util::iso( $finished ), 'canUndo' => ! $running && 'trash' === $job['mode'] && ! empty( $job['trashed'] ) && $trash > 0 && time() - $finished < $trash * DAY_IN_SECONDS, ); } /** * The whole cleanup screen. * * @param int $attack_id Attack id, or 0 for the default. * @return array Cleanup shape. */ public static function view( $attack_id = 0 ) { self::nudge(); $job = self::job(); $attack = self::target( $attack_id ); if ( 0 === $attack_id && ! empty( $job['batchId'] ) && ! empty( $job['attackId'] ) ) { // Keep showing the attack the current job belongs to. $job_attack = Attacks::get( (int) $job['attackId'] ); $attack = $job_attack ? $job_attack : $attack; } $selection = self::select( $attack ); $show = array_slice( array_keys( $selection['junk'] ), 0, 7 ); $orders = array(); foreach ( $show as $id ) { $orders[] = self::order_to_rest( (int) $id, $selection['junk'][ $id ] ); } // While a job runs (or after it), show what it has moved so the list does not go blank. if ( empty( $orders ) && ! empty( $job['trashed'] ) ) { foreach ( array_slice( array_keys( (array) $job['trashed'] ), 0, 7 ) as $id ) { $orders[] = self::order_to_rest( (int) $id, (string) $job['trashed'][ $id ] ); } } if ( $attack ) { $held = (int) $attack['emails_held']; } else { $held = 0; foreach ( Attacks::all( 50, time() - Cleanup_Rules::MANUAL_WINDOW ) as $row ) { $held += (int) $row['emails_held']; } } return array( 'attack' => $attack ? Attacks::summary( $attack ) : null, 'counts' => array( 'junk' => count( $selection['junk'] ), 'kept' => (int) $selection['kept'], 'fakeAccounts' => count( self::accounts( $attack ) ), 'emailsHeld' => $held, ), 'orders' => array_values( array_filter( $orders ) ), 'job' => self::job_to_rest(), ); } /** * One order as a CleanupOrder. * * @param int $id Order id. * @param string $reason declined or stopped. * @return array|null */ private static function order_to_rest( $id, $reason ) { $order = wc_get_order( $id ); if ( ! $order ) { return null; } $created = $order->get_date_created(); $status = $order->get_status(); return array( 'id' => $id, 'number' => (string) $order->get_order_number(), 'createdAt' => Util::iso( $created ? $created->getTimestamp() : 0 ), 'total' => (float) $order->get_total(), 'reason' => 'stopped' === $reason ? __( 'Bot stopped before paying', 'brickmoat' ) : __( 'Stolen card, declined by the bank', 'brickmoat' ), 'status' => in_array( $status, array( 'failed', 'pending', 'trash' ), true ) ? $status : 'pending', 'editUrl' => (string) $order->get_edit_order_url(), ); } /** * Starts moving an attack's junk orders to Trash. * * @param int $attack_id Attack id, or 0 for the last 7 days. * @return true|\WP_Error */ public static function run( $attack_id = 0 ) { $job = self::job(); if ( ! empty( $job['batchId'] ) && 'running' === $job['status'] ) { return new \WP_Error( 'brickmoat_cleanup_running', __( 'A cleanup is already running. Please wait for it to finish.', 'brickmoat' ), array( 'status' => 409 ) ); } $attack = $attack_id > 0 ? Attacks::get( $attack_id ) : null; if ( $attack_id > 0 && ! $attack ) { return new \WP_Error( 'brickmoat_not_found', __( 'That attack could not be found.', 'brickmoat' ), array( 'status' => 404 ) ); } $selection = self::select( $attack ); if ( empty( $selection['junk'] ) ) { return new \WP_Error( 'brickmoat_nothing_to_clean', __( 'There are no junk orders to move.', 'brickmoat' ), array( 'status' => 400 ) ); } $job = array( 'batchId' => wp_generate_uuid4(), 'status' => 'running', 'mode' => 'trash', 'attackId' => $attack ? (int) $attack['id'] : 0, 'todo' => $selection['junk'], 'trashed' => array(), 'total' => count( $selection['junk'] ), 'done' => 0, 'startedAt' => time(), 'touchedAt' => time(), 'finishedAt' => 0, ); update_option( self::JOB_OPTION, $job, false ); self::enqueue( $job['batchId'] ); return true; } /** * Starts restoring a finished cleanup from Trash. * * @param string $batch_id The batch to restore. * @return true|\WP_Error */ public static function undo( $batch_id ) { $job = self::job(); if ( empty( $job['batchId'] ) || ! hash_equals( (string) $job['batchId'], (string) $batch_id ) ) { return new \WP_Error( 'brickmoat_not_found', __( 'That cleanup can no longer be undone.', 'brickmoat' ), array( 'status' => 404 ) ); } if ( 'running' === $job['status'] ) { return new \WP_Error( 'brickmoat_cleanup_running', __( 'The cleanup is still running. Please wait for it to finish.', 'brickmoat' ), array( 'status' => 409 ) ); } if ( 'trash' !== $job['mode'] || empty( $job['trashed'] ) ) { return new \WP_Error( 'brickmoat_nothing_to_undo', __( 'There is nothing to restore.', 'brickmoat' ), array( 'status' => 400 ) ); } $job['status'] = 'running'; $job['mode'] = 'restore'; $job['todo'] = $job['trashed']; $job['total'] = count( $job['trashed'] ); $job['done'] = 0; $job['touchedAt'] = time(); update_option( self::JOB_OPTION, $job, false ); self::enqueue( $job['batchId'] ); return true; } /** * Queues the next batch with Action Scheduler. * * @param string $batch_id Batch id. */ private static function enqueue( $batch_id ) { if ( function_exists( 'as_enqueue_async_action' ) ) { as_enqueue_async_action( self::BATCH_HOOK, array( $batch_id ), Scheduler::GROUP ); } } /** * If the background queue has not picked the job up for a while, moves one batch right now. */ private static function nudge() { $job = self::job(); if ( ! empty( $job['batchId'] ) && 'running' === $job['status'] && time() - (int) $job['touchedAt'] > 6 ) { self::process_batch( (string) $job['batchId'] ); } } /** * Moves (or restores) the next batch of orders. Run by Action Scheduler. * * @param string $batch_id Batch id. */ public static function process_batch( $batch_id ) { if ( ! Util::lock( 'cleanup' ) ) { return; } try { wp_cache_delete( self::JOB_OPTION, 'options' ); $job = self::job(); if ( empty( $job['batchId'] ) || (string) $job['batchId'] !== (string) $batch_id || 'running' !== $job['status'] ) { return; } $batch = array_slice( (array) $job['todo'], 0, self::BATCH_SIZE, true ); $restore = 'restore' === $job['mode']; $moved = 0; foreach ( $batch as $id => $reason ) { unset( $job['todo'][ $id ] ); $order = wc_get_order( (int) $id ); if ( ! $order ) { continue; } if ( $restore ) { if ( 'trash' === $order->get_status() && $order->untrash() ) { unset( $job['trashed'][ $id ] ); ++$moved; } continue; } // Looked at once more, in case it was paid or handled since the list was made. $paid = null !== $order->get_date_paid() || '' !== (string) $order->get_transaction_id(); if ( $paid || ! $order->has_status( array( 'failed', 'pending' ) ) ) { continue; } if ( $order->delete( false ) ) { $job['trashed'][ $id ] = $reason; ++$moved; } } $job['done'] += count( $batch ); $job['touchedAt'] = time(); if ( $job['attackId'] > 0 && $moved > 0 ) { Attacks::add( (int) $job['attackId'], 'junk_cleaned', $restore ? -$moved : $moved ); } if ( empty( $job['todo'] ) ) { $job['status'] = 'done'; $job['done'] = (int) $job['total']; $job['finishedAt'] = time(); if ( $restore ) { // Everything is back: there is no job to show any more. $job = array(); } } update_option( self::JOB_OPTION, $job, false ); delete_transient( 'brickmoat_cleanup_pending' ); self::$selected = array(); if ( ! empty( $job['todo'] ) ) { self::enqueue( (string) $job['batchId'] ); } } catch ( \Throwable $error ) { Util::log_error( 'A cleanup batch failed', $error ); } finally { Util::unlock( 'cleanup' ); } } /** * Customer accounts registered in the window that never paid and looked like a bot. * * @param array|null $attack Attack row or null. * @return array */ public static function accounts( $attack ) { global $wpdb; list( $from, $to ) = self::window( $attack ); $users = get_users( array( 'role__in' => array( 'customer', 'subscriber' ), 'date_query' => array( array( 'after' => gmdate( 'Y-m-d H:i:s', $from ), 'before' => gmdate( 'Y-m-d H:i:s', $to ), 'inclusive' => true, ), ), 'number' => 500, 'fields' => array( 'ID', 'user_email', 'user_registered' ), ) ); if ( empty( $users ) ) { return array(); } $by_hash = array(); $by_id = array(); foreach ( $users as $user ) { $by_id[ (int) $user->ID ] = $user; $hash = Settings::email_hash( $user->user_email ); if ( '' !== $hash ) { $by_hash[ $hash ] = (int) $user->ID; } } $table = Schema::table( 'events' ); $ids = array_map( 'intval', array_keys( $by_id ) ); $hashes = array_map( 'strval', array_keys( $by_hash ) ); if ( empty( $hashes ) ) { // A value no stored email code can equal, so the list below is never empty. $hashes = array( '-' ); } $id_in = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); $hash_in = implode( ',', array_fill( 0, count( $hashes ), '%s' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- $id_in and $hash_in hold only placeholders, one per value. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT user_id, email_hash, decision, outcome FROM %i WHERE (decision <> 'allow' OR outcome = 'declined') AND (user_id IN ({$id_in}) OR email_hash IN ({$hash_in})) LIMIT 5000", array_merge( array( $table ), $ids, $hashes ) ), ARRAY_A ); $suspect = array(); foreach ( (array) $rows as $row ) { $user_id = (int) $row['user_id']; if ( ! isset( $by_id[ $user_id ] ) ) { $user_id = isset( $by_hash[ $row['email_hash'] ] ) ? $by_hash[ $row['email_hash'] ] : 0; } if ( $user_id > 0 && ( ! isset( $suspect[ $user_id ] ) || 'declined' === $row['outcome'] ) ) { $suspect[ $user_id ] = 'declined' === $row['outcome'] ? 'declined' : 'stopped'; } } $out = array(); foreach ( $suspect as $user_id => $why ) { if ( user_can( $user_id, 'edit_posts' ) || get_current_user_id() === $user_id ) { continue; } $paid = wc_get_orders( array( 'customer_id' => $user_id, 'status' => array( 'wc-processing', 'wc-completed', 'wc-on-hold' ), 'limit' => 1, 'return' => 'ids', ) ); if ( ! empty( $paid ) ) { continue; } $user = $by_id[ $user_id ]; $out[] = array( 'userId' => $user_id, 'emailMasked' => Email::mask( $user->user_email ), 'registeredAt' => Util::iso( (int) strtotime( $user->user_registered . ' UTC' ) ), 'reason' => 'declined' === $why ? __( 'Signed up during the attack, a card failed, never paid', 'brickmoat' ) : __( 'Signed up during the attack and was stopped as a bot', 'brickmoat' ), ); } return $out; } /** * Deletes fake accounts. Only accounts on the current fake-account list can be deleted. * * @param int[] $user_ids Accounts to delete. * @return int How many were deleted. */ public static function delete_accounts( array $user_ids ) { require_once ABSPATH . 'wp-admin/includes/user.php'; $listed = array(); foreach ( self::accounts( self::target() ) as $account ) { $listed[ (int) $account['userId'] ] = true; } $deleted = 0; foreach ( array_unique( array_map( 'intval', $user_ids ) ) as $user_id ) { if ( isset( $listed[ $user_id ] ) && current_user_can( 'delete_user', $user_id ) && wp_delete_user( $user_id ) ) { ++$deleted; } } return $deleted; } /** * Forgets the job (reset command and uninstall). */ public static function reset() { delete_option( self::JOB_OPTION ); delete_transient( 'brickmoat_cleanup_pending' ); self::$selected = array(); } }