wp/wp-includes/comment.php
changeset 7 cf61fcea0001
parent 5 5e2f62d02dcd
child 9 177826044cd9
--- a/wp/wp-includes/comment.php	Tue Jun 09 11:14:17 2015 +0000
+++ b/wp/wp-includes/comment.php	Mon Oct 14 17:39:30 2019 +0200
@@ -1,6 +1,6 @@
 <?php
 /**
- * Manages WordPress comments
+ * Core Comment API
  *
  * @package WordPress
  * @subpackage Comment
@@ -44,21 +44,23 @@
 		return false;
 
 	/** This filter is documented in wp-includes/comment-template.php */
-	$comment = apply_filters( 'comment_text', $comment );
+	$comment = apply_filters( 'comment_text', $comment, null, array() );
 
 	// Check for the number of external links if a max allowed number is set.
 	if ( $max_links = get_option( 'comment_max_links' ) ) {
 		$num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out );
 
 		/**
-		 * Filter the maximum number of links allowed in a comment.
+		 * Filters the number of links found in a comment.
 		 *
 		 * @since 3.0.0
+		 * @since 4.7.0 Added the `$comment` parameter.
 		 *
-		 * @param int    $num_links The number of links allowed.
+		 * @param int    $num_links The number of links found.
 		 * @param string $url       Comment author's URL. Included in allowed links total.
+		 * @param string $comment   Content of the comment.
 		 */
