array( 'AIEO_CAPI_Sender', 'send_purchase' ), 'ga4' => array( 'AIEO_GA4_Sender', 'send_purchase' ), 'tiktok' => array( 'AIEO_TikTok_Events_Sender', 'send_purchase' ), 'google_ads' => array( 'AIEO_Google_Ads_EC_Sender', 'send_conversion' ), ); private static $targets = array(); private static $kicked = false; public static function on(): bool { return class_exists( 'AIEO_Signals', false ) && AIEO_Signals::on( 'outbox' ); } public static function table(): string { global $wpdb; return $wpdb->prefix . self::TABLE; } public static function register_target( string $target, callable $send, int $batch = 1, int $needs = 0, array $options = array() ): void { $target = self::word( $target, 16 ); if ( '' !== $target ) { self::$targets[ $target ] = array( 'send' => $send, 'batch' => max( 1, $batch ), 'needs' => max( 0, $needs ), ) + self::options( $options ); } } private static function options( array $t ): array { $out = array( 'held' => ! empty( $t['held'] ) ); foreach ( array( 'keep_sent', 'keep_dead' ) as $key ) { if ( isset( $t[ $key ] ) && is_numeric( $t[ $key ] ) ) { $out[ $key ] = max( 0, min( 3650, (int) $t[ $key ] ) ); } } return $out; } public static function held(): array { $held = array(); foreach ( self::targets() as $target => $t ) { if ( ! empty( $t['held'] ) ) { $held[] = (string) $target; } } return $held; } private static function keeping( string $target, string $key ): int { $targets = self::targets(); if ( isset( $targets[ $target ][ $key ] ) ) { return (int) $targets[ $target ][ $key ]; } return 'keep_dead' === $key ? self::KEEP_DEAD_DAYS : self::KEEP_SENT_DAYS; } public static function targets(): array { $targets = self::$targets; foreach ( self::SENDERS as $target => $sender ) { if ( ! isset( $targets[ $target ] ) && class_exists( $sender[0], false ) ) { $targets[ $target ] = array( 'send' => array( __CLASS__, 'send_orders' ), 'batch' => 1, 'needs' => self::MARKETING, 'held' => false, ); } } $targets = (array) apply_filters( 'aieo_outbox_targets', $targets ); $out = array(); foreach ( $targets as $target => $t ) { $target = is_string( $target ) ? self::word( $target, 16 ) : ''; if ( '' !== $target && is_array( $t ) && isset( $t['send'] ) && is_callable( $t['send'] ) ) { $out[ $target ] = array( 'send' => $t['send'], 'batch' => max( 1, (int) ( $t['batch'] ?? 1 ) ), 'needs' => max( 0, (int) ( $t['needs'] ?? 0 ) ), ) + self::options( $t ); } } return $out; } public static function send_orders( array $rows ): array { $answers = array(); foreach ( $rows as $row ) { $sender = self::SENDERS[ (string) $row['target'] ] ?? null; if ( ! $sender || 'order' !== $row['object_type'] || 'purchase' !== $row['kind'] || ! class_exists( $sender[0], false ) ) { $answers[ (int) $row['id'] ] = array( 'code' => 0, 'verdict' => 'dead', 'error' => 'unknown_kind', 'tried' => false, ); continue; } $order = function_exists( 'wc_get_order' ) ? wc_get_order( (int) $row['object_id'] ) : null; $stamp = $order ? $order->get_meta( self::CONSENT_META ) : ''; if ( is_numeric( $stamp ) && ( (int) $stamp & self::MARKETING ) !== self::MARKETING ) { $answers[ (int) $row['id'] ] = array( 'code' => 0, 'verdict' => 'dead', 'error' => 'consent', 'tried' => false, ); continue; } $instance = call_user_func( array( $sender[0], 'instance' ) ); $answers[ (int) $row['id'] ] = call_user_func( array( $instance, $sender[1] ), (int) $row['object_id'], true ); } return $answers; } public static function put( string $event_id, string $target, string $kind, string $object_type, int $object_id, int $consent ): bool { global $wpdb; if ( ! self::on() ) { return false; } $event_id = substr( trim( $event_id ), 0, 64 ); $target = self::word( $target, 16 ); $kind = self::word( $kind, 32 ); $object_type = self::word( $object_type, 16 ); if ( '' === $event_id || '' === $target || '' === $kind ) { return false; } $consent = max( 0, min( 255, $consent ) ); $targets = self::targets(); $needs = isset( $targets[ $target ] ) ? $targets[ $target ]['needs'] : 0; $dead = $needs > 0 && ( $consent & $needs ) !== $needs; $now = self::now(); $put = $wpdb->query( $wpdb->prepare( 'INSERT IGNORE INTO `' . self::table() . '` (`event_id`, `target`, `kind`, `object_type`, `object_id`, `consent`, `state`, `next_gmt`, `last_error`, `created_gmt`, `updated_gmt`) VALUES (%s, %s, %s, %s, %d, %d, %s, %s, %s, %s, %s)', $event_id, $target, $kind, $object_type, max( 0, $object_id ), $consent, $dead ? 'dead' : 'pending', $now, $dead ? 'consent' : '', $now, $now ) ); if ( 1 !== (int) $put ) { return false; } if ( ! $dead && empty( $targets[ $target ]['held'] ) ) { self::kick(); } return true; } public static function put_purchase( string $target, $order, string $event_id = '' ): bool { if ( ! is_a( $order, 'WC_Order' ) ) { return false; } $id = (int) $order->get_id(); return self::put( '' !== $event_id ? $event_id : 'pur-' . $id, $target, 'purchase', 'order', $id, self::order_consent( $order ) ); } public static function order_consent( $order ): int { $stamped = is_a( $order, 'WC_Order' ) ? $order->get_meta( self::CONSENT_META ) : ''; if ( is_numeric( $stamped ) ) { return max( 0, min( 255, (int) $stamped ) ); } return class_exists( 'AIEO_Signal_Envelope', false ) ? (int) AIEO_Signal_Envelope::consent_bits() : 0; } private static function kick(): void { if ( self::$kicked ) { return; } self::$kicked = true; if ( function_exists( 'aieo_after_response' ) && function_exists( 'aieo_server_event_flush_fn' ) && '' !== aieo_server_event_flush_fn() ) { aieo_after_response( array( __CLASS__, 'after_response' ) ); return; } AIEO_Background_Queue::clear( self::HOOK ); AIEO_Background_Queue::queue( self::HOOK, 5 ); } public static function forget(): void { self::$kicked = false; } public static function after_response(): void { if ( function_exists( 'set_time_limit' ) ) { @set_time_limit( 60 ); } self::run(); } public static function run(): void { if ( ! self::on() ) { return; } if ( self::remaining() ) { AIEO_Background_Queue::queue( self::HOOK, self::AGAIN ); } self::drain(); } public static function heal(): void { if ( ! self::on() ) { return; } if ( self::remaining() && ! AIEO_Background_Queue::queued( self::HOOK ) ) { AIEO_Background_Queue::queue( self::HOOK, MINUTE_IN_SECONDS ); } self::prune(); } const KEEP_SENT_DAYS = 30; const KEEP_DEAD_DAYS = 90; const PRUNE_BATCH = 1000; public static function prune( ?int $now = null ): int { global $wpdb; $now = null === $now ? time() : $now; $taken = 0; $own = array(); foreach ( self::targets() as $target => $t ) { if ( isset( $t['keep_sent'] ) || isset( $t['keep_dead'] ) ) { $own[] = (string) $target; } } $rest = $own ? ' AND `target` NOT IN (' . self::quoted( $own ) . ')' : ''; foreach ( array( 'sent' => self::KEEP_SENT_DAYS, 'dead' => self::KEEP_DEAD_DAYS ) as $state => $days ) { $before = gmdate( 'Y-m-d H:i:s', $now - $days * DAY_IN_SECONDS ); $n = $wpdb->query( $wpdb->prepare( 'DELETE FROM `' . self::table() . '` WHERE `created_gmt` < %s AND `state` = %s', $before, $state ) . $rest . ' ORDER BY `created_gmt` LIMIT ' . (int) self::PRUNE_BATCH ); $taken += max( 0, (int) $n ); } foreach ( $own as $target ) { foreach ( array( 'sent' => 'keep_sent', 'dead' => 'keep_dead' ) as $state => $key ) { $before = gmdate( 'Y-m-d H:i:s', $now - self::keeping( $target, $key ) * DAY_IN_SECONDS ); $n = $wpdb->query( $wpdb->prepare( 'DELETE FROM `' . self::table() . '` WHERE `created_gmt` < %s AND `state` = %s AND `target` = %s ORDER BY `created_gmt` LIMIT %d', $before, $state, $target, self::PRUNE_BATCH ) ); $taken += max( 0, (int) $n ); } } return $taken; } public static function remaining( string $only = '' ): bool { global $wpdb; $where = ''; if ( '' !== $only ) { $where = $wpdb->prepare( ' AND `target` = %s', self::word( $only, 16 ) ); } else { $held = self::held(); if ( $held ) { $where = ' AND `target` NOT IN (' . self::quoted( $held ) . ')'; } } return (bool) $wpdb->get_var( 'SELECT 1 FROM `' . self::table() . "` WHERE `state` IN ('pending','failed','sending'){$where} LIMIT 1" ); } public static function waiting( string $target ): int { global $wpdb; if ( ! self::on() ) { return 0; } return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM `' . self::table() . "` WHERE `target` = %s AND `state` IN ('pending','failed','sending')", self::word( $target, 16 ) ) ); } public static function abandon( string $target, string $error = 'off' ): int { global $wpdb; if ( ! self::on() ) { return 0; } $error = substr( (string) preg_replace( '/[^a-z0-9_.:-]+/', '_', strtolower( $error ) ), 0, 64 ); return max( 0, (int) $wpdb->query( $wpdb->prepare( 'UPDATE `' . self::table() . "` SET `state` = 'dead', `claim` = '', `claim_until_gmt` = NULL, `last_error` = %s, `updated_gmt` = %s WHERE `target` = %s AND `state` IN ('pending','failed','sending')", $error, self::now(), self::word( $target, 16 ) ) ) ); } const FORGET_CHUNK = 500; public static function forget_objects( string $target, string $object_type, array $object_ids ): int { global $wpdb; if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( self::table() ) ) ) !== self::table() ) { return 0; } $target = self::word( $target, 16 ); $object_type = self::word( $object_type, 16 ); $ids = array_values( array_unique( array_filter( array_map( 'intval', $object_ids ), static function ( $id ) { return $id > 0; } ) ) ); if ( '' === $target || '' === $object_type || ! $ids ) { return 0; } $gone = 0; foreach ( array_chunk( $ids, self::FORGET_CHUNK ) as $chunk ) { $gone += max( 0, (int) $wpdb->query( $wpdb->prepare( 'DELETE FROM `' . self::table() . '` WHERE `target` = %s AND `object_type` = %s AND `object_id` IN (' . implode( ',', $chunk ) . ')', $target, $object_type ) ) ); } return $gone; } public static function backoff( int $tries ): int { return (int) min( 3600, 60 * ( 2 ** max( 0, min( 16, $tries ) ) ) ); } public static function verdict( int $code ): string { if ( $code >= 200 && $code < 300 ) { return 'sent'; } if ( 400 === $code ) { return 'dead'; } if ( 401 === $code || 403 === $code ) { return 'pause'; } return 'failed'; } public static function drain( int $budget = 20, string $only = '' ): int { if ( ! self::on() ) { return 0; } $budget = max( 1, $budget ); $deadline = microtime( true ) + $budget; $sent = 0; do { $targets = self::targets(); $open = array_values( array_diff( self::scope( $targets, $only ), array_keys( self::paused() ) ) ); $take = self::round_size( $targets, $open ); $rows = self::claim( $open, $take, max( self::CLAIM, $budget + 60 ) ); if ( ! $rows ) { break; } $claim = (string) $rows[0]['claim']; $by = array(); foreach ( $rows as $row ) { if ( (int) $row['tries'] >= self::MAX_TRIES ) { self::settle( $row, array( 'code' => (int) $row['last_code'], 'verdict' => 'dead', 'error' => 'abandoned', 'tried' => false ) ); continue; } $by[ (string) $row['target'] ][] = $row; } $chunks = array(); foreach ( $by as $target => $group ) { foreach ( array_chunk( $group, $targets[ $target ]['batch'] ) as $chunk ) { $chunks[] = array( $target, $chunk, max( array_map( 'intval', array_column( $chunk, 'tries' ) ) ), count( $chunks ) ); } } usort( $chunks, static function ( $a, $b ) { return $a[2] === $b[2] ? $a[3] <=> $b[3] : $a[2] <=> $b[2]; } ); foreach ( $chunks as $next ) { list( $target, $chunk ) = $next; if ( microtime( true ) >= $deadline || isset( self::paused()[ $target ] ) ) { continue; } $send = array(); foreach ( $chunk as $row ) { $needs = $targets[ $target ]['needs']; if ( $needs > 0 && ( (int) $row['consent'] & $needs ) !== $needs ) { self::settle( $row, array( 'code' => 0, 'verdict' => 'dead', 'error' => 'consent', 'tried' => false ) ); continue; } $send[] = $row; } $send = self::begin( $send ); if ( ! $send ) { continue; } try { $answers = call_user_func( $targets[ $target ]['send'], $send ); } catch ( \Throwable $e ) { $answers = array( 'code' => 0, 'verdict' => 'failed', 'error' => 'exception' ); } $sent += self::settle_many( $send, $answers ); } self::release( $claim ); } while ( count( $rows ) >= $take && microtime( true ) < $deadline ); return $sent; } private static function scope( array $targets, string $only ): array { if ( '' !== $only ) { $only = self::word( $only, 16 ); return isset( $targets[ $only ] ) ? array( $only ) : array(); } $out = array(); foreach ( $targets as $target => $t ) { if ( empty( $t['held'] ) ) { $out[] = (string) $target; } } return $out; } private static function round_size( array $targets, array $open ): int { $take = self::BATCH; foreach ( $open as $target ) { $take = max( $take, (int) ( $targets[ $target ]['batch'] ?? 1 ) ); } return $take; } private static function claim( array $targets, int $limit, int $seconds ): array { global $wpdb; if ( ! $targets ) { return array(); } try { $claim = bin2hex( random_bytes( 16 ) ); } catch ( \Exception $e ) { $claim = md5( uniqid( (string) wp_rand(), true ) ); } $table = self::table(); $now = self::now(); $in = implode( ',', array_map( static function ( $target ) use ( $wpdb ) { return $wpdb->prepare( '%s', (string) $target ); }, $targets ) ); $taken = $wpdb->query( $wpdb->prepare( "UPDATE `{$table}` SET `state` = 'sending', `claim` = %s, `claim_until_gmt` = %s, `updated_gmt` = %s WHERE ( ( `state` IN ('pending','failed') AND `next_gmt` <= %s ) OR ( `state` = 'sending' AND `claim_until_gmt` <= %s ) ) AND `target` IN ({$in}) ORDER BY `next_gmt`, `id` LIMIT %d", $claim, gmdate( 'Y-m-d H:i:s', time() + $seconds ), $now, $now, $now, max( 1, $limit ) ) ); if ( ! $taken ) { return array(); } return (array) $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `{$table}` WHERE `claim` = %s AND `state` = 'sending' ORDER BY `id`", $claim ), ARRAY_A ); } private static function begin( array $rows ): array { global $wpdb; if ( ! $rows ) { return array(); } $table = self::table(); $claim = (string) $rows[0]['claim']; $ids = implode( ',', array_map( 'intval', array_column( $rows, 'id' ) ) ); $begun = (int) $wpdb->query( $wpdb->prepare( "UPDATE `{$table}` SET `tries` = `tries` + 1, `updated_gmt` = %s WHERE `id` IN ({$ids}) AND `claim` = %s AND `state` = 'sending'", self::now(), $claim ) ); if ( $begun < 1 ) { return array(); } $mine = null; if ( count( $rows ) !== $begun ) { $mine = array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT `id` FROM `{$table}` WHERE `id` IN ({$ids}) AND `claim` = %s AND `state` = 'sending'", $claim ) ) ); } $out = array(); foreach ( $rows as $row ) { if ( null === $mine || in_array( (int) $row['id'], $mine, true ) ) { $row['tries'] = (int) $row['tries'] + 1; $out[] = $row; } } return $out; } private static function release( string $claim ): void { global $wpdb; $wpdb->query( $wpdb->prepare( 'UPDATE `' . self::table() . "` SET `state` = CASE WHEN `tries` > 0 THEN 'failed' ELSE 'pending' END, `claim` = '', `claim_until_gmt` = NULL, `updated_gmt` = %s WHERE `claim` = %s AND `state` = 'sending'", self::now(), $claim ) ); } private static function answer( $answers, array $row ): array { $a = $answers; if ( is_array( $a ) && ! array_key_exists( 'code', $a ) && ! array_key_exists( 'verdict', $a ) ) { $a = $a[ (int) $row['id'] ] ?? null; } if ( is_int( $a ) ) { $a = array( 'code' => $a ); } if ( ! is_array( $a ) ) { $a = array( 'code' => 0, 'verdict' => 'failed', 'error' => 'no_answer', ); } $code = max( 0, min( 999, (int) ( $a['code'] ?? 0 ) ) ); $verdict = isset( $a['verdict'] ) && in_array( $a['verdict'], array( 'sent', 'failed', 'dead', 'pause' ), true ) ? $a['verdict'] : self::verdict( $code ); $error = isset( $a['error'] ) ? substr( (string) preg_replace( '/[^a-z0-9_.:-]+/', '_', strtolower( (string) $a['error'] ) ), 0, 64 ) : ''; if ( '' === $error && 'sent' !== $verdict ) { $error = 0 === $code ? 'transport' : 'http_' . $code; } return array( 'code' => $code, 'verdict' => $verdict, 'error' => $error, 'tried' => ! isset( $a['tried'] ) || (bool) $a['tried'], ); } private static function settle( array $row, array $answer, bool $begun = false ): string { $out = self::outcome( $row, $answer, $begun, time() ); if ( $out['pause'] ) { $out['next'] = gmdate( 'Y-m-d H:i:s', self::pause( (string) $row['target'] ) ); } return self::write( array( $row ), $out, self::now() ) > 0 ? $out['state'] : ''; } private static function settle_many( array $rows, $answers ): int { if ( ! $rows ) { return 0; } $time = time(); $now = self::now(); $until = null; $groups = array(); foreach ( $rows as $row ) { $out = self::outcome( $row, self::answer( $answers, $row ), true, $time ); if ( $out['pause'] ) { $until = $until ?? self::pause( (string) $row['target'] ); $out['next'] = gmdate( 'Y-m-d H:i:s', $until ); } $key = implode( "\x1f", array_map( 'strval', $out ) ); $groups[ $key ]['out'] = $out; $groups[ $key ]['rows'][] = $row; } $sent = 0; foreach ( $groups as $group ) { $done = self::write( $group['rows'], $group['out'], $now ); if ( 'sent' === $group['out']['state'] ) { $sent += $done; } } return $sent; } private static function outcome( array $row, array $answer, bool $begun, int $time ): array { $before = max( 0, (int) $row['tries'] - ( $begun ? 1 : 0 ) ); $tries = $before + ( $answer['tried'] ? 1 : 0 ); $next = (string) $row['next_gmt']; $state = $answer['verdict']; $pause = false; if ( 'pause' === $state ) { $tries = $before; $state = $tries > 0 ? 'failed' : 'pending'; $pause = true; } elseif ( 'failed' === $state ) { if ( $tries >= self::MAX_TRIES ) { $state = 'dead'; } else { $next = gmdate( 'Y-m-d H:i:s', $time + self::backoff( max( 0, $tries - 1 ) ) ); } } $tries = min( 255, $tries ); return array( 'state' => $state, 'tries' => (int) $row['tries'] === $tries ? null : $tries, 'next' => (string) $row['next_gmt'] === $next ? null : $next, 'code' => (int) $answer['code'], 'error' => (string) $answer['error'], 'delete' => 'sent' === $state && 0 === self::keeping( (string) $row['target'], 'keep_sent' ), 'pause' => $pause, ); } private static function write( array $rows, array $out, string $now ): int { global $wpdb; $table = self::table(); $claim = (string) $rows[0]['claim']; $done = 0; foreach ( array_chunk( $rows, 500 ) as $part ) { $ids = implode( ',', array_map( 'intval', array_column( $part, 'id' ) ) ); if ( $out['delete'] ) { $done += max( 0, (int) $wpdb->query( $wpdb->prepare( "DELETE FROM `{$table}` WHERE `id` IN ({$ids}) AND `claim` = %s", $claim ) ) ); continue; } $set = array( '`state` = %s' ); $args = array( $out['state'] ); if ( null !== $out['tries'] ) { $set[] = '`tries` = %d'; $args[] = $out['tries']; } if ( null !== $out['next'] ) { $set[] = '`next_gmt` = %s'; $args[] = $out['next']; } array_push( $set, "`claim` = ''", '`claim_until_gmt` = NULL', '`last_code` = %d', '`last_error` = %s' ); array_push( $args, $out['code'], $out['error'] ); if ( 'sent' === $out['state'] ) { $set[] = '`sent_gmt` = %s'; $args[] = $now; } $set[] = '`updated_gmt` = %s'; $args[] = $now; $args[] = $claim; $done += max( 0, (int) $wpdb->query( $wpdb->prepare( "UPDATE `{$table}` SET " . implode( ', ', $set ) . " WHERE `id` IN ({$ids}) AND `claim` = %s", ...$args ) ) ); } return $done; } public static function paused(): array { $kept = get_option( self::PAUSED ); if ( ! is_array( $kept ) || ! $kept ) { return array(); } $now = time(); $live = array(); foreach ( $kept as $target => $until ) { if ( (int) $until > $now ) { $live[ (string) $target ] = (int) $until; } } if ( count( $live ) !== count( $kept ) ) { if ( $live ) { update_option( self::PAUSED, $live, false ); } else { delete_option( self::PAUSED ); } } return $live; } private static function pause( string $target ): int { $paused = self::paused(); $paused[ $target ] = time() + self::PAUSE; update_option( self::PAUSED, $paused, false ); return $paused[ $target ]; } public static function unpause( string $target ): bool { global $wpdb; $target = self::word( $target, 16 ); $paused = self::paused(); if ( '' === $target || ! isset( $paused[ $target ] ) ) { return false; } $until = (int) $paused[ $target ]; unset( $paused[ $target ] ); if ( $paused ) { update_option( self::PAUSED, $paused, false ); } else { delete_option( self::PAUSED ); } if ( self::on() ) { $now = self::now(); $wpdb->query( $wpdb->prepare( 'UPDATE `' . self::table() . "` SET `next_gmt` = %s, `updated_gmt` = %s WHERE `target` = %s AND `state` IN ('pending','failed') AND `next_gmt` = %s", $now, $now, $target, gmdate( 'Y-m-d H:i:s', $until ) ) ); } return true; } public static function status(): array { global $wpdb; $out = array( 'on' => self::on(), 'targets' => array(), 'paused' => array(), 'queued' => false, ); if ( ! $out['on'] ) { return $out; } $none = array_fill_keys( self::STATES, 0 ); foreach ( array_keys( self::targets() ) as $target ) { $out['targets'][ $target ] = $none; } foreach ( (array) $wpdb->get_results( 'SELECT `target`, `state`, COUNT(*) AS `n` FROM `' . self::table() . '` GROUP BY `target`, `state`', ARRAY_A ) as $row ) { $target = (string) $row['target']; if ( ! isset( $out['targets'][ $target ] ) ) { $out['targets'][ $target ] = $none; } $out['targets'][ $target ][ (string) $row['state'] ] = (int) $row['n']; } $out['paused'] = self::paused(); $out['queued'] = AIEO_Background_Queue::queued( self::HOOK ); return $out; } public static function dead( int $limit = 50 ): array { global $wpdb; if ( ! self::on() ) { return array(); } return (array) $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM `' . self::table() . "` WHERE `state` = 'dead' ORDER BY `updated_gmt` DESC, `id` DESC LIMIT %d", max( 1, $limit ) ), ARRAY_A ); } public static function set_aside( string $target ): array { global $wpdb; if ( ! self::on() ) { return array(); } $rows = (array) $wpdb->get_results( $wpdb->prepare( 'SELECT `last_error` AS `error`, `last_code` AS `code`, COUNT(*) AS `n`, MAX(`updated_gmt`) AS `last_gmt` FROM `' . self::table() . "` WHERE `target` = %s AND `state` = 'dead' GROUP BY `last_error`, `last_code` ORDER BY `last_gmt` DESC, `n` DESC", self::word( $target, 16 ) ), ARRAY_A ); foreach ( $rows as $i => $row ) { $rows[ $i ] = array( 'error' => (string) $row['error'], 'code' => (int) $row['code'], 'n' => (int) $row['n'], 'last_gmt' => (string) $row['last_gmt'], ); } return $rows; } public static function may_retry( array $row ): bool { if ( 'dead' !== ( $row['state'] ?? '' ) ) { return false; } $targets = self::targets(); $needs = isset( $targets[ (string) $row['target'] ] ) ? $targets[ (string) $row['target'] ]['needs'] : 0; return 0 === $needs || ( (int) $row['consent'] & $needs ) === $needs; } public static function retry( int $id ): bool { global $wpdb; if ( ! self::on() || $id < 1 ) { return false; } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM `' . self::table() . '` WHERE `id` = %d', $id ), ARRAY_A ); if ( ! is_array( $row ) || ! self::may_retry( $row ) ) { return false; } $now = self::now(); $done = $wpdb->query( $wpdb->prepare( 'UPDATE `' . self::table() . "` SET `state` = 'pending', `tries` = 0, `next_gmt` = %s, `claim` = '', `claim_until_gmt` = NULL, `last_error` = '', `updated_gmt` = %s WHERE `id` = %d AND `state` = 'dead'", $now, $now, $id ) ); if ( ! $done ) { return false; } if ( ! in_array( (string) $row['target'], self::held(), true ) ) { self::kick(); } return true; } private static function now(): string { return gmdate( 'Y-m-d H:i:s' ); } private static function quoted( array $names ): string { global $wpdb; return implode( ',', array_map( static function ( $name ) use ( $wpdb ) { return $wpdb->prepare( '%s', (string) $name ); }, $names ) ); } private static function word( string $word, int $length ): string { return substr( (string) preg_replace( '/[^a-z0-9_]+/', '', strtolower( $word ) ), 0, $length ); } public static function cli( $args, $assoc ) { $verb = isset( $args[0] ) ? (string) $args[0] : 'status'; if ( ! self::on() ) { WP_CLI::error( 'The outbox is off. Switch it on with: wp aieo signals on outbox' ); } if ( 'drain' === $verb ) { $only = isset( $assoc['target'] ) ? (string) $assoc['target'] : ''; $sent = self::drain( isset( $assoc['budget'] ) ? (int) $assoc['budget'] : 20, $only ); WP_CLI::success( $sent . ' sent.' . ( self::remaining( $only ) ? ' Rows remain: see "wp aieo outbox status".' : ' Nothing remains.' ) ); return; } if ( 'retry' === $verb ) { $id = isset( $args[1] ) ? (int) $args[1] : 0; if ( ! self::retry( $id ) ) { WP_CLI::error( 'Row ' . $id . ' is not a dead row that may be sent again (a row without the consent its platform needs is never sent).' ); } WP_CLI::success( 'Row ' . $id . ' is pending again.' ); return; } if ( 'status' !== $verb ) { WP_CLI::error( 'Usage: wp aieo outbox status | drain [--budget=] [--target=] | retry .' ); } $status = self::status(); WP_CLI::line( str_pad( 'target', 14 ) . implode( '', array_map( static function ( $state ) { return str_pad( $state, 10 ); }, self::STATES ) ) ); foreach ( $status['targets'] as $target => $states ) { $line = str_pad( $target, 14 ); foreach ( self::STATES as $state ) { $line .= str_pad( (string) $states[ $state ], 10 ); } WP_CLI::line( $line . ( isset( $status['paused'][ $target ] ) ? 'paused until ' . gmdate( 'Y-m-d H:i', $status['paused'][ $target ] ) . ' GMT' : '' ) ); } WP_CLI::line( $status['queued'] ? 'A run is queued.' : 'No run is queued.' ); foreach ( self::dead( 20 ) as $row ) { WP_CLI::line( 'dead #' . $row['id'] . ' ' . $row['target'] . ' ' . $row['object_type'] . ' ' . $row['object_id'] . ' ' . $row['last_error'] . ' tries ' . $row['tries'] ); } } } if ( defined( 'WP_CLI' ) && WP_CLI && class_exists( 'WP_CLI' ) ) { WP_CLI::add_command( 'aieo outbox', array( 'AIEO_Outbox', 'cli' ), array( 'shortdesc' => 'The outbox of the events sent to the ad platforms (the part "outbox" of the signals): status, drain, retry .', 'synopsis' => array( array( 'type' => 'positional', 'name' => 'verb', 'description' => 'status, drain or retry.', 'optional' => true, ), array( 'type' => 'positional', 'name' => 'id', 'description' => 'For retry: the dead row to send again.', 'optional' => true, ), array( 'type' => 'assoc', 'name' => 'budget', 'description' => 'For drain: the seconds it may take (20).', 'optional' => true, ), array( 'type' => 'assoc', 'name' => 'target', 'description' => 'For drain: one target only; a held target is sent only this way or by its own run.', 'optional' => true, ), ), ) ); } }