3 * Manages WordPress comments
10 * Checks whether a comment passes internal checks to be allowed to add.
12 * If comment moderation is set in the administration, then all comments,
13 * regardless of their type and whitelist will be set to false. If the number of
14 * links exceeds the amount in the administration, then the check fails. If any
15 * of the parameter contents match the blacklist of words, then the check fails.
17 * If the number of links exceeds the amount in the administration, then the
18 * check fails. If any of the parameter contents match the blacklist of words,
19 * then the check fails.
21 * If the comment author was approved before, then the comment is
22 * automatically whitelisted.
24 * If none of the checks fail, then the failback is to set the check to pass
30 * @param string $author Comment Author's name
31 * @param string $email Comment Author's email
32 * @param string $url Comment Author's URL
33 * @param string $comment Comment contents
34 * @param string $user_ip Comment Author's IP address
35 * @param string $user_agent Comment Author's User Agent
36 * @param string $comment_type Comment type, either user submitted comment,
37 * trackback, or pingback
38 * @return bool Whether the checks passed (true) and the comments should be
39 * displayed or set to moderated
41 function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
44 if ( 1 == get_option('comment_moderation') )
45 return false; // If moderation is set to manual
47 $comment = apply_filters( 'comment_text', $comment );
49 // Check # of external links
50 if ( $max_links = get_option( 'comment_max_links' ) ) {
51 $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out );
52 $num_links = apply_filters( 'comment_max_links_url', $num_links, $url ); // provide for counting of $url as a link
53 if ( $num_links >= $max_links )
57 $mod_keys = trim(get_option('moderation_keys'));
58 if ( !empty($mod_keys) ) {
59 $words = explode("\n", $mod_keys );
61 foreach ( (array) $words as $word) {
68 // Do some escaping magic so that '#' chars in the
69 // spam words don't break things:
70 $word = preg_quote($word, '#');
72 $pattern = "#$word#i";
73 if ( preg_match($pattern, $author) ) return false;
74 if ( preg_match($pattern, $email) ) return false;
75 if ( preg_match($pattern, $url) ) return false;
76 if ( preg_match($pattern, $comment) ) return false;
77 if ( preg_match($pattern, $user_ip) ) return false;
78 if ( preg_match($pattern, $user_agent) ) return false;
82 // Comment whitelisting:
83 if ( 1 == get_option('comment_whitelist')) {
84 if ( 'trackback' != $comment_type && 'pingback' != $comment_type && $author != '' && $email != '' ) {
85 // expected_slashed ($author, $email)
86 $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");
87 if ( ( 1 == $ok_to_comment ) &&
88 ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
100 * Retrieve the approved comments for post $post_id.
105 * @param int $post_id The ID of the post
106 * @return array $comments The approved comments
108 function get_approved_comments($post_id) {
110 return $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1' ORDER BY comment_date", $post_id));
114 * Retrieves comment data given a comment ID or comment object.
116 * If an object is passed then the comment data will be cached and then returned
117 * after being passed through a filter. If the comment is empty, then the global
118 * comment variable will be used, if it is set.
120 * If the comment is empty, then the global comment variable will be used, if it
126 * @param object|string|int $comment Comment to retrieve.
127 * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
128 * @return object|array|null Depends on $output value.
130 function get_comment(&$comment, $output = OBJECT) {
134 if ( empty($comment) ) {
135 if ( isset($GLOBALS['comment']) )
136 $_comment = & $GLOBALS['comment'];
139 } elseif ( is_object($comment) ) {
140 wp_cache_add($comment->comment_ID, $comment, 'comment');
141 $_comment = $comment;
143 if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
144 $_comment = & $GLOBALS['comment'];
145 } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
146 $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
149 wp_cache_add($_comment->comment_ID, $_comment, 'comment');
153 $_comment = apply_filters('get_comment', $_comment);
155 if ( $output == OBJECT ) {
157 } elseif ( $output == ARRAY_A ) {
158 $__comment = get_object_vars($_comment);
160 } elseif ( $output == ARRAY_N ) {
161 $__comment = array_values(get_object_vars($_comment));
169 * Retrieve a list of comments.
171 * The comment list can be for the blog as a whole or for an individual post.
173 * The list of comment arguments are 'status', 'orderby', 'comment_date_gmt',
174 * 'order', 'number', 'offset', and 'post_id'.
179 * @param mixed $args Optional. Array or string of options to override defaults.
180 * @return array List of comments.
182 function get_comments( $args = '' ) {
183 $query = new WP_Comment_Query;
184 return $query->query( $args );
188 * WordPress Comment Query class.
192 class WP_Comment_Query {
194 * Metadata query container
198 * @var object WP_Meta_Query
200 var $meta_query = false;
207 * @param string|array $query_vars
210 function query( $query_vars ) {
214 'author_email' => '',
241 $this->query_vars = wp_parse_args( $query_vars, $defaults );
244 $this->meta_query = new WP_Meta_Query();
245 $this->meta_query->parse_query_vars( $this->query_vars );
247 do_action_ref_array( 'pre_get_comments', array( &$this ) );
248 extract( $this->query_vars, EXTR_SKIP );
250 // $args can be whatever, only use the args defined in defaults to compute the key
251 $key = md5( serialize( compact(array_keys($defaults)) ) );
252 $last_changed = wp_cache_get( 'last_changed', 'comment' );
253 if ( ! $last_changed ) {
254 $last_changed = microtime();
255 wp_cache_set( 'last_changed', $last_changed, 'comment' );
257 $cache_key = "get_comments:$key:$last_changed";
259 if ( $cache = wp_cache_get( $cache_key, 'comment' ) )
262 $post_id = absint($post_id);
264 if ( 'hold' == $status )
265 $approved = "comment_approved = '0'";
266 elseif ( 'approve' == $status )
267 $approved = "comment_approved = '1'";
268 elseif ( ! empty( $status ) && 'all' != $status )
269 $approved = $wpdb->prepare( "comment_approved = %s", $status );
271 $approved = "( comment_approved = '0' OR comment_approved = '1' )";
273 $order = ( 'ASC' == strtoupper($order) ) ? 'ASC' : 'DESC';
275 if ( ! empty( $orderby ) ) {
276 $ordersby = is_array($orderby) ? $orderby : preg_split('/[,\s]/', $orderby);
277 $allowed_keys = array(
281 'comment_author_email',
283 'comment_author_url',
294 if ( ! empty( $this->query_vars['meta_key'] ) ) {
295 $allowed_keys[] = $this->query_vars['meta_key'];
296 $allowed_keys[] = 'meta_value';
297 $allowed_keys[] = 'meta_value_num';
299 $ordersby = array_intersect( $ordersby, $allowed_keys );
300 foreach ( $ordersby as $key => $value ) {
301 if ( $value == $this->query_vars['meta_key'] || $value == 'meta_value' ) {
302 $ordersby[ $key ] = "$wpdb->commentmeta.meta_value";
303 } elseif ( $value == 'meta_value_num' ) {
304 $ordersby[ $key ] = "$wpdb->commentmeta.meta_value+0";
307 $orderby = empty( $ordersby ) ? 'comment_date_gmt' : implode(', ', $ordersby);
309 $orderby = 'comment_date_gmt';
312 $number = absint($number);
313 $offset = absint($offset);
315 if ( !empty($number) ) {
317 $limits = 'LIMIT ' . $offset . ',' . $number;
319 $limits = 'LIMIT ' . $number;
325 $fields = 'COUNT(*)';
332 if ( ! empty($post_id) )
333 $where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
334 if ( '' !== $author_email )
335 $where .= $wpdb->prepare( ' AND comment_author_email = %s', $author_email );
337 $where .= $wpdb->prepare( ' AND comment_karma = %d', $karma );
338 if ( 'comment' == $type ) {
339 $where .= " AND comment_type = ''";
340 } elseif( 'pings' == $type ) {
341 $where .= ' AND comment_type IN ("pingback", "trackback")';
342 } elseif ( ! empty( $type ) ) {
343 $where .= $wpdb->prepare( ' AND comment_type = %s', $type );
345 if ( '' !== $parent )
346 $where .= $wpdb->prepare( ' AND comment_parent = %d', $parent );
347 if ( '' !== $user_id )
348 $where .= $wpdb->prepare( ' AND user_id = %d', $user_id );
349 if ( '' !== $search )
350 $where .= $this->get_search_sql( $search, array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' ) );
352 $post_fields = array_filter( compact( array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type', ) ) );
353 if ( ! empty( $post_fields ) ) {
354 $join = "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
355 foreach( $post_fields as $field_name => $field_value )
356 $where .= $wpdb->prepare( " AND {$wpdb->posts}.{$field_name} = %s", $field_value );
359 if ( ! empty( $this->meta_query->queries ) ) {
360 $clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
361 $join .= $clauses['join'];
362 $where .= $clauses['where'];
363 $groupby = "{$wpdb->comments}.comment_ID";
366 $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits', 'groupby' );
367 $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
368 foreach ( $pieces as $piece )
369 $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
372 $groupby = 'GROUP BY ' . $groupby;
374 $query = "SELECT $fields FROM $wpdb->comments $join WHERE $where $groupby ORDER BY $orderby $order $limits";
377 return $wpdb->get_var( $query );
379 $comments = $wpdb->get_results( $query );
380 $comments = apply_filters_ref_array( 'the_comments', array( $comments, &$this ) );
382 wp_cache_add( $cache_key, $comments, 'comment' );
388 * Used internally to generate an SQL string for searching across multiple columns
393 * @param string $string
397 function get_search_sql( $string, $cols ) {
398 $string = esc_sql( like_escape( $string ) );
401 foreach ( $cols as $col )
402 $searches[] = "$col LIKE '%$string%'";
404 return ' AND (' . implode(' OR ', $searches) . ')';
409 * Retrieve all of the WordPress supported comment statuses.
411 * Comments have a limited set of valid status values, this provides the comment
412 * status values and descriptions.
418 * @return array List of comment statuses.
420 function get_comment_statuses() {
422 'hold' => __('Unapproved'),
423 /* translators: comment status */
424 'approve' => _x('Approved', 'adjective'),
425 /* translators: comment status */
426 'spam' => _x('Spam', 'adjective'),
433 * The date the last comment was modified.
438 * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
439 * or 'server' locations.
440 * @return string Last comment modified date.
442 function get_lastcommentmodified($timezone = 'server') {
444 static $cache_lastcommentmodified = array();
446 if ( isset($cache_lastcommentmodified[$timezone]) )
447 return $cache_lastcommentmodified[$timezone];
449 $add_seconds_server = date('Z');
451 switch ( strtolower($timezone)) {
453 $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
456 $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
459 $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));
463 $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
465 return $lastcommentmodified;
469 * The amount of comments in a post or total comments.
471 * A lot like {@link wp_count_comments()}, in that they both return comment
472 * stats (albeit with different types). The {@link wp_count_comments()} actual
473 * caches, but this function does not.
478 * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
479 * @return array The amount of spam, approved, awaiting moderation, and total comments.
481 function get_comment_count( $post_id = 0 ) {
484 $post_id = (int) $post_id;
487 if ( $post_id > 0 ) {
488 $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
491 $totals = (array) $wpdb->get_results("
492 SELECT comment_approved, COUNT( * ) AS total
493 FROM {$wpdb->comments}
495 GROUP BY comment_approved
498 $comment_count = array(
500 "awaiting_moderation" => 0,
502 "total_comments" => 0
505 foreach ( $totals as $row ) {
506 switch ( $row['comment_approved'] ) {
508 $comment_count['spam'] = $row['total'];
509 $comment_count["total_comments"] += $row['total'];
512 $comment_count['approved'] = $row['total'];
513 $comment_count['total_comments'] += $row['total'];
516 $comment_count['awaiting_moderation'] = $row['total'];
517 $comment_count['total_comments'] += $row['total'];
524 return $comment_count;
528 // Comment meta functions
532 * Add meta data field to a comment.
536 * @link http://codex.wordpress.org/Function_Reference/add_comment_meta
538 * @param int $comment_id Comment ID.
539 * @param string $meta_key Metadata name.
540 * @param mixed $meta_value Metadata value.
541 * @param bool $unique Optional, default is false. Whether the same key should not be added.
542 * @return int|bool Meta ID on success, false on failure.
544 function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
545 return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
549 * Remove metadata matching criteria from a comment.
551 * You can match based on the key, or key and value. Removing based on key and
552 * value, will keep from removing duplicate metadata with the same key. It also
553 * allows removing all metadata matching key, if needed.
556 * @uses delete_metadata
557 * @link http://codex.wordpress.org/Function_Reference/delete_comment_meta
559 * @param int $comment_id comment ID
560 * @param string $meta_key Metadata name.
561 * @param mixed $meta_value Optional. Metadata value.
562 * @return bool True on success, false on failure.
564 function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
565 return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
569 * Retrieve comment meta field for a comment.
573 * @link http://codex.wordpress.org/Function_Reference/get_comment_meta
575 * @param int $comment_id Comment ID.
576 * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
577 * @param bool $single Whether to return a single value.
578 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
581 function get_comment_meta($comment_id, $key = '', $single = false) {
582 return get_metadata('comment', $comment_id, $key, $single);
586 * Update comment meta field based on comment ID.
588 * Use the $prev_value parameter to differentiate between meta fields with the
589 * same key and comment ID.
591 * If the meta field for the comment does not exist, it will be added.
594 * @uses update_metadata
595 * @link http://codex.wordpress.org/Function_Reference/update_comment_meta
597 * @param int $comment_id Comment ID.
598 * @param string $meta_key Metadata key.
599 * @param mixed $meta_value Metadata value.
600 * @param mixed $prev_value Optional. Previous value to check before removing.
601 * @return bool True on success, false on failure.
603 function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
604 return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
608 * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
609 * to recall previous comments by this commentator that are still held in moderation.
611 * @param object $comment Comment object.
612 * @param object $user Comment author's object.
616 function wp_set_comment_cookies($comment, $user) {
617 if ( $user->exists() )
620 $comment_cookie_lifetime = apply_filters('comment_cookie_lifetime', 30000000);
621 setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
622 setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
623 setcookie('comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
627 * Sanitizes the cookies sent to the user already.
629 * Will only do anything if the cookies have already been created for the user.
630 * Mostly used after cookies had been sent to use elsewhere.
634 function sanitize_comment_cookies() {
635 if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) {
636 $comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]);
637 $comment_author = wp_unslash($comment_author);
638 $comment_author = esc_attr($comment_author);
639 $_COOKIE['comment_author_'.COOKIEHASH] = $comment_author;
642 if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) {
643 $comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]);
644 $comment_author_email = wp_unslash($comment_author_email);
645 $comment_author_email = esc_attr($comment_author_email);
646 $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
649 if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) {
650 $comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]);
651 $comment_author_url = wp_unslash($comment_author_url);
652 $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
657 * Validates whether this comment is allowed to be made.
661 * @uses apply_filters() Calls 'pre_comment_approved' hook on the type of comment
662 * @uses apply_filters() Calls 'comment_duplicate_trigger' hook on commentdata.
663 * @uses do_action() Calls 'check_comment_flood' hook on $comment_author_IP, $comment_author_email, and $comment_date_gmt
665 * @param array $commentdata Contains information on the comment
666 * @return mixed Signifies the approval status (0|1|'spam')
668 function wp_allow_comment($commentdata) {
670 extract($commentdata, EXTR_SKIP);
672 // Simple duplicate check
673 // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
674 $dupe = $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ", wp_unslash( $comment_post_ID ), wp_unslash( $comment_parent ), wp_unslash( $comment_author ) );
675 if ( $comment_author_email )
676 $dupe .= $wpdb->prepare( "OR comment_author_email = %s ", wp_unslash( $comment_author_email ) );
677 $dupe .= $wpdb->prepare( ") AND comment_content = %s LIMIT 1", wp_unslash( $comment_content ) );
678 if ( $wpdb->get_var($dupe) ) {
679 do_action( 'comment_duplicate_trigger', $commentdata );
680 if ( defined('DOING_AJAX') )
681 die( __('Duplicate comment detected; it looks as though you’ve already said that!') );
683 wp_die( __('Duplicate comment detected; it looks as though you’ve already said that!') );
686 do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt );
688 if ( ! empty( $user_id ) ) {
689 $user = get_userdata( $user_id );
690 $post_author = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", $comment_post_ID));
693 if ( isset( $user ) && ( $user_id == $post_author || $user->has_cap( 'moderate_comments' ) ) ) {
694 // The author and the admins get respect.
697 // Everyone else's comments will be checked.
698 if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) )
702 if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) )
706 $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
711 * Check whether comment flooding is occurring.
713 * Won't run, if current user can manage options, so to not block
718 * @uses apply_filters() Calls 'comment_flood_filter' filter with first
719 * parameter false, last comment timestamp, new comment timestamp.
720 * @uses do_action() Calls 'comment_flood_trigger' action with parameters with
721 * last comment timestamp and new comment timestamp.
723 * @param string $ip Comment IP.
724 * @param string $email Comment author email address.
725 * @param string $date MySQL time string.
727 function check_comment_flood_db( $ip, $email, $date ) {
729 if ( current_user_can( 'manage_options' ) )
730 return; // don't throttle admins
731 $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
732 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 ) ) ) {
733 $time_lastcomment = mysql2date('U', $lasttime, false);
734 $time_newcomment = mysql2date('U', $date, false);
735 $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
737 do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment);
739 if ( defined('DOING_AJAX') )
740 die( __('You are posting comments too quickly. Slow down.') );
742 wp_die( __('You are posting comments too quickly. Slow down.'), '', array('response' => 403) );
748 * Separates an array of comments into an array keyed by comment_type.
752 * @param array $comments Array of comments
753 * @return array Array of comments keyed by comment_type.
755 function separate_comments(&$comments) {
756 $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
757 $count = count($comments);
758 for ( $i = 0; $i < $count; $i++ ) {
759 $type = $comments[$i]->comment_type;
762 $comments_by_type[$type][] = &$comments[$i];
763 if ( 'trackback' == $type || 'pingback' == $type )
764 $comments_by_type['pings'][] = &$comments[$i];
767 return $comments_by_type;
771 * Calculate the total number of comment pages.
774 * @uses get_query_var() Used to fill in the default for $per_page parameter.
775 * @uses get_option() Used to fill in defaults for parameters.
776 * @uses Walker_Comment
778 * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
779 * @param int $per_page Optional comments per page.
780 * @param boolean $threaded Optional control over flat or threaded comments.
781 * @return int Number of comment pages.
783 function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
786 if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
787 return $wp_query->max_num_comment_pages;
789 if ( !$comments || !is_array($comments) )
790 $comments = $wp_query->comments;
792 if ( empty($comments) )
795 if ( !isset($per_page) )
796 $per_page = (int) get_query_var('comments_per_page');
797 if ( 0 === $per_page )
798 $per_page = (int) get_option('comments_per_page');
799 if ( 0 === $per_page )
802 if ( !isset($threaded) )
803 $threaded = get_option('thread_comments');
806 $walker = new Walker_Comment;
807 $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
809 $count = ceil( count( $comments ) / $per_page );
816 * Calculate what page number a comment will appear on for comment paging.
819 * @uses get_comment() Gets the full comment of the $comment_ID parameter.
820 * @uses get_option() Get various settings to control function and defaults.
821 * @uses get_page_of_comment() Used to loop up to top level comment.
823 * @param int $comment_ID Comment ID.
824 * @param array $args Optional args.
825 * @return int|null Comment page number or null on error.
827 function get_page_of_comment( $comment_ID, $args = array() ) {
830 if ( !$comment = get_comment( $comment_ID ) )
833 $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
834 $args = wp_parse_args( $args, $defaults );
836 if ( '' === $args['per_page'] && get_option('page_comments') )
837 $args['per_page'] = get_query_var('comments_per_page');
838 if ( empty($args['per_page']) ) {
839 $args['per_page'] = 0;
842 if ( $args['per_page'] < 1 )
845 if ( '' === $args['max_depth'] ) {
846 if ( get_option('thread_comments') )
847 $args['max_depth'] = get_option('thread_comments_depth');
849 $args['max_depth'] = -1;
852 // Find this comment's top level parent if threading is enabled
853 if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
854 return get_page_of_comment( $comment->comment_parent, $args );
856 $allowedtypes = array(
858 'pingback' => 'pingback',
859 'trackback' => 'trackback',
862 $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
864 // Count comments older than this one
865 $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 ) );
867 // No older comments? Then it's page #1.
868 if ( 0 == $oldercoms )
871 // Divide comments older than this one by comments per page to get this comment's page number
872 return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
876 * Does comment contain blacklisted characters or words.
879 * @uses do_action() Calls 'wp_blacklist_check' hook for all parameters.
881 * @param string $author The author of the comment
882 * @param string $email The email of the comment
883 * @param string $url The url used in the comment
884 * @param string $comment The comment content
885 * @param string $user_ip The comment author IP address
886 * @param string $user_agent The author's browser user agent
887 * @return bool True if comment contains blacklisted content, false if comment does not
889 function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
890 do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent);
892 $mod_keys = trim( get_option('blacklist_keys') );
893 if ( '' == $mod_keys )
894 return false; // If moderation keys are empty
895 $words = explode("\n", $mod_keys );
897 foreach ( (array) $words as $word ) {
901 if ( empty($word) ) { continue; }
903 // Do some escaping magic so that '#' chars in the
904 // spam words don't break things:
905 $word = preg_quote($word, '#');
907 $pattern = "#$word#i";
909 preg_match($pattern, $author)
910 || preg_match($pattern, $email)
911 || preg_match($pattern, $url)
912 || preg_match($pattern, $comment)
913 || preg_match($pattern, $user_ip)
914 || preg_match($pattern, $user_agent)
922 * Retrieve total comments for blog or single post.
924 * The properties of the returned object contain the 'moderated', 'approved',
925 * and spam comments for either the entire blog or single post. Those properties
926 * contain the amount of comments that match the status. The 'total_comments'
927 * property contains the integer of total comments.
929 * The comment stats are cached and then retrieved, if they already exist in the
934 * @param int $post_id Optional. Post ID.
935 * @return object Comment stats.
937 function wp_count_comments( $post_id = 0 ) {
940 $post_id = (int) $post_id;
942 $stats = apply_filters('wp_count_comments', array(), $post_id);
943 if ( !empty($stats) )
946 $count = wp_cache_get("comments-{$post_id}", 'counts');
948 if ( false !== $count )
953 $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
955 $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
958 $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
959 foreach ( (array) $count as $row ) {
960 // Don't count post-trashed toward totals
961 if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
962 $total += $row['num_comments'];
963 if ( isset( $approved[$row['comment_approved']] ) )
964 $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
967 $stats['total_comments'] = $total;
968 foreach ( $approved as $key ) {
969 if ( empty($stats[$key]) )
973 $stats = (object) $stats;
974 wp_cache_set("comments-{$post_id}", $stats, 'counts');
980 * Trashes or deletes a comment.
982 * The comment is moved to trash instead of permanently deleted unless trash is
983 * disabled, item is already in the trash, or $force_delete is true.
985 * The post comment count will be updated if the comment was approved and has a
990 * @uses do_action() Calls 'delete_comment' hook on comment ID
991 * @uses do_action() Calls 'deleted_comment' hook on comment ID after deletion, on success
992 * @uses do_action() Calls 'wp_set_comment_status' hook on comment ID with 'delete' set for the second parameter
993 * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
995 * @param int $comment_id Comment ID
996 * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
997 * @return bool True on success, false on failure.
999 function wp_delete_comment($comment_id, $force_delete = false) {
1001 if (!$comment = get_comment($comment_id))
1004 if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) )
1005 return wp_trash_comment($comment_id);
1007 do_action('delete_comment', $comment_id);
1009 // Move children up a level.
1010 $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
1011 if ( !empty($children) ) {
1012 $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
1013 clean_comment_cache($children);
1017 $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment_id ) );
1018 foreach ( $meta_ids as $mid )
1019 delete_metadata_by_mid( 'comment', $mid );
1021 if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment_id ) ) )
1023 do_action('deleted_comment', $comment_id);
1025 $post_id = $comment->comment_post_ID;
1026 if ( $post_id && $comment->comment_approved == 1 )
1027 wp_update_comment_count($post_id);
1029 clean_comment_cache($comment_id);
1031 do_action('wp_set_comment_status', $comment_id, 'delete');
1032 wp_transition_comment_status('delete', $comment->comment_approved, $comment);
1037 * Moves a comment to the Trash
1039 * If trash is disabled, comment is permanently deleted.
1042 * @uses do_action() on 'trash_comment' before trashing
1043 * @uses do_action() on 'trashed_comment' after trashing
1044 * @uses wp_delete_comment() if trash is disabled
1046 * @param int $comment_id Comment ID.
1047 * @return bool True on success, false on failure.
1049 function wp_trash_comment($comment_id) {
1050 if ( !EMPTY_TRASH_DAYS )
1051 return wp_delete_comment($comment_id, true);
1053 if ( !$comment = get_comment($comment_id) )
1056 do_action('trash_comment', $comment_id);
1058 if ( wp_set_comment_status($comment_id, 'trash') ) {
1059 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
1060 add_comment_meta($comment_id, '_wp_trash_meta_time', time() );
1061 do_action('trashed_comment', $comment_id);
1069 * Removes a comment from the Trash
1072 * @uses do_action() on 'untrash_comment' before untrashing
1073 * @uses do_action() on 'untrashed_comment' after untrashing
1075 * @param int $comment_id Comment ID.
1076 * @return bool True on success, false on failure.
1078 function wp_untrash_comment($comment_id) {
1079 if ( ! (int)$comment_id )
1082 do_action('untrash_comment', $comment_id);
1084 $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
1085 if ( empty($status) )
1088 if ( wp_set_comment_status($comment_id, $status) ) {
1089 delete_comment_meta($comment_id, '_wp_trash_meta_time');
1090 delete_comment_meta($comment_id, '_wp_trash_meta_status');
1091 do_action('untrashed_comment', $comment_id);
1099 * Marks a comment as Spam
1102 * @uses do_action() on 'spam_comment' before spamming
1103 * @uses do_action() on 'spammed_comment' after spamming
1105 * @param int $comment_id Comment ID.
1106 * @return bool True on success, false on failure.
1108 function wp_spam_comment($comment_id) {
1109 if ( !$comment = get_comment($comment_id) )
1112 do_action('spam_comment', $comment_id);
1114 if ( wp_set_comment_status($comment_id, 'spam') ) {
1115 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
1116 do_action('spammed_comment', $comment_id);
1124 * Removes a comment from the Spam
1127 * @uses do_action() on 'unspam_comment' before unspamming
1128 * @uses do_action() on 'unspammed_comment' after unspamming
1130 * @param int $comment_id Comment ID.
1131 * @return bool True on success, false on failure.
1133 function wp_unspam_comment($comment_id) {
1134 if ( ! (int)$comment_id )
1137 do_action('unspam_comment', $comment_id);
1139 $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
1140 if ( empty($status) )
1143 if ( wp_set_comment_status($comment_id, $status) ) {
1144 delete_comment_meta($comment_id, '_wp_trash_meta_status');
1145 do_action('unspammed_comment', $comment_id);
1153 * The status of a comment by ID.
1157 * @param int $comment_id Comment ID
1158 * @return string|bool Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
1160 function wp_get_comment_status($comment_id) {
1161 $comment = get_comment($comment_id);
1165 $approved = $comment->comment_approved;
1167 if ( $approved == null )
1169 elseif ( $approved == '1' )
1171 elseif ( $approved == '0' )
1172 return 'unapproved';
1173 elseif ( $approved == 'spam' )
1175 elseif ( $approved == 'trash' )
1182 * Call hooks for when a comment status transition occurs.
1184 * Calls hooks for comment status transitions. If the new comment status is not the same
1185 * as the previous comment status, then two hooks will be ran, the first is
1186 * 'transition_comment_status' with new status, old status, and comment data. The
1187 * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
1188 * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
1191 * The final action will run whether or not the comment statuses are the same. The
1192 * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
1193 * parameter and COMMENTTYPE is comment_type comment data.
1197 * @param string $new_status New comment status.
1198 * @param string $old_status Previous comment status.
1199 * @param object $comment Comment data.
1201 function wp_transition_comment_status($new_status, $old_status, $comment) {
1202 // Translate raw statuses to human readable formats for the hooks
1203 // This is not a complete list of comment status, it's only the ones that need to be renamed
1204 $comment_statuses = array(
1206 'hold' => 'unapproved', // wp_set_comment_status() uses "hold"
1208 'approve' => 'approved', // wp_set_comment_status() uses "approve"
1210 if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
1211 if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
1214 if ( $new_status != $old_status ) {
1215 do_action('transition_comment_status', $new_status, $old_status, $comment);
1216 do_action("comment_{$old_status}_to_{$new_status}", $comment);
1218 do_action("comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment);
1222 * Get current commenter's name, email, and URL.
1224 * Expects cookies content to already be sanitized. User of this function might
1225 * wish to recheck the returned array for validity.
1227 * @see sanitize_comment_cookies() Use to sanitize cookies
1231 * @return array Comment author, email, url respectively.
1233 function wp_get_current_commenter() {
1234 // Cookies should already be sanitized.
1236 $comment_author = '';
1237 if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
1238 $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
1240 $comment_author_email = '';
1241 if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
1242 $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
1244 $comment_author_url = '';
1245 if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
1246 $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
1248 return apply_filters('wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url'));
1252 * Inserts a comment to the database.
1254 * The available comment data key names are 'comment_author_IP', 'comment_date',
1255 * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'.
1260 * @param array $commentdata Contains information on the comment.
1261 * @return int The new comment's ID.
1263 function wp_insert_comment($commentdata) {
1265 extract(wp_unslash($commentdata), EXTR_SKIP);
1267 if ( ! isset($comment_author_IP) )
1268 $comment_author_IP = '';
1269 if ( ! isset($comment_date) )
1270 $comment_date = current_time('mysql');
1271 if ( ! isset($comment_date_gmt) )
1272 $comment_date_gmt = get_gmt_from_date($comment_date);
1273 if ( ! isset($comment_parent) )
1274 $comment_parent = 0;
1275 if ( ! isset($comment_approved) )
1276 $comment_approved = 1;
1277 if ( ! isset($comment_karma) )
1279 if ( ! isset($user_id) )
1281 if ( ! isset($comment_type) )
1284 $data = 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');
1285 $wpdb->insert($wpdb->comments, $data);
1287 $id = (int) $wpdb->insert_id;
1289 if ( $comment_approved == 1 )
1290 wp_update_comment_count($comment_post_ID);
1292 $comment = get_comment($id);
1293 do_action('wp_insert_comment', $id, $comment);
1295 wp_cache_set( 'last_changed', microtime(), 'comment' );
1301 * Filters and sanitizes comment data.
1303 * Sets the comment data 'filtered' field to true when finished. This can be
1304 * checked as to whether the comment should be filtered and to keep from
1305 * filtering the same comment more than once.
1308 * @uses apply_filters() Calls 'pre_user_id' hook on comment author's user ID
1309 * @uses apply_filters() Calls 'pre_comment_user_agent' hook on comment author's user agent
1310 * @uses apply_filters() Calls 'pre_comment_author_name' hook on comment author's name
1311 * @uses apply_filters() Calls 'pre_comment_content' hook on the comment's content
1312 * @uses apply_filters() Calls 'pre_comment_user_ip' hook on comment author's IP
1313 * @uses apply_filters() Calls 'pre_comment_author_url' hook on comment author's URL
1314 * @uses apply_filters() Calls 'pre_comment_author_email' hook on comment author's email address
1316 * @param array $commentdata Contains information on the comment.
1317 * @return array Parsed comment information.
1319 function wp_filter_comment($commentdata) {
1320 if ( isset($commentdata['user_ID']) )
1321 $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_ID']);
1322 elseif ( isset($commentdata['user_id']) )
1323 $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_id']);
1324 $commentdata['comment_agent'] = apply_filters('pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
1325 $commentdata['comment_author'] = apply_filters('pre_comment_author_name', $commentdata['comment_author']);
1326 $commentdata['comment_content'] = apply_filters('pre_comment_content', $commentdata['comment_content']);
1327 $commentdata['comment_author_IP'] = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']);
1328 $commentdata['comment_author_url'] = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']);
1329 $commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']);
1330 $commentdata['filtered'] = true;
1331 return $commentdata;
1335 * Whether comment should be blocked because of comment flood.
1339 * @param bool $block Whether plugin has already blocked comment.
1340 * @param int $time_lastcomment Timestamp for last comment.
1341 * @param int $time_newcomment Timestamp for new comment.
1342 * @return bool Whether comment should be blocked.
1344 function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
1345 if ( $block ) // a plugin has already blocked... we'll let that decision stand
1347 if ( ($time_newcomment - $time_lastcomment) < 15 )
1353 * Adds a new comment to the database.
1355 * Filters new comment to ensure that the fields are sanitized and valid before
1356 * inserting comment into database. Calls 'comment_post' action with comment ID
1357 * and whether comment is approved by WordPress. Also has 'preprocess_comment'
1358 * filter for processing the comment data before the function handles it.
1360 * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure
1361 * that it is properly set, such as in wp-config.php, for your environment.
1362 * See {@link http://core.trac.wordpress.org/ticket/9235}
1365 * @uses apply_filters() Calls 'preprocess_comment' hook on $commentdata parameter array before processing
1366 * @uses do_action() Calls 'comment_post' hook on $comment_ID returned from adding the comment and if the comment was approved.
1367 * @uses wp_filter_comment() Used to filter comment before adding comment.
1368 * @uses wp_allow_comment() checks to see if comment is approved.
1369 * @uses wp_insert_comment() Does the actual comment insertion to the database.
1371 * @param array $commentdata Contains information on the comment.
1372 * @return int The ID of the comment after adding.
1374 function wp_new_comment( $commentdata ) {
1375 $commentdata = apply_filters('preprocess_comment', $commentdata);
1377 $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
1378 if ( isset($commentdata['user_ID']) )
1379 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
1380 elseif ( isset($commentdata['user_id']) )
1381 $commentdata['user_id'] = (int) $commentdata['user_id'];
1383 $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
1384 $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
1385 $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
1387 $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
1388 $commentdata['comment_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? substr( $_SERVER['HTTP_USER_AGENT'], 0, 254 ) : '';
1390 $commentdata['comment_date'] = current_time('mysql');
1391 $commentdata['comment_date_gmt'] = current_time('mysql', 1);
1393 $commentdata = wp_filter_comment($commentdata);
1395 $commentdata['comment_approved'] = wp_allow_comment($commentdata);
1397 $comment_ID = wp_insert_comment($commentdata);
1399 do_action('comment_post', $comment_ID, $commentdata['comment_approved']);
1401 if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
1402 if ( '0' == $commentdata['comment_approved'] )
1403 wp_notify_moderator($comment_ID);
1405 $post = get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment
1407 if ( get_option('comments_notify') && $commentdata['comment_approved'] && ( ! isset( $commentdata['user_id'] ) || $post->post_author != $commentdata['user_id'] ) )
1408 wp_notify_postauthor($comment_ID, isset( $commentdata['comment_type'] ) ? $commentdata['comment_type'] : '' );
1415 * Sets the status of a comment.
1417 * The 'wp_set_comment_status' action is called after the comment is handled.
1418 * If the comment status is not in the list, then false is returned.
1421 * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
1423 * @param int $comment_id Comment ID.
1424 * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
1425 * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
1426 * @return bool|WP_Error True on success, false or WP_Error on failure.
1428 function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
1432 switch ( $comment_status ) {
1440 if ( get_option('comments_notify') ) {
1441 $comment = get_comment($comment_id);
1442 wp_notify_postauthor($comment_id, $comment->comment_type);
1455 $comment_old = clone get_comment($comment_id);
1457 if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
1459 return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
1464 clean_comment_cache($comment_id);
1466 $comment = get_comment($comment_id);
1468 do_action('wp_set_comment_status', $comment_id, $comment_status);
1469 wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
1471 wp_update_comment_count($comment->comment_post_ID);
1477 * Updates an existing comment in the database.
1479 * Filters the comment and makes sure certain fields are valid before updating.
1483 * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
1485 * @param array $commentarr Contains information on the comment.
1486 * @return int Comment was updated if value is 1, or was not updated if value is 0.
1488 function wp_update_comment($commentarr) {
1491 // First, get all of the original fields
1492 $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
1494 // Escape data pulled from DB.
1495 $comment = wp_slash($comment);
1497 $old_status = $comment['comment_approved'];
1499 // Merge old and new fields with new fields overwriting old ones.
1500 $commentarr = array_merge($comment, $commentarr);
1502 $commentarr = wp_filter_comment( $commentarr );
1504 // Now extract the merged array.
1505 extract(wp_unslash($commentarr), EXTR_SKIP);
1507 $comment_content = apply_filters('comment_save_pre', $comment_content);
1509 $comment_date_gmt = get_gmt_from_date($comment_date);
1511 if ( !isset($comment_approved) )
1512 $comment_approved = 1;
1513 else if ( 'hold' == $comment_approved )
1514 $comment_approved = 0;
1515 else if ( 'approve' == $comment_approved )
1516 $comment_approved = 1;
1518 $data = compact( 'comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt', 'comment_parent' );
1519 $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
1521 clean_comment_cache($comment_ID);
1522 wp_update_comment_count($comment_post_ID);
1523 do_action('edit_comment', $comment_ID);
1524 $comment = get_comment($comment_ID);
1525 wp_transition_comment_status($comment->comment_approved, $old_status, $comment);
1530 * Whether to defer comment counting.
1532 * When setting $defer to true, all post comment counts will not be updated
1533 * until $defer is set to false. When $defer is set to false, then all
1534 * previously deferred updated post comment counts will then be automatically
1535 * updated without having to call wp_update_comment_count() after.
1538 * @staticvar bool $_defer
1540 * @param bool $defer
1543 function wp_defer_comment_counting($defer=null) {
1544 static $_defer = false;
1546 if ( is_bool($defer) ) {
1548 // flush any deferred counts
1550 wp_update_comment_count( null, true );
1557 * Updates the comment count for post(s).
1559 * When $do_deferred is false (is by default) and the comments have been set to
1560 * be deferred, the post_id will be added to a queue, which will be updated at a
1561 * later date and only updated once per post ID.
1563 * If the comments have not be set up to be deferred, then the post will be
1564 * updated. When $do_deferred is set to true, then all previous deferred post
1565 * IDs will be updated along with the current $post_id.
1568 * @see wp_update_comment_count_now() For what could cause a false return value
1570 * @param int $post_id Post ID
1571 * @param bool $do_deferred Whether to process previously deferred post comment counts
1572 * @return bool True on success, false on failure
1574 function wp_update_comment_count($post_id, $do_deferred=false) {
1575 static $_deferred = array();
1577 if ( $do_deferred ) {
1578 $_deferred = array_unique($_deferred);
1579 foreach ( $_deferred as $i => $_post_id ) {
1580 wp_update_comment_count_now($_post_id);
1581 unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
1585 if ( wp_defer_comment_counting() ) {
1586 $_deferred[] = $post_id;
1589 elseif ( $post_id ) {
1590 return wp_update_comment_count_now($post_id);
1596 * Updates the comment count for the post.
1600 * @uses do_action() Calls 'wp_update_comment_count' hook on $post_id, $new, and $old
1601 * @uses do_action() Calls 'edit_posts' hook on $post_id and $post
1603 * @param int $post_id Post ID
1604 * @return bool True on success, false on '0' $post_id or if post with ID does not exist.
1606 function wp_update_comment_count_now($post_id) {
1608 $post_id = (int) $post_id;
1611 if ( !$post = get_post($post_id) )
1614 $old = (int) $post->comment_count;
1615 $new = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id) );
1616 $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) );
1618 clean_post_cache( $post );
1620 do_action('wp_update_comment_count', $post_id, $new, $old);
1621 do_action('edit_post', $post_id, $post);
1627 // Ping and trackback functions.
1631 * Finds a pingback server URI based on the given URL.
1633 * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
1634 * a check for the x-pingback headers first and returns that, if available. The
1635 * check for the rel="pingback" has more overhead than just the header.
1639 * @param string $url URL to ping.
1640 * @param int $deprecated Not Used.
1641 * @return bool|string False on failure, string containing URI on success.
1643 function discover_pingback_server_uri( $url, $deprecated = '' ) {
1644 if ( !empty( $deprecated ) )
1645 _deprecated_argument( __FUNCTION__, '2.7' );
1647 $pingback_str_dquote = 'rel="pingback"';
1648 $pingback_str_squote = 'rel=\'pingback\'';
1650 /** @todo Should use Filter Extension or custom preg_match instead. */
1651 $parsed_url = parse_url($url);
1653 if ( ! isset( $parsed_url['host'] ) ) // Not an URL. This should never happen.
1656 //Do not search for a pingback server on our own uploads
1657 $uploads_dir = wp_upload_dir();
1658 if ( 0 === strpos($url, $uploads_dir['baseurl']) )
1661 $response = wp_safe_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
1663 if ( is_wp_error( $response ) )
1666 if ( wp_remote_retrieve_header( $response, 'x-pingback' ) )
1667 return wp_remote_retrieve_header( $response, 'x-pingback' );
1669 // Not an (x)html, sgml, or xml page, no use going further.
1670 if ( preg_match('#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'content-type' )) )
1673 // Now do a GET since we're going to look in the html headers (and we're sure it's not a binary file)
1674 $response = wp_safe_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
1676 if ( is_wp_error( $response ) )
1679 $contents = wp_remote_retrieve_body( $response );
1681 $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
1682 $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
1683 if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
1684 $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
1685 $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
1686 $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
1687 $pingback_href_start = $pingback_href_pos+6;
1688 $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
1689 $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
1690 $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
1692 // We may find rel="pingback" but an incomplete pingback URL
1693 if ( $pingback_server_url_len > 0 ) { // We got it!
1694 return $pingback_server_url;
1702 * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
1707 function do_all_pings() {
1711 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")) {
1712 delete_metadata_by_mid( 'post', $ping->meta_id );
1713 pingback( $ping->post_content, $ping->ID );
1717 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")) {
1718 delete_metadata_by_mid( 'post', $enclosure->meta_id );
1719 do_enclose( $enclosure->post_content, $enclosure->ID );
1723 $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'");
1724 if ( is_array($trackbacks) )
1725 foreach ( $trackbacks as $trackback )
1726 do_trackbacks($trackback);
1728 //Do Update Services/Generic Pings
1733 * Perform trackbacks.
1738 * @param int $post_id Post ID to do trackbacks on.
1740 function do_trackbacks($post_id) {
1743 $post = get_post( $post_id );
1744 $to_ping = get_to_ping($post_id);
1745 $pinged = get_pung($post_id);
1746 if ( empty($to_ping) ) {
1747 $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) );
1751 if ( empty($post->post_excerpt) )
1752 $excerpt = apply_filters('the_content', $post->post_content, $post->ID);
1754 $excerpt = apply_filters('the_excerpt', $post->post_excerpt);
1755 $excerpt = str_replace(']]>', ']]>', $excerpt);
1756 $excerpt = wp_html_excerpt($excerpt, 252, '…');
1758 $post_title = apply_filters('the_title', $post->post_title, $post->ID);
1759 $post_title = strip_tags($post_title);
1762 foreach ( (array) $to_ping as $tb_ping ) {
1763 $tb_ping = trim($tb_ping);
1764 if ( !in_array($tb_ping, $pinged) ) {
1765 trackback($tb_ping, $post_title, $excerpt, $post_id);
1766 $pinged[] = $tb_ping;
1768 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post_id) );
1775 * Sends pings to all of the ping site services.
1779 * @param int $post_id Post ID. Not actually used.
1780 * @return int Same as Post ID from parameter
1782 function generic_ping($post_id = 0) {
1783 $services = get_option('ping_sites');
1785 $services = explode("\n", $services);
1786 foreach ( (array) $services as $service ) {
1787 $service = trim($service);
1788 if ( '' != $service )
1789 weblog_ping($service);
1796 * Pings back the links found in a post.
1802 * @param string $content Post content to check for links.
1803 * @param int $post_ID Post ID.
1805 function pingback($content, $post_ID) {
1807 include_once(ABSPATH . WPINC . '/class-IXR.php');
1808 include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
1810 // original code by Mort (http://mort.mine.nu:8080)
1811 $post_links = array();
1813 $pung = get_pung($post_ID);
1817 $gunk = '/#~:.?+=&%@!\-';
1819 $any = $ltrs . $gunk . $punc;
1822 // Parsing the post, external links (if any) are stored in the $post_links array
1823 // This regexp comes straight from phpfreaks.com
1824 // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
1825 preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
1828 // Walking thru the links array
1829 // first we get rid of links pointing to sites, not to specific files
1831 // http://dummy-weblog.org
1832 // http://dummy-weblog.org/
1833 // http://dummy-weblog.org/post.php
1834 // We don't wanna ping first and second types, even if they have a valid <link/>
1836 foreach ( (array) $post_links_temp[0] as $link_test ) :
1837 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
1838 && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
1839 if ( $test = @parse_url($link_test) ) {
1840 if ( isset($test['query']) )
1841 $post_links[] = $link_test;
1842 elseif ( isset( $test['path'] ) && ( $test['path'] != '/' ) && ( $test['path'] != '' ) )
1843 $post_links[] = $link_test;
1848 $post_links = array_unique( $post_links );
1849 do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post_ID ) );
1851 foreach ( (array) $post_links as $pagelinkedto ) {
1852 $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
1854 if ( $pingback_server_url ) {
1855 @ set_time_limit( 60 );
1856 // Now, the RPC call
1857 $pagelinkedfrom = get_permalink($post_ID);
1859 // using a timeout of 3 seconds should be enough to cover slow servers
1860 $client = new WP_HTTP_IXR_Client($pingback_server_url);
1861 $client->timeout = 3;
1862 $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . $wp_version, $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom);
1863 // when set to true, this outputs debug messages by itself
1864 $client->debug = false;
1866 if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
1867 add_ping( $post_ID, $pagelinkedto );
1873 * Check whether blog is public before returning sites.
1877 * @param mixed $sites Will return if blog is public, will not return if not public.
1878 * @return mixed Empty string if blog is not public, returns $sites, if site is public.
1880 function privacy_ping_filter($sites) {
1881 if ( '0' != get_option('blog_public') )
1890 * Updates database when sending trackback to prevent duplicates.
1895 * @param string $trackback_url URL to send trackbacks.
1896 * @param string $title Title of post.
1897 * @param string $excerpt Excerpt of post.
1898 * @param int $ID Post ID.
1899 * @return mixed Database query from update.
1901 function trackback($trackback_url, $title, $excerpt, $ID) {
1904 if ( empty($trackback_url) )
1908 $options['timeout'] = 4;
1909 $options['body'] = array(
1911 'url' => get_permalink($ID),
1912 'blog_name' => get_option('blogname'),
1913 'excerpt' => $excerpt
1916 $response = wp_safe_remote_post( $trackback_url, $options );
1918 if ( is_wp_error( $response ) )
1921 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID) );
1922 return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID) );
1932 * @param string $server Host of blog to connect to.
1933 * @param string $path Path to send the ping.
1935 function weblog_ping($server = '', $path = '') {
1937 include_once(ABSPATH . WPINC . '/class-IXR.php');
1938 include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
1940 // using a timeout of 3 seconds should be enough to cover slow servers
1941 $client = new WP_HTTP_IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
1942 $client->timeout = 3;
1943 $client->useragent .= ' -- WordPress/'.$wp_version;
1945 // when set to true, this outputs debug messages by itself
1946 $client->debug = false;
1947 $home = trailingslashit( home_url() );
1948 if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
1949 $client->query('weblogUpdates.ping', get_option('blogname'), $home);
1953 * Default filter attached to pingback_ping_source_uri to validate the pingback's Source URI
1956 * @see wp_http_validate_url()
1958 * @param string $source_uri
1961 function pingback_ping_source_uri( $source_uri ) {
1962 return (string) wp_http_validate_url( $source_uri );
1966 * Default filter attached to xmlrpc_pingback_error.
1968 * Returns a generic pingback error code unless the error code is 48,
1969 * which reports that the pingback is already registered.
1972 * @link http://www.hixie.ch/specs/pingback/pingback#TOC3
1974 * @param IXR_Error $ixr_error
1977 function xmlrpc_pingback_error( $ixr_error ) {
1978 if ( $ixr_error->code === 48 )
1980 return new IXR_Error( 0, '' );
1988 * Removes comment ID from the comment cache.
1991 * @package WordPress
1994 * @param int|array $ids Comment ID or array of comment IDs to remove from cache
1996 function clean_comment_cache($ids) {
1997 foreach ( (array) $ids as $id )
1998 wp_cache_delete($id, 'comment');
2000 wp_cache_set( 'last_changed', microtime(), 'comment' );
2004 * Updates the comment cache of given comments.
2006 * Will add the comments in $comments to the cache. If comment ID already exists
2007 * in the comment cache then it will not be updated. The comment is added to the
2008 * cache using the comment group with the key using the ID of the comments.
2011 * @package WordPress
2014 * @param array $comments Array of comment row objects
2016 function update_comment_cache($comments) {
2017 foreach ( (array) $comments as $comment )
2018 wp_cache_add($comment->comment_ID, $comment, 'comment');
2026 * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
2031 * @param object $posts Post data object.
2032 * @param object $query Query object.
2035 function _close_comments_for_old_posts( $posts, $query ) {
2036 if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) )
2039 $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
2040 if ( ! in_array( $posts[0]->post_type, $post_types ) )
2043 $days_old = (int) get_option( 'close_comments_days_old' );
2047 if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
2048 $posts[0]->comment_status = 'closed';
2049 $posts[0]->ping_status = 'closed';
2056 * Close comments on an old post. Hooked to comments_open and pings_open.
2061 * @param bool $open Comments open or closed
2062 * @param int $post_id Post ID
2063 * @return bool $open
2065 function _close_comments_for_old_post( $open, $post_id ) {
2069 if ( !get_option('close_comments_for_old_posts') )
2072 $days_old = (int) get_option('close_comments_days_old');
2076 $post = get_post($post_id);
2078 $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
2079 if ( ! in_array( $post->post_type, $post_types ) )
2082 if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) )