-		$num_links = apply_filters( 'comment_max_links_url', $num_links, $url );
+		$num_links = apply_filters( 'comment_max_links_url', $num_links, $url, $comment );
 
 		/*
 		 * If the number of links in the comment exceeds the allowed amount,
@@ -110,8 +112,13 @@
 	 */
 	if ( 1 == get_option('comment_whitelist')) {
 		if ( 'trackback' != $comment_type && 'pingback' != $comment_type && $author != '' && $email != '' ) {
-			// expected_slashed ($author, $email)
-			$ok_to_comment = $wpdb->get_var("SELECT comment_approved FROM $wpdb->comments WHERE comment_author = '$author' AND comment_author_email = '$email' and comment_approved = '1' LIMIT 1");
+			$comment_user = get_user_by( 'email', wp_unslash( $email ) );
+			if ( ! empty( $comment_user->ID ) ) {
+				$ok_to_comment = $wpdb->get_var( $wpdb->prepare( "SELECT comment_approved FROM $wpdb->comments WHERE user_id = %d AND comment_approved = '1' LIMIT 1", $comment_user->ID ) );
+			} else {
+				// expected_slashed ($author, $email)
+				$ok_to_comment = $wpdb->get_var( $wpdb->prepare( "SELECT comment_approved FROM $wpdb->comments WHERE comment_author = %s AND comment_author_email = %s and comment_approved = '1' LIMIT 1", $author, $email ) );
+			}
 			if ( ( 1 == $ok_to_comment ) &&
 				( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
 					return true;
@@ -128,11 +135,10 @@
  * Retrieve the approved comments for post $post_id.
  *
  * @since 2.0.0
- * @since 4.1.0 Refactored to leverage {@see WP_Comment_Query} over a direct query.
+ * @since 4.1.0 Refactored to leverage WP_Comment_Query over a direct query.
  *
  * @param  int   $post_id The ID of the post.
- * @param  array $args    Optional. See {@see WP_Comment_Query::query()} for information
- *                        on accepted arguments.
+ * @param  array $args    Optional. See WP_Comment_Query::__construct() for information on accepted arguments.
  * @return int|array $comments The approved comments, or number of comments if `$count`
  *                             argument is true.
  */
@@ -161,32 +167,28 @@
  *
  * @since 2.0.0
  *
- * @global wpdb $wpdb WordPress database abstraction object.
+ * @global WP_Comment $comment
  *
- * @param object|string|int $comment Comment to retrieve.
- * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
- * @return object|array|null Depends on $output value.
+ * @param WP_Comment|string|int $comment Comment to retrieve.
+ * @param string                $output  Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to
+ *                                       a WP_Comment object, an associative array, or a numeric array, respectively. Default OBJECT.
+ * @return WP_Comment|array|null Depends on $output value.
  */
-function get_comment(&$comment, $output = OBJECT) {
-	global $wpdb;
-
-	if ( empty($comment) ) {
-		if ( isset($GLOBALS['comment']) )
-			$_comment = & $GLOBALS['comment'];
-		else
-			$_comment = null;
-	} elseif ( is_object($comment) ) {
-		wp_cache_add($comment->comment_ID, $comment, 'comment');
+function get_comment( &$comment = null, $output = OBJECT ) {
+	if ( empty( $comment ) && isset( $GLOBALS['comment'] ) ) {
+		$comment = $GLOBALS['comment'];
+	}
+
+	if ( $comment instanceof WP_Comment ) {
 		$_comment = $comment;
+	} elseif ( is_object( $comment ) ) {
+		$_comment = new WP_Comment( $comment );
 	} else {
-		if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
-			$_comment = & $GLOBALS['comment'];
-		} elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
-			$_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
-			if ( ! $_comment )
-				return null;
-			wp_cache_add($_comment->comment_ID, $_comment, 'comment');
-		}
+		$_comment = WP_Comment::get_instance( $comment );
+	}
+
+	if ( ! $_comment ) {
+		return null;
 	}
 
 	/**
@@ -201,14 +203,11 @@
 	if ( $output == OBJECT ) {
 		return $_comment;
 	} elseif ( $output == ARRAY_A ) {
-		$__comment = get_object_vars($_comment);
-		return $__comment;
+		return $_comment->to_array();
 	} elseif ( $output == ARRAY_N ) {
-		$__comment = array_values(get_object_vars($_comment));
-		return $__comment;
-	} else {
-		return $_comment;
+		return array_values( $_comment->to_array() );
 	}
+	return $_comment;
 }
 
 /**
@@ -218,7 +217,7 @@
  *
  * @since 2.7.0
  *
- * @param string|array $args Optional. Array or string of arguments. See {@see WP_Comment_Query::parse_query()}
+ * @param string|array $args Optional. Array or string of arguments. See WP_Comment_Query::__construct()
  *                           for information on accepted arguments. Default empty.
  * @return int|array List of comments or number of found comments if `$count` argument is true.
  */
@@ -228,783 +227,6 @@
 }
 
 /**
- * WordPress Comment Query class.
- *
- * See WP_Comment_Query::__construct() for accepted arguments.
- *
- * @since 3.1.0
- */
-class WP_Comment_Query {
-	/**
-	 * SQL for database query.
-	 *
-	 * @since 4.0.1
-	 * @access public
-	 * @var string
-	 */
-	public $request;
-
-	/**
-	 * Metadata query container
-	 *
-	 * @since 3.5.0
-	 * @access public
-	 * @var object WP_Meta_Query
-	 */
-	public $meta_query = false;
-
-	/**
-	 * Date query container
-	 *
-	 * @since 3.7.0
-	 * @access public
-	 * @var object WP_Date_Query
-	 */
-	public $date_query = false;
-
-	/**
-	 * Query vars set by the user.
-	 *
-	 * @since 3.1.0
-	 * @access public
-	 * @var array
-	 */
-	public $query_vars;
-
-	/**
-	 * Default values for query vars.
-	 *
-	 * @since 4.2.0
-	 * @access public
-	 * @var array
-	 */
-	public $query_var_defaults;
-
-	/**
-	 * List of comments located by the query.
-	 *
-	 * @since 4.0.0
-	 * @access public
-	 * @var array
-	 */
-	public $comments;
-
-	/**
-	 * Make private/protected methods readable for backwards compatibility.
-	 *
-	 * @since 4.0.0
-	 * @access public
-	 *
-	 * @param callable $name      Method to call.
-	 * @param array    $arguments Arguments to pass when calling.
-	 * @return mixed|bool Return value of the callback, false otherwise.
-	 */
-	public function __call( $name, $arguments ) {
-		if ( 'get_search_sql' === $name ) {
-			return call_user_func_array( array( $this, $name ), $arguments );
-		}
-		return false;
-	}
-
-	/**
-	 * Constructor.
-	 *
-	 * Sets up the comment query, based on the query vars passed.
-	 *
-	 * @since  4.2.0
-	 * @access public
-	 *
-	 * @param string|array $query {
-	 *     Optional. Array or query string of comment query parameters. Default empty.
-	 *
-	 *     @type string       $author_email        Comment author email address. Default empty.
-	 *     @type array        $author__in          Array of author IDs to include comments for. Default empty.
-	 *     @type array        $author__not_in      Array of author IDs to exclude comments for. Default empty.
-	 *     @type array        $comment__in         Array of comment IDs to include. Default empty.
-	 *     @type array        $comment__not_in     Array of comment IDs to exclude. Default empty.
-	 *     @type bool         $count               Whether to return a comment count (true) or array of comment
-	 *                                             objects (false). Default false.
-	 *     @type array        $date_query          Date query clauses to limit comments by. See WP_Date_Query.
-	 *                                             Default null.
-	 *     @type string       $fields              Comment fields to return. Accepts 'ids' for comment IDs only or
-	 *                                             empty for all fields. Default empty.
-	 *     @type int          $ID                  Currently unused.
-	 *     @type array        $include_unapproved  Array of IDs or email addresses of users whose unapproved comments
-	 *                                             will be returned by the query regardless of `$status`. Default empty.
-	 *     @type int          $karma               Karma score to retrieve matching comments for. Default empty.
-	 *     @type string       $meta_key            Include comments with a matching comment meta key. Default empty.
-	 *     @type string       $meta_value          Include comments with a matching comment meta value. Requires
-	 *                                             `$meta_key` to be set. Default empty.
-	 *     @type array        $meta_query          Meta query clauses to limit retrieved comments by.
-	 *                                             See WP_Meta_Query. Default empty.
-	 *     @type int          $number              Maximum number of comments to retrieve. Default null (no limit).
-	 *     @type int          $offset              Number of comments to offset the query. Used to build LIMIT clause.
-	 *                                             Default 0.
-	 *     @type string|array $orderby             Comment status or array of statuses. To use 'meta_value' or
-	 *                                             'meta_value_num', `$meta_key` must also be defined. To sort by
-	 *                                             a specific `$meta_query` clause, use that clause's array key.
-	 *                                             Accepts 'comment_agent', 'comment_approved', 'comment_author',
-	 *                                             'comment_author_email', 'comment_author_IP',
-	 *                                             'comment_author_url', 'comment_content', 'comment_date',
-	 *                                             'comment_date_gmt', 'comment_ID', 'comment_karma',
-	 *                                             'comment_parent', 'comment_post_ID', 'comment_type', 'user_id',
-	 *                                             'meta_value', 'meta_value_num', the value of $meta_key, and the
-	 *                                             array keys of `$meta_query`. Also accepts false, an empty array,
-	 *                                             or 'none' to disable `ORDER BY` clause.
-	 *                                             Default: 'comment_date_gmt'.
-	 *     @type string       $order               How to order retrieved comments. Accepts 'ASC', 'DESC'.
-	 *                                             Default: 'DESC'.
-	 *     @type int          $parent              Parent ID of comment to retrieve children of. Default empty.
-	 *     @type array        $post_author__in     Array of author IDs to retrieve comments for. Default empty.
-	 *     @type array        $post_author__not_in Array of author IDs *not* to retrieve comments for. Default empty.
-	 *     @type int          $post_ID             Currently unused.
-	 *     @type int          $post_id             Limit results to those affiliated with a given post ID. Default 0.
-	 *     @type array        $post__in            Array of post IDs to include affiliated comments for. Default empty.
-	 *     @type array        $post__not_in        Array of post IDs to exclude affiliated comments for. Default empty.
-	 *     @type int          $post_author         Comment author ID to limit results by. Default empty.
-	 *     @type string       $post_status         Post status to retrieve affiliated comments for. Default empty.
-	 *     @type string       $post_type           Post type to retrieve affiliated comments for. Default empty.
-	 *     @type string       $post_name           Post name to retrieve affiliated comments for. Default empty.
-	 *     @type int          $post_parent         Post parent ID to retrieve affiliated comments for. Default empty.
-	 *     @type string       $search              Search term(s) to retrieve matching comments for. Default empty.
-	 *     @type string       $status              Comment status to limit results by. Accepts 'hold'
-	 *                                             (`comment_status=0`), 'approve' (`comment_status=1`), 'all', or a
-	 *                                             custom comment status. Default 'all'.
-	 *     @type string|array $type                Include comments of a given type, or array of types. Accepts
-	 *                                             'comment', 'pings' (includes 'pingback' and 'trackback'), or any
-	 *                                             custom type string. Default empty.
-	 *     @type array        $type__in            Include comments from a given array of comment types. Default empty.
-	 *     @type array        $type__not_in        Exclude comments from a given array of comment types. Default empty.
-	 *     @type int          $user_id             Include comments for a specific user ID. Default empty.
-	 * }
-	 * @return WP_Comment_Query WP_Comment_Query instance.
-	 */
-	public function __construct( $query = '' ) {
-		$this->query_var_defaults = array(
-			'author_email' => '',
-			'author__in' => '',
-			'author__not_in' => '',
-			'include_unapproved' => '',
-			'fields' => '',
-			'ID' => '',
-			'comment__in' => '',
-			'comment__not_in' => '',
-			'karma' => '',
-			'number' => '',
-			'offset' => '',
-			'orderby' => '',
-			'order' => 'DESC',
-			'parent' => '',
-			'post_author__in' => '',
-			'post_author__not_in' => '',
-			'post_ID' => '',
-			'post_id' => 0,
-			'post__in' => '',
-			'post__not_in' => '',
-			'post_author' => '',
-			'post_name' => '',
-			'post_parent' => '',
-			'post_status' => '',
-			'post_type' => '',
-			'status' => 'all',
-			'type' => '',
-			'type__in' => '',
-			'type__not_in' => '',
-			'user_id' => '',
-			'search' => '',
-			'count' => false,
-			'meta_key' => '',
-			'meta_value' => '',
-			'meta_query' => '',
-			'date_query' => null, // See WP_Date_Query
-		);
-
-		if ( ! empty( $query ) ) {
-			$this->query( $query );
-		}
-	}
-
-	/**
-	 * Parse arguments passed to the comment query with default query parameters.
-	 *
-	 * @since  4.2.0 Extracted from WP_Comment_Query::query().
-	 *
-	 * @access public
-	 *
-	 * @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct()
-	 */
-	public function parse_query( $query = '' ) {
-		if ( empty( $query ) ) {
-			$query = $this->query_vars;
-		}
-
-		$this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
-		do_action_ref_array( 'parse_comment_query', array( &$this ) );
-	}
-
-	/**
-	 * Sets up the WordPress query for retrieving comments.
-	 *
-	 * @since 3.1.0
-	 * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in',
-	 *              'post_author__not_in', 'author__in', 'author__not_in', 'post__in',
-	 *              'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in'
-	 *              arguments to $query_vars.
-	 * @since 4.2.0 Moved parsing to WP_Comment_Query::parse_query().
-	 * @access public
-	 *
-	 * @param string|array $query Array or URL query string of parameters.
-	 * @return array List of comments.
-	 */
-	public function query( $query ) {
-		$this->query_vars = wp_parse_args( $query );
-		return $this->get_comments();
-	}
-
-	/**
-	 * Get a list of comments matching the query vars.
-	 *
-	 * @since 4.2.0
-	 * @access public
-	 *
-	 * @global wpdb $wpdb WordPress database abstraction object.
-	 *
-	 * @return array The list of comments.
-	 */
-	public function get_comments() {
-		global $wpdb;
-
-		$groupby = '';
-
-		$this->parse_query();
-
-		// Parse meta query
-		$this->meta_query = new WP_Meta_Query();
-		$this->meta_query->parse_query_vars( $this->query_vars );
-
-		if ( ! empty( $this->meta_query->queries ) ) {
-			$meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
-		}
-
-		/**
-		 * Fires before comments are retrieved.
-		 *
-		 * @since 3.1.0
-		 *
-		 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
-		 */
-		do_action_ref_array( 'pre_get_comments', array( &$this ) );
-
-		// $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
-		$key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
-		$last_changed = wp_cache_get( 'last_changed', 'comment' );
-		if ( ! $last_changed ) {
-			$last_changed = microtime();
-			wp_cache_set( 'last_changed', $last_changed, 'comment' );
-		}
-		$cache_key = "get_comments:$key:$last_changed";
-
-		if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) {
-			$this->comments = $cache;
-			return $this->comments;
-		}
-
-		$where = array();
-
-		// Assemble clauses related to 'comment_approved'.
-		$approved_clauses = array();
-
-		// 'status' accepts an array or a comma-separated string.
-		$status_clauses = array();
-		$statuses = $this->query_vars['status'];
-		if ( ! is_array( $statuses ) ) {
-			$statuses = preg_split( '/[\s,]+/', $statuses );
-		}
-
-		// 'any' overrides other statuses.
-		if ( ! in_array( 'any', $statuses ) ) {
-			foreach ( $statuses as $status ) {
-				switch ( $status ) {
-					case 'hold' :
-						$status_clauses[] = "comment_approved = '0'";
-						break;
-
-					case 'approve' :
-						$status_clauses[] = "comment_approved = '1'";
-						break;
-
-					case 'all' :
-					case '' :
-						$status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
-						break;
-
-					default :
-						$status_clauses[] = $wpdb->prepare( "comment_approved = %s", $status );
-						break;
-				}
-			}
-
-			if ( ! empty( $status_clauses ) ) {
-				$approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
-			}
-		}
-
-		// User IDs or emails whose unapproved comments are included, regardless of $status.
-		if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
-			$include_unapproved = $this->query_vars['include_unapproved'];
-
-			// Accepts arrays or comma-separated strings.
-			if ( ! is_array( $include_unapproved ) ) {
-				$include_unapproved = preg_split( '/[\s,]+/', $include_unapproved );
-			}
-
-			$unapproved_ids = $unapproved_emails = array();
-			foreach ( $include_unapproved as $unapproved_identifier ) {
-				// Numeric values are assumed to be user ids.
-				if ( is_numeric( $unapproved_identifier ) ) {
-					$approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
-
-				// Otherwise we match against email addresses.
-				} else {
-					$approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
-				}
-			}
-		}
-
-		// Collapse comment_approved clauses into a single OR-separated clause.
-		if ( ! empty( $approved_clauses ) ) {
-			if ( 1 === count( $approved_clauses ) ) {
-				$where[] = $approved_clauses[0];
-			} else {
-				$where[] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
-			}
-		}
-
-		$order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
-
-		// Disable ORDER BY with 'none', an empty array, or boolean false.
-		if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
-			$orderby = '';
-		} elseif ( ! empty( $this->query_vars['orderby'] ) ) {
-			$ordersby = is_array( $this->query_vars['orderby'] ) ?
-				$this->query_vars['orderby'] :
-				preg_split( '/[,\s]/', $this->query_vars['orderby'] );
-
-			$orderby_array = array();
-			$found_orderby_comment_ID = false;
-			foreach ( $ordersby as $_key => $_value ) {
-				if ( ! $_value ) {
-					continue;
-				}
-
-				if ( is_int( $_key ) ) {
-					$_orderby = $_value;
-					$_order = $order;
-				} else {
-					$_orderby = $_key;
-					$_order = $_value;
-				}
-
-				if ( ! $found_orderby_comment_ID && 'comment_ID' === $_orderby ) {
-					$found_orderby_comment_ID = true;
-				}
-
-				$parsed = $this->parse_orderby( $_orderby );
-
-				if ( ! $parsed ) {
-					continue;
-				}
-
-				$orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
-			}
-
-			// If no valid clauses were found, order by comment_date_gmt.
-			if ( empty( $orderby_array ) ) {
-				$orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
-			}
-
-			// To ensure determinate sorting, always include a comment_ID clause.
-			if ( ! $found_orderby_comment_ID ) {
-				$comment_ID_order = '';
-
-				// Inherit order from comment_date or comment_date_gmt, if available.
-				foreach ( $orderby_array as $orderby_clause ) {
-					if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
-						$comment_ID_order = $match[1];
-						break;
-					}
-				}
-
-				// If no date-related order is available, use the date from the first available clause.
-				if ( ! $comment_ID_order ) {
-					foreach ( $orderby_array as $orderby_clause ) {
-						if ( false !== strpos( 'ASC', $orderby_clause ) ) {
-							$comment_ID_order = 'ASC';
-						} else {
-							$comment_ID_order = 'DESC';
-						}
-
-						break;
-					}
-				}
-
-				// Default to DESC.
-				if ( ! $comment_ID_order ) {
-					$comment_ID_order = 'DESC';
-				}
-
-				$orderby_array[] = "$wpdb->comments.comment_ID $comment_ID_order";
-			}
-
-			$orderby = implode( ', ', $orderby_array );
-		} else {
-			$orderby = "$wpdb->comments.comment_date_gmt $order";
-		}
-
-		$number = absint( $this->query_vars['number'] );
-		$offset = absint( $this->query_vars['offset'] );
-
-		if ( ! empty( $number ) ) {
-			if ( $offset ) {
-				$limits = 'LIMIT ' . $offset . ',' . $number;
-			} else {
-				$limits = 'LIMIT ' . $number;
-			}
-		} else {
-			$limits = '';
-		}
-
-		if ( $this->query_vars['count'] ) {
-			$fields = 'COUNT(*)';
-		} else {
-			switch ( strtolower( $this->query_vars['fields'] ) ) {
-				case 'ids':
-					$fields = "$wpdb->comments.comment_ID";
-					break;
-				default:
-					$fields = "*";
-					break;
-			}
-		}
-
-		$join = '';
-
-		$post_id = absint( $this->query_vars['post_id'] );
-		if ( ! empty( $post_id ) ) {
-			$where[] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
-		}
-
-		// Parse comment IDs for an IN clause.
-		if ( ! empty( $this->query_vars['comment__in'] ) ) {
-			$where[] = 'comment_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
-		}
-
-		// Parse comment IDs for a NOT IN clause.
-		if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
-			$where[] = 'comment_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
-		}
-
-		// Parse comment post IDs for an IN clause.
-		if ( ! empty( $this->query_vars['post__in'] ) ) {
-			$where[] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
-		}
-
-		// Parse comment post IDs for a NOT IN clause.
-		if ( ! empty( $this->query_vars['post__not_in'] ) ) {
-			$where[] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
-		}
-
-		if ( '' !== $this->query_vars['author_email'] ) {
-			$where[] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
-		}
-
-		if ( '' !== $this->query_vars['karma'] ) {
-			$where[] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
-		}
-
-		// Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
-		$raw_types = array(
-			'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
-			'NOT IN' => (array) $this->query_vars['type__not_in'],
-		);
-
-		$comment_types = array();
-		foreach ( $raw_types as $operator => $_raw_types ) {
-			$_raw_types = array_unique( $_raw_types );
-
-			foreach ( $_raw_types as $type ) {
-				switch ( $type ) {
-					// An empty translates to 'all', for backward compatibility
-					case '':
-					case 'all' :
-						break;
-
-					case 'comment':
-					case 'comments':
-						$comment_types[ $operator ][] = "''";
-						break;
-
-					case 'pings':
-						$comment_types[ $operator ][] = "'pingback'";
-						$comment_types[ $operator ][] = "'trackback'";
-						break;
-
-					default:
-						$comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
-						break;
-				}
-			}
-
-			if ( ! empty( $comment_types[ $operator ] ) ) {
-				$types_sql = implode( ', ', $comment_types[ $operator ] );
-				$where[] = "comment_type $operator ($types_sql)";
-			}
-		}
-
-		if ( '' !== $this->query_vars['parent'] ) {
-			$where[] = $wpdb->prepare( 'comment_parent = %d', $this->query_vars['parent'] );
-		}
-
-		if ( is_array( $this->query_vars['user_id'] ) ) {
-			$where[] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
-		} elseif ( '' !== $this->query_vars['user_id'] ) {
-			$where[] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
-		}
-
-		if ( '' !== $this->query_vars['search'] ) {
-			$search_sql = $this->get_search_sql(
-				$this->query_vars['search'],
-				array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
-			);
-
-			// Strip leading 'AND'.
-			$where[] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
-		}
-
-		// If any post-related query vars are passed, join the posts table.
-		$join_posts_table = false;
-		$plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type' ) );
-		$post_fields = array_filter( $plucked );
-
-		if ( ! empty( $post_fields ) ) {
-			$join_posts_table = true;
-			foreach ( $post_fields as $field_name => $field_value ) {
-				// $field_value may be an array.
-				$esses = array_fill( 0, count( (array) $field_value ), '%s' );
-				$where[] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
-			}
-		}
-
-		// Comment author IDs for an IN clause.
-		if ( ! empty( $this->query_vars['author__in'] ) ) {
-			$where[] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
-		}
-
-		// Comment author IDs for a NOT IN clause.
-		if ( ! empty( $this->query_vars['author__not_in'] ) ) {
-			$where[] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
-		}
-
-		// Post author IDs for an IN clause.
-		if ( ! empty( $this->query_vars['post_author__in'] ) ) {
-			$join_posts_table = true;
-			$where[] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
-		}
-
-		// Post author IDs for a NOT IN clause.
-		if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
-			$join_posts_table = true;
-			$where[] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
-		}
-
-		if ( $join_posts_table ) {
-			$join = "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
-		}
-
-		if ( ! empty( $meta_query_clauses ) ) {
-			$join .= $meta_query_clauses['join'];
-
-			// Strip leading 'AND'.
-			$where[] = preg_replace( '/^\s*AND\s*/', '', $meta_query_clauses['where'] );
-
-			if ( ! $this->query_vars['count'] ) {
-				$groupby = "{$wpdb->comments}.comment_ID";
-			}
-		}
-
-		$date_query = $this->query_vars['date_query'];
-		if ( ! empty( $date_query ) && is_array( $date_query ) ) {
-			$date_query_object = new WP_Date_Query( $date_query, 'comment_date' );
-			$where[] = preg_replace( '/^\s*AND\s*/', '', $date_query_object->get_sql() );
-		}
-
-		$where = implode( ' AND ', $where );
-
-		$pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
-		/**
-		 * Filter the comment query clauses.
-		 *
-		 * @since 3.1.0
-		 *
-		 * @param array            $pieces A compacted array of comment query clauses.
-		 * @param WP_Comment_Query &$this  Current instance of WP_Comment_Query, passed by reference.
-		 */
-		$clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
-
-		$fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
-		$join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
-		$where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
-		$orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
-		$limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
-		$groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
-
-		if ( $where ) {
-			$where = 'WHERE ' . $where;
-		}
-
-		if ( $groupby ) {
-			$groupby = 'GROUP BY ' . $groupby;
-		}
-
-		if ( $orderby ) {
-			$orderby = "ORDER BY $orderby";
-		}
-
-		$this->request = "SELECT $fields FROM $wpdb->comments $join $where $groupby $orderby $limits";
-
-		if ( $this->query_vars['count'] ) {
-			return $wpdb->get_var( $this->request );
-		}
-
-		if ( 'ids' == $this->query_vars['fields'] ) {
-			$this->comments = $wpdb->get_col( $this->request );
-			return array_map( 'intval', $this->comments );
-		}
-
-		$results = $wpdb->get_results( $this->request );
-		/**
-		 * Filter the comment query results.
-		 *
-		 * @since 3.1.0
-		 *
-		 * @param array            $results  An array of comments.
-		 * @param WP_Comment_Query &$this    Current instance of WP_Comment_Query, passed by reference.
-		 */
-		$comments = apply_filters_ref_array( 'the_comments', array( $results, &$this ) );
-
-		wp_cache_add( $cache_key, $comments, 'comment' );
-
-		$this->comments = $comments;
-		return $this->comments;
-	}
-
-	/**
-	 * Used internally to generate an SQL string for searching across multiple columns
-	 *
-	 * @access protected
-	 * @since 3.1.0
-	 *
-	 * @param string $string
-	 * @param array $cols
-	 * @return string
-	 */
-	protected function get_search_sql( $string, $cols ) {
-		global $wpdb;
-
-		$like = '%' . $wpdb->esc_like( $string ) . '%';
-
-		$searches = array();
-		foreach ( $cols as $col ) {
-			$searches[] = $wpdb->prepare( "$col LIKE %s", $like );
-		}
-
-		return ' AND (' . implode(' OR ', $searches) . ')';
-	}
-
-	/**
-	 * Parse and sanitize 'orderby' keys passed to the comment query.
-	 *
-	 * @since 4.2.0
-	 * @access protected
-	 *
-	 * @global wpdb $wpdb WordPress database abstraction object.
-	 *
-	 * @param string $orderby Alias for the field to order by.
-	 * @return string|bool Value to used in the ORDER clause. False otherwise.
-	 */
-	protected function parse_orderby( $orderby ) {
-		global $wpdb;
-
-		$allowed_keys = array(
-			'comment_agent',
-			'comment_approved',
-			'comment_author',
-			'comment_author_email',
-			'comment_author_IP',
-			'comment_author_url',
-			'comment_content',
-			'comment_date',
-			'comment_date_gmt',
-			'comment_ID',
-			'comment_karma',
-			'comment_parent',
-			'comment_post_ID',
-			'comment_type',
-			'user_id',
-		);
-
-		if ( ! empty( $this->query_vars['meta_key'] ) ) {
-			$allowed_keys[] = $this->query_vars['meta_key'];
-			$allowed_keys[] = 'meta_value';
-			$allowed_keys[] = 'meta_value_num';
-		}
-
-		$meta_query_clauses = $this->meta_query->get_clauses();
-		if ( $meta_query_clauses ) {
-			$allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
-		}
-
-		$parsed = false;
-		if ( $orderby == $this->query_vars['meta_key'] || $orderby == 'meta_value' ) {
-			$parsed = "$wpdb->commentmeta.meta_value";
-		} else if ( $orderby == 'meta_value_num' ) {
-			$parsed = "$wpdb->commentmeta.meta_value+0";
-		} else if ( in_array( $orderby, $allowed_keys ) ) {
-
-			if ( isset( $meta_query_clauses[ $orderby ] ) ) {
-				$meta_clause = $meta_query_clauses[ $orderby ];
-				$parsed = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
-			} else {
-				$parsed = "$wpdb->comments.$orderby";
-			}
-		}
-
-		return $parsed;
-	}
-
-	/**
-	 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
-	 *
-	 * @since 4.2.0
-	 * @access protected
-	 *
-	 * @param string $order The 'order' query variable.
-	 * @return string The sanitized 'order' query variable.
-	 */
-	protected function parse_order( $order ) {
-		if ( ! is_string( $order ) || empty( $order ) ) {
-			return 'DESC';
-		}
-
-		if ( 'ASC' === strtoupper( $order ) ) {
-			return 'ASC';
-		} else {
-			return 'DESC';
-		}
-	}
-}
-
-/**
  * Retrieve all of the WordPress supported comment statuses.
  *
  * Comments have a limited set of valid status values, this provides the comment
@@ -1016,59 +238,109 @@
  */
 function get_comment_statuses() {
 	$status = array(
-		'hold'		=> __('Unapproved'),
-		/* translators: comment status  */
-		'approve'	=> _x('Approved', 'adjective'),
-		/* translators: comment status */
-		'spam'		=> _x('Spam', 'adjective'),
+		'hold'		=> __( 'Unapproved' ),
+		'approve'	=> _x( 'Approved', 'comment status' ),
+		'spam'		=> _x( 'Spam', 'comment status' ),
+		'trash'		=> _x( 'Trash', 'comment status' ),
 	);
 
 	return $status;
 }
 
 /**
+ * Gets the default comment status for a post type.
+ *
+ * @since 4.3.0
+ *
+ * @param string $post_type    Optional. Post type. Default 'post'.
+ * @param string $comment_type Optional. Comment type. Default 'comment'.
+ * @return string Expected return value is 'open' or 'closed'.
+ */
+function get_default_comment_status( $post_type = 'post', $comment_type = 'comment' ) {
+	switch ( $comment_type ) {
+		case 'pingback' :
+		case 'trackback' :
+			$supports = 'trackbacks';
+			$option = 'ping';
+			break;
+		default :
+			$supports = 'comments';
+			$option = 'comment';
+	}
+
+	// Set the status.
+	if ( 'page' === $post_type ) {
+		$status = 'closed';
+	} elseif ( post_type_supports( $post_type, $supports ) ) {
+		$status = get_option( "default_{$option}_status" );
+	} else {
+		$status = 'closed';
+	}
+
+	/**
+	 * Filters the default comment status for the given post type.
+	 *
+	 * @since 4.3.0
+	 *
+	 * @param string $status       Default status for the given post type,
+	 *                             either 'open' or 'closed'.
+	 * @param string $post_type    Post type. Default is `post`.
+	 * @param string $comment_type Type of comment. Default is `comment`.
+	 */
+	return apply_filters( 'get_default_comment_status' , $status, $post_type, $comment_type );
+}
+
+/**
  * The date the last comment was modified.
  *
  * @since 1.5.0
+ * @since 4.7.0 Replaced caching the modified date in a local static variable
+ *              with the Object Cache API.
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
- *		or 'server' locations.
- * @return string Last comment modified date.
+ * @param string $timezone Which timezone to use in reference to 'gmt', 'blog', or 'server' locations.
+ * @return string|false Last comment modified date on success, false on failure.
  */
