Skip to content
This repository was archived by the owner on Sep 24, 2018. It is now read-only.

Commit 52542d3

Browse files
committed
Use string format type of 'ipv4' to validate comment author IP address
New function `rest_is_ip_address()` checks if a value is a valid v4 IP address. It uses regex because core cannot guarantee support for `filter_var`.
1 parent 377c48d commit 52542d3

2 files changed

Lines changed: 30 additions & 5 deletions

File tree

lib/endpoints/class-wp-rest-comments-controller.php

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -748,11 +748,7 @@ protected function prepare_item_for_database( $request ) {
748748
}
749749

750750
if ( isset( $request['author_ip'] ) ) {
751-
if ( filter_var( $request['author_ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
752-
$prepared_comment['comment_author_IP'] = $request['author_ip'];
753-
} else {
754-
return new WP_Error( 'rest_comment_invalid_author_ip', __( 'The IP address you provided is invalid.' ), array( 'status' => 400 ) );
755-
}
751+
$prepared_comment['comment_author_IP'] = $request['author_ip'];
756752
}
757753

758754
if ( isset( $request['type'] ) ) {
@@ -811,6 +807,7 @@ public function get_item_schema() {
811807
'author_ip' => array(
812808
'description' => __( 'IP address for the object author.' ),
813809
'type' => 'string',
810+
'format' => 'ipv4',
814811
'context' => array( 'edit' ),
815812
),
816813
'author_name' => array(

plugin.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,11 @@ function rest_validate_request_arg( $value, $request, $param ) {
320320
return new WP_Error( 'rest_invalid_email', __( 'The email address you provided is invalid.' ) );
321321
}
322322
break;
323+
case 'ipv4' :
324+
if ( ! rest_is_ip_address( $value ) ) {
325+
return new WP_Error( 'rest_invalid_param', sprintf( __( '%s is not a valid IP address.'), $value ) );
326+
}
327+
break;
323328
}
324329
}
325330

@@ -395,10 +400,33 @@ function rest_sanitize_request_arg( $value, $request, $param ) {
395400

396401
case 'uri' :
397402
return esc_url_raw( $value );
403+
404+
case 'ipv4' :
405+
return sanitize_text_field( $value );
398406
}
399407
}
400408

401409
return $value;
402410
}
403411

404412
}
413+
414+
if ( ! function_exists( 'rest_is_ip_address' ) ) {
415+
/**
416+
* Determines if a IPv4 address is valid.
417+
*
418+
* Does not handle IPv6 addresses.
419+
*
420+
* @param string $ipv4 IP 32-bit address.
421+
* @return string|false The valid IPv4 address, otherwise false.
422+
*/
423+
function rest_is_ip_address( $ipv4 ) {
424+
$pattern = '/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';
425+
426+
if ( ! preg_match( $pattern, $ipv4 ) ) {
427+
return false;
428+
}
429+
430+
return $ipv4;
431+
}
432+
}

0 commit comments

Comments
 (0)