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.
165 * @global object $comment
167 * @param object|string|int $comment Comment to retrieve.
168 * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
169 * @return object|array|null Depends on $output value.
171 function get_comment(&$comment, $output = OBJECT) {
174 if ( empty($comment) ) {
175 if ( isset($GLOBALS['comment']) )
176 $_comment = & $GLOBALS['comment'];
179 } elseif ( is_object($comment) ) {
180 wp_cache_add($comment->comment_ID, $comment, 'comment');
181 $_comment = $comment;
183 if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
184 $_comment = & $GLOBALS['comment'];
185 } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
186 $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
189 wp_cache_add($_comment->comment_ID, $_comment, 'comment');
194 * Fires after a comment is retrieved.
198 * @param mixed $_comment Comment data.
200 $_comment = apply_filters( 'get_comment', $_comment );
202 if ( $output == OBJECT ) {
204 } elseif ( $output == ARRAY_A ) {
205 $__comment = get_object_vars($_comment);
207 } elseif ( $output == ARRAY_N ) {
208 $__comment = array_values(get_object_vars($_comment));
216 * Retrieve a list of comments.
218 * The comment list can be for the blog as a whole or for an individual post.
222 * @param string|array $args Optional. Array or string of arguments. See {@see WP_Comment_Query::parse_query()}
223 * for information on accepted arguments. Default empty.
224 * @return int|array List of comments or number of found comments if `$count` argument is true.
226 function get_comments( $args = '' ) {
227 $query = new WP_Comment_Query;
228 return $query->query( $args );
232 * WordPress Comment Query class.
234 * See WP_Comment_Query::__construct() for accepted arguments.
238 class WP_Comment_Query {
240 * SQL for database query.
249 * Metadata query container
253 * @var object WP_Meta_Query
255 public $meta_query = false;
258 * Date query container
262 * @var object WP_Date_Query
264 public $date_query = false;
267 * Query vars set by the user.
276 * Default values for query vars.
282 public $query_var_defaults;
285 * List of comments located by the query.
294 * Make private/protected methods readable for backwards compatibility.
299 * @param callable $name Method to call.
300 * @param array $arguments Arguments to pass when calling.
301 * @return mixed|false Return value of the callback, false otherwise.
303 public function __call( $name, $arguments ) {
304 if ( 'get_search_sql' === $name ) {
305 return call_user_func_array( array( $this, $name ), $arguments );
313 * Sets up the comment query, based on the query vars passed.
318 * @param string|array $query {
319 * Optional. Array or query string of comment query parameters. Default empty.
321 * @type string $author_email Comment author email address. Default empty.
322 * @type array $author__in Array of author IDs to include comments for. Default empty.
323 * @type array $author__not_in Array of author IDs to exclude comments for. Default empty.
324 * @type array $comment__in Array of comment IDs to include. Default empty.
325 * @type array $comment__not_in Array of comment IDs to exclude. Default empty.
326 * @type bool $count Whether to return a comment count (true) or array of comment
327 * objects (false). Default false.
328 * @type array $date_query Date query clauses to limit comments by. See WP_Date_Query.
330 * @type string $fields Comment fields to return. Accepts 'ids' for comment IDs only or
331 * empty for all fields. Default empty.
332 * @type int $ID Currently unused.
333 * @type array $include_unapproved Array of IDs or email addresses of users whose unapproved comments
334 * will be returned by the query regardless of `$status`. Default empty.
335 * @type int $karma Karma score to retrieve matching comments for. Default empty.
336 * @type string $meta_key Include comments with a matching comment meta key. Default empty.
337 * @type string $meta_value Include comments with a matching comment meta value. Requires
338 * `$meta_key` to be set. Default empty.
339 * @type array $meta_query Meta query clauses to limit retrieved comments by.
340 * See WP_Meta_Query. Default empty.
341 * @type int $number Maximum number of comments to retrieve. Default null (no limit).
342 * @type int $offset Number of comments to offset the query. Used to build LIMIT clause.
344 * @type string|array $orderby Comment status or array of statuses. To use 'meta_value' or
345 * 'meta_value_num', `$meta_key` must also be defined. To sort by
346 * a specific `$meta_query` clause, use that clause's array key.
347 * Accepts 'comment_agent', 'comment_approved', 'comment_author',
348 * 'comment_author_email', 'comment_author_IP',
349 * 'comment_author_url', 'comment_content', 'comment_date',
350 * 'comment_date_gmt', 'comment_ID', 'comment_karma',
351 * 'comment_parent', 'comment_post_ID', 'comment_type', 'user_id',
352 * 'meta_value', 'meta_value_num', the value of $meta_key, and the
353 * array keys of `$meta_query`. Also accepts false, an empty array,
354 * or 'none' to disable `ORDER BY` clause.
355 * Default: 'comment_date_gmt'.
356 * @type string $order How to order retrieved comments. Accepts 'ASC', 'DESC'.
358 * @type int $parent Parent ID of comment to retrieve children of. Default empty.
359 * @type array $post_author__in Array of author IDs to retrieve comments for. Default empty.
360 * @type array $post_author__not_in Array of author IDs *not* to retrieve comments for. Default empty.
361 * @type int $post_ID Currently unused.
362 * @type int $post_id Limit results to those affiliated with a given post ID. Default 0.
363 * @type array $post__in Array of post IDs to include affiliated comments for. Default empty.
364 * @type array $post__not_in Array of post IDs to exclude affiliated comments for. Default empty.
365 * @type int $post_author Comment author ID to limit results by. Default empty.
366 * @type string $post_status Post status to retrieve affiliated comments for. Default empty.
367 * @type string $post_type Post type to retrieve affiliated comments for. Default empty.
368 * @type string $post_name Post name to retrieve affiliated comments for. Default empty.
369 * @type int $post_parent Post parent ID to retrieve affiliated comments for. Default empty.
370 * @type string $search Search term(s) to retrieve matching comments for. Default empty.
371 * @type string $status Comment status to limit results by. Accepts 'hold'
372 * (`comment_status=0`), 'approve' (`comment_status=1`), 'all', or a
373 * custom comment status. Default 'all'.
374 * @type string|array $type Include comments of a given type, or array of types. Accepts
375 * 'comment', 'pings' (includes 'pingback' and 'trackback'), or any
376 * custom type string. Default empty.
377 * @type array $type__in Include comments from a given array of comment types. Default empty.
378 * @type array $type__not_in Exclude comments from a given array of comment types. Default empty.
379 * @type int $user_id Include comments for a specific user ID. Default empty.
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|int List of comments, or number of comments when 'count' is passed as a query var.
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 int|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 );
486 * Fires before comments are retrieved.
490 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
492 do_action_ref_array( 'pre_get_comments', array( &$this ) );
494 // Reparse query vars, in case they were modified in a 'pre_get_comments' callback.
495 $this->meta_query->parse_query_vars( $this->query_vars );
496 if ( ! empty( $this->meta_query->queries ) ) {
497 $meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
500 // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
501 $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
502 $last_changed = wp_cache_get( 'last_changed', 'comment' );
503 if ( ! $last_changed ) {
504 $last_changed = microtime();
505 wp_cache_set( 'last_changed', $last_changed, 'comment' );
507 $cache_key = "get_comments:$key:$last_changed";
509 if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) {
510 $this->comments = $cache;
511 return $this->comments;
516 // Assemble clauses related to 'comment_approved'.
517 $approved_clauses = array();
519 // 'status' accepts an array or a comma-separated string.
520 $status_clauses = array();
521 $statuses = $this->query_vars['status'];
522 if ( ! is_array( $statuses ) ) {
523 $statuses = preg_split( '/[\s,]+/', $statuses );
526 // 'any' overrides other statuses.
527 if ( ! in_array( 'any', $statuses ) ) {
528 foreach ( $statuses as $status ) {
531 $status_clauses[] = "comment_approved = '0'";
535 $status_clauses[] = "comment_approved = '1'";
540 $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
544 $status_clauses[] = $wpdb->prepare( "comment_approved = %s", $status );
549 if ( ! empty( $status_clauses ) ) {
550 $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
554 // User IDs or emails whose unapproved comments are included, regardless of $status.
555 if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
556 $include_unapproved = $this->query_vars['include_unapproved'];
558 // Accepts arrays or comma-separated strings.
559 if ( ! is_array( $include_unapproved ) ) {
560 $include_unapproved = preg_split( '/[\s,]+/', $include_unapproved );
563 $unapproved_ids = $unapproved_emails = array();
564 foreach ( $include_unapproved as $unapproved_identifier ) {
565 // Numeric values are assumed to be user ids.
566 if ( is_numeric( $unapproved_identifier ) ) {
567 $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
569 // Otherwise we match against email addresses.
571 $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
576 // Collapse comment_approved clauses into a single OR-separated clause.
577 if ( ! empty( $approved_clauses ) ) {
578 if ( 1 === count( $approved_clauses ) ) {
579 $where[] = $approved_clauses[0];
581 $where[] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
585 $order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
587 // Disable ORDER BY with 'none', an empty array, or boolean false.
588 if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
590 } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
591 $ordersby = is_array( $this->query_vars['orderby'] ) ?
592 $this->query_vars['orderby'] :
593 preg_split( '/[,\s]/', $this->query_vars['orderby'] );
595 $orderby_array = array();
596 $found_orderby_comment_ID = false;
597 foreach ( $ordersby as $_key => $_value ) {
602 if ( is_int( $_key ) ) {
610 if ( ! $found_orderby_comment_ID && 'comment_ID' === $_orderby ) {
611 $found_orderby_comment_ID = true;
614 $parsed = $this->parse_orderby( $_orderby );
620 $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
623 // If no valid clauses were found, order by comment_date_gmt.
624 if ( empty( $orderby_array ) ) {
625 $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
628 // To ensure determinate sorting, always include a comment_ID clause.
629 if ( ! $found_orderby_comment_ID ) {
630 $comment_ID_order = '';
632 // Inherit order from comment_date or comment_date_gmt, if available.
633 foreach ( $orderby_array as $orderby_clause ) {
634 if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
635 $comment_ID_order = $match[1];
640 // If no date-related order is available, use the date from the first available clause.
641 if ( ! $comment_ID_order ) {
642 foreach ( $orderby_array as $orderby_clause ) {
643 if ( false !== strpos( 'ASC', $orderby_clause ) ) {
644 $comment_ID_order = 'ASC';
646 $comment_ID_order = 'DESC';
654 if ( ! $comment_ID_order ) {
655 $comment_ID_order = 'DESC';
658 $orderby_array[] = "$wpdb->comments.comment_ID $comment_ID_order";
661 $orderby = implode( ', ', $orderby_array );
663 $orderby = "$wpdb->comments.comment_date_gmt $order";
666 $number = absint( $this->query_vars['number'] );
667 $offset = absint( $this->query_vars['offset'] );
669 if ( ! empty( $number ) ) {
671 $limits = 'LIMIT ' . $offset . ',' . $number;
673 $limits = 'LIMIT ' . $number;
679 if ( $this->query_vars['count'] ) {
680 $fields = 'COUNT(*)';
682 switch ( strtolower( $this->query_vars['fields'] ) ) {
684 $fields = "$wpdb->comments.comment_ID";
694 $post_id = absint( $this->query_vars['post_id'] );
695 if ( ! empty( $post_id ) ) {
696 $where[] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
699 // Parse comment IDs for an IN clause.
700 if ( ! empty( $this->query_vars['comment__in'] ) ) {
701 $where[] = "$wpdb->comments.comment_ID IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
704 // Parse comment IDs for a NOT IN clause.
705 if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
706 $where[] = "$wpdb->comments.comment_ID NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
709 // Parse comment post IDs for an IN clause.
710 if ( ! empty( $this->query_vars['post__in'] ) ) {
711 $where[] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
714 // Parse comment post IDs for a NOT IN clause.
715 if ( ! empty( $this->query_vars['post__not_in'] ) ) {
716 $where[] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
719 if ( '' !== $this->query_vars['author_email'] ) {
720 $where[] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
723 if ( '' !== $this->query_vars['karma'] ) {
724 $where[] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
727 // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
729 'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
730 'NOT IN' => (array) $this->query_vars['type__not_in'],
733 $comment_types = array();
734 foreach ( $raw_types as $operator => $_raw_types ) {
735 $_raw_types = array_unique( $_raw_types );
737 foreach ( $_raw_types as $type ) {
739 // An empty translates to 'all', for backward compatibility
746 $comment_types[ $operator ][] = "''";
750 $comment_types[ $operator ][] = "'pingback'";
751 $comment_types[ $operator ][] = "'trackback'";
755 $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
760 if ( ! empty( $comment_types[ $operator ] ) ) {
761 $types_sql = implode( ', ', $comment_types[ $operator ] );
762 $where[] = "comment_type $operator ($types_sql)";
766 if ( '' !== $this->query_vars['parent'] ) {
767 $where[] = $wpdb->prepare( 'comment_parent = %d', $this->query_vars['parent'] );
770 if ( is_array( $this->query_vars['user_id'] ) ) {
771 $where[] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
772 } elseif ( '' !== $this->query_vars['user_id'] ) {
773 $where[] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
776 if ( '' !== $this->query_vars['search'] ) {
777 $search_sql = $this->get_search_sql(
778 $this->query_vars['search'],
779 array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
782 // Strip leading 'AND'.
783 $where[] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
786 // If any post-related query vars are passed, join the posts table.
787 $join_posts_table = false;
788 $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type' ) );
789 $post_fields = array_filter( $plucked );
791 if ( ! empty( $post_fields ) ) {
792 $join_posts_table = true;
793 foreach ( $post_fields as $field_name => $field_value ) {
794 // $field_value may be an array.
795 $esses = array_fill( 0, count( (array) $field_value ), '%s' );
796 $where[] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
800 // Comment author IDs for an IN clause.
801 if ( ! empty( $this->query_vars['author__in'] ) ) {
802 $where[] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
805 // Comment author IDs for a NOT IN clause.
806 if ( ! empty( $this->query_vars['author__not_in'] ) ) {
807 $where[] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
810 // Post author IDs for an IN clause.
811 if ( ! empty( $this->query_vars['post_author__in'] ) ) {
812 $join_posts_table = true;
813 $where[] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
816 // Post author IDs for a NOT IN clause.
817 if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
818 $join_posts_table = true;
819 $where[] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
822 if ( $join_posts_table ) {
823 $join = "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
826 if ( ! empty( $meta_query_clauses ) ) {
827 $join .= $meta_query_clauses['join'];
829 // Strip leading 'AND'.
830 $where[] = preg_replace( '/^\s*AND\s*/', '', $meta_query_clauses['where'] );
832 if ( ! $this->query_vars['count'] ) {
833 $groupby = "{$wpdb->comments}.comment_ID";
837 $date_query = $this->query_vars['date_query'];
838 if ( ! empty( $date_query ) && is_array( $date_query ) ) {
839 $date_query_object = new WP_Date_Query( $date_query, 'comment_date' );
840 $where[] = preg_replace( '/^\s*AND\s*/', '', $date_query_object->get_sql() );
843 $where = implode( ' AND ', $where );
845 $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
847 * Filter the comment query clauses.
851 * @param array $pieces A compacted array of comment query clauses.
852 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
854 $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
856 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
857 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
858 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
859 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
860 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
861 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
864 $where = 'WHERE ' . $where;
868 $groupby = 'GROUP BY ' . $groupby;
872 $orderby = "ORDER BY $orderby";
875 $this->request = "SELECT $fields FROM $wpdb->comments $join $where $groupby $orderby $limits";
877 if ( $this->query_vars['count'] ) {
878 return $wpdb->get_var( $this->request );
881 if ( 'ids' == $this->query_vars['fields'] ) {
882 $this->comments = $wpdb->get_col( $this->request );
883 return array_map( 'intval', $this->comments );
886 $results = $wpdb->get_results( $this->request );
888 * Filter the comment query results.
892 * @param array $results An array of comments.
893 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
895 $comments = apply_filters_ref_array( 'the_comments', array( $results, &$this ) );
897 wp_cache_add( $cache_key, $comments, 'comment' );
898 if ( '*' === $fields ) {
899 update_comment_cache( $comments );
902 $this->comments = $comments;
903 return $this->comments;
907 * Used internally to generate an SQL string for searching across multiple columns
914 * @param string $string
918 protected function get_search_sql( $string, $cols ) {
921 $like = '%' . $wpdb->esc_like( $string ) . '%';
924 foreach ( $cols as $col ) {
925 $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
928 return ' AND (' . implode(' OR ', $searches) . ')';
932 * Parse and sanitize 'orderby' keys passed to the comment query.
937 * @global wpdb $wpdb WordPress database abstraction object.
939 * @param string $orderby Alias for the field to order by.
940 * @return string|false Value to used in the ORDER clause. False otherwise.
942 protected function parse_orderby( $orderby ) {
945 $allowed_keys = array(
949 'comment_author_email',
951 'comment_author_url',
963 if ( ! empty( $this->query_vars['meta_key'] ) ) {
964 $allowed_keys[] = $this->query_vars['meta_key'];
965 $allowed_keys[] = 'meta_value';
966 $allowed_keys[] = 'meta_value_num';
969 $meta_query_clauses = $this->meta_query->get_clauses();
970 if ( $meta_query_clauses ) {
971 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
975 if ( $orderby == $this->query_vars['meta_key'] || $orderby == 'meta_value' ) {
976 $parsed = "$wpdb->commentmeta.meta_value";
977 } elseif ( $orderby == 'meta_value_num' ) {
978 $parsed = "$wpdb->commentmeta.meta_value+0";
979 } elseif ( in_array( $orderby, $allowed_keys ) ) {
981 if ( isset( $meta_query_clauses[ $orderby ] ) ) {
982 $meta_clause = $meta_query_clauses[ $orderby ];
983 $parsed = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
985 $parsed = "$wpdb->comments.$orderby";
993 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
998 * @param string $order The 'order' query variable.
999 * @return string The sanitized 'order' query variable.
1001 protected function parse_order( $order ) {
1002 if ( ! is_string( $order ) || empty( $order ) ) {
1006 if ( 'ASC' === strtoupper( $order ) ) {
1015 * Retrieve all of the WordPress supported comment statuses.
1017 * Comments have a limited set of valid status values, this provides the comment
1018 * status values and descriptions.
1022 * @return array List of comment statuses.
1024 function get_comment_statuses() {
1026 'hold' => __('Unapproved'),
1027 /* translators: comment status */
1028 'approve' => _x('Approved', 'adjective'),
1029 /* translators: comment status */
1030 'spam' => _x('Spam', 'adjective'),
1037 * Gets the default comment status for a post type.
1041 * @param string $post_type Optional. Post type. Default 'post'.
1042 * @param string $comment_type Optional. Comment type. Default 'comment'.
1043 * @return string Expected return value is 'open' or 'closed'.
1045 function get_default_comment_status( $post_type = 'post', $comment_type = 'comment' ) {
1046 switch ( $comment_type ) {
1049 $supports = 'trackbacks';
1053 $supports = 'comments';
1054 $option = 'comment';
1058 if ( 'page' === $post_type ) {
1060 } elseif ( post_type_supports( $post_type, $supports ) ) {
1061 $status = get_option( "default_{$option}_status" );
1067 * Filter the default comment status for the given post type.
1071 * @param string $status Default status for the given post type,
1072 * either 'open' or 'closed'.
1073 * @param string $post_type Post type. Default is `post`.
1074 * @param string $comment_type Type of comment. Default is `comment`.
1076 return apply_filters( 'get_default_comment_status' , $status, $post_type, $comment_type );
1080 * The date the last comment was modified.
1084 * @global wpdb $wpdb WordPress database abstraction object.
1085 * @staticvar array $cache_lastcommentmodified
1087 * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
1088 * or 'server' locations.
1089 * @return string Last comment modified date.
1091 function get_lastcommentmodified($timezone = 'server') {
1093 static $cache_lastcommentmodified = array();
1095 if ( isset($cache_lastcommentmodified[$timezone]) )
1096 return $cache_lastcommentmodified[$timezone];
1098 $add_seconds_server = date('Z');
1100 switch ( strtolower($timezone)) {
1102 $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
1105 $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
1108 $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));
1112 $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
1114 return $lastcommentmodified;
1118 * The amount of comments in a post or total comments.
1120 * A lot like {@link wp_count_comments()}, in that they both return comment
1121 * stats (albeit with different types). The {@link wp_count_comments()} actual
1122 * caches, but this function does not.
1126 * @global wpdb $wpdb WordPress database abstraction object.
1128 * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
1129 * @return array The amount of spam, approved, awaiting moderation, and total comments.
1131 function get_comment_count( $post_id = 0 ) {
1134 $post_id = (int) $post_id;
1137 if ( $post_id > 0 ) {
1138 $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
1141 $totals = (array) $wpdb->get_results("
1142 SELECT comment_approved, COUNT( * ) AS total
1143 FROM {$wpdb->comments}
1145 GROUP BY comment_approved
1148 $comment_count = array(
1150 "awaiting_moderation" => 0,
1152 "total_comments" => 0
1155 foreach ( $totals as $row ) {
1156 switch ( $row['comment_approved'] ) {
1158 $comment_count['spam'] = $row['total'];
1159 $comment_count["total_comments"] += $row['total'];
1162 $comment_count['approved'] = $row['total'];
1163 $comment_count['total_comments'] += $row['total'];
1166 $comment_count['awaiting_moderation'] = $row['total'];
1167 $comment_count['total_comments'] += $row['total'];
1174 return $comment_count;
1178 // Comment meta functions
1182 * Add meta data field to a comment.
1185 * @link https://codex.wordpress.org/Function_Reference/add_comment_meta
1187 * @param int $comment_id Comment ID.
1188 * @param string $meta_key Metadata name.
1189 * @param mixed $meta_value Metadata value.
1190 * @param bool $unique Optional, default is false. Whether the same key should not be added.
1191 * @return int|bool Meta ID on success, false on failure.
1193 function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
1194 return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
1198 * Remove metadata matching criteria from a comment.
1200 * You can match based on the key, or key and value. Removing based on key and
1201 * value, will keep from removing duplicate metadata with the same key. It also
1202 * allows removing all metadata matching key, if needed.
1205 * @link https://codex.wordpress.org/Function_Reference/delete_comment_meta
1207 * @param int $comment_id comment ID
1208 * @param string $meta_key Metadata name.
1209 * @param mixed $meta_value Optional. Metadata value.
1210 * @return bool True on success, false on failure.
1212 function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
1213 return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
1217 * Retrieve comment meta field for a comment.
1220 * @link https://codex.wordpress.org/Function_Reference/get_comment_meta
1222 * @param int $comment_id Comment ID.
1223 * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
1224 * @param bool $single Whether to return a single value.
1225 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
1228 function get_comment_meta($comment_id, $key = '', $single = false) {
1229 return get_metadata('comment', $comment_id, $key, $single);
1233 * Update comment meta field based on comment ID.
1235 * Use the $prev_value parameter to differentiate between meta fields with the
1236 * same key and comment ID.
1238 * If the meta field for the comment does not exist, it will be added.
1241 * @link https://codex.wordpress.org/Function_Reference/update_comment_meta
1243 * @param int $comment_id Comment ID.
1244 * @param string $meta_key Metadata key.
1245 * @param mixed $meta_value Metadata value.
1246 * @param mixed $prev_value Optional. Previous value to check before removing.
1247 * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
1249 function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
1250 return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
1254 * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
1255 * to recall previous comments by this commentator that are still held in moderation.
1257 * @param object $comment Comment object.
1258 * @param object $user Comment author's object.
1262 function wp_set_comment_cookies($comment, $user) {
1263 if ( $user->exists() )
1267 * Filter the lifetime of the comment cookie in seconds.
1271 * @param int $seconds Comment cookie lifetime. Default 30000000.
1273 $comment_cookie_lifetime = apply_filters( 'comment_cookie_lifetime', 30000000 );
1274 $secure = ( 'https' === parse_url( home_url(), PHP_URL_SCHEME ) );
1275 setcookie( 'comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
1276 setcookie( 'comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
1277 setcookie( 'comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
1281 * Sanitizes the cookies sent to the user already.
1283 * Will only do anything if the cookies have already been created for the user.
1284 * Mostly used after cookies had been sent to use elsewhere.
1288 function sanitize_comment_cookies() {
1289 if ( isset( $_COOKIE['comment_author_' . COOKIEHASH] ) ) {
1291 * Filter the comment author's name cookie before it is set.
1293 * When this filter hook is evaluated in wp_filter_comment(),
1294 * the comment author's name string is passed.
1298 * @param string $author_cookie The comment author name cookie.
1300 $comment_author = apply_filters( 'pre_comment_author_name', $_COOKIE['comment_author_' . COOKIEHASH] );
1301 $comment_author = wp_unslash($comment_author);
1302 $comment_author = esc_attr($comment_author);
1303 $_COOKIE['comment_author_' . COOKIEHASH] = $comment_author;
1306 if ( isset( $_COOKIE['comment_author_email_' . COOKIEHASH] ) ) {
1308 * Filter the comment author's email cookie before it is set.
1310 * When this filter hook is evaluated in wp_filter_comment(),
1311 * the comment author's email string is passed.
1315 * @param string $author_email_cookie The comment author email cookie.
1317 $comment_author_email = apply_filters( 'pre_comment_author_email', $_COOKIE['comment_author_email_' . COOKIEHASH] );
1318 $comment_author_email = wp_unslash($comment_author_email);
1319 $comment_author_email = esc_attr($comment_author_email);
1320 $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
1323 if ( isset( $_COOKIE['comment_author_url_' . COOKIEHASH] ) ) {
1325 * Filter the comment author's URL cookie before it is set.
1327 * When this filter hook is evaluated in wp_filter_comment(),
1328 * the comment author's URL string is passed.
1332 * @param string $author_url_cookie The comment author URL cookie.
1334 $comment_author_url = apply_filters( 'pre_comment_author_url', $_COOKIE['comment_author_url_' . COOKIEHASH] );
1335 $comment_author_url = wp_unslash($comment_author_url);
1336 $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
1341 * Validates whether this comment is allowed to be made.
1345 * @global wpdb $wpdb WordPress database abstraction object.
1347 * @param array $commentdata Contains information on the comment
1348 * @return int|string Signifies the approval status (0|1|'spam')
1350 function wp_allow_comment( $commentdata ) {
1353 // Simple duplicate check
1354 // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
1355 $dupe = $wpdb->prepare(
1356 "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ",
1357 wp_unslash( $commentdata['comment_post_ID'] ),
1358 wp_unslash( $commentdata['comment_parent'] ),
1359 wp_unslash( $commentdata['comment_author'] )
1361 if ( $commentdata['comment_author_email'] ) {
1362 $dupe .= $wpdb->prepare(
1363 "OR comment_author_email = %s ",
1364 wp_unslash( $commentdata['comment_author_email'] )
1367 $dupe .= $wpdb->prepare(
1368 ") AND comment_content = %s LIMIT 1",
1369 wp_unslash( $commentdata['comment_content'] )
1371 if ( $wpdb->get_var( $dupe ) ) {
1373 * Fires immediately after a duplicate comment is detected.
1377 * @param array $commentdata Comment data.
1379 do_action( 'comment_duplicate_trigger', $commentdata );
1380 if ( defined( 'DOING_AJAX' ) ) {
1381 die( __('Duplicate comment detected; it looks as though you’ve already said that!') );
1383 wp_die( __( 'Duplicate comment detected; it looks as though you’ve already said that!' ), 409 );
1387 * Fires immediately before a comment is marked approved.
1389 * Allows checking for comment flooding.
1393 * @param string $comment_author_IP Comment author's IP address.
1394 * @param string $comment_author_email Comment author's email.
1395 * @param string $comment_date_gmt GMT date the comment was posted.
1398 'check_comment_flood',
1399 $commentdata['comment_author_IP'],
1400 $commentdata['comment_author_email'],
1401 $commentdata['comment_date_gmt']
1404 if ( ! empty( $commentdata['user_id'] ) ) {
1405 $user = get_userdata( $commentdata['user_id'] );
1406 $post_author = $wpdb->get_var( $wpdb->prepare(
1407 "SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1",
1408 $commentdata['comment_post_ID']
1412 if ( isset( $user ) && ( $commentdata['user_id'] == $post_author || $user->has_cap( 'moderate_comments' ) ) ) {
1413 // The author and the admins get respect.
1416 // Everyone else's comments will be checked.
1418 $commentdata['comment_author'],
1419 $commentdata['comment_author_email'],
1420 $commentdata['comment_author_url'],
1421 $commentdata['comment_content'],
1422 $commentdata['comment_author_IP'],
1423 $commentdata['comment_agent'],
1424 $commentdata['comment_type']
1431 if ( wp_blacklist_check(
1432 $commentdata['comment_author'],
1433 $commentdata['comment_author_email'],
1434 $commentdata['comment_author_url'],
1435 $commentdata['comment_content'],
1436 $commentdata['comment_author_IP'],
1437 $commentdata['comment_agent']
1444 * Filter a comment's approval status before it is set.
1448 * @param bool|string $approved The approval status. Accepts 1, 0, or 'spam'.
1449 * @param array $commentdata Comment data.
1451 $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
1456 * Check whether comment flooding is occurring.
1458 * Won't run, if current user can manage options, so to not block
1463 * @global wpdb $wpdb WordPress database abstraction object.
1465 * @param string $ip Comment IP.
1466 * @param string $email Comment author email address.
1467 * @param string $date MySQL time string.
1469 function check_comment_flood_db( $ip, $email, $date ) {
1471 if ( current_user_can( 'manage_options' ) )
1472 return; // don't throttle admins
1473 $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
1474 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 ) ) ) {
1475 $time_lastcomment = mysql2date('U', $lasttime, false);
1476 $time_newcomment = mysql2date('U', $date, false);
1478 * Filter the comment flood status.
1482 * @param bool $bool Whether a comment flood is occurring. Default false.
1483 * @param int $time_lastcomment Timestamp of when the last comment was posted.
1484 * @param int $time_newcomment Timestamp of when the new comment was posted.
1486 $flood_die = apply_filters( 'comment_flood_filter', false, $time_lastcomment, $time_newcomment );
1489 * Fires before the comment flood message is triggered.
1493 * @param int $time_lastcomment Timestamp of when the last comment was posted.
1494 * @param int $time_newcomment Timestamp of when the new comment was posted.
1496 do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment );
1498 if ( defined('DOING_AJAX') )
1499 die( __('You are posting comments too quickly. Slow down.') );
1501 wp_die( __( 'You are posting comments too quickly. Slow down.' ), 429 );
1507 * Separates an array of comments into an array keyed by comment_type.
1511 * @param array $comments Array of comments
1512 * @return array Array of comments keyed by comment_type.
1514 function separate_comments(&$comments) {
1515 $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
1516 $count = count($comments);
1517 for ( $i = 0; $i < $count; $i++ ) {
1518 $type = $comments[$i]->comment_type;
1521 $comments_by_type[$type][] = &$comments[$i];
1522 if ( 'trackback' == $type || 'pingback' == $type )
1523 $comments_by_type['pings'][] = &$comments[$i];
1526 return $comments_by_type;
1530 * Calculate the total number of comment pages.
1534 * @uses Walker_Comment
1536 * @global WP_Query $wp_query
1538 * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
1539 * @param int $per_page Optional comments per page.
1540 * @param bool $threaded Optional control over flat or threaded comments.
1541 * @return int Number of comment pages.
1543 function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
1546 if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
1547 return $wp_query->max_num_comment_pages;
1549 if ( ( ! $comments || ! is_array( $comments ) ) && ! empty( $wp_query->comments ) )
1550 $comments = $wp_query->comments;
1552 if ( empty($comments) )
1555 if ( ! get_option( 'page_comments' ) )
1558 if ( !isset($per_page) )
1559 $per_page = (int) get_query_var('comments_per_page');
1560 if ( 0 === $per_page )
1561 $per_page = (int) get_option('comments_per_page');
1562 if ( 0 === $per_page )
1565 if ( !isset($threaded) )
1566 $threaded = get_option('thread_comments');
1569 $walker = new Walker_Comment;
1570 $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
1572 $count = ceil( count( $comments ) / $per_page );
1579 * Calculate what page number a comment will appear on for comment paging.
1583 * @global wpdb $wpdb
1585 * @param int $comment_ID Comment ID.
1586 * @param array $args Optional args.
1587 * @return int|null Comment page number or null on error.
1589 function get_page_of_comment( $comment_ID, $args = array() ) {
1592 if ( !$comment = get_comment( $comment_ID ) )
1595 $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
1596 $args = wp_parse_args( $args, $defaults );
1598 if ( '' === $args['per_page'] && get_option('page_comments') )
1599 $args['per_page'] = get_query_var('comments_per_page');
1600 if ( empty($args['per_page']) ) {
1601 $args['per_page'] = 0;
1604 if ( $args['per_page'] < 1 )
1607 if ( '' === $args['max_depth'] ) {
1608 if ( get_option('thread_comments') )
1609 $args['max_depth'] = get_option('thread_comments_depth');
1611 $args['max_depth'] = -1;
1614 // Find this comment's top level parent if threading is enabled
1615 if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
1616 return get_page_of_comment( $comment->comment_parent, $args );
1618 $allowedtypes = array(
1620 'pingback' => 'pingback',
1621 'trackback' => 'trackback',
1624 $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
1626 // Count comments older than this one
1627 $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 ) );
1629 // No older comments? Then it's page #1.
1630 if ( 0 == $oldercoms )
1633 // Divide comments older than this one by comments per page to get this comment's page number
1634 return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
1638 * Does comment contain blacklisted characters or words.
1642 * @param string $author The author of the comment
1643 * @param string $email The email of the comment
1644 * @param string $url The url used in the comment
1645 * @param string $comment The comment content
1646 * @param string $user_ip The comment author IP address
1647 * @param string $user_agent The author's browser user agent
1648 * @return bool True if comment contains blacklisted content, false if comment does not
1650 function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
1652 * Fires before the comment is tested for blacklisted characters or words.
1656 * @param string $author Comment author.
1657 * @param string $email Comment author's email.
1658 * @param string $url Comment author's URL.
1659 * @param string $comment Comment content.
1660 * @param string $user_ip Comment author's IP address.
1661 * @param string $user_agent Comment author's browser user agent.
1663 do_action( 'wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent );
1665 $mod_keys = trim( get_option('blacklist_keys') );
1666 if ( '' == $mod_keys )
1667 return false; // If moderation keys are empty
1668 $words = explode("\n", $mod_keys );
1670 foreach ( (array) $words as $word ) {
1671 $word = trim($word);
1674 if ( empty($word) ) { continue; }
1676 // Do some escaping magic so that '#' chars in the
1677 // spam words don't break things:
1678 $word = preg_quote($word, '#');
1680 $pattern = "#$word#i";
1682 preg_match($pattern, $author)
1683 || preg_match($pattern, $email)
1684 || preg_match($pattern, $url)
1685 || preg_match($pattern, $comment)
1686 || preg_match($pattern, $user_ip)
1687 || preg_match($pattern, $user_agent)
1695 * Retrieve total comments for blog or single post.
1697 * The properties of the returned object contain the 'moderated', 'approved',
1698 * and spam comments for either the entire blog or single post. Those properties
1699 * contain the amount of comments that match the status. The 'total_comments'
1700 * property contains the integer of total comments.
1702 * The comment stats are cached and then retrieved, if they already exist in the
1707 * @global wpdb $wpdb
1709 * @param int $post_id Optional. Post ID.
1710 * @return object|array Comment stats.
1712 function wp_count_comments( $post_id = 0 ) {
1715 $post_id = (int) $post_id;
1718 * Filter the comments count for a given post.
1722 * @param array $count An empty array.
1723 * @param int $post_id The post ID.
1725 $stats = apply_filters( 'wp_count_comments', array(), $post_id );
1726 if ( !empty($stats) )
1729 $count = wp_cache_get("comments-{$post_id}", 'counts');
1731 if ( false !== $count )
1736 $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
1738 $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
1741 $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
1742 foreach ( (array) $count as $row ) {
1743 // Don't count post-trashed toward totals
1744 if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
1745 $total += $row['num_comments'];
1746 if ( isset( $approved[$row['comment_approved']] ) )
1747 $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
1750 $stats['total_comments'] = $total;
1751 foreach ( $approved as $key ) {
1752 if ( empty($stats[$key]) )
1756 $stats = (object) $stats;
1757 wp_cache_set("comments-{$post_id}", $stats, 'counts');
1763 * Trashes or deletes a comment.
1765 * The comment is moved to trash instead of permanently deleted unless trash is
1766 * disabled, item is already in the trash, or $force_delete is true.
1768 * The post comment count will be updated if the comment was approved and has a
1769 * post ID available.
1773 * @global wpdb $wpdb WordPress database abstraction object.
1775 * @param int $comment_id Comment ID
1776 * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
1777 * @return bool True on success, false on failure.
1779 function wp_delete_comment($comment_id, $force_delete = false) {
1781 if (!$comment = get_comment($comment_id))
1784 if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) )
1785 return wp_trash_comment($comment_id);
1788 * Fires immediately before a comment is deleted from the database.
1792 * @param int $comment_id The comment ID.
1794 do_action( 'delete_comment', $comment_id );
1796 // Move children up a level.
1797 $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
1798 if ( !empty($children) ) {
1799 $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
1800 clean_comment_cache($children);
1804 $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment_id ) );
1805 foreach ( $meta_ids as $mid )
1806 delete_metadata_by_mid( 'comment', $mid );
1808 if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment_id ) ) )
1812 * Fires immediately after a comment is deleted from the database.
1816 * @param int $comment_id The comment ID.
1818 do_action( 'deleted_comment', $comment_id );
1820 $post_id = $comment->comment_post_ID;
1821 if ( $post_id && $comment->comment_approved == 1 )
1822 wp_update_comment_count($post_id);
1824 clean_comment_cache($comment_id);
1826 /** This action is documented in wp-includes/comment.php */
1827 do_action( 'wp_set_comment_status', $comment_id, 'delete' );
1829 wp_transition_comment_status('delete', $comment->comment_approved, $comment);
1834 * Moves a comment to the Trash
1836 * If trash is disabled, comment is permanently deleted.
1840 * @param int $comment_id Comment ID.
1841 * @return bool True on success, false on failure.
1843 function wp_trash_comment($comment_id) {
1844 if ( !EMPTY_TRASH_DAYS )
1845 return wp_delete_comment($comment_id, true);
1847 if ( !$comment = get_comment($comment_id) )
1851 * Fires immediately before a comment is sent to the Trash.
1855 * @param int $comment_id The comment ID.
1857 do_action( 'trash_comment', $comment_id );
1859 if ( wp_set_comment_status($comment_id, 'trash') ) {
1860 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
1861 add_comment_meta($comment_id, '_wp_trash_meta_time', time() );
1864 * Fires immediately after a comment is sent to Trash.
1868 * @param int $comment_id The comment ID.
1870 do_action( 'trashed_comment', $comment_id );
1878 * Removes a comment from the Trash
1882 * @param int $comment_id Comment ID.
1883 * @return bool True on success, false on failure.
1885 function wp_untrash_comment($comment_id) {
1886 if ( ! (int)$comment_id )
1890 * Fires immediately before a comment is restored from the Trash.
1894 * @param int $comment_id The comment ID.
1896 do_action( 'untrash_comment', $comment_id );
1898 $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
1899 if ( empty($status) )
1902 if ( wp_set_comment_status($comment_id, $status) ) {
1903 delete_comment_meta($comment_id, '_wp_trash_meta_time');
1904 delete_comment_meta($comment_id, '_wp_trash_meta_status');
1906 * Fires immediately after a comment is restored from the Trash.
1910 * @param int $comment_id The comment ID.
1912 do_action( 'untrashed_comment', $comment_id );
1920 * Marks a comment as Spam
1924 * @param int $comment_id Comment ID.
1925 * @return bool True on success, false on failure.
1927 function wp_spam_comment($comment_id) {
1928 if ( !$comment = get_comment($comment_id) )
1932 * Fires immediately before a comment is marked as Spam.
1936 * @param int $comment_id The comment ID.
1938 do_action( 'spam_comment', $comment_id );
1940 if ( wp_set_comment_status($comment_id, 'spam') ) {
1941 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
1943 * Fires immediately after a comment is marked as Spam.
1947 * @param int $comment_id The comment ID.
1949 do_action( 'spammed_comment', $comment_id );
1957 * Removes a comment from the Spam
1961 * @param int $comment_id Comment ID.
1962 * @return bool True on success, false on failure.
1964 function wp_unspam_comment($comment_id) {
1965 if ( ! (int)$comment_id )
1969 * Fires immediately before a comment is unmarked as Spam.
1973 * @param int $comment_id The comment ID.
1975 do_action( 'unspam_comment', $comment_id );
1977 $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
1978 if ( empty($status) )
1981 if ( wp_set_comment_status($comment_id, $status) ) {
1982 delete_comment_meta($comment_id, '_wp_trash_meta_status');
1984 * Fires immediately after a comment is unmarked as Spam.
1988 * @param int $comment_id The comment ID.
1990 do_action( 'unspammed_comment', $comment_id );
1998 * The status of a comment by ID.
2002 * @param int $comment_id Comment ID
2003 * @return false|string Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
2005 function wp_get_comment_status($comment_id) {
2006 $comment = get_comment($comment_id);
2010 $approved = $comment->comment_approved;
2012 if ( $approved == null )
2014 elseif ( $approved == '1' )
2016 elseif ( $approved == '0' )
2017 return 'unapproved';
2018 elseif ( $approved == 'spam' )
2020 elseif ( $approved == 'trash' )
2027 * Call hooks for when a comment status transition occurs.
2029 * Calls hooks for comment status transitions. If the new comment status is not the same
2030 * as the previous comment status, then two hooks will be ran, the first is
2031 * 'transition_comment_status' with new status, old status, and comment data. The
2032 * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
2033 * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
2036 * The final action will run whether or not the comment statuses are the same. The
2037 * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
2038 * parameter and COMMENTTYPE is comment_type comment data.
2042 * @param string $new_status New comment status.
2043 * @param string $old_status Previous comment status.
2044 * @param object $comment Comment data.
2046 function wp_transition_comment_status($new_status, $old_status, $comment) {
2048 * Translate raw statuses to human readable formats for the hooks.
2049 * This is not a complete list of comment status, it's only the ones
2050 * that need to be renamed
2052 $comment_statuses = array(
2054 'hold' => 'unapproved', // wp_set_comment_status() uses "hold"
2056 'approve' => 'approved', // wp_set_comment_status() uses "approve"
2058 if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
2059 if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
2062 if ( $new_status != $old_status ) {
2064 * Fires when the comment status is in transition.
2068 * @param int|string $new_status The new comment status.
2069 * @param int|string $old_status The old comment status.
2070 * @param object $comment The comment data.
2072 do_action( 'transition_comment_status', $new_status, $old_status, $comment );
2074 * Fires when the comment status is in transition from one specific status to another.
2076 * The dynamic portions of the hook name, `$old_status`, and `$new_status`,
2077 * refer to the old and new comment statuses, respectively.
2081 * @param object $comment Comment object.
2083 do_action( "comment_{$old_status}_to_{$new_status}", $comment );
2086 * Fires when the status of a specific comment type is in transition.
2088 * The dynamic portions of the hook name, `$new_status`, and `$comment->comment_type`,
2089 * refer to the new comment status, and the type of comment, respectively.
2091 * Typical comment types include an empty string (standard comment), 'pingback',
2096 * @param int $comment_ID The comment ID.
2097 * @param obj $comment Comment object.
2099 do_action( "comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment );
2103 * Get current commenter's name, email, and URL.
2105 * Expects cookies content to already be sanitized. User of this function might
2106 * wish to recheck the returned array for validity.
2108 * @see sanitize_comment_cookies() Use to sanitize cookies
2112 * @return array Comment author, email, url respectively.
2114 function wp_get_current_commenter() {
2115 // Cookies should already be sanitized.
2117 $comment_author = '';
2118 if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
2119 $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
2121 $comment_author_email = '';
2122 if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
2123 $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
2125 $comment_author_url = '';
2126 if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
2127 $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
2130 * Filter the current commenter's name, email, and URL.
2134 * @param string $comment_author Comment author's name.
2135 * @param string $comment_author_email Comment author's email.
2136 * @param string $comment_author_url Comment author's URL.
2138 return apply_filters( 'wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url') );
2142 * Inserts a comment into the database.
2146 * @global wpdb $wpdb WordPress database abstraction object.
2148 * @param array $commentdata {
2149 * Array of arguments for inserting a new comment.
2151 * @type string $comment_agent The HTTP user agent of the `$comment_author` when
2152 * the comment was submitted. Default empty.
2153 * @type int|string $comment_approved Whether the comment has been approved. Default 1.
2154 * @type string $comment_author The name of the author of the comment. Default empty.
2155 * @type string $comment_author_email The email address of the `$comment_author`. Default empty.
2156 * @type string $comment_author_IP The IP address of the `$comment_author`. Default empty.
2157 * @type string $comment_author_url The URL address of the `$comment_author`. Default empty.
2158 * @type string $comment_content The content of the comment. Default empty.
2159 * @type string $comment_date The date the comment was submitted. To set the date
2160 * manually, `$comment_date_gmt` must also be specified.
2161 * Default is the current time.
2162 * @type string $comment_date_gmt The date the comment was submitted in the GMT timezone.
2163 * Default is `$comment_date` in the site's GMT timezone.
2164 * @type int $comment_karma The karma of the comment. Default 0.
2165 * @type int $comment_parent ID of this comment's parent, if any. Default 0.
2166 * @type int $comment_post_ID ID of the post that relates to the comment, if any.
2168 * @type string $comment_type Comment type. Default empty.
2169 * @type int $user_id ID of the user who submitted the comment. Default 0.
2171 * @return int|false The new comment's ID on success, false on failure.
2173 function wp_insert_comment( $commentdata ) {
2175 $data = wp_unslash( $commentdata );
2177 $comment_author = ! isset( $data['comment_author'] ) ? '' : $data['comment_author'];
2178 $comment_author_email = ! isset( $data['comment_author_email'] ) ? '' : $data['comment_author_email'];
2179 $comment_author_url = ! isset( $data['comment_author_url'] ) ? '' : $data['comment_author_url'];
2180 $comment_author_IP = ! isset( $data['comment_author_IP'] ) ? '' : $data['comment_author_IP'];
2182 $comment_date = ! isset( $data['comment_date'] ) ? current_time( 'mysql' ) : $data['comment_date'];
2183 $comment_date_gmt = ! isset( $data['comment_date_gmt'] ) ? get_gmt_from_date( $comment_date ) : $data['comment_date_gmt'];
2185 $comment_post_ID = ! isset( $data['comment_post_ID'] ) ? '' : $data['comment_post_ID'];
2186 $comment_content = ! isset( $data['comment_content'] ) ? '' : $data['comment_content'];
2187 $comment_karma = ! isset( $data['comment_karma'] ) ? 0 : $data['comment_karma'];
2188 $comment_approved = ! isset( $data['comment_approved'] ) ? 1 : $data['comment_approved'];
2189 $comment_agent = ! isset( $data['comment_agent'] ) ? '' : $data['comment_agent'];
2190 $comment_type = ! isset( $data['comment_type'] ) ? '' : $data['comment_type'];
2191 $comment_parent = ! isset( $data['comment_parent'] ) ? 0 : $data['comment_parent'];
2193 $user_id = ! isset( $data['user_id'] ) ? 0 : $data['user_id'];
2195 $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' );
2196 if ( ! $wpdb->insert( $wpdb->comments, $compacted ) ) {
2200 $id = (int) $wpdb->insert_id;
2202 if ( $comment_approved == 1 ) {
2203 wp_update_comment_count( $comment_post_ID );
2205 $comment = get_comment( $id );
2208 * Fires immediately after a comment is inserted into the database.
2212 * @param int $id The comment ID.
2213 * @param obj $comment Comment object.
2215 do_action( 'wp_insert_comment', $id, $comment );
2217 wp_cache_set( 'last_changed', microtime(), 'comment' );
2223 * Filters and sanitizes comment data.
2225 * Sets the comment data 'filtered' field to true when finished. This can be
2226 * checked as to whether the comment should be filtered and to keep from
2227 * filtering the same comment more than once.
2231 * @param array $commentdata Contains information on the comment.
2232 * @return array Parsed comment information.
2234 function wp_filter_comment($commentdata) {
2235 if ( isset( $commentdata['user_ID'] ) ) {
2237 * Filter the comment author's user id before it is set.
2239 * The first time this filter is evaluated, 'user_ID' is checked
2240 * (for back-compat), followed by the standard 'user_id' value.
2244 * @param int $user_ID The comment author's user ID.
2246 $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_ID'] );
2247 } elseif ( isset( $commentdata['user_id'] ) ) {
2248 /** This filter is documented in wp-includes/comment.php */
2249 $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_id'] );
2253 * Filter the comment author's browser user agent before it is set.
2257 * @param int $comment_agent The comment author's browser user agent.
2259 $commentdata['comment_agent'] = apply_filters( 'pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
2260 /** This filter is documented in wp-includes/comment.php */
2261 $commentdata['comment_author'] = apply_filters( 'pre_comment_author_name', $commentdata['comment_author'] );
2263 * Filter the comment content before it is set.
2267 * @param int $comment_content The comment content.
2269 $commentdata['comment_content'] = apply_filters( 'pre_comment_content', $commentdata['comment_content'] );
2271 * Filter the comment author's IP before it is set.
2275 * @param int $comment_author_ip The comment author's IP.
2277 $commentdata['comment_author_IP'] = apply_filters( 'pre_comment_user_ip', $commentdata['comment_author_IP'] );
2278 /** This filter is documented in wp-includes/comment.php */
2279 $commentdata['comment_author_url'] = apply_filters( 'pre_comment_author_url', $commentdata['comment_author_url'] );
2280 /** This filter is documented in wp-includes/comment.php */
2281 $commentdata['comment_author_email'] = apply_filters( 'pre_comment_author_email', $commentdata['comment_author_email'] );
2282 $commentdata['filtered'] = true;
2283 return $commentdata;
2287 * Whether a comment should be blocked because of comment flood.
2291 * @param bool $block Whether plugin has already blocked comment.
2292 * @param int $time_lastcomment Timestamp for last comment.
2293 * @param int $time_newcomment Timestamp for new comment.
2294 * @return bool Whether comment should be blocked.
2296 function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
2297 if ( $block ) // a plugin has already blocked... we'll let that decision stand
2299 if ( ($time_newcomment - $time_lastcomment) < 15 )
2305 * Adds a new comment to the database.
2307 * Filters new comment to ensure that the fields are sanitized and valid before
2308 * inserting comment into database. Calls 'comment_post' action with comment ID
2309 * and whether comment is approved by WordPress. Also has 'preprocess_comment'
2310 * filter for processing the comment data before the function handles it.
2312 * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure
2313 * that it is properly set, such as in wp-config.php, for your environment.
2314 * See {@link https://core.trac.wordpress.org/ticket/9235}
2317 * @since 4.3.0 'comment_agent' and 'comment_author_IP' can be set via `$commentdata`.
2319 * @see wp_insert_comment()
2321 * @global wpdb $wpdb
2323 * @param array $commentdata Contains information on the comment. See wp_insert_comment()
2324 * for information on accepted arguments.
2325 * @return int|false The ID of the comment on success, false on failure.
2327 function wp_new_comment( $commentdata ) {
2330 if ( isset( $commentdata['user_ID'] ) ) {
2331 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
2334 $prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0;
2337 * Filter a comment's data before it is sanitized and inserted into the database.
2341 * @param array $commentdata Comment data.
2343 $commentdata = apply_filters( 'preprocess_comment', $commentdata );
2345 $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
2346 if ( isset( $commentdata['user_ID'] ) && $prefiltered_user_id !== (int) $commentdata['user_ID'] ) {
2347 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
2348 } elseif ( isset( $commentdata['user_id'] ) ) {
2349 $commentdata['user_id'] = (int) $commentdata['user_id'];
2352 $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
2353 $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
2354 $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
2356 if ( ! isset( $commentdata['comment_author_IP'] ) ) {
2357 $commentdata['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
2359 $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '', $commentdata['comment_author_IP'] );
2361 if ( ! isset( $commentdata['comment_agent'] ) ) {
2362 $commentdata['comment_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT']: '';
2364 $commentdata['comment_agent'] = substr( $commentdata['comment_agent'], 0, 254 );
2366 if ( empty( $commentdata['comment_date'] ) ) {
2367 $commentdata['comment_date'] = current_time('mysql');
2370 if ( empty( $commentdata['comment_date_gmt'] ) ) {
2371 $commentdata['comment_date_gmt'] = current_time( 'mysql', 1 );
2374 $commentdata = wp_filter_comment($commentdata);
2376 $commentdata['comment_approved'] = wp_allow_comment($commentdata);
2378 $comment_ID = wp_insert_comment($commentdata);
2379 if ( ! $comment_ID ) {
2380 $fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' );
2382 foreach( $fields as $field ) {
2383 if ( isset( $commentdata[ $field ] ) ) {
2384 $commentdata[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $commentdata[ $field ] );
2388 $commentdata = wp_filter_comment( $commentdata );
2390 $commentdata['comment_approved'] = wp_allow_comment( $commentdata );
2392 $comment_ID = wp_insert_comment( $commentdata );
2393 if ( ! $comment_ID ) {
2399 * Fires immediately after a comment is inserted into the database.
2403 * @param int $comment_ID The comment ID.
2404 * @param int $comment_approved 1 (true) if the comment is approved, 0 (false) if not.
2406 do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'] );
2408 if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
2409 if ( '0' == $commentdata['comment_approved'] ) {
2410 wp_notify_moderator( $comment_ID );
2413 // wp_notify_postauthor() checks if notifying the author of their own comment.
2414 // By default, it won't, but filters can override this.
2415 if ( get_option( 'comments_notify' ) && $commentdata['comment_approved'] ) {
2416 wp_notify_postauthor( $comment_ID );
2424 * Sets the status of a comment.
2426 * The 'wp_set_comment_status' action is called after the comment is handled.
2427 * If the comment status is not in the list, then false is returned.
2433 * @param int $comment_id Comment ID.
2434 * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
2435 * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
2436 * @return bool|WP_Error True on success, false or WP_Error on failure.
2438 function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
2441 switch ( $comment_status ) {
2449 if ( get_option('comments_notify') ) {
2450 wp_notify_postauthor( $comment_id );
2463 $comment_old = clone get_comment($comment_id);
2465 if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
2467 return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
2472 clean_comment_cache($comment_id);
2474 $comment = get_comment($comment_id);
2477 * Fires immediately before transitioning a comment's status from one to another
2482 * @param int $comment_id Comment ID.
2483 * @param string|bool $comment_status Current comment status. Possible values include
2484 * 'hold', 'approve', 'spam', 'trash', or false.
2486 do_action( 'wp_set_comment_status', $comment_id, $comment_status );
2488 wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
2490 wp_update_comment_count($comment->comment_post_ID);
2496 * Updates an existing comment in the database.
2498 * Filters the comment and makes sure certain fields are valid before updating.
2502 * @global wpdb $wpdb WordPress database abstraction object.
2504 * @param array $commentarr Contains information on the comment.
2505 * @return int Comment was updated if value is 1, or was not updated if value is 0.
2507 function wp_update_comment($commentarr) {
2510 // First, get all of the original fields
2511 $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
2512 if ( empty( $comment ) ) {
2516 // Make sure that the comment post ID is valid (if specified).
2517 if ( isset( $commentarr['comment_post_ID'] ) && ! get_post( $commentarr['comment_post_ID'] ) ) {
2521 // Escape data pulled from DB.
2522 $comment = wp_slash($comment);
2524 $old_status = $comment['comment_approved'];
2526 // Merge old and new fields with new fields overwriting old ones.
2527 $commentarr = array_merge($comment, $commentarr);
2529 $commentarr = wp_filter_comment( $commentarr );
2531 // Now extract the merged array.
2532 $data = wp_unslash( $commentarr );
2535 * Filter the comment content before it is updated in the database.
2539 * @param string $comment_content The comment data.
2541 $data['comment_content'] = apply_filters( 'comment_save_pre', $data['comment_content'] );
2543 $data['comment_date_gmt'] = get_gmt_from_date( $data['comment_date'] );
2545 if ( ! isset( $data['comment_approved'] ) ) {
2546 $data['comment_approved'] = 1;
2547 } elseif ( 'hold' == $data['comment_approved'] ) {
2548 $data['comment_approved'] = 0;
2549 } elseif ( 'approve' == $data['comment_approved'] ) {
2550 $data['comment_approved'] = 1;
2553 $comment_ID = $data['comment_ID'];
2554 $comment_post_ID = $data['comment_post_ID'];
2555 $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' );
2556 $data = wp_array_slice_assoc( $data, $keys );
2557 $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
2559 clean_comment_cache( $comment_ID );
2560 wp_update_comment_count( $comment_post_ID );
2562 * Fires immediately after a comment is updated in the database.
2564 * The hook also fires immediately before comment status transition hooks are fired.
2568 * @param int $comment_ID The comment ID.
2570 do_action( 'edit_comment', $comment_ID );
2571 $comment = get_comment($comment_ID);
2572 wp_transition_comment_status($comment->comment_approved, $old_status, $comment);
2577 * Whether to defer comment counting.
2579 * When setting $defer to true, all post comment counts will not be updated
2580 * until $defer is set to false. When $defer is set to false, then all
2581 * previously deferred updated post comment counts will then be automatically
2582 * updated without having to call wp_update_comment_count() after.
2585 * @staticvar bool $_defer
2587 * @param bool $defer
2590 function wp_defer_comment_counting($defer=null) {
2591 static $_defer = false;
2593 if ( is_bool($defer) ) {
2595 // flush any deferred counts
2597 wp_update_comment_count( null, true );
2604 * Updates the comment count for post(s).
2606 * When $do_deferred is false (is by default) and the comments have been set to
2607 * be deferred, the post_id will be added to a queue, which will be updated at a
2608 * later date and only updated once per post ID.
2610 * If the comments have not be set up to be deferred, then the post will be
2611 * updated. When $do_deferred is set to true, then all previous deferred post
2612 * IDs will be updated along with the current $post_id.
2615 * @see wp_update_comment_count_now() For what could cause a false return value
2617 * @staticvar array $_deferred
2619 * @param int $post_id Post ID
2620 * @param bool $do_deferred Whether to process previously deferred post comment counts
2621 * @return bool|void True on success, false on failure
2623 function wp_update_comment_count($post_id, $do_deferred=false) {
2624 static $_deferred = array();
2626 if ( $do_deferred ) {
2627 $_deferred = array_unique($_deferred);
2628 foreach ( $_deferred as $i => $_post_id ) {
2629 wp_update_comment_count_now($_post_id);
2630 unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
2634 if ( wp_defer_comment_counting() ) {
2635 $_deferred[] = $post_id;
2638 elseif ( $post_id ) {
2639 return wp_update_comment_count_now($post_id);
2645 * Updates the comment count for the post.
2649 * @global wpdb $wpdb WordPress database abstraction object.
2651 * @param int $post_id Post ID
2652 * @return bool True on success, false on '0' $post_id or if post with ID does not exist.
2654 function wp_update_comment_count_now($post_id) {
2656 $post_id = (int) $post_id;
2659 if ( !$post = get_post($post_id) )
2662 $old = (int) $post->comment_count;
2663 $new = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id) );
2664 $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) );
2666 clean_post_cache( $post );
2669 * Fires immediately after a post's comment count is updated in the database.
2673 * @param int $post_id Post ID.
2674 * @param int $new The new comment count.
2675 * @param int $old The old comment count.
2677 do_action( 'wp_update_comment_count', $post_id, $new, $old );
2678 /** This action is documented in wp-includes/post.php */
2679 do_action( 'edit_post', $post_id, $post );
2685 // Ping and trackback functions.
2689 * Finds a pingback server URI based on the given URL.
2691 * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
2692 * a check for the x-pingback headers first and returns that, if available. The
2693 * check for the rel="pingback" has more overhead than just the header.
2697 * @param string $url URL to ping.
2698 * @param int $deprecated Not Used.
2699 * @return false|string False on failure, string containing URI on success.
2701 function discover_pingback_server_uri( $url, $deprecated = '' ) {
2702 if ( !empty( $deprecated ) )
2703 _deprecated_argument( __FUNCTION__, '2.7' );
2705 $pingback_str_dquote = 'rel="pingback"';
2706 $pingback_str_squote = 'rel=\'pingback\'';
2708 /** @todo Should use Filter Extension or custom preg_match instead. */
2709 $parsed_url = parse_url($url);
2711 if ( ! isset( $parsed_url['host'] ) ) // Not an URL. This should never happen.
2714 //Do not search for a pingback server on our own uploads
2715 $uploads_dir = wp_upload_dir();
2716 if ( 0 === strpos($url, $uploads_dir['baseurl']) )
2719 $response = wp_safe_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
2721 if ( is_wp_error( $response ) )
2724 if ( wp_remote_retrieve_header( $response, 'x-pingback' ) )
2725 return wp_remote_retrieve_header( $response, 'x-pingback' );
2727 // Not an (x)html, sgml, or xml page, no use going further.
2728 if ( preg_match('#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'content-type' )) )
2731 // Now do a GET since we're going to look in the html headers (and we're sure it's not a binary file)
2732 $response = wp_safe_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
2734 if ( is_wp_error( $response ) )
2737 $contents = wp_remote_retrieve_body( $response );
2739 $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
2740 $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
2741 if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
2742 $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
2743 $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
2744 $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
2745 $pingback_href_start = $pingback_href_pos+6;
2746 $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
2747 $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
2748 $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
2750 // We may find rel="pingback" but an incomplete pingback URL
2751 if ( $pingback_server_url_len > 0 ) { // We got it!
2752 return $pingback_server_url;
2760 * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
2764 * @global wpdb $wpdb WordPress database abstraction object.
2766 function do_all_pings() {
2770 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")) {
2771 delete_metadata_by_mid( 'post', $ping->meta_id );
2772 pingback( $ping->post_content, $ping->ID );
2776 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")) {
2777 delete_metadata_by_mid( 'post', $enclosure->meta_id );
2778 do_enclose( $enclosure->post_content, $enclosure->ID );
2782 $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'");
2783 if ( is_array($trackbacks) )
2784 foreach ( $trackbacks as $trackback )
2785 do_trackbacks($trackback);
2787 //Do Update Services/Generic Pings
2792 * Perform trackbacks.
2796 * @global wpdb $wpdb WordPress database abstraction object.
2798 * @param int $post_id Post ID to do trackbacks on.
2800 function do_trackbacks($post_id) {
2803 $post = get_post( $post_id );
2804 $to_ping = get_to_ping($post_id);
2805 $pinged = get_pung($post_id);
2806 if ( empty($to_ping) ) {
2807 $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) );
2811 if ( empty($post->post_excerpt) ) {
2812 /** This filter is documented in wp-includes/post-template.php */
2813 $excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
2815 /** This filter is documented in wp-includes/post-template.php */
2816 $excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );
2819 $excerpt = str_replace(']]>', ']]>', $excerpt);
2820 $excerpt = wp_html_excerpt($excerpt, 252, '…');
2822 /** This filter is documented in wp-includes/post-template.php */
2823 $post_title = apply_filters( 'the_title', $post->post_title, $post->ID );
2824 $post_title = strip_tags($post_title);
2827 foreach ( (array) $to_ping as $tb_ping ) {
2828 $tb_ping = trim($tb_ping);
2829 if ( !in_array($tb_ping, $pinged) ) {
2830 trackback($tb_ping, $post_title, $excerpt, $post_id);
2831 $pinged[] = $tb_ping;
2833 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post_id) );
2840 * Sends pings to all of the ping site services.
2844 * @param int $post_id Post ID.
2845 * @return int Same as Post ID from parameter
2847 function generic_ping( $post_id = 0 ) {
2848 $services = get_option('ping_sites');
2850 $services = explode("\n", $services);
2851 foreach ( (array) $services as $service ) {
2852 $service = trim($service);
2853 if ( '' != $service )
2854 weblog_ping($service);
2861 * Pings back the links found in a post.
2865 * @global string $wp_version
2867 * @param string $content Post content to check for links.
2868 * @param int $post_ID Post ID.
2870 function pingback($content, $post_ID) {
2872 include_once(ABSPATH . WPINC . '/class-IXR.php');
2873 include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
2875 // original code by Mort (http://mort.mine.nu:8080)
2876 $post_links = array();
2878 $pung = get_pung($post_ID);
2881 // Parsing the post, external links (if any) are stored in the $post_links array
2882 $post_links_temp = wp_extract_urls( $content );
2885 // Walking thru the links array
2886 // first we get rid of links pointing to sites, not to specific files
2888 // http://dummy-weblog.org
2889 // http://dummy-weblog.org/
2890 // http://dummy-weblog.org/post.php
2891 // We don't wanna ping first and second types, even if they have a valid <link/>
2893 foreach ( (array) $post_links_temp as $link_test ) :
2894 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
2895 && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
2896 if ( $test = @parse_url($link_test) ) {
2897 if ( isset($test['query']) )
2898 $post_links[] = $link_test;
2899 elseif ( isset( $test['path'] ) && ( $test['path'] != '/' ) && ( $test['path'] != '' ) )
2900 $post_links[] = $link_test;
2905 $post_links = array_unique( $post_links );
2907 * Fires just before pinging back links found in a post.
2911 * @param array &$post_links An array of post links to be checked, passed by reference.
2912 * @param array &$pung Whether a link has already been pinged, passed by reference.
2913 * @param int $post_ID The post ID.
2915 do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post_ID ) );
2917 foreach ( (array) $post_links as $pagelinkedto ) {
2918 $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
2920 if ( $pingback_server_url ) {
2921 @ set_time_limit( 60 );
2922 // Now, the RPC call
2923 $pagelinkedfrom = get_permalink($post_ID);
2925 // using a timeout of 3 seconds should be enough to cover slow servers
2926 $client = new WP_HTTP_IXR_Client($pingback_server_url);
2927 $client->timeout = 3;
2929 * Filter the user agent sent when pinging-back a URL.
2933 * @param string $concat_useragent The user agent concatenated with ' -- WordPress/'
2934 * and the WordPress version.
2935 * @param string $useragent The useragent.
2936 * @param string $pingback_server_url The server URL being linked to.
2937 * @param string $pagelinkedto URL of page linked to.
2938 * @param string $pagelinkedfrom URL of page linked from.
2940 $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . $wp_version, $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom );
2941 // when set to true, this outputs debug messages by itself
2942 $client->debug = false;
2944 if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
2945 add_ping( $post_ID, $pagelinkedto );
2951 * Check whether blog is public before returning sites.
2955 * @param mixed $sites Will return if blog is public, will not return if not public.
2956 * @return mixed Empty string if blog is not public, returns $sites, if site is public.
2958 function privacy_ping_filter($sites) {
2959 if ( '0' != get_option('blog_public') )
2968 * Updates database when sending trackback to prevent duplicates.
2972 * @global wpdb $wpdb WordPress database abstraction object.
2974 * @param string $trackback_url URL to send trackbacks.
2975 * @param string $title Title of post.
2976 * @param string $excerpt Excerpt of post.
2977 * @param int $ID Post ID.
2978 * @return int|false|void Database query from update.
2980 function trackback($trackback_url, $title, $excerpt, $ID) {
2983 if ( empty($trackback_url) )
2987 $options['timeout'] = 4;
2988 $options['body'] = array(
2990 'url' => get_permalink($ID),
2991 'blog_name' => get_option('blogname'),
2992 'excerpt' => $excerpt
2995 $response = wp_safe_remote_post( $trackback_url, $options );
2997 if ( is_wp_error( $response ) )
3000 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID) );
3001 return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID) );
3009 * @global string $wp_version
3011 * @param string $server Host of blog to connect to.
3012 * @param string $path Path to send the ping.
3014 function weblog_ping($server = '', $path = '') {
3016 include_once(ABSPATH . WPINC . '/class-IXR.php');
3017 include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
3019 // using a timeout of 3 seconds should be enough to cover slow servers
3020 $client = new WP_HTTP_IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
3021 $client->timeout = 3;
3022 $client->useragent .= ' -- WordPress/'.$wp_version;
3024 // when set to true, this outputs debug messages by itself
3025 $client->debug = false;
3026 $home = trailingslashit( home_url() );
3027 if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
3028 $client->query('weblogUpdates.ping', get_option('blogname'), $home);
3032 * Default filter attached to pingback_ping_source_uri to validate the pingback's Source URI
3035 * @see wp_http_validate_url()
3037 * @param string $source_uri
3040 function pingback_ping_source_uri( $source_uri ) {
3041 return (string) wp_http_validate_url( $source_uri );
3045 * Default filter attached to xmlrpc_pingback_error.
3047 * Returns a generic pingback error code unless the error code is 48,
3048 * which reports that the pingback is already registered.
3051 * @link http://www.hixie.ch/specs/pingback/pingback#TOC3
3053 * @param IXR_Error $ixr_error
3056 function xmlrpc_pingback_error( $ixr_error ) {
3057 if ( $ixr_error->code === 48 )
3059 return new IXR_Error( 0, '' );
3067 * Removes comment ID from the comment cache.
3071 * @param int|array $ids Comment ID or array of comment IDs to remove from cache
3073 function clean_comment_cache($ids) {
3074 foreach ( (array) $ids as $id )
3075 wp_cache_delete($id, 'comment');
3077 wp_cache_set( 'last_changed', microtime(), 'comment' );
3081 * Updates the comment cache of given comments.
3083 * Will add the comments in $comments to the cache. If comment ID already exists
3084 * in the comment cache then it will not be updated. The comment is added to the
3085 * cache using the comment group with the key using the ID of the comments.
3089 * @param array $comments Array of comment row objects
3091 function update_comment_cache($comments) {
3092 foreach ( (array) $comments as $comment )
3093 wp_cache_add($comment->comment_ID, $comment, 'comment');
3101 * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
3106 * @param WP_Post $posts Post data object.
3107 * @param WP_Query $query Query object.
3110 function _close_comments_for_old_posts( $posts, $query ) {
3111 if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) )
3115 * Filter the list of post types to automatically close comments for.
3119 * @param array $post_types An array of registered post types. Default array with 'post'.
3121 $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
3122 if ( ! in_array( $posts[0]->post_type, $post_types ) )
3125 $days_old = (int) get_option( 'close_comments_days_old' );
3129 if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
3130 $posts[0]->comment_status = 'closed';
3131 $posts[0]->ping_status = 'closed';
3138 * Close comments on an old post. Hooked to comments_open and pings_open.
3143 * @param bool $open Comments open or closed
3144 * @param int $post_id Post ID
3145 * @return bool $open
3147 function _close_comments_for_old_post( $open, $post_id ) {
3151 if ( !get_option('close_comments_for_old_posts') )
3154 $days_old = (int) get_option('close_comments_days_old');
3158 $post = get_post($post_id);
3160 /** This filter is documented in wp-includes/comment.php */
3161 $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
3162 if ( ! in_array( $post->post_type, $post_types ) )
3165 if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) )