-function get_lastcommentmodified($timezone = 'server') {
+function get_lastcommentmodified( $timezone = 'server' ) {
 	global $wpdb;
-	static $cache_lastcommentmodified = array();
-
-	if ( isset($cache_lastcommentmodified[$timezone]) )
-		return $cache_lastcommentmodified[$timezone];
-
-	$add_seconds_server = date('Z');
-
-	switch ( strtolower($timezone)) {
+
+	$timezone = strtolower( $timezone );
+	$key = "lastcommentmodified:$timezone";
+
+	$comment_modified_date = wp_cache_get( $key, 'timeinfo' );
+	if ( false !== $comment_modified_date ) {
+		return $comment_modified_date;
+	}
+
+	switch ( $timezone ) {
 		case 'gmt':
-			$lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
+			$comment_modified_date = $wpdb->get_var( "SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1" );
 			break;
 		case 'blog':
-			$lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
+			$comment_modified_date = $wpdb->get_var( "SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1" );
 			break;
 		case 'server':
-			$lastcommentmodified = $wpdb->get_var($wpdb->prepare("SELECT DATE_ADD(comment_date_gmt, INTERVAL %s SECOND) FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1", $add_seconds_server));
+			$add_seconds_server = date( 'Z' );
+
+			$comment_modified_date = $wpdb->get_var( $wpdb->prepare( "SELECT DATE_ADD(comment_date_gmt, INTERVAL %s SECOND) FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1", $add_seconds_server ) );
 			break;
 	}
 
-	$cache_lastcommentmodified[$timezone] = $lastcommentmodified;
-
-	return $lastcommentmodified;
+	if ( $comment_modified_date ) {
+		wp_cache_set( $key, $comment_modified_date, 'timeinfo' );
+
+		return $comment_modified_date;
+	}
+
+	return false;
 }
 
 /**
  * The amount of comments in a post or total comments.
  *
- * A lot like {@link wp_count_comments()}, in that they both return comment
- * stats (albeit with different types). The {@link wp_count_comments()} actual
- * caches, but this function does not.
+ * A lot like wp_count_comments(), in that they both return comment stats (albeit with different types).
+ * The wp_count_comments() actually caches, but this function does not.
  *
  * @since 2.0.0
  *
@@ -1095,25 +367,36 @@
 	", ARRAY_A);
 
 	$comment_count = array(
-		"approved"              => 0,
-		"awaiting_moderation"   => 0,
-		"spam"                  => 0,
-		"total_comments"        => 0
+		'approved'            => 0,
+		'awaiting_moderation' => 0,
+		'spam'                => 0,
+		'trash'               => 0,
+		'post-trashed'        => 0,
+		'total_comments'      => 0,
+		'all'                 => 0,
 	);
 
 	foreach ( $totals as $row ) {
 		switch ( $row['comment_approved'] ) {
+			case 'trash':
+				$comment_count['trash'] = $row['total'];
+				break;
+			case 'post-trashed':
+				$comment_count['post-trashed'] = $row['total'];
+				break;
 			case 'spam':
 				$comment_count['spam'] = $row['total'];
-				$comment_count["total_comments"] += $row['total'];
+				$comment_count['total_comments'] += $row['total'];
 				break;
-			case 1:
+			case '1':
 				$comment_count['approved'] = $row['total'];
 				$comment_count['total_comments'] += $row['total'];
+				$comment_count['all'] += $row['total'];
 				break;
-			case 0:
+			case '0':
 				$comment_count['awaiting_moderation'] = $row['total'];
 				$comment_count['total_comments'] += $row['total'];
+				$comment_count['all'] += $row['total'];
 				break;
 			default:
 				break;
@@ -1140,7 +423,11 @@
  * @return int|bool Meta ID on success, false on failure.
  */
 function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
-	return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
+	$added = add_metadata( 'comment', $comment_id, $meta_key, $meta_value, $unique );
+	if ( $added ) {
+		wp_cache_set( 'last_changed', microtime(), 'comment' );
+	}
+	return $added;
 }
 
 /**
@@ -1159,7 +446,11 @@
  * @return bool True on success, false on failure.
  */
 function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
-	return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
+	$deleted = delete_metadata( 'comment', $comment_id, $meta_key, $meta_value );
+	if ( $deleted ) {
+		wp_cache_set( 'last_changed', microtime(), 'comment' );
+	}
+	return $deleted;
 }
 
 /**
@@ -1196,34 +487,76 @@
  * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  */
 function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
-	return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
+	$updated = update_metadata( 'comment', $comment_id, $meta_key, $meta_value, $prev_value );
+	if ( $updated ) {
+		wp_cache_set( 'last_changed', microtime(), 'comment' );
+	}
+	return $updated;
+}
+
+/**
+ * Queues comments for metadata lazy-loading.
+ *
+ * @since 4.5.0
+ *
+ * @param array $comments Array of comment objects.
+ */
+function wp_queue_comments_for_comment_meta_lazyload( $comments ) {
+	// Don't use `wp_list_pluck()` to avoid by-reference manipulation.
+	$comment_ids = array();
+	if ( is_array( $comments ) ) {
+		foreach ( $comments as $comment ) {
+			if ( $comment instanceof WP_Comment ) {
+				$comment_ids[] = $comment->comment_ID;
+			}
+		}
+	}
+
+	if ( $comment_ids ) {
+		$lazyloader = wp_metadata_lazyloader();
+		$lazyloader->queue_objects( 'comment', $comment_ids );
+	}
 }
 
 /**
  * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
  * to recall previous comments by this commentator that are still held in moderation.
  *
- * @param object $comment Comment object.
- * @param object $user Comment author's object.
+ * @since 3.4.0
+ * @since 4.9.6 The `$cookies_consent` parameter was added.
  *
- * @since 3.4.0
+ * @param WP_Comment $comment         Comment object.
+ * @param WP_User    $user            Comment author's user object. The user may not exist.
+ * @param boolean    $cookies_consent Optional. Comment author's consent to store cookies. Default true.
  */
