3 * Manages WordPress comments
10 * Check whether a comment passes internal checks to be allowed to add.
12 * If manual comment moderation is set in the administration, then all checks,
13 * regardless of their type and whitelist, will fail and the function will
16 * If the number of links exceeds the amount in the administration, then the
17 * check fails. If any of the parameter contents match the blacklist of words,
18 * then the check fails.
20 * If the comment author was approved before, then the comment is automatically
23 * If all checks pass, the function will return true.
27 * @global wpdb $wpdb WordPress database abstraction object.
29 * @param string $author Comment author name.
30 * @param string $email Comment author email.
31 * @param string $url Comment author URL.
32 * @param string $comment Content of the comment.
33 * @param string $user_ip Comment author IP address.
34 * @param string $user_agent Comment author User-Agent.
35 * @param string $comment_type Comment type, either user-submitted comment,
36 * trackback, or pingback.
37 * @return bool If all checks pass, true, otherwise false.
39 function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
42 // If manual moderation is enabled, skip all checks and return false.
43 if ( 1 == get_option('comment_moderation') )
46 /** This filter is documented in wp-includes/comment-template.php */
47 $comment = apply_filters( 'comment_text', $comment );
49 // Check for the number of external links if a max allowed number is set.
50 if ( $max_links = get_option( 'comment_max_links' ) ) {
51 $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out );
54 * Filter the maximum number of links allowed in a comment.
58 * @param int $num_links The number of links allowed.
59 * @param string $url Comment author's URL. Included in allowed links total.
61 $num_links = apply_filters( 'comment_max_links_url', $num_links, $url );
64 * If the number of links in the comment exceeds the allowed amount,
65 * fail the check by returning false.
67 if ( $num_links >= $max_links )
71 $mod_keys = trim(get_option('moderation_keys'));
73 // If moderation 'keys' (keywords) are set, process them.
74 if ( !empty($mod_keys) ) {
75 $words = explode("\n", $mod_keys );
77 foreach ( (array) $words as $word) {
85 * Do some escaping magic so that '#' (number of) characters in the spam
86 * words don't break things:
88 $word = preg_quote($word, '#');
91 * Check the comment fields for moderation keywords. If any are found,
92 * fail the check for the given field by returning false.
94 $pattern = "#$word#i";
95 if ( preg_match($pattern, $author) ) return false;
96 if ( preg_match($pattern, $email) ) return false;
97 if ( preg_match($pattern, $url) ) return false;
98 if ( preg_match($pattern, $comment) ) return false;
99 if ( preg_match($pattern, $user_ip) ) return false;
100 if ( preg_match($pattern, $user_agent) ) return false;
105 * Check if the option to approve comments by previously-approved authors is enabled.
107 * If it is enabled, check whether the comment author has a previously-approved comment,
108 * as well as whether there are any moderation keywords (if set) present in the author
109 * email address. If both checks pass, return true. Otherwise, return false.
111 if ( 1 == get_option('comment_whitelist')) {
112 if ( 'trackback' != $comment_type && 'pingback' != $comment_type && $author != '' && $email != '' ) {
113 // expected_slashed ($author, $email)
114 $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");
115 if ( ( 1 == $ok_to_comment ) &&
116 ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
128 * Retrieve the approved comments for post $post_id.
131 * @since 4.1.0 Refactored to leverage {@see WP_Comment_Query} over a direct query.
133 * @param int $post_id The ID of the post.
134 * @param array $args Optional. See {@see WP_Comment_Query::query()} for information
135 * on accepted arguments.
136 * @return int|array $comments The approved comments, or number of comments if `$count`
139 function get_approved_comments( $post_id, $args = array() ) {
146 'post_id' => $post_id,
149 $r = wp_parse_args( $args, $defaults );
151 $query = new WP_Comment_Query;
152 return $query->query( $r );
156 * Retrieves comment data given a comment ID or comment object.
158 * If an object is passed then the comment data will be cached and then returned
159 * after being passed through a filter. If the comment is empty, then the global
160 * comment variable will be used, if it is set.
164 * @global wpdb $wpdb WordPress database abstraction object.
166 * @param object|string|int $comment Comment to retrieve.
167 * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
168 * @return object|array|null Depends on $output value.
170 function get_comment(&$comment, $output = OBJECT) {
173 if ( empty($comment) ) {
174 if ( isset($GLOBALS['comment']) )
175 $_comment = & $GLOBALS['comment'];
178 } elseif ( is_object($comment) ) {
179 wp_cache_add($comment->comment_ID, $comment, 'comment');
180 $_comment = $comment;
182 if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
183 $_comment = & $GLOBALS['comment'];
184 } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
185 $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
188 wp_cache_add($_comment->comment_ID, $_comment, 'comment');
193 * Fires after a comment is retrieved.
197 * @param mixed $_comment Comment data.
199 $_comment = apply_filters( 'get_comment', $_comment );
201 if ( $output == OBJECT ) {
203 } elseif ( $output == ARRAY_A ) {
204 $__comment = get_object_vars($_comment);
206 } elseif ( $output == ARRAY_N ) {
207 $__comment = array_values(get_object_vars($_comment));
215 * Retrieve a list of comments.
217 * The comment list can be for the blog as a whole or for an individual post.
221 * @param string|array $args Optional. Array or string of arguments. See {@see WP_Comment_Query::parse_query()}
222 * for information on accepted arguments. Default empty.
223 * @return int|array List of comments or number of found comments if `$count` argument is true.
225 function get_comments( $args = '' ) {
226 $query = new WP_Comment_Query;
227 return $query->query( $args );
231 * WordPress Comment Query class.
233 * See WP_Comment_Query::__construct() for accepted arguments.
237 class WP_Comment_Query {
239 * SQL for database query.
248 * Metadata query container
252 * @var object WP_Meta_Query
254 public $meta_query = false;
257 * Date query container
261 * @var object WP_Date_Query
263 public $date_query = false;
266 * Query vars set by the user.
275 * Default values for query vars.
281 public $query_var_defaults;
284 * List of comments located by the query.
293 * Make private/protected methods readable for backwards compatibility.
298 * @param callable $name Method to call.
299 * @param array $arguments Arguments to pass when calling.
300 * @return mixed|bool Return value of the callback, false otherwise.
302 public function __call( $name, $arguments ) {
303 if ( 'get_search_sql' === $name ) {
304 return call_user_func_array( array( $this, $name ), $arguments );
312 * Sets up the comment query, based on the query vars passed.
317 * @param string|array $query {
318 * Optional. Array or query string of comment query parameters. Default empty.
320 * @type string $author_email Comment author email address. Default empty.
321 * @type array $author__in Array of author IDs to include comments for. Default empty.
322 * @type array $author__not_in Array of author IDs to exclude comments for. Default empty.
323 * @type array $comment__in Array of comment IDs to include. Default empty.
324 * @type array $comment__not_in Array of comment IDs to exclude. Default empty.
325 * @type bool $count Whether to return a comment count (true) or array of comment
326 * objects (false). Default false.
327 * @type array $date_query Date query clauses to limit comments by. See WP_Date_Query.
329 * @type string $fields Comment fields to return. Accepts 'ids' for comment IDs only or
330 * empty for all fields. Default empty.
331 * @type int $ID Currently unused.
332 * @type array $include_unapproved Array of IDs or email addresses of users whose unapproved comments
333 * will be returned by the query regardless of `$status`. Default empty.
334 * @type int $karma Karma score to retrieve matching comments for. Default empty.
335 * @type string $meta_key Include comments with a matching comment meta key. Default empty.
336 * @type string $meta_value Include comments with a matching comment meta value. Requires
337 * `$meta_key` to be set. Default empty.
338 * @type array $meta_query Meta query clauses to limit retrieved comments by.
339 * See WP_Meta_Query. Default empty.
340 * @type int $number Maximum number of comments to retrieve. Default null (no limit).
341 * @type int $offset Number of comments to offset the query. Used to build LIMIT clause.
343 * @type string|array $orderby Comment status or array of statuses. To use 'meta_value' or
344 * 'meta_value_num', `$meta_key` must also be defined. To sort by
345 * a specific `$meta_query` clause, use that clause's array key.
346 * Accepts 'comment_agent', 'comment_approved', 'comment_author',
347 * 'comment_author_email', 'comment_author_IP',
348 * 'comment_author_url', 'comment_content', 'comment_date',
349 * 'comment_date_gmt', 'comment_ID', 'comment_karma',
350 * 'comment_parent', 'comment_post_ID', 'comment_type', 'user_id',
351 * 'meta_value', 'meta_value_num', the value of $meta_key, and the
352 * array keys of `$meta_query`. Also accepts false, an empty array,
353 * or 'none' to disable `ORDER BY` clause.
354 * Default: 'comment_date_gmt'.
355 * @type string $order How to order retrieved comments. Accepts 'ASC', 'DESC'.
357 * @type int $parent Parent ID of comment to retrieve children of. Default empty.
358 * @type array $post_author__in Array of author IDs to retrieve comments for. Default empty.
359 * @type array $post_author__not_in Array of author IDs *not* to retrieve comments for. Default empty.
360 * @type int $post_ID Currently unused.
361 * @type int $post_id Limit results to those affiliated with a given post ID. Default 0.
362 * @type array $post__in Array of post IDs to include affiliated comments for. Default empty.
363 * @type array $post__not_in Array of post IDs to exclude affiliated comments for. Default empty.
364 * @type int $post_author Comment author ID to limit results by. Default empty.
365 * @type string $post_status Post status to retrieve affiliated comments for. Default empty.
366 * @type string $post_type Post type to retrieve affiliated comments for. Default empty.
367 * @type string $post_name Post name to retrieve affiliated comments for. Default empty.
368 * @type int $post_parent Post parent ID to retrieve affiliated comments for. Default empty.
369 * @type string $search Search term(s) to retrieve matching comments for. Default empty.
370 * @type string $status Comment status to limit results by. Accepts 'hold'
371 * (`comment_status=0`), 'approve' (`comment_status=1`), 'all', or a
372 * custom comment status. Default 'all'.
373 * @type string|array $type Include comments of a given type, or array of types. Accepts
374 * 'comment', 'pings' (includes 'pingback' and 'trackback'), or any
375 * custom type string. Default empty.
376 * @type array $type__in Include comments from a given array of comment types. Default empty.
377 * @type array $type__not_in Exclude comments from a given array of comment types. Default empty.
378 * @type int $user_id Include comments for a specific user ID. Default empty.
380 * @return WP_Comment_Query WP_Comment_Query instance.
382 public function __construct( $query = '' ) {
383 $this->query_var_defaults = array(
384 'author_email' => '',
386 'author__not_in' => '',
387 'include_unapproved' => '',
391 'comment__not_in' => '',
398 'post_author__in' => '',
399 'post_author__not_in' => '',
403 'post__not_in' => '',
412 'type__not_in' => '',
419 'date_query' => null, // See WP_Date_Query
422 if ( ! empty( $query ) ) {
423 $this->query( $query );
428 * Parse arguments passed to the comment query with default query parameters.
430 * @since 4.2.0 Extracted from WP_Comment_Query::query().
434 * @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct()
436 public function parse_query( $query = '' ) {
437 if ( empty( $query ) ) {
438 $query = $this->query_vars;
441 $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
442 do_action_ref_array( 'parse_comment_query', array( &$this ) );
446 * Sets up the WordPress query for retrieving comments.
449 * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in',
450 * 'post_author__not_in', 'author__in', 'author__not_in', 'post__in',
451 * 'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in'
452 * arguments to $query_vars.
453 * @since 4.2.0 Moved parsing to WP_Comment_Query::parse_query().
456 * @param string|array $query Array or URL query string of parameters.
457 * @return array List of comments.
459 public function query( $query ) {
460 $this->query_vars = wp_parse_args( $query );
461 return $this->get_comments();
465 * Get a list of comments matching the query vars.
470 * @global wpdb $wpdb WordPress database abstraction object.
472 * @return array The list of comments.
474 public function get_comments() {
479 $this->parse_query();
482 $this->meta_query = new WP_Meta_Query();
483 $this->meta_query->parse_query_vars( $this->query_vars );
485 if ( ! empty( $this->meta_query->queries ) ) {
486 $meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
490 * Fires before comments are retrieved.
494 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
496 do_action_ref_array( 'pre_get_comments', array( &$this ) );
498 // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
499 $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
500 $last_changed = wp_cache_get( 'last_changed', 'comment' );
501 if ( ! $last_changed ) {
502 $last_changed = microtime();
503 wp_cache_set( 'last_changed', $last_changed, 'comment' );
505 $cache_key = "get_comments:$key:$last_changed";
507 if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) {
508 $this->comments = $cache;
509 return $this->comments;
514 // Assemble clauses related to 'comment_approved'.
515 $approved_clauses = array();
517 // 'status' accepts an array or a comma-separated string.
518 $status_clauses = array();
519 $statuses = $this->query_vars['status'];
520 if ( ! is_array( $statuses ) ) {
521 $statuses = preg_split( '/[\s,]+/', $statuses );
524 // 'any' overrides other statuses.
525 if ( ! in_array( 'any', $statuses ) ) {
526 foreach ( $statuses as $status ) {
529 $status_clauses[] = "comment_approved = '0'";
533 $status_clauses[] = "comment_approved = '1'";
538 $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
542 $status_clauses[] = $wpdb->prepare( "comment_approved = %s", $status );
547 if ( ! empty( $status_clauses ) ) {
548 $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
552 // User IDs or emails whose unapproved comments are included, regardless of $status.
553 if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
554 $include_unapproved = $this->query_vars['include_unapproved'];
556 // Accepts arrays or comma-separated strings.
557 if ( ! is_array( $include_unapproved ) ) {
558 $include_unapproved = preg_split( '/[\s,]+/', $include_unapproved );
561 $unapproved_ids = $unapproved_emails = array();
562 foreach ( $include_unapproved as $unapproved_identifier ) {
563 // Numeric values are assumed to be user ids.
564 if ( is_numeric( $unapproved_identifier ) ) {
565 $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
567 // Otherwise we match against email addresses.
569 $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
574 // Collapse comment_approved clauses into a single OR-separated clause.
575 if ( ! empty( $approved_clauses ) ) {
576 if ( 1 === count( $approved_clauses ) ) {
577 $where[] = $approved_clauses[0];
579 $where[] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
583 $order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
585 // Disable ORDER BY with 'none', an empty array, or boolean false.
586 if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
588 } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
589 $ordersby = is_array( $this->query_vars['orderby'] ) ?
590 $this->query_vars['orderby'] :
591 preg_split( '/[,\s]/', $this->query_vars['orderby'] );
593 $orderby_array = array();
594 $found_orderby_comment_ID = false;
595 foreach ( $ordersby as $_key => $_value ) {
600 if ( is_int( $_key ) ) {
608 if ( ! $found_orderby_comment_ID && 'comment_ID' === $_orderby ) {
609 $found_orderby_comment_ID = true;
612 $parsed = $this->parse_orderby( $_orderby );
618 $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
621 // If no valid clauses were found, order by comment_date_gmt.
622 if ( empty( $orderby_array ) ) {
623 $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
626 // To ensure determinate sorting, always include a comment_ID clause.
627 if ( ! $found_orderby_comment_ID ) {
628 $comment_ID_order = '';
630 // Inherit order from comment_date or comment_date_gmt, if available.
631 foreach ( $orderby_array as $orderby_clause ) {
632 if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
633 $comment_ID_order = $match[1];
638 // If no date-related order is available, use the date from the first available clause.
639 if ( ! $comment_ID_order ) {
640 foreach ( $orderby_array as $orderby_clause ) {
641 if ( false !== strpos( 'ASC', $orderby_clause ) ) {
642 $comment_ID_order = 'ASC';
644 $comment_ID_order = 'DESC';
652 if ( ! $comment_ID_order ) {
653 $comment_ID_order = 'DESC';
656 $orderby_array[] = "$wpdb->comments.comment_ID $comment_ID_order";
659 $orderby = implode( ', ', $orderby_array );
661 $orderby = "$wpdb->comments.comment_date_gmt $order";
664 $number = absint( $this->query_vars['number'] );
665 $offset = absint( $this->query_vars['offset'] );
667 if ( ! empty( $number ) ) {
669 $limits = 'LIMIT ' . $offset . ',' . $number;
671 $limits = 'LIMIT ' . $number;
677 if ( $this->query_vars['count'] ) {
678 $fields = 'COUNT(*)';
680 switch ( strtolower( $this->query_vars['fields'] ) ) {
682 $fields = "$wpdb->comments.comment_ID";
692 $post_id = absint( $this->query_vars['post_id'] );
693 if ( ! empty( $post_id ) ) {
694 $where[] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
697 // Parse comment IDs for an IN clause.
698 if ( ! empty( $this->query_vars['comment__in'] ) ) {
699 $where[] = 'comment_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
702 // Parse comment IDs for a NOT IN clause.
703 if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
704 $where[] = 'comment_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
707 // Parse comment post IDs for an IN clause.
708 if ( ! empty( $this->query_vars['post__in'] ) ) {
709 $where[] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
712 // Parse comment post IDs for a NOT IN clause.
713 if ( ! empty( $this->query_vars['post__not_in'] ) ) {
714 $where[] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
717 if ( '' !== $this->query_vars['author_email'] ) {
718 $where[] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
721 if ( '' !== $this->query_vars['karma'] ) {
722 $where[] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
725 // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
727 'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
728 'NOT IN' => (array) $this->query_vars['type__not_in'],
731 $comment_types = array();
732 foreach ( $raw_types as $operator => $_raw_types ) {
733 $_raw_types = array_unique( $_raw_types );
735 foreach ( $_raw_types as $type ) {
737 // An empty translates to 'all', for backward compatibility
744 $comment_types[ $operator ][] = "''";
748 $comment_types[ $operator ][] = "'pingback'";
749 $comment_types[ $operator ][] = "'trackback'";
753 $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
758 if ( ! empty( $comment_types[ $operator ] ) ) {
759 $types_sql = implode( ', ', $comment_types[ $operator ] );
760 $where[] = "comment_type $operator ($types_sql)";
764 if ( '' !== $this->query_vars['parent'] ) {
765 $where[] = $wpdb->prepare( 'comment_parent = %d', $this->query_vars['parent'] );
768 if ( is_array( $this->query_vars['user_id'] ) ) {
769 $where[] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
770 } elseif ( '' !== $this->query_vars['user_id'] ) {
771 $where[] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
774 if ( '' !== $this->query_vars['search'] ) {
775 $search_sql = $this->get_search_sql(
776 $this->query_vars['search'],
777 array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
780 // Strip leading 'AND'.
781 $where[] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
784 // If any post-related query vars are passed, join the posts table.
785 $join_posts_table = false;
786 $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type' ) );
787 $post_fields = array_filter( $plucked );
789 if ( ! empty( $post_fields ) ) {
790 $join_posts_table = true;
791 foreach ( $post_fields as $field_name => $field_value ) {
792 // $field_value may be an array.
793 $esses = array_fill( 0, count( (array) $field_value ), '%s' );
794 $where[] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
798 // Comment author IDs for an IN clause.
799 if ( ! empty( $this->query_vars['author__in'] ) ) {
800 $where[] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
803 // Comment author IDs for a NOT IN clause.
804 if ( ! empty( $this->query_vars['author__not_in'] ) ) {
805 $where[] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
808 // Post author IDs for an IN clause.
809 if ( ! empty( $this->query_vars['post_author__in'] ) ) {
810 $join_posts_table = true;
811 $where[] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
814 // Post author IDs for a NOT IN clause.
815 if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
816 $join_posts_table = true;
817 $where[] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
820 if ( $join_posts_table ) {
821 $join = "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
824 if ( ! empty( $meta_query_clauses ) ) {
825 $join .= $meta_query_clauses['join'];
827 // Strip leading 'AND'.
828 $where[] = preg_replace( '/^\s*AND\s*/', '', $meta_query_clauses['where'] );
830 if ( ! $this->query_vars['count'] ) {
831 $groupby = "{$wpdb->comments}.comment_ID";
835 $date_query = $this->query_vars['date_query'];
836 if ( ! empty( $date_query ) && is_array( $date_query ) ) {
837 $date_query_object = new WP_Date_Query( $date_query, 'comment_date' );
838 $where[] = preg_replace( '/^\s*AND\s*/', '', $date_query_object->get_sql() );
841 $where = implode( ' AND ', $where );
843 $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
845 * Filter the comment query clauses.
849 * @param array $pieces A compacted array of comment query clauses.
850 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
852 $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
854 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
855 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
856 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
857 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
858 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
859 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
862 $where = 'WHERE ' . $where;
866 $groupby = 'GROUP BY ' . $groupby;
870 $orderby = "ORDER BY $orderby";
873 $this->request = "SELECT $fields FROM $wpdb->comments $join $where $groupby $orderby $limits";
875 if ( $this->query_vars['count'] ) {
876 return $wpdb->get_var( $this->request );
879 if ( 'ids' == $this->query_vars['fields'] ) {
880 $this->comments = $wpdb->get_col( $this->request );
881 return array_map( 'intval', $this->comments );
884 $results = $wpdb->get_results( $this->request );
886 * Filter the comment query results.
890 * @param array $results An array of comments.
891 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
893 $comments = apply_filters_ref_array( 'the_comments', array( $results, &$this ) );
895 wp_cache_add( $cache_key, $comments, 'comment' );
897 $this->comments = $comments;
898 return $this->comments;
902 * Used internally to generate an SQL string for searching across multiple columns
907 * @param string $string
911 protected function get_search_sql( $string, $cols ) {
914 $like = '%' . $wpdb->esc_like( $string ) . '%';
917 foreach ( $cols as $col ) {
918 $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
921 return ' AND (' . implode(' OR ', $searches) . ')';
925 * Parse and sanitize 'orderby' keys passed to the comment query.
930 * @global wpdb $wpdb WordPress database abstraction object.
932 * @param string $orderby Alias for the field to order by.
933 * @return string|bool Value to used in the ORDER clause. False otherwise.
935 protected function parse_orderby( $orderby ) {
938 $allowed_keys = array(
942 'comment_author_email',
944 'comment_author_url',
956 if ( ! empty( $this->query_vars['meta_key'] ) ) {
957 $allowed_keys[] = $this->query_vars['meta_key'];
958 $allowed_keys[] = 'meta_value';
959 $allowed_keys[] = 'meta_value_num';
962 $meta_query_clauses = $this->meta_query->get_clauses();
963 if ( $meta_query_clauses ) {
964 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
968 if ( $orderby == $this->query_vars['meta_key'] || $orderby == 'meta_value' ) {
969 $parsed = "$wpdb->commentmeta.meta_value";
970 } else if ( $orderby == 'meta_value_num' ) {
971 $parsed = "$wpdb->commentmeta.meta_value+0";
972 } else if ( in_array( $orderby, $allowed_keys ) ) {
974 if ( isset( $meta_query_clauses[ $orderby ] ) ) {
975 $meta_clause = $meta_query_clauses[ $orderby ];
976 $parsed = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
978 $parsed = "$wpdb->comments.$orderby";
986 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
991 * @param string $order The 'order' query variable.
992 * @return string The sanitized 'order' query variable.
994 protected function parse_order( $order ) {
995 if ( ! is_string( $order ) || empty( $order ) ) {
999 if ( 'ASC' === strtoupper( $order ) ) {
1008 * Retrieve all of the WordPress supported comment statuses.
1010 * Comments have a limited set of valid status values, this provides the comment
1011 * status values and descriptions.
1015 * @return array List of comment statuses.
1017 function get_comment_statuses() {
1019 'hold' => __('Unapproved'),
1020 /* translators: comment status */
1021 'approve' => _x('Approved', 'adjective'),
1022 /* translators: comment status */
1023 'spam' => _x('Spam', 'adjective'),
1030 * The date the last comment was modified.
1034 * @global wpdb $wpdb WordPress database abstraction object.
1036 * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
1037 * or 'server' locations.
1038 * @return string Last comment modified date.
1040 function get_lastcommentmodified($timezone = 'server') {
1042 static $cache_lastcommentmodified = array();
1044 if ( isset($cache_lastcommentmodified[$timezone]) )
1045 return $cache_lastcommentmodified[$timezone];
1047 $add_seconds_server = date('Z');
1049 switch ( strtolower($timezone)) {
1051 $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
1054 $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
1057 $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));
1061 $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
1063 return $lastcommentmodified;
1067 * The amount of comments in a post or total comments.
1069 * A lot like {@link wp_count_comments()}, in that they both return comment
1070 * stats (albeit with different types). The {@link wp_count_comments()} actual
1071 * caches, but this function does not.
1075 * @global wpdb $wpdb WordPress database abstraction object.
1077 * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
1078 * @return array The amount of spam, approved, awaiting moderation, and total comments.
1080 function get_comment_count( $post_id = 0 ) {
1083 $post_id = (int) $post_id;
1086 if ( $post_id > 0 ) {
1087 $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
1090 $totals = (array) $wpdb->get_results("
1091 SELECT comment_approved, COUNT( * ) AS total
1092 FROM {$wpdb->comments}
1094 GROUP BY comment_approved
1097 $comment_count = array(
1099 "awaiting_moderation" => 0,
1101 "total_comments" => 0
1104 foreach ( $totals as $row ) {
1105 switch ( $row['comment_approved'] ) {
1107 $comment_count['spam'] = $row['total'];
1108 $comment_count["total_comments"] += $row['total'];
1111 $comment_count['approved'] = $row['total'];
1112 $comment_count['total_comments'] += $row['total'];
1115 $comment_count['awaiting_moderation'] = $row['total'];
1116 $comment_count['total_comments'] += $row['total'];
1123 return $comment_count;
1127 // Comment meta functions
1131 * Add meta data field to a comment.
1134 * @link https://codex.wordpress.org/Function_Reference/add_comment_meta
1136 * @param int $comment_id Comment ID.
1137 * @param string $meta_key Metadata name.
1138 * @param mixed $meta_value Metadata value.
1139 * @param bool $unique Optional, default is false. Whether the same key should not be added.
1140 * @return int|bool Meta ID on success, false on failure.
1142 function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
1143 return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
1147 * Remove metadata matching criteria from a comment.
1149 * You can match based on the key, or key and value. Removing based on key and
1150 * value, will keep from removing duplicate metadata with the same key. It also
1151 * allows removing all metadata matching key, if needed.
1154 * @link https://codex.wordpress.org/Function_Reference/delete_comment_meta
1156 * @param int $comment_id comment ID
1157 * @param string $meta_key Metadata name.
1158 * @param mixed $meta_value Optional. Metadata value.
1159 * @return bool True on success, false on failure.
1161 function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
1162 return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
1166 * Retrieve comment meta field for a comment.
1169 * @link https://codex.wordpress.org/Function_Reference/get_comment_meta
1171 * @param int $comment_id Comment ID.
1172 * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
1173 * @param bool $single Whether to return a single value.
1174 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
1177 function get_comment_meta($comment_id, $key = '', $single = false) {
1178 return get_metadata('comment', $comment_id, $key, $single);
1182 * Update comment meta field based on comment ID.
1184 * Use the $prev_value parameter to differentiate between meta fields with the
1185 * same key and comment ID.
1187 * If the meta field for the comment does not exist, it will be added.
1190 * @link https://codex.wordpress.org/Function_Reference/update_comment_meta
1192 * @param int $comment_id Comment ID.
1193 * @param string $meta_key Metadata key.
1194 * @param mixed $meta_value Metadata value.
1195 * @param mixed $prev_value Optional. Previous value to check before removing.
1196 * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
1198 function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
1199 return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
1203 * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
1204 * to recall previous comments by this commentator that are still held in moderation.
1206 * @param object $comment Comment object.
1207 * @param object $user Comment author's object.
1211 function wp_set_comment_cookies($comment, $user) {
1212 if ( $user->exists() )
1216 * Filter the lifetime of the comment cookie in seconds.
1220 * @param int $seconds Comment cookie lifetime. Default 30000000.
1222 $comment_cookie_lifetime = apply_filters( 'comment_cookie_lifetime', 30000000 );
1223 $secure = ( 'https' === parse_url( home_url(), PHP_URL_SCHEME ) );
1224 setcookie( 'comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
1225 setcookie( 'comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
1226 setcookie( 'comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
1230 * Sanitizes the cookies sent to the user already.
1232 * Will only do anything if the cookies have already been created for the user.
1233 * Mostly used after cookies had been sent to use elsewhere.
1237 function sanitize_comment_cookies() {
1238 if ( isset( $_COOKIE['comment_author_' . COOKIEHASH] ) ) {
1240 * Filter the comment author's name cookie before it is set.
1242 * When this filter hook is evaluated in wp_filter_comment(),
1243 * the comment author's name string is passed.
1247 * @param string $author_cookie The comment author name cookie.
1249 $comment_author = apply_filters( 'pre_comment_author_name', $_COOKIE['comment_author_' . COOKIEHASH] );
1250 $comment_author = wp_unslash($comment_author);
1251 $comment_author = esc_attr($comment_author);
1252 $_COOKIE['comment_author_' . COOKIEHASH] = $comment_author;
1255 if ( isset( $_COOKIE['comment_author_email_' . COOKIEHASH] ) ) {
1257 * Filter the comment author's email cookie before it is set.
1259 * When this filter hook is evaluated in wp_filter_comment(),
1260 * the comment author's email string is passed.
1264 * @param string $author_email_cookie The comment author email cookie.
1266 $comment_author_email = apply_filters( 'pre_comment_author_email', $_COOKIE['comment_author_email_' . COOKIEHASH] );
1267 $comment_author_email = wp_unslash($comment_author_email);
1268 $comment_author_email = esc_attr($comment_author_email);
1269 $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
1272 if ( isset( $_COOKIE['comment_author_url_' . COOKIEHASH] ) ) {
1274 * Filter the comment author's URL cookie before it is set.
1276 * When this filter hook is evaluated in wp_filter_comment(),
1277 * the comment author's URL string is passed.
1281 * @param string $author_url_cookie The comment author URL cookie.
1283 $comment_author_url = apply_filters( 'pre_comment_author_url', $_COOKIE['comment_author_url_' . COOKIEHASH] );
1284 $comment_author_url = wp_unslash($comment_author_url);
1285 $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
1290 * Validates whether this comment is allowed to be made.
1294 * @global wpdb $wpdb WordPress database abstraction object.
1296 * @param array $commentdata Contains information on the comment
1297 * @return mixed Signifies the approval status (0|1|'spam')
1299 function wp_allow_comment( $commentdata ) {
1302 // Simple duplicate check
1303 // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
1304 $dupe = $wpdb->prepare(
1305 "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ",
1306 wp_unslash( $commentdata['comment_post_ID'] ),
1307 wp_unslash( $commentdata['comment_parent'] ),
1308 wp_unslash( $commentdata['comment_author'] )
1310 if ( $commentdata['comment_author_email'] ) {
1311 $dupe .= $wpdb->prepare(
1312 "OR comment_author_email = %s ",
1313 wp_unslash( $commentdata['comment_author_email'] )
1316 $dupe .= $wpdb->prepare(
1317 ") AND comment_content = %s LIMIT 1",
1318 wp_unslash( $commentdata['comment_content'] )
1320 if ( $wpdb->get_var( $dupe ) ) {
1322 * Fires immediately after a duplicate comment is detected.
1326 * @param array $commentdata Comment data.
1328 do_action( 'comment_duplicate_trigger', $commentdata );
1329 if ( defined( 'DOING_AJAX' ) ) {
1330 die( __('Duplicate comment detected; it looks as though you’ve already said that!') );
1332 wp_die( __( 'Duplicate comment detected; it looks as though you’ve already said that!' ), 409 );
1336 * Fires immediately before a comment is marked approved.
1338 * Allows checking for comment flooding.
1342 * @param string $comment_author_IP Comment author's IP address.
1343 * @param string $comment_author_email Comment author's email.
1344 * @param string $comment_date_gmt GMT date the comment was posted.
1347 'check_comment_flood',
1348 $commentdata['comment_author_IP'],
1349 $commentdata['comment_author_email'],
1350 $commentdata['comment_date_gmt']
1353 if ( ! empty( $commentdata['user_id'] ) ) {
1354 $user = get_userdata( $commentdata['user_id'] );
1355 $post_author = $wpdb->get_var( $wpdb->prepare(
1356 "SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1",
1357 $commentdata['comment_post_ID']
1361 if ( isset( $user ) && ( $commentdata['user_id'] == $post_author || $user->has_cap( 'moderate_comments' ) ) ) {
1362 // The author and the admins get respect.
1365 // Everyone else's comments will be checked.
1367 $commentdata['comment_author'],
1368 $commentdata['comment_author_email'],
1369 $commentdata['comment_author_url'],
1370 $commentdata['comment_content'],
1371 $commentdata['comment_author_IP'],
1372 $commentdata['comment_agent'],
1373 $commentdata['comment_type']
1380 if ( wp_blacklist_check(
1381 $commentdata['comment_author'],
1382 $commentdata['comment_author_email'],
1383 $commentdata['comment_author_url'],
1384 $commentdata['comment_content'],
1385 $commentdata['comment_author_IP'],
1386 $commentdata['comment_agent']
1393 * Filter a comment's approval status before it is set.
1397 * @param bool|string $approved The approval status. Accepts 1, 0, or 'spam'.
1398 * @param array $commentdata Comment data.
1400 $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
1405 * Check whether comment flooding is occurring.
1407 * Won't run, if current user can manage options, so to not block
1412 * @global wpdb $wpdb WordPress database abstraction object.
1414 * @param string $ip Comment IP.
1415 * @param string $email Comment author email address.
1416 * @param string $date MySQL time string.
1418 function check_comment_flood_db( $ip, $email, $date ) {
1420 if ( current_user_can( 'manage_options' ) )
1421 return; // don't throttle admins
1422 $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
1423 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 ) ) ) {
1424 $time_lastcomment = mysql2date('U', $lasttime, false);
1425 $time_newcomment = mysql2date('U', $date, false);
1427 * Filter the comment flood status.
1431 * @param bool $bool Whether a comment flood is occurring. Default false.
1432 * @param int $time_lastcomment Timestamp of when the last comment was posted.
1433 * @param int $time_newcomment Timestamp of when the new comment was posted.
1435 $flood_die = apply_filters( 'comment_flood_filter', false, $time_lastcomment, $time_newcomment );
1438 * Fires before the comment flood message is triggered.
1442 * @param int $time_lastcomment Timestamp of when the last comment was posted.
1443 * @param int $time_newcomment Timestamp of when the new comment was posted.
1445 do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment );
1447 if ( defined('DOING_AJAX') )
1448 die( __('You are posting comments too quickly. Slow down.') );
1450 wp_die( __( 'You are posting comments too quickly. Slow down.' ), 429 );
1456 * Separates an array of comments into an array keyed by comment_type.
1460 * @param array $comments Array of comments
1461 * @return array Array of comments keyed by comment_type.
1463 function separate_comments(&$comments) {
1464 $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
1465 $count = count($comments);
1466 for ( $i = 0; $i < $count; $i++ ) {
1467 $type = $comments[$i]->comment_type;
1470 $comments_by_type[$type][] = &$comments[$i];
1471 if ( 'trackback' == $type || 'pingback' == $type )
1472 $comments_by_type['pings'][] = &$comments[$i];
1475 return $comments_by_type;
1479 * Calculate the total number of comment pages.
1483 * @uses Walker_Comment
1485 * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
1486 * @param int $per_page Optional comments per page.
1487 * @param boolean $threaded Optional control over flat or threaded comments.
1488 * @return int Number of comment pages.
1490 function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
1493 if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
1494 return $wp_query->max_num_comment_pages;
1496 if ( ( ! $comments || ! is_array( $comments ) ) && ! empty( $wp_query->comments ) )
1497 $comments = $wp_query->comments;
1499 if ( empty($comments) )
1502 if ( ! get_option( 'page_comments' ) )
1505 if ( !isset($per_page) )
1506 $per_page = (int) get_query_var('comments_per_page');
1507 if ( 0 === $per_page )
1508 $per_page = (int) get_option('comments_per_page');
1509 if ( 0 === $per_page )
1512 if ( !isset($threaded) )
1513 $threaded = get_option('thread_comments');
1516 $walker = new Walker_Comment;
1517 $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
1519 $count = ceil( count( $comments ) / $per_page );
1526 * Calculate what page number a comment will appear on for comment paging.
1530 * @param int $comment_ID Comment ID.
1531 * @param array $args Optional args.
1532 * @return int|null Comment page number or null on error.
1534 function get_page_of_comment( $comment_ID, $args = array() ) {
1537 if ( !$comment = get_comment( $comment_ID ) )
1540 $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
1541 $args = wp_parse_args( $args, $defaults );
1543 if ( '' === $args['per_page'] && get_option('page_comments') )
1544 $args['per_page'] = get_query_var('comments_per_page');
1545 if ( empty($args['per_page']) ) {
1546 $args['per_page'] = 0;
1549 if ( $args['per_page'] < 1 )
1552 if ( '' === $args['max_depth'] ) {
1553 if ( get_option('thread_comments') )
1554 $args['max_depth'] = get_option('thread_comments_depth');
1556 $args['max_depth'] = -1;
1559 // Find this comment's top level parent if threading is enabled
1560 if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
1561 return get_page_of_comment( $comment->comment_parent, $args );
1563 $allowedtypes = array(
1565 'pingback' => 'pingback',
1566 'trackback' => 'trackback',
1569 $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
1571 // Count comments older than this one
1572 $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 ) );
1574 // No older comments? Then it's page #1.
1575 if ( 0 == $oldercoms )
1578 // Divide comments older than this one by comments per page to get this comment's page number
1579 return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
1583 * Does comment contain blacklisted characters or words.
1587 * @param string $author The author of the comment
1588 * @param string $email The email of the comment
1589 * @param string $url The url used in the comment
1590 * @param string $comment The comment content
1591 * @param string $user_ip The comment author IP address
1592 * @param string $user_agent The author's browser user agent
1593 * @return bool True if comment contains blacklisted content, false if comment does not
1595 function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
1597 * Fires before the comment is tested for blacklisted characters or words.
1601 * @param string $author Comment author.
1602 * @param string $email Comment author's email.
1603 * @param string $url Comment author's URL.
1604 * @param string $comment Comment content.
1605 * @param string $user_ip Comment author's IP address.
1606 * @param string $user_agent Comment author's browser user agent.
1608 do_action( 'wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent );
1610 $mod_keys = trim( get_option('blacklist_keys') );
1611 if ( '' == $mod_keys )
1612 return false; // If moderation keys are empty
1613 $words = explode("\n", $mod_keys );
1615 foreach ( (array) $words as $word ) {
1616 $word = trim($word);
1619 if ( empty($word) ) { continue; }
1621 // Do some escaping magic so that '#' chars in the
1622 // spam words don't break things:
1623 $word = preg_quote($word, '#');
1625 $pattern = "#$word#i";
1627 preg_match($pattern, $author)
1628 || preg_match($pattern, $email)
1629 || preg_match($pattern, $url)
1630 || preg_match($pattern, $comment)
1631 || preg_match($pattern, $user_ip)
1632 || preg_match($pattern, $user_agent)
1640 * Retrieve total comments for blog or single post.
1642 * The properties of the returned object contain the 'moderated', 'approved',
1643 * and spam comments for either the entire blog or single post. Those properties
1644 * contain the amount of comments that match the status. The 'total_comments'
1645 * property contains the integer of total comments.
1647 * The comment stats are cached and then retrieved, if they already exist in the
1652 * @param int $post_id Optional. Post ID.
1653 * @return object Comment stats.
1655 function wp_count_comments( $post_id = 0 ) {
1658 $post_id = (int) $post_id;
1661 * Filter the comments count for a given post.
1665 * @param array $count An empty array.
1666 * @param int $post_id The post ID.
1668 $stats = apply_filters( 'wp_count_comments', array(), $post_id );
1669 if ( !empty($stats) )
1672 $count = wp_cache_get("comments-{$post_id}", 'counts');
1674 if ( false !== $count )
1679 $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
1681 $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
1684 $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
1685 foreach ( (array) $count as $row ) {
1686 // Don't count post-trashed toward totals
1687 if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
1688 $total += $row['num_comments'];
1689 if ( isset( $approved[$row['comment_approved']] ) )
1690 $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
1693 $stats['total_comments'] = $total;
1694 foreach ( $approved as $key ) {
1695 if ( empty($stats[$key]) )
1699 $stats = (object) $stats;
1700 wp_cache_set("comments-{$post_id}", $stats, 'counts');
1706 * Trashes or deletes a comment.
1708 * The comment is moved to trash instead of permanently deleted unless trash is
1709 * disabled, item is already in the trash, or $force_delete is true.
1711 * The post comment count will be updated if the comment was approved and has a
1712 * post ID available.
1716 * @global wpdb $wpdb WordPress database abstraction object.
1718 * @param int $comment_id Comment ID
1719 * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
1720 * @return bool True on success, false on failure.
1722 function wp_delete_comment($comment_id, $force_delete = false) {
1724 if (!$comment = get_comment($comment_id))
1727 if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) )
1728 return wp_trash_comment($comment_id);
1731 * Fires immediately before a comment is deleted from the database.
1735 * @param int $comment_id The comment ID.
1737 do_action( 'delete_comment', $comment_id );
1739 // Move children up a level.
1740 $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
1741 if ( !empty($children) ) {
1742 $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
1743 clean_comment_cache($children);
1747 $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment_id ) );
1748 foreach ( $meta_ids as $mid )
1749 delete_metadata_by_mid( 'comment', $mid );
1751 if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment_id ) ) )
1755 * Fires immediately after a comment is deleted from the database.
1759 * @param int $comment_id The comment ID.
1761 do_action( 'deleted_comment', $comment_id );
1763 $post_id = $comment->comment_post_ID;
1764 if ( $post_id && $comment->comment_approved == 1 )
1765 wp_update_comment_count($post_id);
1767 clean_comment_cache($comment_id);
1769 /** This action is documented in wp-includes/comment.php */
1770 do_action( 'wp_set_comment_status', $comment_id, 'delete' );
1772 wp_transition_comment_status('delete', $comment->comment_approved, $comment);
1777 * Moves a comment to the Trash
1779 * If trash is disabled, comment is permanently deleted.
1783 * @param int $comment_id Comment ID.
1784 * @return bool True on success, false on failure.
1786 function wp_trash_comment($comment_id) {
1787 if ( !EMPTY_TRASH_DAYS )
1788 return wp_delete_comment($comment_id, true);
1790 if ( !$comment = get_comment($comment_id) )
1794 * Fires immediately before a comment is sent to the Trash.
1798 * @param int $comment_id The comment ID.
1800 do_action( 'trash_comment', $comment_id );
1802 if ( wp_set_comment_status($comment_id, 'trash') ) {
1803 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
1804 add_comment_meta($comment_id, '_wp_trash_meta_time', time() );
1807 * Fires immediately after a comment is sent to Trash.
1811 * @param int $comment_id The comment ID.
1813 do_action( 'trashed_comment', $comment_id );
1821 * Removes a comment from the Trash
1825 * @param int $comment_id Comment ID.
1826 * @return bool True on success, false on failure.
1828 function wp_untrash_comment($comment_id) {
1829 if ( ! (int)$comment_id )
1833 * Fires immediately before a comment is restored from the Trash.
1837 * @param int $comment_id The comment ID.
1839 do_action( 'untrash_comment', $comment_id );
1841 $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
1842 if ( empty($status) )
1845 if ( wp_set_comment_status($comment_id, $status) ) {
1846 delete_comment_meta($comment_id, '_wp_trash_meta_time');
1847 delete_comment_meta($comment_id, '_wp_trash_meta_status');
1849 * Fires immediately after a comment is restored from the Trash.
1853 * @param int $comment_id The comment ID.
1855 do_action( 'untrashed_comment', $comment_id );
1863 * Marks a comment as Spam
1867 * @param int $comment_id Comment ID.
1868 * @return bool True on success, false on failure.
1870 function wp_spam_comment($comment_id) {
1871 if ( !$comment = get_comment($comment_id) )
1875 * Fires immediately before a comment is marked as Spam.
1879 * @param int $comment_id The comment ID.
1881 do_action( 'spam_comment', $comment_id );
1883 if ( wp_set_comment_status($comment_id, 'spam') ) {
1884 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
1886 * Fires immediately after a comment is marked as Spam.
1890 * @param int $comment_id The comment ID.
1892 do_action( 'spammed_comment', $comment_id );
1900 * Removes a comment from the Spam
1904 * @param int $comment_id Comment ID.
1905 * @return bool True on success, false on failure.
1907 function wp_unspam_comment($comment_id) {
1908 if ( ! (int)$comment_id )
1912 * Fires immediately before a comment is unmarked as Spam.
1916 * @param int $comment_id The comment ID.
1918 do_action( 'unspam_comment', $comment_id );
1920 $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
1921 if ( empty($status) )
1924 if ( wp_set_comment_status($comment_id, $status) ) {
1925 delete_comment_meta($comment_id, '_wp_trash_meta_status');
1927 * Fires immediately after a comment is unmarked as Spam.
1931 * @param int $comment_id The comment ID.
1933 do_action( 'unspammed_comment', $comment_id );
1941 * The status of a comment by ID.
1945 * @param int $comment_id Comment ID
1946 * @return false|string Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
1948 function wp_get_comment_status($comment_id) {
1949 $comment = get_comment($comment_id);
1953 $approved = $comment->comment_approved;
1955 if ( $approved == null )
1957 elseif ( $approved == '1' )
1959 elseif ( $approved == '0' )
1960 return 'unapproved';
1961 elseif ( $approved == 'spam' )
1963 elseif ( $approved == 'trash' )
1970 * Call hooks for when a comment status transition occurs.
1972 * Calls hooks for comment status transitions. If the new comment status is not the same
1973 * as the previous comment status, then two hooks will be ran, the first is
1974 * 'transition_comment_status' with new status, old status, and comment data. The
1975 * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
1976 * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
1979 * The final action will run whether or not the comment statuses are the same. The
1980 * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
1981 * parameter and COMMENTTYPE is comment_type comment data.
1985 * @param string $new_status New comment status.
1986 * @param string $old_status Previous comment status.
1987 * @param object $comment Comment data.
1989 function wp_transition_comment_status($new_status, $old_status, $comment) {
1991 * Translate raw statuses to human readable formats for the hooks.
1992 * This is not a complete list of comment status, it's only the ones
1993 * that need to be renamed
1995 $comment_statuses = array(
1997 'hold' => 'unapproved', // wp_set_comment_status() uses "hold"
1999 'approve' => 'approved', // wp_set_comment_status() uses "approve"
2001 if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
2002 if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
2005 if ( $new_status != $old_status ) {
2007 * Fires when the comment status is in transition.
2011 * @param int|string $new_status The new comment status.
2012 * @param int|string $old_status The old comment status.
2013 * @param object $comment The comment data.
2015 do_action( 'transition_comment_status', $new_status, $old_status, $comment );
2017 * Fires when the comment status is in transition from one specific status to another.
2019 * The dynamic portions of the hook name, `$old_status`, and `$new_status`,
2020 * refer to the old and new comment statuses, respectively.
2024 * @param object $comment Comment object.
2026 do_action( "comment_{$old_status}_to_{$new_status}", $comment );
2029 * Fires when the status of a specific comment type is in transition.
2031 * The dynamic portions of the hook name, `$new_status`, and `$comment->comment_type`,
2032 * refer to the new comment status, and the type of comment, respectively.
2034 * Typical comment types include an empty string (standard comment), 'pingback',
2039 * @param int $comment_ID The comment ID.
2040 * @param obj $comment Comment object.
2042 do_action( "comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment );
2046 * Get current commenter's name, email, and URL.
2048 * Expects cookies content to already be sanitized. User of this function might
2049 * wish to recheck the returned array for validity.
2051 * @see sanitize_comment_cookies() Use to sanitize cookies
2055 * @return array Comment author, email, url respectively.
2057 function wp_get_current_commenter() {
2058 // Cookies should already be sanitized.
2060 $comment_author = '';
2061 if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
2062 $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
2064 $comment_author_email = '';
2065 if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
2066 $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
2068 $comment_author_url = '';
2069 if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
2070 $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
2073 * Filter the current commenter's name, email, and URL.
2077 * @param string $comment_author Comment author's name.
2078 * @param string $comment_author_email Comment author's email.
2079 * @param string $comment_author_url Comment author's URL.
2081 return apply_filters( 'wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url') );
2085 * Inserts a comment to the database.
2087 * The available comment data key names are 'comment_author_IP', 'comment_date',
2088 * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'.
2092 * @global wpdb $wpdb WordPress database abstraction object.
2094 * @param array $commentdata Contains information on the comment.
2095 * @return int|bool The new comment's ID on success, false on failure.
2097 function wp_insert_comment( $commentdata ) {
2099 $data = wp_unslash( $commentdata );
2101 $comment_author = ! isset( $data['comment_author'] ) ? '' : $data['comment_author'];
2102 $comment_author_email = ! isset( $data['comment_author_email'] ) ? '' : $data['comment_author_email'];
2103 $comment_author_url = ! isset( $data['comment_author_url'] ) ? '' : $data['comment_author_url'];
2104 $comment_author_IP = ! isset( $data['comment_author_IP'] ) ? '' : $data['comment_author_IP'];
2106 $comment_date = ! isset( $data['comment_date'] ) ? current_time( 'mysql' ) : $data['comment_date'];
2107 $comment_date_gmt = ! isset( $data['comment_date_gmt'] ) ? get_gmt_from_date( $comment_date ) : $data['comment_date_gmt'];
2109 $comment_post_ID = ! isset( $data['comment_post_ID'] ) ? '' : $data['comment_post_ID'];
2110 $comment_content = ! isset( $data['comment_content'] ) ? '' : $data['comment_content'];
2111 $comment_karma = ! isset( $data['comment_karma'] ) ? 0 : $data['comment_karma'];
2112 $comment_approved = ! isset( $data['comment_approved'] ) ? 1 : $data['comment_approved'];
2113 $comment_agent = ! isset( $data['comment_agent'] ) ? '' : $data['comment_agent'];
2114 $comment_type = ! isset( $data['comment_type'] ) ? '' : $data['comment_type'];
2115 $comment_parent = ! isset( $data['comment_parent'] ) ? 0 : $data['comment_parent'];
2117 $user_id = ! isset( $data['user_id'] ) ? 0 : $data['user_id'];
2119 $compacted = compact( 'comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_karma', 'comment_approved', 'comment_agent', 'comment_type', 'comment_parent', 'user_id' );
2120 if ( ! $wpdb->insert( $wpdb->comments, $compacted ) ) {
2121 $fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' );
2123 foreach( $fields as $field ) {
2124 if ( isset( $compacted[ $field ] ) ) {
2125 $compacted[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $compacted[ $field ] );
2129 if ( ! $wpdb->insert( $wpdb->comments, $compacted ) ) {
2134 $id = (int) $wpdb->insert_id;
2136 if ( $comment_approved == 1 ) {
2137 wp_update_comment_count( $comment_post_ID );
2139 $comment = get_comment( $id );
2142 * Fires immediately after a comment is inserted into the database.
2146 * @param int $id The comment ID.
2147 * @param obj $comment Comment object.
2149 do_action( 'wp_insert_comment', $id, $comment );
2151 wp_cache_set( 'last_changed', microtime(), 'comment' );
2157 * Filters and sanitizes comment data.
2159 * Sets the comment data 'filtered' field to true when finished. This can be
2160 * checked as to whether the comment should be filtered and to keep from
2161 * filtering the same comment more than once.
2165 * @param array $commentdata Contains information on the comment.
2166 * @return array Parsed comment information.
2168 function wp_filter_comment($commentdata) {
2169 if ( isset( $commentdata['user_ID'] ) ) {
2171 * Filter the comment author's user id before it is set.
2173 * The first time this filter is evaluated, 'user_ID' is checked
2174 * (for back-compat), followed by the standard 'user_id' value.
2178 * @param int $user_ID The comment author's user ID.
2180 $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_ID'] );
2181 } elseif ( isset( $commentdata['user_id'] ) ) {
2182 /** This filter is documented in wp-includes/comment.php */
2183 $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_id'] );
2187 * Filter the comment author's browser user agent before it is set.
2191 * @param int $comment_agent The comment author's browser user agent.
2193 $commentdata['comment_agent'] = apply_filters( 'pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
2194 /** This filter is documented in wp-includes/comment.php */
2195 $commentdata['comment_author'] = apply_filters( 'pre_comment_author_name', $commentdata['comment_author'] );
2197 * Filter the comment content before it is set.
2201 * @param int $comment_content The comment content.
2203 $commentdata['comment_content'] = apply_filters( 'pre_comment_content', $commentdata['comment_content'] );
2205 * Filter the comment author's IP before it is set.
2209 * @param int $comment_author_ip The comment author's IP.
2211 $commentdata['comment_author_IP'] = apply_filters( 'pre_comment_user_ip', $commentdata['comment_author_IP'] );
2212 /** This filter is documented in wp-includes/comment.php */
2213 $commentdata['comment_author_url'] = apply_filters( 'pre_comment_author_url', $commentdata['comment_author_url'] );
2214 /** This filter is documented in wp-includes/comment.php */
2215 $commentdata['comment_author_email'] = apply_filters( 'pre_comment_author_email', $commentdata['comment_author_email'] );
2216 $commentdata['filtered'] = true;
2217 return $commentdata;
2221 * Whether a comment should be blocked because of comment flood.
2225 * @param bool $block Whether plugin has already blocked comment.
2226 * @param int $time_lastcomment Timestamp for last comment.
2227 * @param int $time_newcomment Timestamp for new comment.
2228 * @return bool Whether comment should be blocked.
2230 function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
2231 if ( $block ) // a plugin has already blocked... we'll let that decision stand
2233 if ( ($time_newcomment - $time_lastcomment) < 15 )
2239 * Adds a new comment to the database.
2241 * Filters new comment to ensure that the fields are sanitized and valid before
2242 * inserting comment into database. Calls 'comment_post' action with comment ID
2243 * and whether comment is approved by WordPress. Also has 'preprocess_comment'
2244 * filter for processing the comment data before the function handles it.
2246 * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure
2247 * that it is properly set, such as in wp-config.php, for your environment.
2248 * See {@link https://core.trac.wordpress.org/ticket/9235}
2251 * @param array $commentdata Contains information on the comment.
2252 * @return int|bool The ID of the comment on success, false on failure.
2254 function wp_new_comment( $commentdata ) {
2255 if ( isset( $commentdata['user_ID'] ) ) {
2256 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
2259 $prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0;
2262 * Filter a comment's data before it is sanitized and inserted into the database.
2266 * @param array $commentdata Comment data.
2268 $commentdata = apply_filters( 'preprocess_comment', $commentdata );
2270 $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
2271 if ( isset( $commentdata['user_ID'] ) && $prefiltered_user_id !== (int) $commentdata['user_ID'] ) {
2272 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
2273 } elseif ( isset( $commentdata['user_id'] ) ) {
2274 $commentdata['user_id'] = (int) $commentdata['user_id'];
2277 $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
2278 $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
2279 $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
2281 $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
2282 $commentdata['comment_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? substr( $_SERVER['HTTP_USER_AGENT'], 0, 254 ) : '';
2284 if ( empty( $commentdata['comment_date'] ) ) {
2285 $commentdata['comment_date'] = current_time('mysql');
2288 if ( empty( $commentdata['comment_date_gmt'] ) ) {
2289 $commentdata['comment_date_gmt'] = current_time( 'mysql', 1 );
2292 $commentdata = wp_filter_comment($commentdata);
2294 $commentdata['comment_approved'] = wp_allow_comment($commentdata);
2296 $comment_ID = wp_insert_comment($commentdata);
2297 if ( ! $comment_ID ) {
2302 * Fires immediately after a comment is inserted into the database.
2306 * @param int $comment_ID The comment ID.
2307 * @param int $comment_approved 1 (true) if the comment is approved, 0 (false) if not.
2309 do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'] );
2311 if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
2312 if ( '0' == $commentdata['comment_approved'] ) {
2313 wp_notify_moderator( $comment_ID );
2316 // wp_notify_postauthor() checks if notifying the author of their own comment.
2317 // By default, it won't, but filters can override this.
2318 if ( get_option( 'comments_notify' ) && $commentdata['comment_approved'] ) {
2319 wp_notify_postauthor( $comment_ID );
2327 * Sets the status of a comment.
2329 * The 'wp_set_comment_status' action is called after the comment is handled.
2330 * If the comment status is not in the list, then false is returned.
2334 * @param int $comment_id Comment ID.
2335 * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
2336 * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
2337 * @return bool|WP_Error True on success, false or WP_Error on failure.
2339 function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
2342 switch ( $comment_status ) {
2350 if ( get_option('comments_notify') ) {
2351 wp_notify_postauthor( $comment_id );
2364 $comment_old = clone get_comment($comment_id);
2366 if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
2368 return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
2373 clean_comment_cache($comment_id);
2375 $comment = get_comment($comment_id);
2378 * Fires immediately before transitioning a comment's status from one to another
2383 * @param int $comment_id Comment ID.
2384 * @param string|bool $comment_status Current comment status. Possible values include
2385 * 'hold', 'approve', 'spam', 'trash', or false.
2387 do_action( 'wp_set_comment_status', $comment_id, $comment_status );
2389 wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
2391 wp_update_comment_count($comment->comment_post_ID);
2397 * Updates an existing comment in the database.
2399 * Filters the comment and makes sure certain fields are valid before updating.
2403 * @global wpdb $wpdb WordPress database abstraction object.
2405 * @param array $commentarr Contains information on the comment.
2406 * @return int Comment was updated if value is 1, or was not updated if value is 0.
2408 function wp_update_comment($commentarr) {
2411 // First, get all of the original fields
2412 $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
2413 if ( empty( $comment ) ) {
2417 // Make sure that the comment post ID is valid (if specified).
2418 if ( isset( $commentarr['comment_post_ID'] ) && ! get_post( $commentarr['comment_post_ID'] ) ) {
2422 // Escape data pulled from DB.
2423 $comment = wp_slash($comment);
2425 $old_status = $comment['comment_approved'];
2427 // Merge old and new fields with new fields overwriting old ones.
2428 $commentarr = array_merge($comment, $commentarr);
2430 $commentarr = wp_filter_comment( $commentarr );
2432 // Now extract the merged array.
2433 $data = wp_unslash( $commentarr );
2436 * Filter the comment content before it is updated in the database.
2440 * @param string $comment_content The comment data.
2442 $data['comment_content'] = apply_filters( 'comment_save_pre', $data['comment_content'] );
2444 $data['comment_date_gmt'] = get_gmt_from_date( $data['comment_date'] );
2446 if ( ! isset( $data['comment_approved'] ) ) {
2447 $data['comment_approved'] = 1;
2448 } elseif ( 'hold' == $data['comment_approved'] ) {
2449 $data['comment_approved'] = 0;
2450 } elseif ( 'approve' == $data['comment_approved'] ) {
2451 $data['comment_approved'] = 1;
2454 $comment_ID = $data['comment_ID'];
2455 $comment_post_ID = $data['comment_post_ID'];
2456 $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' );
2457 $data = wp_array_slice_assoc( $data, $keys );
2458 $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
2460 clean_comment_cache( $comment_ID );
2461 wp_update_comment_count( $comment_post_ID );
2463 * Fires immediately after a comment is updated in the database.
2465 * The hook also fires immediately before comment status transition hooks are fired.
2469 * @param int $comment_ID The comment ID.
2471 do_action( 'edit_comment', $comment_ID );
2472 $comment = get_comment($comment_ID);
2473 wp_transition_comment_status($comment->comment_approved, $old_status, $comment);
2478 * Whether to defer comment counting.
2480 * When setting $defer to true, all post comment counts will not be updated
2481 * until $defer is set to false. When $defer is set to false, then all
2482 * previously deferred updated post comment counts will then be automatically
2483 * updated without having to call wp_update_comment_count() after.
2486 * @staticvar bool $_defer
2488 * @param bool $defer
2491 function wp_defer_comment_counting($defer=null) {
2492 static $_defer = false;
2494 if ( is_bool($defer) ) {
2496 // flush any deferred counts
2498 wp_update_comment_count( null, true );
2505 * Updates the comment count for post(s).
2507 * When $do_deferred is false (is by default) and the comments have been set to
2508 * be deferred, the post_id will be added to a queue, which will be updated at a
2509 * later date and only updated once per post ID.
2511 * If the comments have not be set up to be deferred, then the post will be
2512 * updated. When $do_deferred is set to true, then all previous deferred post
2513 * IDs will be updated along with the current $post_id.
2516 * @see wp_update_comment_count_now() For what could cause a false return value
2518 * @param int $post_id Post ID
2519 * @param bool $do_deferred Whether to process previously deferred post comment counts
2520 * @return bool|null True on success, false on failure
2522 function wp_update_comment_count($post_id, $do_deferred=false) {
2523 static $_deferred = array();
2525 if ( $do_deferred ) {
2526 $_deferred = array_unique($_deferred);
2527 foreach ( $_deferred as $i => $_post_id ) {
2528 wp_update_comment_count_now($_post_id);
2529 unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
2533 if ( wp_defer_comment_counting() ) {
2534 $_deferred[] = $post_id;
2537 elseif ( $post_id ) {
2538 return wp_update_comment_count_now($post_id);
2544 * Updates the comment count for the post.
2548 * @global wpdb $wpdb WordPress database abstraction object.
2550 * @param int $post_id Post ID
2551 * @return bool True on success, false on '0' $post_id or if post with ID does not exist.
2553 function wp_update_comment_count_now($post_id) {
2555 $post_id = (int) $post_id;
2558 if ( !$post = get_post($post_id) )
2561 $old = (int) $post->comment_count;
2562 $new = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id) );
2563 $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) );
2565 clean_post_cache( $post );
2568 * Fires immediately after a post's comment count is updated in the database.
2572 * @param int $post_id Post ID.
2573 * @param int $new The new comment count.
2574 * @param int $old The old comment count.
2576 do_action( 'wp_update_comment_count', $post_id, $new, $old );
2577 /** This action is documented in wp-includes/post.php */
2578 do_action( 'edit_post', $post_id, $post );
2584 // Ping and trackback functions.
2588 * Finds a pingback server URI based on the given URL.
2590 * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
2591 * a check for the x-pingback headers first and returns that, if available. The
2592 * check for the rel="pingback" has more overhead than just the header.
2596 * @param string $url URL to ping.
2597 * @param int $deprecated Not Used.
2598 * @return false|string False on failure, string containing URI on success.
2600 function discover_pingback_server_uri( $url, $deprecated = '' ) {
2601 if ( !empty( $deprecated ) )
2602 _deprecated_argument( __FUNCTION__, '2.7' );
2604 $pingback_str_dquote = 'rel="pingback"';
2605 $pingback_str_squote = 'rel=\'pingback\'';
2607 /** @todo Should use Filter Extension or custom preg_match instead. */
2608 $parsed_url = parse_url($url);
2610 if ( ! isset( $parsed_url['host'] ) ) // Not an URL. This should never happen.
2613 //Do not search for a pingback server on our own uploads
2614 $uploads_dir = wp_upload_dir();
2615 if ( 0 === strpos($url, $uploads_dir['baseurl']) )
2618 $response = wp_safe_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
2620 if ( is_wp_error( $response ) )
2623 if ( wp_remote_retrieve_header( $response, 'x-pingback' ) )
2624 return wp_remote_retrieve_header( $response, 'x-pingback' );
2626 // Not an (x)html, sgml, or xml page, no use going further.
2627 if ( preg_match('#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'content-type' )) )
2630 // Now do a GET since we're going to look in the html headers (and we're sure it's not a binary file)
2631 $response = wp_safe_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
2633 if ( is_wp_error( $response ) )
2636 $contents = wp_remote_retrieve_body( $response );
2638 $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
2639 $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
2640 if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
2641 $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
2642 $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
2643 $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
2644 $pingback_href_start = $pingback_href_pos+6;
2645 $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
2646 $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
2647 $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
2649 // We may find rel="pingback" but an incomplete pingback URL
2650 if ( $pingback_server_url_len > 0 ) { // We got it!
2651 return $pingback_server_url;
2659 * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
2663 * @global wpdb $wpdb WordPress database abstraction object.
2665 function do_all_pings() {
2669 while ($ping = $wpdb->get_row("SELECT ID, post_content, meta_id FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_pingme' LIMIT 1")) {
2670 delete_metadata_by_mid( 'post', $ping->meta_id );
2671 pingback( $ping->post_content, $ping->ID );
2675 while ($enclosure = $wpdb->get_row("SELECT ID, post_content, meta_id FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_encloseme' LIMIT 1")) {
2676 delete_metadata_by_mid( 'post', $enclosure->meta_id );
2677 do_enclose( $enclosure->post_content, $enclosure->ID );
2681 $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'");
2682 if ( is_array($trackbacks) )
2683 foreach ( $trackbacks as $trackback )
2684 do_trackbacks($trackback);
2686 //Do Update Services/Generic Pings
2691 * Perform trackbacks.
2695 * @global wpdb $wpdb WordPress database abstraction object.
2697 * @param int $post_id Post ID to do trackbacks on.
2699 function do_trackbacks($post_id) {
2702 $post = get_post( $post_id );
2703 $to_ping = get_to_ping($post_id);
2704 $pinged = get_pung($post_id);
2705 if ( empty($to_ping) ) {
2706 $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) );
2710 if ( empty($post->post_excerpt) ) {
2711 /** This filter is documented in wp-includes/post-template.php */
2712 $excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
2714 /** This filter is documented in wp-includes/post-template.php */
2715 $excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );
2718 $excerpt = str_replace(']]>', ']]>', $excerpt);
2719 $excerpt = wp_html_excerpt($excerpt, 252, '…');
2721 /** This filter is documented in wp-includes/post-template.php */
2722 $post_title = apply_filters( 'the_title', $post->post_title, $post->ID );
2723 $post_title = strip_tags($post_title);
2726 foreach ( (array) $to_ping as $tb_ping ) {
2727 $tb_ping = trim($tb_ping);
2728 if ( !in_array($tb_ping, $pinged) ) {
2729 trackback($tb_ping, $post_title, $excerpt, $post_id);
2730 $pinged[] = $tb_ping;
2732 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post_id) );
2739 * Sends pings to all of the ping site services.
2743 * @param int $post_id Post ID.
2744 * @return int Same as Post ID from parameter
2746 function generic_ping( $post_id = 0 ) {
2747 $services = get_option('ping_sites');
2749 $services = explode("\n", $services);
2750 foreach ( (array) $services as $service ) {
2751 $service = trim($service);
2752 if ( '' != $service )
2753 weblog_ping($service);
2760 * Pings back the links found in a post.
2765 * @param string $content Post content to check for links.
2766 * @param int $post_ID Post ID.
2768 function pingback($content, $post_ID) {
2770 include_once(ABSPATH . WPINC . '/class-IXR.php');
2771 include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
2773 // original code by Mort (http://mort.mine.nu:8080)
2774 $post_links = array();
2776 $pung = get_pung($post_ID);
2779 // Parsing the post, external links (if any) are stored in the $post_links array
2780 $post_links_temp = wp_extract_urls( $content );
2783 // Walking thru the links array
2784 // first we get rid of links pointing to sites, not to specific files
2786 // http://dummy-weblog.org
2787 // http://dummy-weblog.org/
2788 // http://dummy-weblog.org/post.php
2789 // We don't wanna ping first and second types, even if they have a valid <link/>
2791 foreach ( (array) $post_links_temp as $link_test ) :
2792 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
2793 && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
2794 if ( $test = @parse_url($link_test) ) {
2795 if ( isset($test['query']) )
2796 $post_links[] = $link_test;
2797 elseif ( isset( $test['path'] ) && ( $test['path'] != '/' ) && ( $test['path'] != '' ) )
2798 $post_links[] = $link_test;
2803 $post_links = array_unique( $post_links );
2805 * Fires just before pinging back links found in a post.
2809 * @param array &$post_links An array of post links to be checked, passed by reference.
2810 * @param array &$pung Whether a link has already been pinged, passed by reference.
2811 * @param int $post_ID The post ID.
2813 do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post_ID ) );
2815 foreach ( (array) $post_links as $pagelinkedto ) {
2816 $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
2818 if ( $pingback_server_url ) {
2819 @ set_time_limit( 60 );
2820 // Now, the RPC call
2821 $pagelinkedfrom = get_permalink($post_ID);
2823 // using a timeout of 3 seconds should be enough to cover slow servers
2824 $client = new WP_HTTP_IXR_Client($pingback_server_url);
2825 $client->timeout = 3;
2827 * Filter the user agent sent when pinging-back a URL.
2831 * @param string $concat_useragent The user agent concatenated with ' -- WordPress/'
2832 * and the WordPress version.
2833 * @param string $useragent The useragent.
2834 * @param string $pingback_server_url The server URL being linked to.
2835 * @param string $pagelinkedto URL of page linked to.
2836 * @param string $pagelinkedfrom URL of page linked from.
2838 $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . $wp_version, $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom );
2839 // when set to true, this outputs debug messages by itself
2840 $client->debug = false;
2842 if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
2843 add_ping( $post_ID, $pagelinkedto );
2849 * Check whether blog is public before returning sites.
2853 * @param mixed $sites Will return if blog is public, will not return if not public.
2854 * @return mixed Empty string if blog is not public, returns $sites, if site is public.
2856 function privacy_ping_filter($sites) {
2857 if ( '0' != get_option('blog_public') )
2866 * Updates database when sending trackback to prevent duplicates.
2870 * @global wpdb $wpdb WordPress database abstraction object.
2872 * @param string $trackback_url URL to send trackbacks.
2873 * @param string $title Title of post.
2874 * @param string $excerpt Excerpt of post.
2875 * @param int $ID Post ID.
2876 * @return mixed Database query from update.
2878 function trackback($trackback_url, $title, $excerpt, $ID) {
2881 if ( empty($trackback_url) )
2885 $options['timeout'] = 4;
2886 $options['body'] = array(
2888 'url' => get_permalink($ID),
2889 'blog_name' => get_option('blogname'),
2890 'excerpt' => $excerpt
2893 $response = wp_safe_remote_post( $trackback_url, $options );
2895 if ( is_wp_error( $response ) )
2898 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID) );
2899 return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID) );
2908 * @param string $server Host of blog to connect to.
2909 * @param string $path Path to send the ping.
2911 function weblog_ping($server = '', $path = '') {
2913 include_once(ABSPATH . WPINC . '/class-IXR.php');
2914 include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
2916 // using a timeout of 3 seconds should be enough to cover slow servers
2917 $client = new WP_HTTP_IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
2918 $client->timeout = 3;
2919 $client->useragent .= ' -- WordPress/'.$wp_version;
2921 // when set to true, this outputs debug messages by itself
2922 $client->debug = false;
2923 $home = trailingslashit( home_url() );
2924 if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
2925 $client->query('weblogUpdates.ping', get_option('blogname'), $home);
2929 * Default filter attached to pingback_ping_source_uri to validate the pingback's Source URI
2932 * @see wp_http_validate_url()
2934 * @param string $source_uri
2937 function pingback_ping_source_uri( $source_uri ) {
2938 return (string) wp_http_validate_url( $source_uri );
2942 * Default filter attached to xmlrpc_pingback_error.
2944 * Returns a generic pingback error code unless the error code is 48,
2945 * which reports that the pingback is already registered.
2948 * @link http://www.hixie.ch/specs/pingback/pingback#TOC3
2950 * @param IXR_Error $ixr_error
2953 function xmlrpc_pingback_error( $ixr_error ) {
2954 if ( $ixr_error->code === 48 )
2956 return new IXR_Error( 0, '' );
2964 * Removes comment ID from the comment cache.
2968 * @param int|array $ids Comment ID or array of comment IDs to remove from cache
2970 function clean_comment_cache($ids) {
2971 foreach ( (array) $ids as $id )
2972 wp_cache_delete($id, 'comment');
2974 wp_cache_set( 'last_changed', microtime(), 'comment' );
2978 * Updates the comment cache of given comments.
2980 * Will add the comments in $comments to the cache. If comment ID already exists
2981 * in the comment cache then it will not be updated. The comment is added to the
2982 * cache using the comment group with the key using the ID of the comments.
2986 * @param array $comments Array of comment row objects
2988 function update_comment_cache($comments) {
2989 foreach ( (array) $comments as $comment )
2990 wp_cache_add($comment->comment_ID, $comment, 'comment');
2998 * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
3003 * @param object $posts Post data object.
3004 * @param object $query Query object.
3007 function _close_comments_for_old_posts( $posts, $query ) {
3008 if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) )
3012 * Filter the list of post types to automatically close comments for.
3016 * @param array $post_types An array of registered post types. Default array with 'post'.
3018 $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
3019 if ( ! in_array( $posts[0]->post_type, $post_types ) )
3022 $days_old = (int) get_option( 'close_comments_days_old' );
3026 if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
3027 $posts[0]->comment_status = 'closed';
3028 $posts[0]->ping_status = 'closed';
3035 * Close comments on an old post. Hooked to comments_open and pings_open.
3040 * @param bool $open Comments open or closed
3041 * @param int $post_id Post ID
3042 * @return bool $open
3044 function _close_comments_for_old_post( $open, $post_id ) {
3048 if ( !get_option('close_comments_for_old_posts') )
3051 $days_old = (int) get_option('close_comments_days_old');
3055 $post = get_post($post_id);
3057 /** This filter is documented in wp-includes/comment.php */
3058 $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
3059 if ( ! in_array( $post->post_type, $post_types ) )
3062 if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) )