self::CRON_HOOK ) ); } } catch ( \Exception $e ) { Logger::error( 'cron', 'MCP connection sweep scheduling failed', array( 'hook' => self::CRON_HOOK, 'error' => $e->getMessage() ) ); } } /** * Walk every active connection and disable the ones whose owner lost * access. A connection that is not 'active' is never read by this * walk (listActiveChunk() already filters on status), so it is * inherently a no-op for any already-disabled or revoked row. * * @return int Number of connections disabled by this run (0 if the lock could not be acquired). */ public function sweep(): int { if ( get_transient( self::LOCK_TRANSIENT ) ) { return 0; } if ( ! set_transient( self::LOCK_TRANSIENT, time(), self::LOCK_TTL_SECONDS ) ) { Logger::warn( 'cron', 'MCP connection sweep skipped, lock not acquired' ); return 0; } $disabled_count = 0; try { $connections = new ConnectionStore(); $audit_log = new AuditLogStore(); $after_id = 0; $examined = 0; do { $chunk = $connections->listActiveChunk( $after_id, self::CHUNK_SIZE ); if ( empty( $chunk ) ) { break; } foreach ( $chunk as $connection ) { $after_id = max( $after_id, (int) $connection['id'] ); ++$examined; if ( $this->ownerStillQualifies( (int) $connection['user_id'] ) ) { continue; } $id_disabled = $connections->disable( (int) $connection['id'], ConnectionStore::DISABLED_REASON_CAPABILITY_LOST ); if ( ! $id_disabled ) { continue; } ++$disabled_count; $audit_log->write( array( 'connection_id' => (int) $connection['id'], 'user_id' => (int) $connection['user_id'], 'event_type' => AuditLogStore::EVENT_CONNECTION_DISABLED, 'outcome' => AuditLogStore::OUTCOME_SUCCESS, 'subject_type' => 'connection', 'subject_id' => (int) $connection['id'], 'request_summary' => array( 'reason' => ConnectionStore::DISABLED_REASON_CAPABILITY_LOST ), ) ); } } while ( count( $chunk ) === self::CHUNK_SIZE && $examined < self::MAX_ROWS_PER_RUN ); return $disabled_count; } catch ( \Exception $e ) { Logger::error( 'cron', 'MCP connection sweep failed', array( 'error' => $e->getMessage() ) ); return $disabled_count; } finally { delete_transient( self::LOCK_TRANSIENT ); } } /** * Whether a connection's owner still exists and still holds * `manage_woocommerce`. * * @param int $user_id Owner user id. * @return bool */ private function ownerStillQualifies( int $user_id ): bool { if ( $user_id <= 0 ) { return false; } $user = get_userdata( $user_id ); if ( ! $user ) { return false; } return user_can( $user, self::REQUIRED_CAPABILITY ); } /** * Static cron callback. * * @return void */ public static function cron_callback(): void { try { $sweeper = new self(); $sweeper->sweep(); } catch ( \Exception $e ) { Logger::error( 'cron', 'MCP connection sweep callback failed', array( 'error' => $e->getMessage() ) ); } } }