-function wp_set_comment_cookies($comment, $user) {
-	if ( $user->exists() )
+function wp_set_comment_cookies( $comment, $user, $cookies_consent = true ) {
+	// If the user already exists, or the user opted out of cookies, don't set cookies.
+	if ( $user->exists() ) {
 		return;
+	}
+
+	if ( false === $cookies_consent ) {
+		// Remove any existing cookies.
+		$past = time() - YEAR_IN_SECONDS;
+		setcookie( 'comment_author_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
+		setcookie( 'comment_author_email_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
+		setcookie( 'comment_author_url_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
+
+		return;
+	}
 
 	/**
-	 * Filter the lifetime of the comment cookie in seconds.
+	 * Filters the lifetime of the comment cookie in seconds.
 	 *
 	 * @since 2.8.0
 	 *
 	 * @param int $seconds Comment cookie lifetime. Default 30000000.
 	 */
-	$comment_cookie_lifetime = apply_filters( 'comment_cookie_lifetime', 30000000 );
+	$comment_cookie_lifetime = time() + apply_filters( 'comment_cookie_lifetime', 30000000 );
 	$secure = ( 'https' === parse_url( home_url(), PHP_URL_SCHEME ) );
-	setcookie( 'comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
-	setcookie( 'comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
-	setcookie( 'comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
+	setcookie( 'comment_author_' . COOKIEHASH, $comment->comment_author, $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
+	setcookie( 'comment_author_email_' . COOKIEHASH, $comment->comment_author_email, $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
+	setcookie( 'comment_author_url_' . COOKIEHASH, esc_url( $comment->comment_author_url ), $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
 }
 
 /**
@@ -1237,7 +570,7 @@
 function sanitize_comment_cookies() {
 	if ( isset( $_COOKIE['comment_author_' . COOKIEHASH] ) ) {
 		/**
-		 * Filter the comment author's name cookie before it is set.
+		 * Filters the comment author's name cookie before it is set.
 		 *
 		 * When this filter hook is evaluated in wp_filter_comment(),
 		 * the comment author's name string is passed.
@@ -1254,7 +587,7 @@
 
 	if ( isset( $_COOKIE['comment_author_email_' . COOKIEHASH] ) ) {
 		/**
-		 * Filter the comment author's email cookie before it is set.
+		 * Filters the comment author's email cookie before it is set.
 		 *
 		 * When this filter hook is evaluated in wp_filter_comment(),
 		 * the comment author's email string is passed.
@@ -1271,7 +604,7 @@
 
 	if ( isset( $_COOKIE['comment_author_url_' . COOKIEHASH] ) ) {
 		/**
-		 * Filter the comment author's URL cookie before it is set.
+		 * Filters the comment author's URL cookie before it is set.
 		 *
 		 * When this filter hook is evaluated in wp_filter_comment(),
 		 * the comment author's URL string is passed.
@@ -1290,13 +623,19 @@
  * Validates whether this comment is allowed to be made.
  *
  * @since 2.0.0
+ * @since 4.7.0 The `$avoid_die` parameter was added, allowing the function to
+ *              return a WP_Error object instead of dying.
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param array $commentdata Contains information on the comment
- * @return mixed Signifies the approval status (0|1|'spam')
+ * @param array $commentdata Contains information on the comment.
+ * @param bool  $avoid_die   When true, a disallowed comment will result in the function
+ *                           returning a WP_Error object, rather than executing wp_die().
+ *                           Default false.
+ * @return int|string|WP_Error Allowed comments return the approval status (0|1|'spam').
+ *                             If `$avoid_die` is true, disallowed comments return a WP_Error.
  */
-function wp_allow_comment( $commentdata ) {
+function wp_allow_comment( $commentdata, $avoid_die = false ) {
 	global $wpdb;
 
 	// Simple duplicate check
@@ -1309,7 +648,7 @@
 	);
 	if ( $commentdata['comment_author_email'] ) {
 		$dupe .= $wpdb->prepare(
-			"OR comment_author_email = %s ",
+			"AND comment_author_email = %s ",
 			wp_unslash( $commentdata['comment_author_email'] )
 		);
 	}
@@ -1317,7 +656,22 @@
 		") AND comment_content = %s LIMIT 1",
 		wp_unslash( $commentdata['comment_content'] )
 	);
-	if ( $wpdb->get_var( $dupe ) ) {
+
+	$dupe_id = $wpdb->get_var( $dupe );
+
+	/**
+	 * Filters the ID, if any, of the duplicate comment found when creating a new comment.
+	 *
+	 * Return an empty value from this filter to allow what WP considers a duplicate comment.
+	 *
+	 * @since 4.4.0
+	 *
+	 * @param int   $dupe_id     ID of the comment identified as a duplicate.
+	 * @param array $commentdata Data for the comment being created.
+	 */
+	$dupe_id = apply_filters( 'duplicate_comment_id', $dupe_id, $commentdata );
+
+	if ( $dupe_id ) {
 		/**
 		 * Fires immediately after a duplicate comment is detected.
 		 *
@@ -1326,10 +680,15 @@
 		 * @param array $commentdata Comment data.
 		 */
 		do_action( 'comment_duplicate_trigger', $commentdata );
-		if ( defined( 'DOING_AJAX' ) ) {
-			die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
+		if ( true === $avoid_die ) {
+			return new WP_Error( 'comment_duplicate', __( 'Duplicate comment detected; it looks as though you&#8217;ve already said that!' ), 409 );
+		} else {
+			if ( wp_doing_ajax() ) {
+				die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
+			}
+
+			wp_die( __( 'Duplicate comment detected; it looks as though you&#8217;ve already said that!' ), 409 );
 		}
-		wp_die( __( 'Duplicate comment detected; it looks as though you&#8217;ve already said that!' ), 409 );
 	}
 
 	/**
@@ -1338,18 +697,49 @@
 	 * Allows checking for comment flooding.
 	 *
 	 * @since 2.3.0
+	 * @since 4.7.0 The `$avoid_die` parameter was added.
 	 *
 	 * @param string $comment_author_IP    Comment author's IP address.
 	 * @param string $comment_author_email Comment author's email.
 	 * @param string $comment_date_gmt     GMT date the comment was posted.
+	 * @param bool   $avoid_die            Whether to prevent executing wp_die()
+	 *                                     or die() if a comment flood is occurring.
 	 */
 	do_action(
 		'check_comment_flood',
 		$commentdata['comment_author_IP'],
 		$commentdata['comment_author_email'],
-		$commentdata['comment_date_gmt']
+		$commentdata['comment_date_gmt'],
+		$avoid_die
 	);
 
+	/**
+	 * Filters whether a comment is part of a comment flood.
+	 *
+	 * The default check is wp_check_comment_flood(). See check_comment_flood_db().
+	 *
+	 * @since 4.7.0
+	 *
+	 * @param bool   $is_flood             Is a comment flooding occurring? Default false.
+	 * @param string $comment_author_IP    Comment author's IP address.
+	 * @param string $comment_author_email Comment author's email.
+	 * @param string $comment_date_gmt     GMT date the comment was posted.
+	 * @param bool   $avoid_die            Whether to prevent executing wp_die()
+	 *                                     or die() if a comment flood is occurring.
+	 */
+	$is_flood = apply_filters(
+		'wp_is_comment_flood',
+		false,
+		$commentdata['comment_author_IP'],
+		$commentdata['comment_author_email'],
+		$commentdata['comment_date_gmt'],
+		$avoid_die
+	);
+
+	if ( $is_flood ) {
+		return new WP_Error( 'comment_flood', __( 'You are posting comments too quickly. Slow down.' ), 429 );
+	}
+
 	if ( ! empty( $commentdata['user_id'] ) ) {
 		$user = get_userdata( $commentdata['user_id'] );
 		$post_author = $wpdb->get_var( $wpdb->prepare(
@@ -1385,46 +775,92 @@
 			$commentdata['comment_author_IP'],
 			$commentdata['comment_agent']
 		) ) {
-			$approved = 'spam';
+			$approved = EMPTY_TRASH_DAYS ? 'trash' : 'spam';
 		}
 	}
 
 	/**
-	 * Filter a comment's approval status before it is set.
+	 * Filters a comment's approval status before it is set.
 	 *
 	 * @since 2.1.0
+	 * @since 4.9.0 Returning a WP_Error value from the filter will shortcircuit comment insertion and
+	 *              allow skipping further processing.
 	 *
-	 * @param bool|string $approved    The approval status. Accepts 1, 0, or 'spam'.
-	 * @param array       $commentdata Comment data.
+	 * @param bool|string|WP_Error $approved    The approval status. Accepts 1, 0, 'spam' or WP_Error.
+	 * @param array                $commentdata Comment data.
 	 */
 	$approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
 	return $approved;
 }
 
 /**
- * Check whether comment flooding is occurring.
+ * Hooks WP's native database-based comment-flood check.
+ *
+ * This wrapper maintains backward compatibility with plugins that expect to
+ * be able to unhook the legacy check_comment_flood_db() function from
+ * 'check_comment_flood' using remove_action().
+ *
+ * @since 2.3.0
+ * @since 4.7.0 Converted to be an add_filter() wrapper.
+ */
+function check_comment_flood_db() {
+	add_filter( 'wp_is_comment_flood', 'wp_check_comment_flood', 10, 5 );
+}
+
+/**
+ * Checks whether comment flooding is occurring.
  *
  * Won't run, if current user can manage options, so to not block
  * administrators.
  *
- * @since 2.3.0
+ * @since 4.7.0
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param string $ip Comment IP.
- * @param string $email Comment author email address.
- * @param string $date MySQL time string.
+ * @param bool   $is_flood  Is a comment flooding occurring?
+ * @param string $ip        Comment author's IP address.
+ * @param string $email     Comment author's email address.
+ * @param string $date      MySQL time string.
+ * @param bool   $avoid_die When true, a disallowed comment will result in the function
+ *                          returning a WP_Error object, rather than executing wp_die().
+ *                          Default false.
+ * @return bool Whether comment flooding is occurring.
  */
-function check_comment_flood_db( $ip, $email, $date ) {
+function wp_check_comment_flood( $is_flood, $ip, $email, $date, $avoid_die = false ) {
+
 	global $wpdb;
-	if ( current_user_can( 'manage_options' ) )
-		return; // don't throttle admins
+
+	// Another callback has declared a flood. Trust it.
+	if ( true === $is_flood ) {
+		return $is_flood;
+	}
+
+	// don't throttle admins or moderators
+	if ( current_user_can( 'manage_options' ) || current_user_can( 'moderate_comments' ) ) {
+		return false;
+	}
 	$hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
-	if ( $lasttime = $wpdb->get_var( $wpdb->prepare( "SELECT `comment_date_gmt` FROM `$wpdb->comments` WHERE `comment_date_gmt` >= %s AND ( `comment_author_IP` = %s OR `comment_author_email` = %s ) ORDER BY `comment_date_gmt` DESC LIMIT 1", $hour_ago, $ip, $email ) ) ) {
+
+	if ( is_user_logged_in() ) {
+		$user = get_current_user_id();
+		$check_column = '`user_id`';
+	} else {
+		$user = $ip;
+		$check_column = '`comment_author_IP`';
+	}
+
+	$sql = $wpdb->prepare(
+		"SELECT `comment_date_gmt` FROM `$wpdb->comments` WHERE `comment_date_gmt` >= %s AND ( $check_column = %s OR `comment_author_email` = %s ) ORDER BY `comment_date_gmt` DESC LIMIT 1",
+		$hour_ago,
+		$user,
+		$email
+	);
+	$lasttime = $wpdb->get_var( $sql );
+	if ( $lasttime ) {
 		$time_lastcomment = mysql2date('U', $lasttime, false);
 		$time_newcomment  = mysql2date('U', $date, false);
 		/**
-		 * Filter the comment flood status.
+		 * Filters the comment flood status.
 		 *
 		 * @since 2.1.0
 		 *
@@ -1443,13 +879,19 @@
 			 * @param int $time_newcomment  Timestamp of when the new comment was posted.
 			 */
 			do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment );
-
-			if ( defined('DOING_AJAX') )
-				die( __('You are posting comments too quickly. Slow down.') );
-
-			wp_die( __( 'You are posting comments too quickly. Slow down.' ), 429 );
+			if ( true === $avoid_die ) {
+				return true;
+			} else {
+				if ( wp_doing_ajax() ) {
+					die( __('You are posting comments too quickly. Slow down.') );
+				}
+
+				wp_die( __( 'You are posting comments too quickly. Slow down.' ), 429 );
+			}
 		}
 	}
+
+	return false;
 }
 
 /**
@@ -1482,9 +924,11 @@
  *
  * @uses Walker_Comment
  *
- * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
- * @param int $per_page Optional comments per page.
- * @param boolean $threaded Optional control over flat or threaded comments.
+ * @global WP_Query $wp_query
+ *
+ * @param array $comments Optional array of WP_Comment objects. Defaults to $wp_query->comments
+ * @param int   $per_page Optional comments per page.
+ * @param bool  $threaded Optional control over flat or threaded comments.
  * @return int Number of comment pages.
  */
 function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
@@ -1499,8 +943,9 @@
 	if ( empty($comments) )
 		return 0;
 
-	if ( ! get_option( 'page_comments' ) )
+	if ( ! get_option( 'page_comments' ) ) {
 		return 1;
+	}
 
 	if ( !isset($per_page) )
 		$per_page = (int) get_query_var('comments_per_page');
@@ -1527,56 +972,207 @@
  *
  * @since 2.7.0
  *
- * @param int $comment_ID Comment ID.
- * @param array $args Optional args.
+ * @global wpdb $wpdb WordPress database abstraction object.
+ *
+ * @param int   $comment_ID Comment ID.
+ * @param array $args {
+ *      Array of optional arguments.
+ *      @type string     $type      Limit paginated comments to those matching a given type. Accepts 'comment',
+ *                                  'trackback', 'pingback', 'pings' (trackbacks and pingbacks), or 'all'.
+ *                                  Default is 'all'.
+ *      @type int        $per_page  Per-page count to use when calculating pagination. Defaults to the value of the
+ *                                  'comments_per_page' option.
+ *      @type int|string $max_depth If greater than 1, comment page will be determined for the top-level parent of
+ *                                  `$comment_ID`. Defaults to the value of the 'thread_comments_depth' option.
+ * } *
  * @return int|null Comment page number or null on error.
  */
 function get_page_of_comment( $comment_ID, $args = array() ) {
 	global $wpdb;
 
+	$page = null;
+
 	if ( !$comment = get_comment( $comment_ID ) )
 		return;
 
 	$defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
 	$args = wp_parse_args( $args, $defaults );
-
-	if ( '' === $args['per_page'] && get_option('page_comments') )
-		$args['per_page'] = get_query_var('comments_per_page');
+	$original_args = $args;
+
+	// Order of precedence: 1. `$args['per_page']`, 2. 'comments_per_page' query_var, 3. 'comments_per_page' option.
+	if ( get_option( 'page_comments' ) ) {
+		if ( '' === $args['per_page'] ) {
+			$args['per_page'] = get_query_var( 'comments_per_page' );
+		}
+
+		if ( '' === $args['per_page'] ) {
+			$args['per_page'] = get_option( 'comments_per_page' );
+		}
+	}
+
 	if ( empty($args['per_page']) ) {
 		$args['per_page'] = 0;
 		$args['page'] = 0;
 	}
-	if ( $args['per_page'] < 1 )
-		return 1;
-
-	if ( '' === $args['max_depth'] ) {
-		if ( get_option('thread_comments') )
-			$args['max_depth'] = get_option('thread_comments_depth');
-		else
-			$args['max_depth'] = -1;
+
+	if ( $args['per_page'] < 1 ) {
+		$page = 1;
+	}
+
+	if ( null === $page ) {
+		if ( '' === $args['max_depth'] ) {
+			if ( get_option('thread_comments') )
+				$args['max_depth'] = get_option('thread_comments_depth');
+			else
+				$args['max_depth'] = -1;
+		}
+
+		// Find this comment's top level parent if threading is enabled
+		if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
+			return get_page_of_comment( $comment->comment_parent, $args );
+
+		$comment_args = array(
+			'type'       => $args['type'],
+			'post_id'    => $comment->comment_post_ID,
+			'fields'     => 'ids',
+			'count'      => true,
+			'status'     => 'approve',
+			'parent'     => 0,
+			'date_query' => array(
+				array(
+					'column' => "$wpdb->comments.comment_date_gmt",
+					'before' => $comment->comment_date_gmt,
+				)
+			),
+		);
+
+		$comment_query = new WP_Comment_Query();
+		$older_comment_count = $comment_query->query( $comment_args );
+
+		// No older comments? Then it's page #1.
+		if ( 0 == $older_comment_count ) {
+			$page = 1;
+
+		// Divide comments older than this one by comments per page to get this comment's page number
+		} else {
+			$page = ceil( ( $older_comment_count + 1 ) / $args['per_page'] );
+		}
 	}
 
-	// Find this comment's top level parent if threading is enabled
-	if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
-		return get_page_of_comment( $comment->comment_parent, $args );
-
-	$allowedtypes = array(
-		'comment' => '',
-		'pingback' => 'pingback',
-		'trackback' => 'trackback',
+	/**
+	 * Filters the calculated page on which a comment appears.
+	 *
+	 * @since 4.4.0
+	 * @since 4.7.0 Introduced the `$comment_ID` parameter.
+	 *
+	 * @param int   $page          Comment page.
+	 * @param array $args {
+	 *     Arguments used to calculate pagination. These include arguments auto-detected by the function,
+	 *     based on query vars, system settings, etc. For pristine arguments passed to the function,
+	 *     see `$original_args`.
+	 *
+	 *     @type string $type      Type of comments to count.
+	 *     @type int    $page      Calculated current page.
+	 *     @type int    $per_page  Calculated number of comments per page.
+	 *     @type int    $max_depth Maximum comment threading depth allowed.
+	 * }
+	 * @param array $original_args {
+	 *     Array of arguments passed to the function. Some or all of these may not be set.
+	 *
+	 *     @type string $type      Type of comments to count.
+	 *     @type int    $page      Current comment page.
+	 *     @type int    $per_page  Number of comments per page.
+	 *     @type int    $max_depth Maximum comment threading depth allowed.
+	 * }
+	 * @param int $comment_ID ID of the comment.
+	 */
+	return apply_filters( 'get_page_of_comment', (int) $page, $args, $original_args, $comment_ID );
+}
+
+/**
+ * Retrieves the maximum character lengths for the comment form fields.
+ *
+ * @since 4.5.0
+ *
+ * @global wpdb $wpdb WordPress database abstraction object.
+ *
+ * @return array Maximum character length for the comment form fields.
+ */
+function wp_get_comment_fields_max_lengths() {
+	global $wpdb;
+
+	$lengths = array(
+		'comment_author'       => 245,
+		'comment_author_email' => 100,
+		'comment_author_url'   => 200,
+		'comment_content'      => 65525,
 	);
 
-	$comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
-
-	// Count comments older than this one
-	$oldercoms = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = 0 AND comment_approved = '1' AND comment_date_gmt < '%s'" . $comtypewhere, $comment->comment_post_ID, $comment->comment_date_gmt ) );
-
-	// No older comments? Then it's page #1.
-	if ( 0 == $oldercoms )
-		return 1;
-
-	// Divide comments older than this one by comments per page to get this comment's page number
-	return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
+	if ( $wpdb->is_mysql ) {
+		foreach ( $lengths as $column => $length ) {
+			$col_length = $wpdb->get_col_length( $wpdb->comments, $column );
+			$max_length = 0;
+
+			// No point if we can't get the DB column lengths
+			if ( is_wp_error( $col_length ) ) {
+				break;
+			}
+
+			if ( ! is_array( $col_length ) && (int) $col_length > 0 ) {
+				$max_length = (int) $col_length;
+			} elseif ( is_array( $col_length ) && isset( $col_length['length'] ) && intval( $col_length['length'] ) > 0 ) {
+				$max_length = (int) $col_length['length'];
+
+				if ( ! empty( $col_length['type'] ) && 'byte' === $col_length['type'] ) {
+					$max_length = $max_length - 10;
+				}
+			}
+
+			if ( $max_length > 0 ) {
+				$lengths[ $column ] = $max_length;
+			}
+		}
+	}
+
+	/**
+	 * Filters the lengths for the comment form fields.
+	 *
+	 * @since 4.5.0
+	 *
+	 * @param array $lengths Associative array `'field_name' => 'maximum length'`.
+	 */
+	return apply_filters( 'wp_get_comment_fields_max_lengths', $lengths );
+}
+
+/**
+ * Compares the lengths of comment data against the maximum character limits.
+ *
+ * @since 4.7.0
+ *
+ * @param array $comment_data Array of arguments for inserting a comment.
+ * @return WP_Error|true WP_Error when a comment field exceeds the limit,
+ *                       otherwise true.
+ */
+function wp_check_comment_data_max_lengths( $comment_data ) {
+	$max_lengths = wp_get_comment_fields_max_lengths();
+
+	if ( isset( $comment_data['comment_author'] ) && mb_strlen( $comment_data['comment_author'], '8bit' ) > $max_lengths['comment_author'] ) {
+		return new WP_Error( 'comment_author_column_length', __( '<strong>ERROR</strong>: your name is too long.' ), 200 );
+	}
+
+	if ( isset( $comment_data['comment_author_email'] ) && strlen( $comment_data['comment_author_email'] ) > $max_lengths['comment_author_email'] ) {
+		return new WP_Error( 'comment_author_email_column_length', __( '<strong>ERROR</strong>: your email address is too long.' ), 200 );
+	}
+
+	if ( isset( $comment_data['comment_author_url'] ) && strlen( $comment_data['comment_author_url'] ) > $max_lengths['comment_author_url'] ) {
+		return new WP_Error( 'comment_author_url_column_length', __( '<strong>ERROR</strong>: your url is too long.' ), 200 );
+	}
+
+	if ( isset( $comment_data['comment_content'] ) && mb_strlen( $comment_data['comment_content'], '8bit' ) > $max_lengths['comment_content'] ) {
+		return new WP_Error( 'comment_content_column_length', __( '<strong>ERROR</strong>: your comment is too long.' ), 200 );
+	}
+
+	return true;
 }
 
 /**
@@ -1588,7 +1184,7 @@
  * @param string $email The email of the comment
  * @param string $url The url used in the comment
  * @param string $comment The comment content
- * @param string $user_ip The comment author IP address
+ * @param string $user_ip The comment author's IP address
  * @param string $user_agent The author's browser user agent
  * @return bool True if comment contains blacklisted content, false if comment does not
  */
@@ -1610,6 +1206,10 @@
 	$mod_keys = trim( get_option('blacklist_keys') );
 	if ( '' == $mod_keys )
 		return false; // If moderation keys are empty
+
+	// Ensure HTML tags are not being used to bypass the blacklist.
+	$comment_without_html = wp_strip_all_tags( $comment );
+
 	$words = explode("\n", $mod_keys );
 
 	foreach ( (array) $words as $word ) {
@@ -1628,6 +1228,7 @@
 			|| preg_match($pattern, $email)
 			|| preg_match($pattern, $url)
 			|| preg_match($pattern, $comment)
+			|| preg_match($pattern, $comment_without_html)
 			|| preg_match($pattern, $user_ip)
 			|| preg_match($pattern, $user_agent)
 		 )
@@ -1650,56 +1251,37 @@
  * @since 2.5.0
  *
  * @param int $post_id Optional. Post ID.
- * @return object Comment stats.
+ * @return object|array Comment stats.
  */
 function wp_count_comments( $post_id = 0 ) {
-	global $wpdb;
-
 	$post_id = (int) $post_id;
 
 	/**
-	 * Filter the comments count for a given post.
+	 * Filters the comments count for a given post.
 	 *
 	 * @since 2.7.0
 	 *
 	 * @param array $count   An empty array.
 	 * @param int   $post_id The post ID.
 	 */
-	$stats = apply_filters( 'wp_count_comments', array(), $post_id );
-	if ( !empty($stats) )
-		return $stats;
-
-	$count = wp_cache_get("comments-{$post_id}", 'counts');
-
-	if ( false !== $count )
+	$filtered = apply_filters( 'wp_count_comments', array(), $post_id );
+	if ( ! empty( $filtered ) ) {
+		return $filtered;
+	}
+
+	$count = wp_cache_get( "comments-{$post_id}", 'counts' );
+	if ( false !== $count ) {
 		return $count;
-
-	$where = '';
-	if ( $post_id > 0 )
-		$where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
-
-	$count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
-
-	$total = 0;
-	$approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
-	foreach ( (array) $count as $row ) {
-		// Don't count post-trashed toward totals
-		if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
-			$total += $row['num_comments'];
-		if ( isset( $approved[$row['comment_approved']] ) )
-			$stats[$approved[$row['comment_approved']]] = $row['num_comments'];
 	}
 
-	$stats['total_comments'] = $total;
-	foreach ( $approved as $key ) {
-		if ( empty($stats[$key]) )
-			$stats[$key] = 0;
-	}
-
-	$stats = (object) $stats;
-	wp_cache_set("comments-{$post_id}", $stats, 'counts');
-
-	return $stats;
+	$stats = get_comment_count( $post_id );
+	$stats['moderated'] = $stats['awaiting_moderation'];
+	unset( $stats['awaiting_moderation'] );
+
+	$stats_object = (object) $stats;
+	wp_cache_set( "comments-{$post_id}", $stats_object, 'counts' );
+
+	return $stats_object;
 }
 
 /**
@@ -1715,8 +1297,8 @@
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param int $comment_id Comment ID
- * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
+ * @param int|WP_Comment $comment_id   Comment ID or WP_Comment object.
+ * @param bool           $force_delete Whether to bypass trash and force deletion. Default is false.
  * @return bool True on success, false on failure.
  */
 function wp_delete_comment($comment_id, $force_delete = false) {
@@ -1724,50 +1306,54 @@
 	if (!$comment = get_comment($comment_id))
 		return false;
 
-	if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) )
+	if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status( $comment ), array( 'trash', 'spam' ) ) )
 		return wp_trash_comment($comment_id);
 
 	/**
 	 * Fires immediately before a comment is deleted from the database.
 	 *
 	 * @since 1.2.0
+	 * @since 4.9.0 Added the `$comment` parameter.
 	 *
-	 * @param int $comment_id The comment ID.
+	 * @param int        $comment_id The comment ID.
+	 * @param WP_Comment $comment    The comment to be deleted.
 	 */
-	do_action( 'delete_comment', $comment_id );
+	do_action( 'delete_comment', $comment->comment_ID, $comment );
 
 	// Move children up a level.
-	$children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
+	$children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment->comment_ID) );
 	if ( !empty($children) ) {
-		$wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
+		$wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment->comment_ID));
 		clean_comment_cache($children);
 	}
 
 	// Delete metadata
-	$meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment_id ) );
+	$meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment->comment_ID ) );
 	foreach ( $meta_ids as $mid )
 		delete_metadata_by_mid( 'comment', $mid );
 
-	if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment_id ) ) )
+	if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment->comment_ID ) ) )
 		return false;
 
 	/**
 	 * Fires immediately after a comment is deleted from the database.
 	 *
 	 * @since 2.9.0
+	 * @since 4.9.0 Added the `$comment` parameter.
 	 *
-	 * @param int $comment_id The comment ID.
+	 * @param int        $comment_id The comment ID.
+	 * @param WP_Comment $comment    The deleted comment.
 	 */
