$key, 'value' => self::pack( $value ), ), $seconds ); } /** * Keeps a value only when there is none yet, and says whether it did. * * @param string $key The key. * @param string $value The value. * @param int $seconds How long it is kept. */ public function add( string $key, string $value, int $seconds ): bool { if ( wp_using_ext_object_cache() ) { return wp_cache_add( self::name( $key ), self::pack( $value ), self::GROUP, $seconds ); } if ( str_starts_with( $key, self::RATE . 'key:' ) ) { return null === $this->get( $key ) && self::keep_day_key( $key, $value, $seconds ); } if ( false !== get_transient( self::name( $key ) ) ) { return false; } return set_transient( self::name( $key ), self::pack( $value ), $seconds ); } /** * Adds one to a count: the new count, or null when it cannot count. A * persistent object cache counts atomically. Otherwise the counts for one * minute share a transient, and count nearly, as two requests at the same * moment may count once between them, which a limit of 120 a minute can * bear. A new minute starts it afresh, and past MOST addresses a new one * is not counted here. * * @param string $key The key: the minute, then a colon and the hashed address. * @param int $seconds How long the count lasts. */ public function increment( string $key, int $seconds ): ?int { if ( wp_using_ext_object_cache() ) { $name = self::name( $key ); wp_cache_add( $name, 0, self::GROUP, $seconds ); $count = wp_cache_incr( $name, 1, self::GROUP ); return false === $count ? null : (int) $count; } $split = strrpos( $key, ':' ); if ( false === $split ) { return null; } $window = substr( $key, 0, $split ); $id = substr( $key, $split + 1 ); $kept = get_transient( self::COUNTS ); $counts = is_array( $kept ) && ( $kept['window'] ?? null ) === $window && is_array( $kept['counts'] ?? null ) ? $kept['counts'] : array(); if ( ! isset( $counts[ $id ] ) && count( $counts ) >= self::MOST ) { return null; } $counts[ $id ] = (int) ( $counts[ $id ] ?? 0 ) + 1; $saved = set_transient( self::COUNTS, array( 'window' => $window, 'counts' => $counts, ), $seconds ); return $saved ? $counts[ $id ] : null; } /** * Deletes the rate limit's transients once their minute or day is over, * which the hourly check does, so no hashed address outlives its day. */ public static function sweep(): void { if ( wp_using_ext_object_cache() ) { return; } // Reading an expired transient deletes it. get_transient( self::COUNTS ); $kept = get_transient( self::DAY_KEY ); $day = (int) floor( time() / DAY_IN_SECONDS ); if ( is_array( $kept ) && self::RATE . 'key:' . $day !== ( $kept['key'] ?? null ) ) { delete_transient( self::DAY_KEY ); } } }