capability ) ) { return new WP_Error( 'mailpuff_forbidden', __( 'Forbidden.', 'mailpuff' ), array( 'status' => 403 ) ); } return true; } /** * Cloudflare's published ranges (cloudflare.com/ips, 2026-10-26). A request * from one of them carries the visitor's address in CF-Connecting-IP. */ const CLOUDFLARE_RANGES = array( '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32', ); /** * Fixed-window rate limiter: at most RATE_LIMIT requests per visitor per * minute. With a persistent object cache the count is atomic; without * one, a transient (two requests at the same instant may count once). * * @param string $bucket Separate counter for an endpoint family ('' is the shared one). * @return bool True if the request is allowed. */ protected function within_rate_limit( $bucket = '' ) { $window = (int) floor( time() / 60 ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_md5 $tkey = 'mailpuff_rl_' . md5( self::rate_key( $this->client_ip() ) . $bucket . $window ); if ( wp_using_ext_object_cache() ) { wp_cache_add( $tkey, 0, 'mailpuff_rl', 2 * MINUTE_IN_SECONDS ); return (int) wp_cache_incr( $tkey, 1, 'mailpuff_rl' ) <= self::RATE_LIMIT; } $count = (int) get_transient( $tkey ); if ( $count >= self::RATE_LIMIT ) { return false; } // Two-minute TTL so the transient survives across the window boundary. set_transient( $tkey, $count + 1, 2 * MINUTE_IN_SECONDS ); return true; } /** * What a visitor is counted by: the IPv4 address, or an IPv6 address's * /64 network (one connection can hold a whole /64). * * @param string $ip Address. * @return string */ private static function rate_key( $ip ) { if ( false === strpos( $ip, ':' ) ) { return $ip; } $packed = @inet_pton( $ip ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- an unparseable address is handled below. return false === $packed ? $ip : bin2hex( substr( $packed, 0, 8 ) ) . '::/64'; } /** * The visitor's address, for rate limits. * * REMOTE_ADDR is the real TCP peer and can't be spoofed, so it is the * default. Only when that peer is Cloudflare (CLOUDFLARE_RANGES) is its * CF-Connecting-IP header used: from anywhere else the header can be set * to anything. Another proxy in front of the site can be taught through * the `mailpuff_client_ip` filter. * * @return string */ protected function client_ip() { $remote = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '0.0.0.0'; $ip = $remote; if ( isset( $_SERVER['HTTP_CF_CONNECTING_IP'] ) && self::in_ranges( $remote, self::CLOUDFLARE_RANGES ) ) { $cf = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ); if ( false !== filter_var( $cf, FILTER_VALIDATE_IP ) ) { $ip = $cf; } } /** * The visitor's address used for rate limits. * * @param string $ip The address chosen (REMOTE_ADDR, or CF-Connecting-IP behind Cloudflare). * @param string $remote REMOTE_ADDR. */ $filtered = (string) apply_filters( 'mailpuff_client_ip', $ip, $remote ); return false !== filter_var( $filtered, FILTER_VALIDATE_IP ) ? $filtered : $remote; } /** * Whether an address is in one of the CIDR ranges. * * @param string $ip Address. * @param string[] $ranges CIDR ranges. * @return bool */ protected static function in_ranges( $ip, array $ranges ) { $addr = @inet_pton( $ip ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- an unparseable address matches nothing. if ( false === $addr ) { return false; } foreach ( $ranges as $range ) { list( $net, $bits ) = array_pad( explode( '/', $range, 2 ), 2, '' ); $net = @inet_pton( $net ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( false === $net || strlen( $net ) !== strlen( $addr ) ) { continue; } $bits = (int) $bits; $bytes = intdiv( $bits, 8 ); if ( substr( $addr, 0, $bytes ) !== substr( $net, 0, $bytes ) ) { continue; } $rest = $bits % 8; if ( 0 === $rest ) { return true; } $mask = chr( ( 0xff << ( 8 - $rest ) ) & 0xff ); if ( ( $addr[ $bytes ] & $mask ) === ( $net[ $bytes ] & $mask ) ) { return true; } } return false; } /** * Returns a success response. * * @param mixed $data Response data. * @param int $status HTTP status code. * @return WP_REST_Response */ protected function success( $data, $status = 200 ) { return new WP_REST_Response( $data, $status ); } /** * Returns an error response. * * @param string $code Error code. * @param string $message Error message. * @param int $status HTTP status code. * @return WP_Error */ protected function error( $code, $message, $status = 400 ) { return new WP_Error( $code, $message, array( 'status' => $status ) ); } /** * Paginates a query result. * * @param WP_REST_Request $request Request object. * @return array { page, per_page, offset } */ protected function get_pagination( $request ) { $page = max( 1, absint( $request->get_param( 'page' ) ) ); $per_page = absint( $request->get_param( 'per_page' ) ); $per_page = $per_page ? $per_page : 20; $per_page = min( $per_page, 100 ); return array( 'page' => $page, 'per_page' => $per_page, 'offset' => ( $page - 1 ) * $per_page, ); } /** * Run a COUNT-style query, always through prepare(). * * @param string $sql SQL with %i/%s/%d placeholders (table names as %i). * @param array $params Values for the placeholders. * @return int */ protected function count_rows( $sql, $params ) { global $wpdb; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- the SQL is assembled by the caller from literal fragments, every value and table name is a placeholder. return (int) $wpdb->get_var( $wpdb->prepare( $sql, $params ) ); } /** * Run a paginated SELECT. * * Appends LIMIT %d OFFSET %d to the given SQL and prepares with * the caller's params plus the pagination values. * * @param string $sql SQL up to and including ORDER BY. * @param array $params Values for placeholders in $sql. * @param array $pagination Output of get_pagination(). * @return array */ protected function paginated_query( $sql, $params, $pagination ) { global $wpdb; $sql .= ' LIMIT %d OFFSET %d'; $all_params = array_merge( $params, array( (int) $pagination['per_page'], (int) $pagination['offset'] ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- the SQL is assembled by the caller from literal fragments, every value and table name is a placeholder. return $wpdb->get_results( $wpdb->prepare( $sql, $all_params ) ); } /** * Build the standard { items, total, page, pages } response. * * @param array $items Row set. * @param int $total Total matching rows. * @param array $pagination Output of get_pagination(). * @param array $extra Extra top-level keys to merge in (e.g. counts). * @return WP_REST_Response */ protected function paginated_response( $items, $total, $pagination, $extra = array() ) { $per_page = max( 1, (int) $pagination['per_page'] ); return $this->success( array_merge( array( 'items' => $items, 'total' => (int) $total, 'page' => (int) $pagination['page'], 'pages' => (int) ceil( $total / $per_page ), ), $extra ) ); } /** * Build a { all, : n, ... } map from a status/count query, so a * list endpoint can return sidebar tab counts in the same round-trip * instead of the client firing one extra request per status. * * The query must SELECT a `status` column and a `c` count column, * grouped by status. Counts are global (filters are intentionally not * applied) so the tabs show the same totals on every view. * * @param string $sql SQL returning rows of ( status, c ); table names as %i. * @param array $params Values for the placeholders in $sql. * @return array */ protected function status_counts( $sql, $params ) { global $wpdb; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- the SQL is assembled by the caller from literal fragments, every value and table name is a placeholder. $rows = $wpdb->get_results( $wpdb->prepare( $sql, $params ) ); $counts = array( 'all' => 0 ); foreach ( (array) $rows as $row ) { $counts[ $row->status ] = (int) $row->c; $counts['all'] += (int) $row->c; } return $counts; } }