-	do_action( 'deleted_comment', $comment_id );
+	do_action( 'deleted_comment', $comment->comment_ID, $comment );
 
 	$post_id = $comment->comment_post_ID;
 	if ( $post_id && $comment->comment_approved == 1 )
 		wp_update_comment_count($post_id);
 
-	clean_comment_cache($comment_id);
+	clean_comment_cache( $comment->comment_ID );
 
 	/** This action is documented in wp-includes/comment.php */
-	do_action( 'wp_set_comment_status', $comment_id, 'delete' );
+	do_action( 'wp_set_comment_status', $comment->comment_ID, 'delete' );
 
 	wp_transition_comment_status('delete', $comment->comment_approved, $comment);
 	return true;
@@ -1780,7 +1366,7 @@
  *
  * @since 2.9.0
  *
- * @param int $comment_id Comment ID.
+ * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  * @return bool True on success, false on failure.
  */
 function wp_trash_comment($comment_id) {
@@ -1794,23 +1380,29 @@
 	 * Fires immediately before a comment is sent to the Trash.
 	 *
 	 * @since 2.9.0
+	 * @since 4.9.0 Added the `$comment` parameter.
 	 *
-	 * @param int $comment_id The comment ID.
+	 * @param int        $comment_id The comment ID.
+	 * @param WP_Comment $comment    The comment to be trashed.
 	 */
-	do_action( 'trash_comment', $comment_id );
-
-	if ( wp_set_comment_status($comment_id, 'trash') ) {
-		add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
-		add_comment_meta($comment_id, '_wp_trash_meta_time', time() );
+	do_action( 'trash_comment', $comment->comment_ID, $comment );
+
+	if ( wp_set_comment_status( $comment, 'trash' ) ) {
+		delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
+		delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
+		add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved );
+		add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() );
 
 		/**
 		 * Fires immediately after a comment is sent to Trash.
 		 *
 		 * @since 2.9.0
+		 * @since 4.9.0 Added the `$comment` parameter.
 		 *
-		 * @param int $comment_id The comment ID.
+		 * @param int        $comment_id The comment ID.
+		 * @param WP_Comment $comment    The trashed comment.
 		 */
-		do_action( 'trashed_comment', $comment_id );
+		do_action( 'trashed_comment', $comment->comment_ID, $comment );
 		return true;
 	}
 
@@ -1822,37 +1414,43 @@
  *
  * @since 2.9.0
  *
- * @param int $comment_id Comment ID.
+ * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  * @return bool True on success, false on failure.
  */
 function wp_untrash_comment($comment_id) {
-	if ( ! (int)$comment_id )
+	$comment = get_comment( $comment_id );
+	if ( ! $comment ) {
 		return false;
+	}
 
 	/**
 	 * Fires immediately before a comment is restored from the Trash.
 	 *
 	 * @since 2.9.0
+	 * @since 4.9.0 Added the `$comment` parameter.
 	 *
-	 * @param int $comment_id The comment ID.
+	 * @param int        $comment_id The comment ID.
+	 * @param WP_Comment $comment    The comment to be untrashed.
 	 */
-	do_action( 'untrash_comment', $comment_id );
-
-	$status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
+	do_action( 'untrash_comment', $comment->comment_ID, $comment );
+
+	$status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true );
 	if ( empty($status) )
 		$status = '0';
 
