wpdb = $wpdb instanceof \wpdb ? $wpdb : $GLOBALS['wpdb']; $this->table = $this->wpdb->prefix . 'aipt_mcp_connections'; } /** * Fully-qualified table name. * * @return string */ public function table(): string { return $this->table; } /** * Create a connection row. * * @param array{auth_type:string,user_id:int,oauth_client_id?:int,label?:string,permission_level?:string,created_by_ip_hash?:string,now?:string} $data Connection fields. * @return int|null New row id, or null when the input is invalid or the insert failed. */ public function create( array $data ): ?int { $wpdb = $this->wpdb; $auth_type = isset( $data['auth_type'] ) ? (string) $data['auth_type'] : ''; $user_id = isset( $data['user_id'] ) ? (int) $data['user_id'] : 0; $level = isset( $data['permission_level'] ) ? (string) $data['permission_level'] : McpPermissionLevel::DEFAULT_LEVEL; if ( ! in_array( $auth_type, array( self::AUTH_TYPE_OAUTH, self::AUTH_TYPE_API_KEY ), true ) ) { return null; } if ( $user_id <= 0 ) { return null; } if ( ! McpPermissionLevel::isValid( $level ) ) { return null; } $now = isset( $data['now'] ) ? (string) $data['now'] : gmdate( 'Y-m-d H:i:s' ); $result = $wpdb->insert( $this->table, array( 'auth_type' => $auth_type, 'user_id' => $user_id, 'oauth_client_id' => isset( $data['oauth_client_id'] ) ? (int) $data['oauth_client_id'] : 0, 'label' => isset( $data['label'] ) ? (string) $data['label'] : '', 'permission_level' => $level, 'status' => self::STATUS_ACTIVE, 'created_by_ip_hash' => isset( $data['created_by_ip_hash'] ) ? (string) $data['created_by_ip_hash'] : '', 'created_at' => $now, ), array( '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%s' ) ); if ( false === $result ) { $this->logError( __FUNCTION__ ); return null; } return (int) $wpdb->insert_id; } /** * Read one connection by id. * * @param int $id Row id. * @return array|null * @phpstan-return McpConnectionRow|null */ public function find( int $id ): ?array { $wpdb = $this->wpdb; if ( $id <= 0 ) { return null; } $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$this->table} WHERE id = %d", $id ), ARRAY_A ); if ( is_array( $row ) ) { return $this->mapRow( $row ); } if ( '' !== $wpdb->last_error ) { $this->logError( __FUNCTION__ ); } return null; } /** * List a user's own connections, newest first. * * @param int $user_id Owner user id. * @param int $limit Max rows. * @param int $offset Row offset. * @return array> * @phpstan-return array */ public function listForUser( int $user_id, int $limit = 50, int $offset = 0 ): array { return $this->listAll( array( 'user_id' => $user_id, 'limit' => $limit, 'offset' => $offset, ) ); } /** * List connections, optionally filtered, newest first. * * @param array{status?:string,user_id?:int,limit?:int,offset?:int} $args Filters. * @return array> * @phpstan-return array */ public function listAll( array $args = array() ): array { $wpdb = $this->wpdb; $where = array(); $params = array(); if ( ! empty( $args['status'] ) ) { $where[] = 'status = %s'; $params[] = (string) $args['status']; } if ( ! empty( $args['user_id'] ) ) { $where[] = 'user_id = %d'; $params[] = (int) $args['user_id']; } $limit = isset( $args['limit'] ) ? max( 1, (int) $args['limit'] ) : 50; $offset = isset( $args['offset'] ) ? max( 0, (int) $args['offset'] ) : 0; $where_sql = empty( $where ) ? '' : ' WHERE ' . implode( ' AND ', $where ); $params[] = $limit; $params[] = $offset; $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$this->table}{$where_sql} ORDER BY created_at DESC, id DESC LIMIT %d OFFSET %d", $params ), ARRAY_A ); if ( '' !== $wpdb->last_error ) { $this->logError( __FUNCTION__ ); return array(); } return array_map( array( $this, 'mapRow' ), is_array( $rows ) ? $rows : array() ); } /** * Count a user's own connections. * * @param int $user_id Owner user id. * @return int|null Null on a database error. */ public function countForUser( int $user_id ): ?int { $wpdb = $this->wpdb; $value = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$this->table} WHERE user_id = %d", $user_id ) ); if ( null === $value ) { $this->logError( __FUNCTION__ ); return null; } return (int) $value; } /** * Count every connection, optionally filtered by status/user. * * @param array{status?:string,user_id?:int} $args Filters. * @return int|null Null on a database error. */ public function countAll( array $args = array() ): ?int { $wpdb = $this->wpdb; $where = array(); $params = array(); if ( ! empty( $args['status'] ) ) { $where[] = 'status = %s'; $params[] = (string) $args['status']; } if ( ! empty( $args['user_id'] ) ) { $where[] = 'user_id = %d'; $params[] = (int) $args['user_id']; } $where_sql = empty( $where ) ? '' : ' WHERE ' . implode( ' AND ', $where ); $sql = "SELECT COUNT(*) FROM {$this->table}{$where_sql}"; $value = empty( $params ) ? $wpdb->get_var( $sql ) : $wpdb->get_var( $wpdb->prepare( $sql, $params ) ); if ( null === $value ) { $this->logError( __FUNCTION__ ); return null; } return (int) $value; } /** * Count every active connection, site-wide (no user filter). The free * connection cap is a single site-wide pool, not * per-user, so callers enforcing it must use this rather than * {@see countForUser()}. * * @return int|null Null on a database error, so a cap check can fail closed. */ public function countActive(): ?int { $wpdb = $this->wpdb; $value = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$this->table} WHERE status = %s", self::STATUS_ACTIVE ) ); if ( null === $value ) { $this->logError( __FUNCTION__ ); return null; } return (int) $value; } /** * Rename a connection. * * @param int $id Row id. * @param string $label New label. * @return bool */ public function updateLabel( int $id, string $label ): bool { $wpdb = $this->wpdb; if ( $id <= 0 ) { return false; } $result = $wpdb->update( $this->table, array( 'label' => $label ), array( 'id' => $id ), array( '%s' ), array( '%d' ) ); if ( false === $result ) { $this->logError( __FUNCTION__ ); return false; } return true; } /** * Change a connection's permission level. * * @param int $id Row id. * @param string $level New level; must be a valid {@see McpPermissionLevel}. * @return bool */ public function updateLevel( int $id, string $level ): bool { $wpdb = $this->wpdb; if ( $id <= 0 || ! McpPermissionLevel::isValid( $level ) ) { return false; } $result = $wpdb->update( $this->table, array( 'permission_level' => $level ), array( 'id' => $id ), array( '%s' ), array( '%d' ) ); if ( false === $result ) { $this->logError( __FUNCTION__ ); return false; } return true; } /** * Revoke a connection. Only takes effect from 'active' or 'disabled'; a * row already 'revoked' is left untouched and this returns false. * * @param int $id Row id. * @param string $reason One of the REVOKED_REASON_* constants. * @param int $revoked_by User id performing the revoke (0 for a system action). * @param string|null $now UTC datetime string; defaults to the current time. * @return bool True when a row was actually revoked by this call. */ public function revoke( int $id, string $reason, int $revoked_by, ?string $now = null ): bool { $wpdb = $this->wpdb; if ( $id <= 0 ) { return false; } $now = $now ?? gmdate( 'Y-m-d H:i:s' ); $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET status = %s, revoked_reason = %s, revoked_at = %s, revoked_by = %d WHERE id = %d AND status IN (%s, %s)", self::STATUS_REVOKED, $reason, $now, $revoked_by, $id, self::STATUS_ACTIVE, self::STATUS_DISABLED ) ); if ( false === $affected ) { $this->logError( __FUNCTION__ ); return false; } return (int) $affected > 0; } /** * Disable one connection. Only takes effect from 'active'; already * disabled or revoked rows are left untouched and this returns false. * * @param int $id Row id. * @param string $reason One of the DISABLED_REASON_* constants. * @param string|null $now UTC datetime string; defaults to the current time. * @return bool True when a row was actually disabled by this call. */ public function disable( int $id, string $reason, ?string $now = null ): bool { $wpdb = $this->wpdb; if ( $id <= 0 ) { return false; } $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET status = %s, disabled_reason = %s WHERE id = %d AND status = %s", self::STATUS_DISABLED, $reason, $id, self::STATUS_ACTIVE ) ); if ( false === $affected ) { $this->logError( __FUNCTION__ ); return false; } return (int) $affected > 0; } /** * Disable every active connection owned by a user in one statement. * Used when the owner is removed (delete_user/wpmu_delete_user/ * remove_user_from_blog) — connections are disabled, never deleted. * * @param int $user_id Owner user id. * @param string $reason One of the DISABLED_REASON_* constants. * @return int Number of rows disabled by this call; 0 on a database error or when none were active. */ public function disableForUser( int $user_id, string $reason ): int { $wpdb = $this->wpdb; if ( $user_id <= 0 ) { return 0; } $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET status = %s, disabled_reason = %s WHERE user_id = %d AND status = %s", self::STATUS_DISABLED, $reason, $user_id, self::STATUS_ACTIVE ) ); if ( false === $affected ) { $this->logError( __FUNCTION__ ); return 0; } return (int) $affected; } /** * One page of active connections, ordered by id, for the capability * sweeper's chunked walk. * * @param int $after_id Only rows with id greater than this are returned. * @param int $limit Max rows. * @return array> * @phpstan-return array */ public function listActiveChunk( int $after_id, int $limit ): array { $wpdb = $this->wpdb; $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$this->table} WHERE status = %s AND id > %d ORDER BY id ASC LIMIT %d", self::STATUS_ACTIVE, $after_id, max( 1, $limit ) ), ARRAY_A ); if ( '' !== $wpdb->last_error ) { $this->logError( __FUNCTION__ ); return array(); } return array_map( array( $this, 'mapRow' ), is_array( $rows ) ? $rows : array() ); } /** * Record that a connection was just used, throttled so a busy * connection writes this column at most once per * {@see TOUCH_THROTTLE_SECONDS}. The throttle condition runs in SQL so * concurrent requests never race each other into redundant writes. * * @param int $id Row id. * @param string $now Current UTC datetime (`gmdate('Y-m-d H:i:s')` or a fixed value for tests). * @return void */ public function touchLastUsed( int $id, string $now ): void { $wpdb = $this->wpdb; if ( $id <= 0 ) { return; } $cutoff_ts = strtotime( $now ) - self::TOUCH_THROTTLE_SECONDS; $cutoff = false !== $cutoff_ts ? gmdate( 'Y-m-d H:i:s', $cutoff_ts ) : $now; $result = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET last_used_at = %s WHERE id = %d AND (last_used_at IS NULL OR last_used_at < %s)", $now, $id, $cutoff ) ); if ( false === $result ) { $this->logError( __FUNCTION__ ); } } /** * Find the active connection, if any, linking one user to one OAuth * client. Used at token-exchange time so a client re-authorizing the * same user reuses its existing connection instead of minting a second * one that would needlessly consume another slot of the free cap. * * @param int $user_id Owner user id. * @param int $oauth_client_id OAuth client row id (never 0 for an api_key connection, which this never matches). * @return array|null * @phpstan-return McpConnectionRow|null */ public function findActiveForClient( int $user_id, int $oauth_client_id ): ?array { $wpdb = $this->wpdb; if ( $user_id <= 0 || $oauth_client_id <= 0 ) { return null; } $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$this->table} WHERE user_id = %d AND oauth_client_id = %d AND status = %s ORDER BY id DESC LIMIT 1", $user_id, $oauth_client_id, self::STATUS_ACTIVE ), ARRAY_A ); if ( is_array( $row ) ) { return $this->mapRow( $row ); } if ( '' !== $wpdb->last_error ) { $this->logError( __FUNCTION__ ); } return null; } /** * Normalize a raw row: cast integer columns, clamp the Business-only * column to null. * * @param array $row Raw row from $wpdb. * @return array * @phpstan-return McpConnectionRow */ private function mapRow( array $row ): array { return array( 'id' => (int) ( $row['id'] ?? 0 ), 'auth_type' => (string) ( $row['auth_type'] ?? '' ), 'user_id' => (int) ( $row['user_id'] ?? 0 ), 'oauth_client_id' => (int) ( $row['oauth_client_id'] ?? 0 ), 'label' => (string) ( $row['label'] ?? '' ), 'permission_level' => (string) ( $row['permission_level'] ?? '' ), 'custom_tool_overrides' => null, 'status' => (string) ( $row['status'] ?? '' ), 'revoked_reason' => (string) ( $row['revoked_reason'] ?? '' ), 'disabled_reason' => (string) ( $row['disabled_reason'] ?? '' ), 'created_by_ip_hash' => (string) ( $row['created_by_ip_hash'] ?? '' ), 'created_at' => (string) ( $row['created_at'] ?? '' ), 'last_used_at' => isset( $row['last_used_at'] ) ? (string) $row['last_used_at'] : null, 'revoked_at' => isset( $row['revoked_at'] ) ? (string) $row['revoked_at'] : null, 'revoked_by' => (int) ( $row['revoked_by'] ?? 0 ), ); } /** * Log the wpdb error for a failed call. Never throws, never surfaces * the error to the caller beyond the method's own null/false/0 return. * * @param string $method Calling method name, for the log line. * @return void */ private function logError( string $method ): void { $wpdb = $this->wpdb; } }