-	if ( wp_set_comment_status($comment_id, $status) ) {
-		delete_comment_meta($comment_id, '_wp_trash_meta_time');
-		delete_comment_meta($comment_id, '_wp_trash_meta_status');
+	if ( wp_set_comment_status( $comment, $status ) ) {
+		delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
+		delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
 		/**
 		 * Fires immediately after a comment is restored from the Trash.
 		 *
 		 * @since 2.9.0
+		 * @since 4.9.0 Added the `$comment` parameter.
 		 *
-		 * @param int $comment_id The comment ID.
+		 * @param int        $comment_id The comment ID.
+		 * @param WP_Comment $comment    The untrashed comment.
 		 */
-		do_action( 'untrashed_comment', $comment_id );
+		do_action( 'untrashed_comment', $comment->comment_ID, $comment );
 		return true;
 	}
 
@@ -1864,32 +1462,41 @@
  *
  * @since 2.9.0
  *
- * @param int $comment_id Comment ID.
+ * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  * @return bool True on success, false on failure.
  */
-function wp_spam_comment($comment_id) {
-	if ( !$comment = get_comment($comment_id) )
+function wp_spam_comment( $comment_id ) {
+	$comment = get_comment( $comment_id );
+	if ( ! $comment ) {
 		return false;
+	}
 
 	/**
 	 * Fires immediately before a comment is marked as Spam.
 	 *
 	 * @since 2.9.0
+	 * @since 4.9.0 Added the `$comment` parameter.
 	 *
-	 * @param int $comment_id The comment ID.
+	 * @param int        $comment_id The comment ID.
+	 * @param WP_Comment $comment    The comment to be marked as spam.
 	 */
-	do_action( 'spam_comment', $comment_id );
-
-	if ( wp_set_comment_status($comment_id, 'spam') ) {
-		add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
+	do_action( 'spam_comment', $comment->comment_ID, $comment );
+
+	if ( wp_set_comment_status( $comment, 'spam' ) ) {
+		delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
+		delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
+		add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved );
+		add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() );
 		/**
 		 * Fires immediately after a comment is marked as Spam.
 		 *
 		 * @since 2.9.0
+		 * @since 4.9.0 Added the `$comment` parameter.
 		 *
-		 * @param int $comment_id The comment ID.
+		 * @param int        $comment_id The comment ID.
+		 * @param WP_Comment $comment    The comment marked as spam.
 		 */
-		do_action( 'spammed_comment', $comment_id );
+		do_action( 'spammed_comment', $comment->comment_ID, $comment );
 		return true;
 	}
 
@@ -1901,36 +1508,43 @@
  *
  * @since 2.9.0
  *
- * @param int $comment_id Comment ID.
+ * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  * @return bool True on success, false on failure.
  */
-function wp_unspam_comment($comment_id) {
-	if ( ! (int)$comment_id )
+function wp_unspam_comment( $comment_id ) {
+	$comment = get_comment( $comment_id );
+	if ( ! $comment ) {
 		return false;
+	}
 
 	/**
 	 * Fires immediately before a comment is unmarked as Spam.
 	 *
 	 * @since 2.9.0
+	 * @since 4.9.0 Added the `$comment` parameter.
 	 *
-	 * @param int $comment_id The comment ID.
+	 * @param int        $comment_id The comment ID.
+	 * @param WP_Comment $comment    The comment to be unmarked as spam.
 	 */
-	do_action( 'unspam_comment', $comment_id );
-
-	$status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
+	do_action( 'unspam_comment', $comment->comment_ID, $comment );
+
+	$status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true );
 	if ( empty($status) )
 		$status = '0';
 
-	if ( wp_set_comment_status($comment_id, $status) ) {
-		delete_comment_meta($comment_id, '_wp_trash_meta_status');
+	if ( wp_set_comment_status( $comment, $status ) ) {
+		delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
+		delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
 		/**
 		 * Fires immediately after a comment is unmarked as Spam.
 		 *
 		 * @since 2.9.0
+		 * @since 4.9.0 Added the `$comment` parameter.
 		 *
-		 * @param int $comment_id The comment ID.
+		 * @param int        $comment_id The comment ID.
+		 * @param WP_Comment $comment    The comment unmarked as spam.
 		 */
-		do_action( 'unspammed_comment', $comment_id );
+		do_action( 'unspammed_comment', $comment->comment_ID, $comment );
 		return true;
 	}
 
@@ -1942,7 +1556,7 @@
  *
  * @since 1.0.0
  *
- * @param int $comment_id Comment ID
+ * @param int|WP_Comment $comment_id Comment ID or WP_Comment object
  * @return false|string Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
  */
 function wp_get_comment_status($comment_id) {
@@ -1971,14 +1585,12 @@
  *
  * Calls hooks for comment status transitions. If the new comment status is not the same
  * as the previous comment status, then two hooks will be ran, the first is
- * 'transition_comment_status' with new status, old status, and comment data. The
- * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
- * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
+ * {@see 'transition_comment_status'} with new status, old status, and comment data. The
+ * next action called is {@see comment_$old_status_to_$new_status'}. It has the
  * comment data.
  *
  * The final action will run whether or not the comment statuses are the same. The
- * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
- * parameter and COMMENTTYPE is comment_type comment data.
+ * action is named {@see 'comment_$new_status_$comment->comment_type'}.
  *
  * @since 2.7.0
  *
@@ -2021,7 +1633,7 @@
 		 *
 		 * @since 2.7.0
 		 *
-		 * @param object $comment Comment object.
+		 * @param WP_Comment $comment Comment object.
 		 */
 		do_action( "comment_{$old_status}_to_{$new_status}", $comment );
 	}
@@ -2036,13 +1648,33 @@
 	 *
 	 * @since 2.7.0
 	 *
-	 * @param int $comment_ID The comment ID.
-	 * @param obj $comment    Comment object.
+	 * @param int        $comment_ID The comment ID.
+	 * @param WP_Comment $comment    Comment object.
 	 */
 	do_action( "comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment );
 }
 
 /**
+ * Clear the lastcommentmodified cached value when a comment status is changed.
+ *
+ * Deletes the lastcommentmodified cache key when a comment enters or leaves
+ * 'approved' status.
+ *
+ * @since 4.7.0
+ * @access private
+ *
+ * @param string $new_status The new comment status.
+ * @param string $old_status The old comment status.
+ */
+function _clear_modified_cache_on_transition_comment_status( $new_status, $old_status ) {
+	if ( 'approved' === $new_status || 'approved' === $old_status ) {
+		foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
+			wp_cache_delete( "lastcommentmodified:$timezone", 'timeinfo' );
+		}
+	}
+}
+
+/**
  * Get current commenter's name, email, and URL.
  *
  * Expects cookies content to already be sanitized. User of this function might
@@ -2070,29 +1702,55 @@
 		$comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
 
 	/**
-	 * Filter the current commenter's name, email, and URL.
+	 * Filters the current commenter's name, email, and URL.
 	 *
 	 * @since 3.1.0
 	 *
-	 * @param string $comment_author       Comment author's name.
-	 * @param string $comment_author_email Comment author's email.
-	 * @param string $comment_author_url   Comment author's URL.
+	 * @param array $comment_author_data {
+	 *     An array of current commenter variables.
+	 *
+	 *     @type string $comment_author       The name of the author of the comment. Default empty.
+	 *     @type string $comment_author_email The email address of the `$comment_author`. Default empty.
+	 *     @type string $comment_author_url   The URL address of the `$comment_author`. Default empty.
+	 * }
 	 */
 	return apply_filters( 'wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url') );
 }
 
 /**
- * Inserts a comment to the database.
- *
- * The available comment data key names are 'comment_author_IP', 'comment_date',
- * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'.
+ * Inserts a comment into the database.
  *
  * @since 2.0.0
+ * @since 4.4.0 Introduced `$comment_meta` argument.
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param array $commentdata Contains information on the comment.
- * @return int|bool The new comment's ID on success, false on failure.
+ * @param array $commentdata {
+ *     Array of arguments for inserting a new comment.
+ *
+ *     @type string     $comment_agent        The HTTP user agent of the `$comment_author` when
+ *                                            the comment was submitted. Default empty.
+ *     @type int|string $comment_approved     Whether the comment has been approved. Default 1.
+ *     @type string     $comment_author       The name of the author of the comment. Default empty.
+ *     @type string     $comment_author_email The email address of the `$comment_author`. Default empty.
+ *     @type string     $comment_author_IP    The IP address of the `$comment_author`. Default empty.
+ *     @type string     $comment_author_url   The URL address of the `$comment_author`. Default empty.
+ *     @type string     $comment_content      The content of the comment. Default empty.
+ *     @type string     $comment_date         The date the comment was submitted. To set the date
+ *                                            manually, `$comment_date_gmt` must also be specified.
+ *                                            Default is the current time.
+ *     @type string     $comment_date_gmt     The date the comment was submitted in the GMT timezone.
+ *                                            Default is `$comment_date` in the site's GMT timezone.
+ *     @type int        $comment_karma        The karma of the comment. Default 0.
+ *     @type int        $comment_parent       ID of this comment's parent, if any. Default 0.
+ *     @type int        $comment_post_ID      ID of the post that relates to the comment, if any.
+ *                                            Default 0.
+ *     @type string     $comment_type         Comment type. Default empty.
+ *     @type array      $comment_meta         Optional. Array of key/value pairs to be stored in commentmeta for the
+ *                                            new comment.
+ *     @type int        $user_id              ID of the user who submitted the comment. Default 0.
+ * }
+ * @return int|false The new comment's ID on success, false on failure.
  */
 function wp_insert_comment( $commentdata ) {
 	global $wpdb;
@@ -2106,7 +1764,7 @@
 	$comment_date     = ! isset( $data['comment_date'] )     ? current_time( 'mysql' )            : $data['comment_date'];
 	$comment_date_gmt = ! isset( $data['comment_date_gmt'] ) ? get_gmt_from_date( $comment_date ) : $data['comment_date_gmt'];
 
-	$comment_post_ID  = ! isset( $data['comment_post_ID'] )  ? '' : $data['comment_post_ID'];
+	$comment_post_ID  = ! isset( $data['comment_post_ID'] )  ? 0  : $data['comment_post_ID'];
 	$comment_content  = ! isset( $data['comment_content'] )  ? '' : $data['comment_content'];
 	$comment_karma    = ! isset( $data['comment_karma'] )    ? 0  : $data['comment_karma'];
 	$comment_approved = ! isset( $data['comment_approved'] ) ? 1  : $data['comment_approved'];
@@ -2125,21 +1783,33 @@
 
 	if ( $comment_approved == 1 ) {
 		wp_update_comment_count( $comment_post_ID );
+
+		foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
+			wp_cache_delete( "lastcommentmodified:$timezone", 'timeinfo' );
+		}
 	}
+
+	clean_comment_cache( $id );
+
 	$comment = get_comment( $id );
 
+	// If metadata is provided, store it.
+	if ( isset( $commentdata['comment_meta'] ) && is_array( $commentdata['comment_meta'] ) ) {
+		foreach ( $commentdata['comment_meta'] as $meta_key => $meta_value ) {
+			add_comment_meta( $comment->comment_ID, $meta_key, $meta_value, true );
+		}
+	}
+
 	/**
 	 * Fires immediately after a comment is inserted into the database.
 	 *
 	 * @since 2.8.0
 	 *
-	 * @param int $id      The comment ID.
-	 * @param obj $comment Comment object.
+	 * @param int        $id      The comment ID.
+	 * @param WP_Comment $comment Comment object.
 	 */
 	do_action( 'wp_insert_comment', $id, $comment );
 
-	wp_cache_set( 'last_changed', microtime(), 'comment' );
-
 	return $id;
 }
 
@@ -2158,7 +1828,7 @@
 function wp_filter_comment($commentdata) {
 	if ( isset( $commentdata['user_ID'] ) ) {
 		/**
-		 * Filter the comment author's user id before it is set.
+		 * Filters the comment author's user id before it is set.
 		 *
 		 * The first time this filter is evaluated, 'user_ID' is checked
 		 * (for back-compat), followed by the standard 'user_id' value.
@@ -2174,29 +1844,29 @@
 	}
 
 	/**
-	 * Filter the comment author's browser user agent before it is set.
+	 * Filters the comment author's browser user agent before it is set.
 	 *
 	 * @since 1.5.0
 	 *
-	 * @param int $comment_agent The comment author's browser user agent.
+	 * @param string $comment_agent The comment author's browser user agent.
 	 */
 	$commentdata['comment_agent'] = apply_filters( 'pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
 	/** This filter is documented in wp-includes/comment.php */
 	$commentdata['comment_author'] = apply_filters( 'pre_comment_author_name', $commentdata['comment_author'] );
 	/**
-	 * Filter the comment content before it is set.
+	 * Filters the comment content before it is set.
 	 *
 	 * @since 1.5.0
 	 *
-	 * @param int $comment_content The comment content.
+	 * @param string $comment_content The comment content.
 	 */
 	$commentdata['comment_content'] = apply_filters( 'pre_comment_content', $commentdata['comment_content'] );
 	/**
-	 * Filter the comment author's IP before it is set.
+	 * Filters the comment author's IP address before it is set.
 	 *
 	 * @since 1.5.0
 	 *
-	 * @param int $comment_author_ip The comment author's IP.
+	 * @param string $comment_author_ip The comment author's IP address.
 	 */
 	$commentdata['comment_author_IP'] = apply_filters( 'pre_comment_user_ip', $commentdata['comment_author_IP'] );
 	/** This filter is documented in wp-includes/comment.php */
@@ -2229,19 +1899,47 @@
  * Adds a new comment to the database.
  *
  * Filters new comment to ensure that the fields are sanitized and valid before
- * inserting comment into database. Calls 'comment_post' action with comment ID
- * and whether comment is approved by WordPress. Also has 'preprocess_comment'
+ * inserting comment into database. Calls {@see 'comment_post'} action with comment ID
+ * and whether comment is approved by WordPress. Also has {@see 'preprocess_comment'}
  * filter for processing the comment data before the function handles it.
  *
- * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure
+ * We use `REMOTE_ADDR` here directly. If you are behind a proxy, you should ensure
  * that it is properly set, such as in wp-config.php, for your environment.
+ *
  * See {@link https://core.trac.wordpress.org/ticket/9235}
  *
  * @since 1.5.0
- * @param array $commentdata Contains information on the comment.
- * @return int|bool The ID of the comment on success, false on failure.
+ * @since 4.3.0 'comment_agent' and 'comment_author_IP' can be set via `$commentdata`.
+ * @since 4.7.0 The `$avoid_die` parameter was added, allowing the function to
+ *              return a WP_Error object instead of dying.
+ *
+ * @see wp_insert_comment()
+ * @global wpdb $wpdb WordPress database abstraction object.
+ *
+ * @param array $commentdata {
+ *     Comment data.
+ *
+ *     @type string $comment_author       The name of the comment author.
+ *     @type string $comment_author_email The comment author email address.
+ *     @type string $comment_author_url   The comment author URL.
+ *     @type string $comment_content      The content of the comment.
+ *     @type string $comment_date         The date the comment was submitted. Default is the current time.
+ *     @type string $comment_date_gmt     The date the comment was submitted in the GMT timezone.
+ *                                        Default is `$comment_date` in the GMT timezone.
+ *     @type int    $comment_parent       The ID of this comment's parent, if any. Default 0.
+ *     @type int    $comment_post_ID      The ID of the post that relates to the comment.
+ *     @type int    $user_id              The ID of the user who submitted the comment. Default 0.
+ *     @type int    $user_ID              Kept for backward-compatibility. Use `$user_id` instead.
+ *     @type string $comment_agent        Comment author user agent. Default is the value of 'HTTP_USER_AGENT'
+ *                                        in the `$_SERVER` superglobal sent in the original request.
+ *     @type string $comment_author_IP    Comment author IP address in IPv4 format. Default is the value of
+ *                                        'REMOTE_ADDR' in the `$_SERVER` superglobal sent in the original request.
+ * }
+ * @param bool $avoid_die Should errors be returned as WP_Error objects instead of
+ *                        executing wp_die()? Default false.
+ * @return int|false|WP_Error The ID of the comment on success, false or WP_Error on failure.
  */
-function wp_new_comment( $commentdata ) {
+function wp_new_comment( $commentdata, $avoid_die = false ) {
 	global $wpdb;
 
 	if ( isset( $commentdata['user_ID'] ) ) {
@@ -2251,7 +1949,7 @@
 	$prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0;
 
 	/**
-	 * Filter a comment's data before it is sanitized and inserted into the database.
+	 * Filters a comment's data before it is sanitized and inserted into the database.
 	 *
 	 * @since 1.5.0
 	 *
@@ -2270,8 +1968,15 @@
 	$parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
 	$commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
 
-	$commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
-	$commentdata['comment_agent']     = isset( $_SERVER['HTTP_USER_AGENT'] ) ? substr( $_SERVER['HTTP_USER_AGENT'], 0, 254 ) : '';
+	if ( ! isset( $commentdata['comment_author_IP'] ) ) {
+		$commentdata['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
+	}
+	$commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '', $commentdata['comment_author_IP'] );
+
+	if ( ! isset( $commentdata['comment_agent'] ) ) {
+		$commentdata['comment_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT']: '';
+	}
+	$commentdata['comment_agent'] = substr( $commentdata['comment_agent'], 0, 254 );
 
 	if ( empty( $commentdata['comment_date'] ) ) {
 		$commentdata['comment_date'] = current_time('mysql');
@@ -2283,13 +1988,16 @@
 
 	$commentdata = wp_filter_comment($commentdata);
 
-	$commentdata['comment_approved'] = wp_allow_comment($commentdata);
+	$commentdata['comment_approved'] = wp_allow_comment( $commentdata, $avoid_die );
+	if ( is_wp_error( $commentdata['comment_approved'] ) ) {
+		return $commentdata['comment_approved'];
+	}
 
 	$comment_ID = wp_insert_comment($commentdata);
 	if ( ! $comment_ID ) {
 		$fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' );
 
-		foreach( $fields as $field ) {
+		foreach ( $fields as $field ) {
 			if ( isset( $commentdata[ $field ] ) ) {
 				$commentdata[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $commentdata[ $field ] );
 			}
@@ -2297,7 +2005,10 @@
 
 		$commentdata = wp_filter_comment( $commentdata );
 
-		$commentdata['comment_approved'] = wp_allow_comment( $commentdata );
+		$commentdata['comment_approved'] = wp_allow_comment( $commentdata, $avoid_die );
+		if ( is_wp_error( $commentdata['comment_approved'] ) ) {
+			return $commentdata['comment_approved'];
+		}
 
 		$comment_ID = wp_insert_comment( $commentdata );
 		if ( ! $comment_ID ) {
@@ -2309,38 +2020,97 @@
 	 * Fires immediately after a comment is inserted into the database.
 	 *
 	 * @since 1.2.0
+	 * @since 4.5.0 The `$commentdata` parameter was added.
 	 *
-	 * @param int $comment_ID       The comment ID.
-	 * @param int $comment_approved 1 (true) if the comment is approved, 0 (false) if not.
+	 * @param int        $comment_ID       The comment ID.
+	 * @param int|string $comment_approved 1 if the comment is approved, 0 if not, 'spam' if spam.
+	 * @param array      $commentdata      Comment data.
 	 */
-	do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'] );
-
-	if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
-		if ( '0' == $commentdata['comment_approved'] ) {
-			wp_notify_moderator( $comment_ID );
-		}
-
-		// wp_notify_postauthor() checks if notifying the author of their own comment.
-		// By default, it won't, but filters can override this.
-		if ( get_option( 'comments_notify' ) && $commentdata['comment_approved'] ) {
-			wp_notify_postauthor( $comment_ID );
-		}
-	}
+	do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'], $commentdata );
 
 	return $comment_ID;
 }
 
 /**
+ * Send a comment moderation notification to the comment moderator.
+ *
+ * @since 4.4.0
+ *
+ * @param int $comment_ID ID of the comment.
+ * @return bool True on success, false on failure.
+ */
+function wp_new_comment_notify_moderator( $comment_ID ) {
+	$comment = get_comment( $comment_ID );
+
+	// Only send notifications for pending comments.
+	$maybe_notify = ( '0' == $comment->comment_approved );
+
+	/** This filter is documented in wp-includes/comment.php */
+	$maybe_notify = apply_filters( 'notify_moderator', $maybe_notify, $comment_ID );
+
+	if ( ! $maybe_notify ) {
+		return false;
+	}
+
+	return wp_notify_moderator( $comment_ID );
+}
+
+/**
+ * Send a notification of a new comment to the post author.
+ *
+ * @since 4.4.0
+ *
+ * Uses the {@see 'notify_post_author'} filter to determine whether the post author
+ * should be notified when a new comment is added, overriding site setting.
+ *
+ * @param int $comment_ID Comment ID.
+ * @return bool True on success, false on failure.
+ */
+function wp_new_comment_notify_postauthor( $comment_ID ) {
+	$comment = get_comment( $comment_ID );
+
+	$maybe_notify = get_option( 'comments_notify' );
+
+	/**
+	 * Filters whether to send the post author new comment notification emails,
+	 * overriding the site setting.
+	 *
+	 * @since 4.4.0
+	 *
+	 * @param bool $maybe_notify Whether to notify the post author about the new comment.
+	 * @param int  $comment_ID   The ID of the comment for the notification.
+	 */
+	$maybe_notify = apply_filters( 'notify_post_author', $maybe_notify, $comment_ID );
+
+	/*
+	 * wp_notify_postauthor() checks if notifying the author of their own comment.
+	 * By default, it won't, but filters can override this.
+	 */
+	if ( ! $maybe_notify ) {
+		return false;
+	}
+
+	// Only send notifications for approved comments.
+	if ( ! isset( $comment->comment_approved ) || '1' != $comment->comment_approved ) {
+		return false;
+	}
+
+	return wp_notify_postauthor( $comment_ID );
+}
+
+/**
  * Sets the status of a comment.
  *
- * The 'wp_set_comment_status' action is called after the comment is handled.
+ * The {@see 'wp_set_comment_status'} action is called after the comment is handled.
  * If the comment status is not in the list, then false is returned.
  *
  * @since 1.0.0
  *
- * @param int $comment_id Comment ID.
- * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
- * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
+ * @global wpdb $wpdb WordPress database abstraction object.
+ *
+ * @param int|WP_Comment $comment_id     Comment ID or WP_Comment object.
+ * @param string         $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
+ * @param bool           $wp_error       Whether to return a WP_Error object if there is a failure. Default is false.
  * @return bool|WP_Error True on success, false or WP_Error on failure.
  */
 function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
@@ -2354,9 +2124,7 @@
 		case 'approve':
 		case '1':
 			$status = '1';
-			if ( get_option('comments_notify') ) {
-				wp_notify_postauthor( $comment_id );
-			}
+			add_action( 'wp_set_comment_status', 'wp_new_comment_notify_postauthor' );
 			break;
 		case 'spam':
 			$status = 'spam';
@@ -2370,16 +2138,16 @@
 
 	$comment_old = clone get_comment($comment_id);
 
-	if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
+	if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array( 'comment_ID' => $comment_old->comment_ID ) ) ) {
 		if ( $wp_error )
 			return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
 		else
 			return false;
 	}
 
-	clean_comment_cache($comment_id);
-
-	$comment = get_comment($comment_id);
+	clean_comment_cache( $comment_old->comment_ID );
+
+	$comment = get_comment( $comment_old->comment_ID );
 
 	/**
 	 * Fires immediately before transitioning a comment's status from one to another
@@ -2391,7 +2159,7 @@
 	 * @param string|bool $comment_status Current comment status. Possible values include
 	 *                                    'hold', 'approve', 'spam', 'trash', or false.
 	 */
-	do_action( 'wp_set_comment_status', $comment_id, $comment_status );
+	do_action( 'wp_set_comment_status', $comment->comment_ID, $comment_status );
 
 	wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
 
@@ -2406,6 +2174,7 @@
  * Filters the comment and makes sure certain fields are valid before updating.
  *
  * @since 2.0.0
+ * @since 4.9.0 Add updating comment meta during comment update.
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
@@ -2422,7 +2191,7 @@
 	}
 
 	// Make sure that the comment post ID is valid (if specified).
-	if ( isset( $commentarr['comment_post_ID'] ) && ! get_post( $commentarr['comment_post_ID'] ) ) {
+	if ( ! empty( $commentarr['comment_post_ID'] ) && ! get_post( $commentarr['comment_post_ID'] ) ) {
 		return 0;
 	}
 
@@ -2440,7 +2209,7 @@
 	$data = wp_unslash( $commentarr );
 
 	/**
-	 * Filter the comment content before it is updated in the database.
+	 * Filters the comment content before it is updated in the database.
 	 *
 	 * @since 1.5.0
 	 *
@@ -2460,10 +2229,32 @@
 
 	$comment_ID = $data['comment_ID'];
 	$comment_post_ID = $data['comment_post_ID'];
-	$keys = array( 'comment_post_ID', 'comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt', 'comment_type', 'comment_parent', 'user_id' );
+
+	/**
+	 * Filters the comment data immediately before it is updated in the database.
+	 *
+	 * Note: data being passed to the filter is already unslashed.
+	 *
+	 * @since 4.7.0
+	 *
+	 * @param array $data       The new, processed comment data.
+	 * @param array $comment    The old, unslashed comment data.
+	 * @param array $commentarr The new, raw comment data.
+	 */
+	$data = apply_filters( 'wp_update_comment_data', $data, $comment, $commentarr );
+
+	$keys = array( 'comment_post_ID', 'comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt', 'comment_type', 'comment_parent', 'user_id', 'comment_agent', 'comment_author_IP' );
 	$data = wp_array_slice_assoc( $data, $keys );
+
 	$rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
 
+	// If metadata is provided, store it.
+	if ( isset( $commentarr['comment_meta'] ) && is_array( $commentarr['comment_meta'] ) ) {
+		foreach ( $commentarr['comment_meta'] as $meta_key => $meta_value ) {
+			update_comment_meta( $comment_ID, $meta_key, $meta_value );
+		}
+	}
+
 	clean_comment_cache( $comment_ID );
 	wp_update_comment_count( $comment_post_ID );
 	/**
@@ -2472,10 +2263,12 @@
 	 * The hook also fires immediately before comment status transition hooks are fired.
 	 *
 	 * @since 1.2.0
+	 * @since 4.6.0 Added the `$data` parameter.
 	 *
-	 * @param int $comment_ID The comment ID.
+	 * @param int   $comment_ID The comment ID.
+	 * @param array $data       Comment data.
 	 */
-	do_action( 'edit_comment', $comment_ID );
+	do_action( 'edit_comment', $comment_ID, $data );
 	$comment = get_comment($comment_ID);
 	wp_transition_comment_status($comment->comment_approved, $old_status, $comment);
 	return $rval;
@@ -2522,13 +2315,21 @@
  * @since 2.1.0
  * @see wp_update_comment_count_now() For what could cause a false return value
  *
- * @param int $post_id Post ID
- * @param bool $do_deferred Whether to process previously deferred post comment counts
- * @return bool|null True on success, false on failure
+ * @staticvar array $_deferred
+ *
+ * @param int|null $post_id     Post ID.
+ * @param bool     $do_deferred Optional. Whether to process previously deferred
+ *                              post comment counts. Default false.
+ * @return bool|void True on success, false on failure or if post with ID does
+ *                   not exist.
  */
 function wp_update_comment_count($post_id, $do_deferred=false) {
 	static $_deferred = array();
 
+	if ( empty( $post_id ) && ! $do_deferred ) {
+		return false;
+	}
+
 	if ( $do_deferred ) {
 		$_deferred = array_unique($_deferred);
 		foreach ( $_deferred as $i => $_post_id ) {
@@ -2562,11 +2363,32 @@
 	$post_id = (int) $post_id;
 	if ( !$post_id )
 		return false;
+
+	wp_cache_delete( 'comments-0', 'counts' );
+	wp_cache_delete( "comments-{$post_id}", 'counts' );
+
 	if ( !$post = get_post($post_id) )
 		return false;
 
 	$old = (int) $post->comment_count;
-	$new = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id) );
+
+	/**
+	 * Filters a post's comment count before it is updated in the database.
+	 *
+	 * @since 4.5.0
+	 *
+	 * @param int $new     The new comment count. Default null.
+	 * @param int $old     The old comment count.
+	 * @param int $post_id Post ID.
+	 */
+	$new = apply_filters( 'pre_wp_update_comment_count_now', null, $old, $post_id );
+
+	if ( is_null( $new ) ) {
+		$new = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id ) );
+	} else {
+		$new = (int) $new;
+	}
+
 	$wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) );
 
 	clean_post_cache( $post );
@@ -2606,7 +2428,7 @@
  */
 function discover_pingback_server_uri( $url, $deprecated = '' ) {
 	if ( !empty( $deprecated ) )
-		_deprecated_argument( __FUNCTION__, '2.7' );
+		_deprecated_argument( __FUNCTION__, '2.7.0' );
 
 	$pingback_str_dquote = 'rel="pingback"';
 	$pingback_str_squote = 'rel=\'pingback\'';
@@ -2614,11 +2436,11 @@
 	/** @todo Should use Filter Extension or custom preg_match instead. */
 	$parsed_url = parse_url($url);
 
-	if ( ! isset( $parsed_url['host'] ) ) // Not an URL. This should never happen.
+	if ( ! isset( $parsed_url['host'] ) ) // Not a URL. This should never happen.
 		return false;
 
 	//Do not search for a pingback server on our own uploads
-	$uploads_dir = wp_upload_dir();
+	$uploads_dir = wp_get_upload_dir();
 	if ( 0 === strpos($url, $uploads_dir['baseurl']) )
 		return false;
 
@@ -2698,19 +2520,23 @@
  * Perform trackbacks.
  *
  * @since 1.5.0
+ * @since 4.7.0 $post_id can be a WP_Post object.
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param int $post_id Post ID to do trackbacks on.
+ * @param int|WP_Post $post_id Post object or ID to do trackbacks on.
  */
-function do_trackbacks($post_id) {
+function do_trackbacks( $post_id ) {
 	global $wpdb;
-
 	$post = get_post( $post_id );
-	$to_ping = get_to_ping($post_id);
-	$pinged  = get_pung($post_id);
-	if ( empty($to_ping) ) {
-		$wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) );
+	if ( ! $post ) {
+		return false;
+	}
+
+	$to_ping = get_to_ping( $post );
+	$pinged  = get_pung( $post );
+	if ( empty( $to_ping ) ) {
+		$wpdb->update($wpdb->posts, array( 'to_ping' => '' ), array( 'ID' => $post->ID ) );
 		return;
 	}
 
@@ -2733,10 +2559,11 @@
 		foreach ( (array) $to_ping as $tb_ping ) {
 			$tb_ping = trim($tb_ping);
 			if ( !in_array($tb_ping, $pinged) ) {
-				trackback($tb_ping, $post_title, $excerpt, $post_id);
+				trackback( $tb_ping, $post_title, $excerpt, $post->ID );
 				$pinged[] = $tb_ping;
 			} else {
-				$wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post_id) );
+				$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s,
+					'')) WHERE ID = %d", $tb_ping, $post->ID ) );
 			}
 		}
 	}
@@ -2767,20 +2594,28 @@
  * Pings back the links found in a post.
  *
  * @since 0.71
- * @uses $wp_version
+ * @since 4.7.0 $post_id can be a WP_Post object.
  *
- * @param string $content Post content to check for links.
- * @param int $post_ID Post ID.
+ * @param string $content Post content to check for links. If empty will retrieve from post.
+ * @param int|WP_Post $post_id Post Object or ID.
  */
-function pingback($content, $post_ID) {
-	global $wp_version;
-	include_once(ABSPATH . WPINC . '/class-IXR.php');
-	include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
+function pingback( $content, $post_id ) {
+	include_once( ABSPATH . WPINC . '/class-IXR.php' );
+	include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' );
 
 	// original code by Mort (http://mort.mine.nu:8080)
 	$post_links = array();
 
-	$pung = get_pung($post_ID);
+	$post = get_post( $post_id );
+	if ( ! $post ) {
+		return;
+	}
+
+	$pung = get_pung( $post );
+
+	if ( empty( $content ) ) {
+		$content = $post->post_content;
+	}
 
 	// Step 1
 	// Parsing the post, external links (if any) are stored in the $post_links array
@@ -2796,7 +2631,7 @@
 	// We don't wanna ping first and second types, even if they have a valid <link/>
 
 	foreach ( (array) $post_links_temp as $link_test ) :
-		if ( !in_array($link_test, $pung) && (url_to_postid($link_test) != $post_ID) // If we haven't pung it already and it isn't a link to itself
+		if ( ! in_array( $link_test, $pung ) && ( url_to_postid( $link_test ) != $post->ID ) // If we haven't pung it already and it isn't a link to itself
 				&& !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
 			if ( $test = @parse_url($link_test) ) {
 				if ( isset($test['query']) )
@@ -2813,11 +2648,11 @@
 	 *
 	 * @since 2.0.0
 	 *
-	 * @param array &$post_links An array of post links to be checked, passed by reference.
-	 * @param array &$pung       Whether a link has already been pinged, passed by reference.
-	 * @param int   $post_ID     The post ID.
+	 * @param array $post_links An array of post links to be checked (passed by reference).
+	 * @param array $pung       Whether a link has already been pinged (passed by reference).
+	 * @param int   $post_ID    The post ID.
 	 */
-	do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post_ID ) );
+	do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post->ID ) );
 
 	foreach ( (array) $post_links as $pagelinkedto ) {
 		$pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
@@ -2825,13 +2660,13 @@
 		if ( $pingback_server_url ) {
 			@ set_time_limit( 60 );
 			// Now, the RPC call
-			$pagelinkedfrom = get_permalink($post_ID);
+			$pagelinkedfrom = get_permalink( $post );
 
 			// using a timeout of 3 seconds should be enough to cover slow servers
 			$client = new WP_HTTP_IXR_Client($pingback_server_url);
 			$client->timeout = 3;
 			/**
-			 * Filter the user agent sent when pinging-back a URL.
+			 * Filters the user agent sent when pinging-back a URL.
 			 *
 			 * @since 2.9.0
 			 *
@@ -2842,12 +2677,12 @@
 			 * @param string $pagelinkedto        URL of page linked to.
 			 * @param string $pagelinkedfrom      URL of page linked from.
 			 */
-			$client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . $wp_version, $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom );
+			$client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . get_bloginfo( 'version' ), $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom );
 			// when set to true, this outputs debug messages by itself
 			$client->debug = false;
 
 			if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
-				add_ping( $post_ID, $pagelinkedto );
+				add_ping( $post, $pagelinkedto );
 		}
 	}
 }
@@ -2880,7 +2715,7 @@
  * @param string $title Title of post.
  * @param string $excerpt Excerpt of post.
  * @param int $ID Post ID.
- * @return mixed Database query from update.
+ * @return int|false|void Database query from update.
  */
 function trackback($trackback_url, $title, $excerpt, $ID) {
 	global $wpdb;
@@ -2889,7 +2724,7 @@
 		return;
 
 	$options = array();
-	$options['timeout'] = 4;
+	$options['timeout'] = 10;
 	$options['body'] = array(
 		'title' => $title,
 		'url' => get_permalink($ID),
@@ -2910,20 +2745,18 @@
  * Send a pingback.
  *
  * @since 1.2.0
- * @uses $wp_version
  *
  * @param string $server Host of blog to connect to.
  * @param string $path Path to send the ping.
  */
 function weblog_ping($server = '', $path = '') {
-	global $wp_version;
-	include_once(ABSPATH . WPINC . '/class-IXR.php');
-	include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
+	include_once( ABSPATH . WPINC . '/class-IXR.php' );
+	include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' );
 
 	// using a timeout of 3 seconds should be enough to cover slow servers
 	$client = new WP_HTTP_IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
 	$client->timeout = 3;
-	$client->useragent .= ' -- WordPress/'.$wp_version;
+	$client->useragent .= ' -- WordPress/' . get_bloginfo( 'version' );
 
 	// when set to true, this outputs debug messages by itself
 	$client->debug = false;
@@ -2952,7 +2785,7 @@
  * which reports that the pingback is already registered.
  *
  * @since 3.5.1
- * @link http://www.hixie.ch/specs/pingback/pingback#TOC3
+ * @link https://www.hixie.ch/specs/pingback/pingback#TOC3
  *
  * @param IXR_Error $ixr_error
  * @return IXR_Error
@@ -2968,15 +2801,25 @@
 //
 
 /**
- * Removes comment ID from the comment cache.
+ * Removes a comment from the object cache.
  *
  * @since 2.3.0
  *
- * @param int|array $ids Comment ID or array of comment IDs to remove from cache
+ * @param int|array $ids Comment ID or an array of comment IDs to remove from cache.
  */
 function clean_comment_cache($ids) {
-	foreach ( (array) $ids as $id )
-		wp_cache_delete($id, 'comment');
+	foreach ( (array) $ids as $id ) {
+		wp_cache_delete( $id, 'comment' );
+
+		/**
+		 * Fires immediately after a comment has been removed from the object cache.
+		 *
+		 * @since 4.5.0
+		 *
+		 * @param int $id Comment ID.
+		 */
+		do_action( 'clean_comment_cache', $id );
+	}
 
 	wp_cache_set( 'last_changed', microtime(), 'comment' );
 }
@@ -2989,12 +2832,46 @@
  * cache using the comment group with the key using the ID of the comments.
  *
  * @since 2.3.0
+ * @since 4.4.0 Introduced the `$update_meta_cache` parameter.
  *
- * @param array $comments Array of comment row objects
+ * @param array $comments          Array of comment row objects
+ * @param bool  $update_meta_cache Whether to update commentmeta cache. Default true.
  */
-function update_comment_cache($comments) {
+function update_comment_cache( $comments, $update_meta_cache = true ) {
 	foreach ( (array) $comments as $comment )
 		wp_cache_add($comment->comment_ID, $comment, 'comment');
+
+	if ( $update_meta_cache ) {
+		// Avoid `wp_list_pluck()` in case `$comments` is passed by reference.
+		$comment_ids = array();
+		foreach ( $comments as $comment ) {
+			$comment_ids[] = $comment->comment_ID;
+		}
+		update_meta_cache( 'comment', $comment_ids );
+	}
+}
+
+/**
+ * Adds any comments from the given IDs to the cache that do not already exist in cache.
+ *
+ * @since 4.4.0
+ * @access private
+ *
+ * @see update_comment_cache()
+ * @global wpdb $wpdb WordPress database abstraction object.
+ *
+ * @param array $comment_ids       Array of comment IDs.
+ * @param bool  $update_meta_cache Optional. Whether to update the meta cache. Default true.
+ */
+function _prime_comment_caches( $comment_ids, $update_meta_cache = true ) {
+	global $wpdb;
+
+	$non_cached_ids = _get_non_cached_ids( $comment_ids, 'comment' );
+	if ( !empty( $non_cached_ids ) ) {
+		$fresh_comments = $wpdb->get_results( sprintf( "SELECT $wpdb->comments.* FROM $wpdb->comments WHERE comment_ID IN (%s)", join( ",", array_map( 'intval', $non_cached_ids ) ) ) );
+
+		update_comment_cache( $fresh_comments, $update_meta_cache );
+	}
 }
 
 //
@@ -3007,16 +2884,16 @@
  * @access private
  * @since 2.7.0
  *
- * @param object $posts Post data object.
- * @param object $query Query object.
- * @return object
+ * @param WP_Post  $posts Post data object.
+ * @param WP_Query $query Query object.
+ * @return array
  */
 function _close_comments_for_old_posts( $posts, $query ) {
 	if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) )
 		return $posts;
 
 	/**
-	 * Filter the list of post types to automatically close comments for.
+	 * Filters the list of post types to automatically close comments for.
 	 *
 	 * @since 3.2.0
 	 *
@@ -3066,8 +2943,447 @@
 	if ( ! in_array( $post->post_type, $post_types ) )
 		return $open;
 
+	// Undated drafts should not show up as comments closed.
+	if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
+		return $open;
+	}
+
 	if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) )
 		return false;
 
 	return $open;
 }
+
+/**
+ * Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form.
+ *
+ * This function expects unslashed data, as opposed to functions such as `wp_new_comment()` which
+ * expect slashed data.
+ *
+ * @since 4.4.0
+ *
+ * @param array $comment_data {
+ *     Comment data.
+ *
+ *     @type string|int $comment_post_ID             The ID of the post that relates to the comment.
+ *     @type string     $author                      The name of the comment author.
+ *     @type string     $email                       The comment author email address.
+ *     @type string     $url                         The comment author URL.
+ *     @type string     $comment                     The content of the comment.
+ *     @type string|int $comment_parent              The ID of this comment's parent, if any. Default 0.
+ *     @type string     $_wp_unfiltered_html_comment The nonce value for allowing unfiltered HTML.
+ * }
+ * @return WP_Comment|WP_Error A WP_Comment object on success, a WP_Error object on failure.
+ */
+function wp_handle_comment_submission( $comment_data ) {
+
+	$comment_post_ID = $comment_parent = 0;
+	$comment_author = $comment_author_email = $comment_author_url = $comment_content = null;
+
+	if ( isset( $comment_data['comment_post_ID'] ) ) {
+		$comment_post_ID = (int) $comment_data['comment_post_ID'];
+	}
+	if ( isset( $comment_data['author'] ) && is_string( $comment_data['author'] ) ) {
+		$comment_author = trim( strip_tags( $comment_data['author'] ) );
+	}
+	if ( isset( $comment_data['email'] ) && is_string( $comment_data['email'] ) ) {
+		$comment_author_email = trim( $comment_data['email'] );
+	}
+	if ( isset( $comment_data['url'] ) && is_string( $comment_data['url'] ) ) {
+		$comment_author_url = trim( $comment_data['url'] );
+	}
+	if ( isset( $comment_data['comment'] ) && is_string( $comment_data['comment'] ) ) {
+		$comment_content = trim( $comment_data['comment'] );
+	}
+	if ( isset( $comment_data['comment_parent'] ) ) {
+		$comment_parent = absint( $comment_data['comment_parent'] );
+	}
+
+	$post = get_post( $comment_post_ID );
+
+	if ( empty( $post->comment_status ) ) {
+
+		/**
+		 * Fires when a comment is attempted on a post that does not exist.
+		 *
+		 * @since 1.5.0
+		 *
+		 * @param int $comment_post_ID Post ID.
+		 */
+		do_action( 'comment_id_not_found', $comment_post_ID );
+
+		return new WP_Error( 'comment_id_not_found' );
+
+	}
+
+	// get_post_status() will get the parent status for attachments.
+	$status = get_post_status( $post );
+
+	if ( ( 'private' == $status ) && ! current_user_can( 'read_post', $comment_post_ID ) ) {
+		return new WP_Error( 'comment_id_not_found' );
+	}
+
+	$status_obj = get_post_status_object( $status );
+
+	if ( ! comments_open( $comment_post_ID ) ) {
+
+		/**
+		 * Fires when a comment is attempted on a post that has comments closed.
+		 *
+		 * @since 1.5.0
+		 *
+		 * @param int $comment_post_ID Post ID.
+		 */
+		do_action( 'comment_closed', $comment_post_ID );
+
+		return new WP_Error( 'comment_closed', __( 'Sorry, comments are closed for this item.' ), 403 );
+
+	} elseif ( 'trash' == $status ) {
+
+		/**
+		 * Fires when a comment is attempted on a trashed post.
+		 *
+		 * @since 2.9.0
+		 *
+		 * @param int $comment_post_ID Post ID.
+		 */
+		do_action( 'comment_on_trash', $comment_post_ID );
+
+		return new WP_Error( 'comment_on_trash' );
+
+	} elseif ( ! $status_obj->public && ! $status_obj->private ) {
+
+		/**
+		 * Fires when a comment is attempted on a post in draft mode.
+		 *
+		 * @since 1.5.1
+		 *
+		 * @param int $comment_post_ID Post ID.
+		 */
+		do_action( 'comment_on_draft', $comment_post_ID );
+		
+		if ( current_user_can( 'read_post', $comment_post_ID ) ) {
+			return new WP_Error( 'comment_on_draft', __( 'Sorry, comments are not allowed for this item.' ), 403 );
+		} else {
+			return new WP_Error( 'comment_on_draft' );
+		}
+
+	} elseif ( post_password_required( $comment_post_ID ) ) {
+
+		/**
+		 * Fires when a comment is attempted on a password-protected post.
+		 *
+		 * @since 2.9.0
+		 *
+		 * @param int $comment_post_ID Post ID.
+		 */
+		do_action( 'comment_on_password_protected', $comment_post_ID );
+
+		return new WP_Error( 'comment_on_password_protected' );
+
+	} else {
+
+		/**
+		 * Fires before a comment is posted.
+		 *
+		 * @since 2.8.0
+		 *
+		 * @param int $comment_post_ID Post ID.
+		 */
+		do_action( 'pre_comment_on_post', $comment_post_ID );
+
+	}
+
+	// If the user is logged in
+	$user = wp_get_current_user();
+	if ( $user->exists() ) {
+		if ( empty( $user->display_name ) ) {
+			$user->display_name=$user->user_login;
+		}
+		$comment_author       = $user->display_name;
+		$comment_author_email = $user->user_email;
+		$comment_author_url   = $user->user_url;
+		$user_ID              = $user->ID;
+		if ( current_user_can( 'unfiltered_html' ) ) {
+			if ( ! isset( $comment_data['_wp_unfiltered_html_comment'] )
+				|| ! wp_verify_nonce( $comment_data['_wp_unfiltered_html_comment'], 'unfiltered-html-comment_' . $comment_post_ID )
+			) {
+				kses_remove_filters(); // start with a clean slate
+				kses_init_filters(); // set up the filters
+			}
+		}
+	} else {
+		if ( get_option( 'comment_registration' ) ) {
+			return new WP_Error( 'not_logged_in', __( 'Sorry, you must be logged in to comment.' ), 403 );
+		}
+	}
+
+	$comment_type = '';
+
+	if ( get_option( 'require_name_email' ) && ! $user->exists() ) {
+		if ( '' == $comment_author_email || '' == $comment_author ) {
+			return new WP_Error( 'require_name_email', __( '<strong>ERROR</strong>: please fill the required fields (name, email).' ), 200 );
+		} elseif ( ! is_email( $comment_author_email ) ) {
+			return new WP_Error( 'require_valid_email', __( '<strong>ERROR</strong>: please enter a valid email address.' ), 200 );
+		}
+	}
+
+	if ( '' == $comment_content ) {
+		return new WP_Error( 'require_valid_comment', __( '<strong>ERROR</strong>: please type a comment.' ), 200 );
+	}
+
+	$commentdata = compact(
+		'comment_post_ID',
+		'comment_author',
+		'comment_author_email',
+		'comment_author_url',
+		'comment_content',
+		'comment_type',
+		'comment_parent',
+		'user_ID'
+	);
+
+	$check_max_lengths = wp_check_comment_data_max_lengths( $commentdata );
+	if ( is_wp_error( $check_max_lengths ) ) {
+		return $check_max_lengths;
+	}
+
+	$comment_id = wp_new_comment( wp_slash( $commentdata ), true );
+	if ( is_wp_error( $comment_id ) ) {
+		return $comment_id;
+	}
+
+	if ( ! $comment_id ) {
+		return new WP_Error( 'comment_save_error', __( '<strong>ERROR</strong>: The comment could not be saved. Please try again later.' ), 500 );
+	}
+
+	return get_comment( $comment_id );
+}
+
+/**
+ * Registers the personal data exporter for comments.
+ *
+ * @since 4.9.6
+ *
+ * @param array $exporters An array of personal data exporters.
+ * @return array $exporters An array of personal data exporters.
+ */
+function wp_register_comment_personal_data_exporter( $exporters ) {
+	$exporters['wordpress-comments'] = array(
+		'exporter_friendly_name' => __( 'WordPress Comments' ),
+		'callback'               => 'wp_comments_personal_data_exporter',
+	);
+
+	return $exporters;
+}
+
+/**
+ * Finds and exports personal data associated with an email address from the comments table.
+ *
+ * @since 4.9.6
+ *
+ * @param string $email_address The comment author email address.
+ * @param int    $page          Comment page.
+ * @return array $return An array of personal data.
+ */
+function wp_comments_personal_data_exporter( $email_address, $page = 1 ) {
+	// Limit us to 500 comments at a time to avoid timing out.
+	$number = 500;
+	$page   = (int) $page;
+
+	$data_to_export = array();
+
+	$comments = get_comments(
+		array(
+			'author_email'              => $email_address,
+			'number'                    => $number,
+			'paged'                     => $page,
+			'order_by'                  => 'comment_ID',
+			'order'                     => 'ASC',
+			'update_comment_meta_cache' => false,
+		)
+	);
+
+	$comment_prop_to_export = array(
+		'comment_author'       => __( 'Comment Author' ),
+		'comment_author_email' => __( 'Comment Author Email' ),
+		'comment_author_url'   => __( 'Comment Author URL' ),
+		'comment_author_IP'    => __( 'Comment Author IP' ),
+		'comment_agent'        => __( 'Comment Author User Agent' ),
+		'comment_date'         => __( 'Comment Date' ),
+		'comment_content'      => __( 'Comment Content' ),
+		'comment_link'         => __( 'Comment URL' ),
+	);
+
+	foreach ( (array) $comments as $comment ) {
+		$comment_data_to_export = array();
+
+		foreach ( $comment_prop_to_export as $key => $name ) {
+			$value = '';
+
+			switch ( $key ) {
+				case 'comment_author':
+				case 'comment_author_email':
+				case 'comment_author_url':
+				case 'comment_author_IP':
+				case 'comment_agent':
+				case 'comment_date':
+					$value = $comment->{$key};
+					break;
+
+				case 'comment_content':
+					$value = get_comment_text( $comment->comment_ID );
+					break;
+
+				case 'comment_link':
+					$value = get_comment_link( $comment->comment_ID );
+					$value = sprintf(
+						'<a href="%s" target="_blank" rel="noreferrer noopener">%s</a>',
+						esc_url( $value ),
+						esc_html( $value )
+					);
+					break;
+			}
+
+			if ( ! empty( $value ) ) {
+				$comment_data_to_export[] = array(
+					'name'  => $name,
+					'value' => $value,
+				);
+			}
+		}
+
+		$data_to_export[] = array(
+			'group_id'    => 'comments',
+			'group_label' => __( 'Comments' ),
+			'item_id'     => "comment-{$comment->comment_ID}",
+			'data'        => $comment_data_to_export,
+		);
+	}
+
+	$done = count( $comments ) < $number;
+
+	return array(
+		'data' => $data_to_export,
+		'done' => $done,
+	);
+}
+
+/**
+ * Registers the personal data eraser for comments.
+ *
+ * @since 4.9.6
+ *
+ * @param  array $erasers An array of personal data erasers.
+ * @return array $erasers An array of personal data erasers.
+ */
+function wp_register_comment_personal_data_eraser( $erasers ) {
+	$erasers['wordpress-comments'] = array(
+		'eraser_friendly_name' => __( 'WordPress Comments' ),
+		'callback'             => 'wp_comments_personal_data_eraser',
+	);
+
+	return $erasers;
+}
+
+/**
+ * Erases personal data associated with an email address from the comments table.
+ *
+ * @since 4.9.6
+ *
+ * @param  string $email_address The comment author email address.
+ * @param  int    $page          Comment page.
+ * @return array
+ */
+function wp_comments_personal_data_eraser( $email_address, $page = 1 ) {
+	global $wpdb;
+
+	if ( empty( $email_address ) ) {
+		return array(
+			'items_removed'  => false,
+			'items_retained' => false,
+			'messages'       => array(),
+			'done'           => true,
+		);
+	}
+
+	// Limit us to 500 comments at a time to avoid timing out.
+	$number         = 500;
+	$page           = (int) $page;
+	$items_removed  = false;
+	$items_retained = false;
+
+	$comments = get_comments(
+		array(
+			'author_email'       => $email_address,
+			'number'             => $number,
+			'paged'              => $page,
+			'order_by'           => 'comment_ID',
+			'order'              => 'ASC',
+			'include_unapproved' => true,
+		)
+	);
+
+	/* translators: Name of a comment's author after being anonymized. */
+	$anon_author = __( 'Anonymous' );
+	$messages    = array();
+
+	foreach ( (array) $comments as $comment ) {
+		$anonymized_comment                         = array();
+		$anonymized_comment['comment_agent']        = '';
+		$anonymized_comment['comment_author']       = $anon_author;
+		$anonymized_comment['comment_author_email'] = '';
+		$anonymized_comment['comment_author_IP']    = wp_privacy_anonymize_data( 'ip', $comment->comment_author_IP );
+		$anonymized_comment['comment_author_url']   = '';
+		$anonymized_comment['user_id']              = 0;
+
+		$comment_id = (int) $comment->comment_ID;
+
+		/**
+		 * Filters whether to anonymize the comment.
+		 *
+		 * @since 4.9.6
+		 *
+		 * @param bool|string                    Whether to apply the comment anonymization (bool).
+		 *                                       Custom prevention message (string). Default true.
+		 * @param WP_Comment $comment            WP_Comment object.
+		 * @param array      $anonymized_comment Anonymized comment data.
+		 */
+		$anon_message = apply_filters( 'wp_anonymize_comment', true, $comment, $anonymized_comment );
+
+		if ( true !== $anon_message ) {
+			if ( $anon_message && is_string( $anon_message ) ) {
+				$messages[] = esc_html( $anon_message );
+			} else {
+				/* translators: %d: Comment ID */
+				$messages[] = sprintf( __( 'Comment %d contains personal data but could not be anonymized.' ), $comment_id );
+			}
+
+			$items_retained = true;
+
+			continue;
+		}
+
+		$args = array(
+			'comment_ID' => $comment_id,
+		);
+
+		$updated = $wpdb->update( $wpdb->comments, $anonymized_comment, $args );
+
+		if ( $updated ) {
+			$items_removed = true;
+			clean_comment_cache( $comment_id );
+		} else {
+			$items_retained = true;
+		}
+	}
+
+	$done = count( $comments ) < $number;
+
+	return array(
+		'items_removed'  => $items_removed,
+		'items_retained' => $items_retained,
+		'messages'       => $messages,
+		'done'           => $done,
+	);
+}