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 is a trackback and part of the blogroll, then the trackback is
22 * automatically whitelisted. If the comment author was approved before, then
23 * the comment is automatically whitelisted.
25 * If none of the checks fail, then the failback is to set the check to pass
31 * @param string $author Comment Author's name
32 * @param string $email Comment Author's email
33 * @param string $url Comment Author's URL
34 * @param string $comment Comment contents
35 * @param string $user_ip Comment Author's IP address
36 * @param string $user_agent Comment Author's User Agent
37 * @param string $comment_type Comment type, either user submitted comment,
38 * trackback, or pingback
39 * @return bool Whether the checks passed (true) and the comments should be
40 * displayed or set to moderated
42 function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
45 if ( 1 == get_option('comment_moderation') )
46 return false; // If moderation is set to manual
48 // Check # of external links
49 if ( $max_links = get_option( 'comment_max_links' ) ) {
50 $num_links = preg_match_all( '/<a [^>]*href/i', apply_filters( 'comment_text', $comment ), $out );
51 $num_links = apply_filters( 'comment_max_links_url', $num_links, $url ); // provide for counting of $url as a link
52 if ( $num_links >= $max_links )
56 $mod_keys = trim(get_option('moderation_keys'));
57 if ( !empty($mod_keys) ) {
58 $words = explode("\n", $mod_keys );
60 foreach ( (array) $words as $word) {
67 // Do some escaping magic so that '#' chars in the
68 // spam words don't break things:
69 $word = preg_quote($word, '#');
71 $pattern = "#$word#i";
72 if ( preg_match($pattern, $author) ) return false;
73 if ( preg_match($pattern, $email) ) return false;
74 if ( preg_match($pattern, $url) ) return false;
75 if ( preg_match($pattern, $comment) ) return false;
76 if ( preg_match($pattern, $user_ip) ) return false;
77 if ( preg_match($pattern, $user_agent) ) return false;
81 // Comment whitelisting:
82 if ( 1 == get_option('comment_whitelist')) {
83 if ( 'trackback' == $comment_type || 'pingback' == $comment_type ) { // check if domain is in blogroll
84 $uri = parse_url($url);
85 $domain = $uri['host'];
86 $uri = parse_url( home_url() );
87 $home_domain = $uri['host'];
88 if ( $wpdb->get_var($wpdb->prepare("SELECT link_id FROM $wpdb->links WHERE link_url LIKE (%s) LIMIT 1", '%'.$domain.'%')) || $domain == $home_domain )
92 } elseif ( $author != '' && $email != '' ) {
93 // expected_slashed ($author, $email)
94 $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");
95 if ( ( 1 == $ok_to_comment ) &&
96 ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
108 * Retrieve the approved comments for post $post_id.
113 * @param int $post_id The ID of the post
114 * @return array $comments The approved comments
116 function get_approved_comments($post_id) {
118 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));
122 * Retrieves comment data given a comment ID or comment object.
124 * If an object is passed then the comment data will be cached and then returned
125 * after being passed through a filter. If the comment is empty, then the global
126 * comment variable will be used, if it is set.
128 * If the comment is empty, then the global comment variable will be used, if it
134 * @param object|string|int $comment Comment to retrieve.
135 * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
136 * @return object|array|null Depends on $output value.
138 function &get_comment(&$comment, $output = OBJECT) {
142 if ( empty($comment) ) {
143 if ( isset($GLOBALS['comment']) )
144 $_comment = & $GLOBALS['comment'];
147 } elseif ( is_object($comment) ) {
148 wp_cache_add($comment->comment_ID, $comment, 'comment');
149 $_comment = $comment;
151 if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
152 $_comment = & $GLOBALS['comment'];
153 } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
154 $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
157 wp_cache_add($_comment->comment_ID, $_comment, 'comment');
161 $_comment = apply_filters('get_comment', $_comment);
163 if ( $output == OBJECT ) {
165 } elseif ( $output == ARRAY_A ) {
166 $__comment = get_object_vars($_comment);
168 } elseif ( $output == ARRAY_N ) {
169 $__comment = array_values(get_object_vars($_comment));
177 * Retrieve a list of comments.
179 * The comment list can be for the blog as a whole or for an individual post.
181 * The list of comment arguments are 'status', 'orderby', 'comment_date_gmt',
182 * 'order', 'number', 'offset', and 'post_id'.
187 * @param mixed $args Optional. Array or string of options to override defaults.
188 * @return array List of comments.
190 function get_comments( $args = '' ) {
194 'author_email' => '',
209 $args = wp_parse_args( $args, $defaults );
210 extract( $args, EXTR_SKIP );
212 // $args can be whatever, only use the args defined in defaults to compute the key
213 $key = md5( serialize( compact(array_keys($defaults)) ) );
214 $last_changed = wp_cache_get('last_changed', 'comment');
215 if ( !$last_changed ) {
216 $last_changed = time();
217 wp_cache_set('last_changed', $last_changed, 'comment');
219 $cache_key = "get_comments:$key:$last_changed";
221 if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) {
225 $post_id = absint($post_id);
227 if ( 'hold' == $status )
228 $approved = "comment_approved = '0'";
229 elseif ( 'approve' == $status )
230 $approved = "comment_approved = '1'";
231 elseif ( 'spam' == $status )
232 $approved = "comment_approved = 'spam'";
233 elseif ( 'trash' == $status )
234 $approved = "comment_approved = 'trash'";
236 $approved = "( comment_approved = '0' OR comment_approved = '1' )";
238 $order = ( 'ASC' == $order ) ? 'ASC' : 'DESC';
240 if ( ! empty( $orderby ) ) {
241 $ordersby = is_array($orderby) ? $orderby : preg_split('/[,\s]/', $orderby);
242 $ordersby = array_intersect(
248 'comment_author_email',
250 'comment_author_url',
262 $orderby = empty( $ordersby ) ? 'comment_date_gmt' : implode(', ', $ordersby);
264 $orderby = 'comment_date_gmt';
267 $number = absint($number);
268 $offset = absint($offset);
270 if ( !empty($number) ) {
272 $number = 'LIMIT ' . $offset . ',' . $number;
274 $number = 'LIMIT ' . $number;
282 if ( ! empty($post_id) )
283 $post_where .= $wpdb->prepare( 'comment_post_ID = %d AND ', $post_id );
284 if ( '' !== $author_email )
285 $post_where .= $wpdb->prepare( 'comment_author_email = %s AND ', $author_email );
287 $post_where .= $wpdb->prepare( 'comment_karma = %d AND ', $karma );
288 if ( 'comment' == $type )
289 $post_where .= "comment_type = '' AND ";
290 elseif ( ! empty( $type ) )
291 $post_where .= $wpdb->prepare( 'comment_type = %s AND ', $type );
292 if ( '' !== $parent )
293 $post_where .= $wpdb->prepare( 'comment_parent = %d AND ', $parent );
294 if ( '' !== $user_id )
295 $post_where .= $wpdb->prepare( 'user_id = %d AND ', $user_id );
297 $comments = $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE $post_where $approved ORDER BY $orderby $order $number" );
298 wp_cache_add( $cache_key, $comments, 'comment' );
304 * Retrieve all of the WordPress supported comment statuses.
306 * Comments have a limited set of valid status values, this provides the comment
307 * status values and descriptions.
313 * @return array List of comment statuses.
315 function get_comment_statuses( ) {
317 'hold' => __('Unapproved'),
318 /* translators: comment status */
319 'approve' => _x('Approved', 'adjective'),
320 /* translators: comment status */
321 'spam' => _x('Spam', 'adjective'),
329 * The date the last comment was modified.
333 * @global array $cache_lastcommentmodified
335 * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
336 * or 'server' locations.
337 * @return string Last comment modified date.
339 function get_lastcommentmodified($timezone = 'server') {
340 global $cache_lastcommentmodified, $wpdb;
342 if ( isset($cache_lastcommentmodified[$timezone]) )
343 return $cache_lastcommentmodified[$timezone];
345 $add_seconds_server = date('Z');
347 switch ( strtolower($timezone)) {
349 $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
352 $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
355 $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));
359 $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
361 return $lastcommentmodified;
365 * The amount of comments in a post or total comments.
367 * A lot like {@link wp_count_comments()}, in that they both return comment
368 * stats (albeit with different types). The {@link wp_count_comments()} actual
369 * caches, but this function does not.
374 * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
375 * @return array The amount of spam, approved, awaiting moderation, and total comments.
377 function get_comment_count( $post_id = 0 ) {
380 $post_id = (int) $post_id;
383 if ( $post_id > 0 ) {
384 $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
387 $totals = (array) $wpdb->get_results("
388 SELECT comment_approved, COUNT( * ) AS total
389 FROM {$wpdb->comments}
391 GROUP BY comment_approved
394 $comment_count = array(
396 "awaiting_moderation" => 0,
398 "total_comments" => 0
401 foreach ( $totals as $row ) {
402 switch ( $row['comment_approved'] ) {
404 $comment_count['spam'] = $row['total'];
405 $comment_count["total_comments"] += $row['total'];
408 $comment_count['approved'] = $row['total'];
409 $comment_count['total_comments'] += $row['total'];
412 $comment_count['awaiting_moderation'] = $row['total'];
413 $comment_count['total_comments'] += $row['total'];
420 return $comment_count;
424 // Comment meta functions
428 * Add meta data field to a comment.
432 * @link http://codex.wordpress.org/Function_Reference/add_comment_meta
434 * @param int $comment_id Comment ID.
435 * @param string $key Metadata name.
436 * @param mixed $value Metadata value.
437 * @param bool $unique Optional, default is false. Whether the same key should not be added.
438 * @return bool False for failure. True for success.
440 function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
441 return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
445 * Remove metadata matching criteria from a comment.
447 * You can match based on the key, or key and value. Removing based on key and
448 * value, will keep from removing duplicate metadata with the same key. It also
449 * allows removing all metadata matching key, if needed.
452 * @uses delete_metadata
453 * @link http://codex.wordpress.org/Function_Reference/delete_comment_meta
455 * @param int $comment_id comment ID
456 * @param string $meta_key Metadata name.
457 * @param mixed $meta_value Optional. Metadata value.
458 * @return bool False for failure. True for success.
460 function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
461 return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
465 * Retrieve comment meta field for a comment.
469 * @link http://codex.wordpress.org/Function_Reference/get_comment_meta
471 * @param int $comment_id Comment ID.
472 * @param string $key The meta key to retrieve.
473 * @param bool $single Whether to return a single value.
474 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
477 function get_comment_meta($comment_id, $key, $single = false) {
478 return get_metadata('comment', $comment_id, $key, $single);
482 * Update comment meta field based on comment ID.
484 * Use the $prev_value parameter to differentiate between meta fields with the
485 * same key and comment ID.
487 * If the meta field for the comment does not exist, it will be added.
490 * @uses update_metadata
491 * @link http://codex.wordpress.org/Function_Reference/update_comment_meta
493 * @param int $comment_id Comment ID.
494 * @param string $key Metadata key.
495 * @param mixed $value Metadata value.
496 * @param mixed $prev_value Optional. Previous value to check before removing.
497 * @return bool False on failure, true if success.
499 function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
500 return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
504 * Sanitizes the cookies sent to the user already.
506 * Will only do anything if the cookies have already been created for the user.
507 * Mostly used after cookies had been sent to use elsewhere.
511 function sanitize_comment_cookies() {
512 if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) {
513 $comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]);
514 $comment_author = stripslashes($comment_author);
515 $comment_author = esc_attr($comment_author);
516 $_COOKIE['comment_author_'.COOKIEHASH] = $comment_author;
519 if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) {
520 $comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]);
521 $comment_author_email = stripslashes($comment_author_email);
522 $comment_author_email = esc_attr($comment_author_email);
523 $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
526 if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) {
527 $comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]);
528 $comment_author_url = stripslashes($comment_author_url);
529 $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
534 * Validates whether this comment is allowed to be made.
538 * @uses apply_filters() Calls 'pre_comment_approved' hook on the type of comment
539 * @uses apply_filters() Calls 'comment_duplicate_trigger' hook on commentdata.
540 * @uses do_action() Calls 'check_comment_flood' hook on $comment_author_IP, $comment_author_email, and $comment_date_gmt
542 * @param array $commentdata Contains information on the comment
543 * @return mixed Signifies the approval status (0|1|'spam')
545 function wp_allow_comment($commentdata) {
547 extract($commentdata, EXTR_SKIP);
549 // Simple duplicate check
550 // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
551 $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND comment_approved != 'trash' AND ( comment_author = '$comment_author' ";
552 if ( $comment_author_email )
553 $dupe .= "OR comment_author_email = '$comment_author_email' ";
554 $dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
555 if ( $wpdb->get_var($dupe) ) {
556 do_action( 'comment_duplicate_trigger', $commentdata );
557 if ( defined('DOING_AJAX') )
558 die( __('Duplicate comment detected; it looks as though you’ve already said that!') );
560 wp_die( __('Duplicate comment detected; it looks as though you’ve already said that!') );
563 do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt );
565 if ( isset($user_id) && $user_id) {
566 $userdata = get_userdata($user_id);
567 $user = new WP_User($user_id);
568 $post_author = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", $comment_post_ID));
571 if ( isset($userdata) && ( $user_id == $post_author || $user->has_cap('moderate_comments') ) ) {
572 // The author and the admins get respect.
575 // Everyone else's comments will be checked.
576 if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) )
580 if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) )
584 $approved = apply_filters('pre_comment_approved', $approved);
589 * Check whether comment flooding is occurring.
591 * Won't run, if current user can manage options, so to not block
596 * @uses apply_filters() Calls 'comment_flood_filter' filter with first
597 * parameter false, last comment timestamp, new comment timestamp.
598 * @uses do_action() Calls 'comment_flood_trigger' action with parameters with
599 * last comment timestamp and new comment timestamp.
601 * @param string $ip Comment IP.
602 * @param string $email Comment author email address.
603 * @param string $date MySQL time string.
605 function check_comment_flood_db( $ip, $email, $date ) {
607 if ( current_user_can( 'manage_options' ) )
608 return; // don't throttle admins
609 $hour_ago = gmdate( 'Y-m-d H:i:s', time() - 3600 );
610 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 ) ) ) {
611 $time_lastcomment = mysql2date('U', $lasttime, false);
612 $time_newcomment = mysql2date('U', $date, false);
613 $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
615 do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment);
617 if ( defined('DOING_AJAX') )
618 die( __('You are posting comments too quickly. Slow down.') );
620 wp_die( __('You are posting comments too quickly. Slow down.'), '', array('response' => 403) );
626 * Separates an array of comments into an array keyed by comment_type.
630 * @param array $comments Array of comments
631 * @return array Array of comments keyed by comment_type.
633 function &separate_comments(&$comments) {
634 $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
635 $count = count($comments);
636 for ( $i = 0; $i < $count; $i++ ) {
637 $type = $comments[$i]->comment_type;
640 $comments_by_type[$type][] = &$comments[$i];
641 if ( 'trackback' == $type || 'pingback' == $type )
642 $comments_by_type['pings'][] = &$comments[$i];
645 return $comments_by_type;
649 * Calculate the total number of comment pages.
652 * @uses get_query_var() Used to fill in the default for $per_page parameter.
653 * @uses get_option() Used to fill in defaults for parameters.
654 * @uses Walker_Comment
656 * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
657 * @param int $per_page Optional comments per page.
658 * @param boolean $threaded Optional control over flat or threaded comments.
659 * @return int Number of comment pages.
661 function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
664 if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
665 return $wp_query->max_num_comment_pages;
667 if ( !$comments || !is_array($comments) )
668 $comments = $wp_query->comments;
670 if ( empty($comments) )
673 if ( !isset($per_page) )
674 $per_page = (int) get_query_var('comments_per_page');
675 if ( 0 === $per_page )
676 $per_page = (int) get_option('comments_per_page');
677 if ( 0 === $per_page )
680 if ( !isset($threaded) )
681 $threaded = get_option('thread_comments');
684 $walker = new Walker_Comment;
685 $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
687 $count = ceil( count( $comments ) / $per_page );
694 * Calculate what page number a comment will appear on for comment paging.
697 * @uses get_comment() Gets the full comment of the $comment_ID parameter.
698 * @uses get_option() Get various settings to control function and defaults.
699 * @uses get_page_of_comment() Used to loop up to top level comment.
701 * @param int $comment_ID Comment ID.
702 * @param array $args Optional args.
703 * @return int|null Comment page number or null on error.
705 function get_page_of_comment( $comment_ID, $args = array() ) {
708 if ( !$comment = get_comment( $comment_ID ) )
711 $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
712 $args = wp_parse_args( $args, $defaults );
714 if ( '' === $args['per_page'] && get_option('page_comments') )
715 $args['per_page'] = get_query_var('comments_per_page');
716 if ( empty($args['per_page']) ) {
717 $args['per_page'] = 0;
720 if ( $args['per_page'] < 1 )
723 if ( '' === $args['max_depth'] ) {
724 if ( get_option('thread_comments') )
725 $args['max_depth'] = get_option('thread_comments_depth');
727 $args['max_depth'] = -1;
730 // Find this comment's top level parent if threading is enabled
731 if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
732 return get_page_of_comment( $comment->comment_parent, $args );
734 $allowedtypes = array(
736 'pingback' => 'pingback',
737 'trackback' => 'trackback',
740 $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
742 // Count comments older than this one
743 $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 ) );
745 // No older comments? Then it's page #1.
746 if ( 0 == $oldercoms )
749 // Divide comments older than this one by comments per page to get this comment's page number
750 return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
754 * Does comment contain blacklisted characters or words.
757 * @uses do_action() Calls 'wp_blacklist_check' hook for all parameters.
759 * @param string $author The author of the comment
760 * @param string $email The email of the comment
761 * @param string $url The url used in the comment
762 * @param string $comment The comment content
763 * @param string $user_ip The comment author IP address
764 * @param string $user_agent The author's browser user agent
765 * @return bool True if comment contains blacklisted content, false if comment does not
767 function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
768 do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent);
770 $mod_keys = trim( get_option('blacklist_keys') );
771 if ( '' == $mod_keys )
772 return false; // If moderation keys are empty
773 $words = explode("\n", $mod_keys );
775 foreach ( (array) $words as $word ) {
779 if ( empty($word) ) { continue; }
781 // Do some escaping magic so that '#' chars in the
782 // spam words don't break things:
783 $word = preg_quote($word, '#');
785 $pattern = "#$word#i";
787 preg_match($pattern, $author)
788 || preg_match($pattern, $email)
789 || preg_match($pattern, $url)
790 || preg_match($pattern, $comment)
791 || preg_match($pattern, $user_ip)
792 || preg_match($pattern, $user_agent)
800 * Retrieve total comments for blog or single post.
802 * The properties of the returned object contain the 'moderated', 'approved',
803 * and spam comments for either the entire blog or single post. Those properties
804 * contain the amount of comments that match the status. The 'total_comments'
805 * property contains the integer of total comments.
807 * The comment stats are cached and then retrieved, if they already exist in the
812 * @param int $post_id Optional. Post ID.
813 * @return object Comment stats.
815 function wp_count_comments( $post_id = 0 ) {
818 $post_id = (int) $post_id;
820 $stats = apply_filters('wp_count_comments', array(), $post_id);
821 if ( !empty($stats) )
824 $count = wp_cache_get("comments-{$post_id}", 'counts');
826 if ( false !== $count )
831 $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
833 $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
836 $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
837 $known_types = array_keys( $approved );
838 foreach ( (array) $count as $row ) {
839 // Don't count post-trashed toward totals
840 if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
841 $total += $row['num_comments'];
842 if ( in_array( $row['comment_approved'], $known_types ) )
843 $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
846 $stats['total_comments'] = $total;
847 foreach ( $approved as $key ) {
848 if ( empty($stats[$key]) )
852 $stats = (object) $stats;
853 wp_cache_set("comments-{$post_id}", $stats, 'counts');
859 * Trashes or deletes a comment.
861 * The comment is moved to trash instead of permanently deleted unless trash is
862 * disabled, item is already in the trash, or $force_delete is true.
864 * The post comment count will be updated if the comment was approved and has a
869 * @uses do_action() Calls 'delete_comment' hook on comment ID
870 * @uses do_action() Calls 'deleted_comment' hook on comment ID after deletion, on success
871 * @uses do_action() Calls 'wp_set_comment_status' hook on comment ID with 'delete' set for the second parameter
872 * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
874 * @param int $comment_id Comment ID
875 * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
876 * @return bool False if delete comment query failure, true on success.
878 function wp_delete_comment($comment_id, $force_delete = false) {
880 if (!$comment = get_comment($comment_id))
883 if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) )
884 return wp_trash_comment($comment_id);
886 do_action('delete_comment', $comment_id);
888 // Move children up a level.
889 $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
890 if ( !empty($children) ) {
891 $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
892 clean_comment_cache($children);
896 $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d ", $comment_id ) );
897 if ( !empty($meta_ids) ) {
898 do_action( 'delete_commentmeta', $meta_ids );
899 $in_meta_ids = "'" . implode("', '", $meta_ids) . "'";
900 $wpdb->query( "DELETE FROM $wpdb->commentmeta WHERE meta_id IN ($in_meta_ids)" );
901 do_action( 'deleted_commentmeta', $meta_ids );
904 if ( ! $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment_id) ) )
906 do_action('deleted_comment', $comment_id);
908 $post_id = $comment->comment_post_ID;
909 if ( $post_id && $comment->comment_approved == 1 )
910 wp_update_comment_count($post_id);
912 clean_comment_cache($comment_id);
914 do_action('wp_set_comment_status', $comment_id, 'delete');
915 wp_transition_comment_status('delete', $comment->comment_approved, $comment);
920 * Moves a comment to the Trash
922 * If trash is disabled, comment is permanently deleted.
925 * @uses do_action() on 'trash_comment' before trashing
926 * @uses do_action() on 'trashed_comment' after trashing
927 * @uses wp_delete_comment() if trash is disabled
929 * @param int $comment_id Comment ID.
930 * @return mixed False on failure
932 function wp_trash_comment($comment_id) {
933 if ( !EMPTY_TRASH_DAYS )
934 return wp_delete_comment($comment_id, true);
936 if ( !$comment = get_comment($comment_id) )
939 do_action('trash_comment', $comment_id);
941 if ( wp_set_comment_status($comment_id, 'trash') ) {
942 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
943 add_comment_meta($comment_id, '_wp_trash_meta_time', time() );
944 do_action('trashed_comment', $comment_id);
952 * Removes a comment from the Trash
955 * @uses do_action() on 'untrash_comment' before untrashing
956 * @uses do_action() on 'untrashed_comment' after untrashing
958 * @param int $comment_id Comment ID.
959 * @return mixed False on failure
961 function wp_untrash_comment($comment_id) {
962 if ( ! (int)$comment_id )
965 do_action('untrash_comment', $comment_id);
967 $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
968 if ( empty($status) )
971 if ( wp_set_comment_status($comment_id, $status) ) {
972 delete_comment_meta($comment_id, '_wp_trash_meta_time');
973 delete_comment_meta($comment_id, '_wp_trash_meta_status');
974 do_action('untrashed_comment', $comment_id);
982 * Marks a comment as Spam
985 * @uses do_action() on 'spam_comment' before spamming
986 * @uses do_action() on 'spammed_comment' after spamming
988 * @param int $comment_id Comment ID.
989 * @return mixed False on failure
991 function wp_spam_comment($comment_id) {
992 if ( !$comment = get_comment($comment_id) )
995 do_action('spam_comment', $comment_id);
997 if ( wp_set_comment_status($comment_id, 'spam') ) {
998 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
999 do_action('spammed_comment', $comment_id);
1007 * Removes a comment from the Spam
1010 * @uses do_action() on 'unspam_comment' before unspamming
1011 * @uses do_action() on 'unspammed_comment' after unspamming
1013 * @param int $comment_id Comment ID.
1014 * @return mixed False on failure
1016 function wp_unspam_comment($comment_id) {
1017 if ( ! (int)$comment_id )
1020 do_action('unspam_comment', $comment_id);
1022 $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
1023 if ( empty($status) )
1026 if ( wp_set_comment_status($comment_id, $status) ) {
1027 delete_comment_meta($comment_id, '_wp_trash_meta_status');
1028 do_action('unspammed_comment', $comment_id);
1036 * The status of a comment by ID.
1040 * @param int $comment_id Comment ID
1041 * @return string|bool Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
1043 function wp_get_comment_status($comment_id) {
1044 $comment = get_comment($comment_id);
1048 $approved = $comment->comment_approved;
1050 if ( $approved == NULL )
1052 elseif ( $approved == '1' )
1054 elseif ( $approved == '0' )
1055 return 'unapproved';
1056 elseif ( $approved == 'spam' )
1058 elseif ( $approved == 'trash' )
1065 * Call hooks for when a comment status transition occurs.
1067 * Calls hooks for comment status transitions. If the new comment status is not the same
1068 * as the previous comment status, then two hooks will be ran, the first is
1069 * 'transition_comment_status' with new status, old status, and comment data. The
1070 * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
1071 * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
1074 * The final action will run whether or not the comment statuses are the same. The
1075 * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
1076 * parameter and COMMENTTYPE is comment_type comment data.
1080 * @param string $new_status New comment status.
1081 * @param string $old_status Previous comment status.
1082 * @param object $comment Comment data.
1084 function wp_transition_comment_status($new_status, $old_status, $comment) {
1085 // Translate raw statuses to human readable formats for the hooks
1086 // This is not a complete list of comment status, it's only the ones that need to be renamed
1087 $comment_statuses = array(
1089 'hold' => 'unapproved', // wp_set_comment_status() uses "hold"
1091 'approve' => 'approved', // wp_set_comment_status() uses "approve"
1093 if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
1094 if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
1097 if ( $new_status != $old_status ) {
1098 do_action('transition_comment_status', $new_status, $old_status, $comment);
1099 do_action("comment_${old_status}_to_$new_status", $comment);
1101 do_action("comment_${new_status}_$comment->comment_type", $comment->comment_ID, $comment);
1105 * Get current commenter's name, email, and URL.
1107 * Expects cookies content to already be sanitized. User of this function might
1108 * wish to recheck the returned array for validity.
1110 * @see sanitize_comment_cookies() Use to sanitize cookies
1114 * @return array Comment author, email, url respectively.
1116 function wp_get_current_commenter() {
1117 // Cookies should already be sanitized.
1119 $comment_author = '';
1120 if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
1121 $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
1123 $comment_author_email = '';
1124 if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
1125 $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
1127 $comment_author_url = '';
1128 if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
1129 $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
1131 return compact('comment_author', 'comment_author_email', 'comment_author_url');
1135 * Inserts a comment to the database.
1137 * The available comment data key names are 'comment_author_IP', 'comment_date',
1138 * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'.
1143 * @param array $commentdata Contains information on the comment.
1144 * @return int The new comment's ID.
1146 function wp_insert_comment($commentdata) {
1148 extract(stripslashes_deep($commentdata), EXTR_SKIP);
1150 if ( ! isset($comment_author_IP) )
1151 $comment_author_IP = '';
1152 if ( ! isset($comment_date) )
1153 $comment_date = current_time('mysql');
1154 if ( ! isset($comment_date_gmt) )
1155 $comment_date_gmt = get_gmt_from_date($comment_date);
1156 if ( ! isset($comment_parent) )
1157 $comment_parent = 0;
1158 if ( ! isset($comment_approved) )
1159 $comment_approved = 1;
1160 if ( ! isset($comment_karma) )
1162 if ( ! isset($user_id) )
1164 if ( ! isset($comment_type) )
1167 $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');
1168 $wpdb->insert($wpdb->comments, $data);
1170 $id = (int) $wpdb->insert_id;
1172 if ( $comment_approved == 1 )
1173 wp_update_comment_count($comment_post_ID);
1175 $comment = get_comment($id);
1176 do_action('wp_insert_comment', $id, $comment);
1182 * Filters and sanitizes comment data.
1184 * Sets the comment data 'filtered' field to true when finished. This can be
1185 * checked as to whether the comment should be filtered and to keep from
1186 * filtering the same comment more than once.
1189 * @uses apply_filters() Calls 'pre_user_id' hook on comment author's user ID
1190 * @uses apply_filters() Calls 'pre_comment_user_agent' hook on comment author's user agent
1191 * @uses apply_filters() Calls 'pre_comment_author_name' hook on comment author's name
1192 * @uses apply_filters() Calls 'pre_comment_content' hook on the comment's content
1193 * @uses apply_filters() Calls 'pre_comment_user_ip' hook on comment author's IP
1194 * @uses apply_filters() Calls 'pre_comment_author_url' hook on comment author's URL
1195 * @uses apply_filters() Calls 'pre_comment_author_email' hook on comment author's email address
1197 * @param array $commentdata Contains information on the comment.
1198 * @return array Parsed comment information.
1200 function wp_filter_comment($commentdata) {
1201 if ( isset($commentdata['user_ID']) )
1202 $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_ID']);
1203 elseif ( isset($commentdata['user_id']) )
1204 $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_id']);
1205 $commentdata['comment_agent'] = apply_filters('pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
1206 $commentdata['comment_author'] = apply_filters('pre_comment_author_name', $commentdata['comment_author']);
1207 $commentdata['comment_content'] = apply_filters('pre_comment_content', $commentdata['comment_content']);
1208 $commentdata['comment_author_IP'] = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']);
1209 $commentdata['comment_author_url'] = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']);
1210 $commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']);
1211 $commentdata['filtered'] = true;
1212 return $commentdata;
1216 * Whether comment should be blocked because of comment flood.
1220 * @param bool $block Whether plugin has already blocked comment.
1221 * @param int $time_lastcomment Timestamp for last comment.
1222 * @param int $time_newcomment Timestamp for new comment.
1223 * @return bool Whether comment should be blocked.
1225 function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
1226 if ( $block ) // a plugin has already blocked... we'll let that decision stand
1228 if ( ($time_newcomment - $time_lastcomment) < 15 )
1234 * Adds a new comment to the database.
1236 * Filters new comment to ensure that the fields are sanitized and valid before
1237 * inserting comment into database. Calls 'comment_post' action with comment ID
1238 * and whether comment is approved by WordPress. Also has 'preprocess_comment'
1239 * filter for processing the comment data before the function handles it.
1242 * @uses apply_filters() Calls 'preprocess_comment' hook on $commentdata parameter array before processing
1243 * @uses do_action() Calls 'comment_post' hook on $comment_ID returned from adding the comment and if the comment was approved.
1244 * @uses wp_filter_comment() Used to filter comment before adding comment.
1245 * @uses wp_allow_comment() checks to see if comment is approved.
1246 * @uses wp_insert_comment() Does the actual comment insertion to the database.
1248 * @param array $commentdata Contains information on the comment.
1249 * @return int The ID of the comment after adding.
1251 function wp_new_comment( $commentdata ) {
1252 $commentdata = apply_filters('preprocess_comment', $commentdata);
1254 $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
1255 if ( isset($commentdata['user_ID']) )
1256 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
1257 elseif ( isset($commentdata['user_id']) )
1258 $commentdata['user_id'] = (int) $commentdata['user_id'];
1260 $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
1261 $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
1262 $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
1264 $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
1265 $commentdata['comment_agent'] = substr($_SERVER['HTTP_USER_AGENT'], 0, 254);
1267 $commentdata['comment_date'] = current_time('mysql');
1268 $commentdata['comment_date_gmt'] = current_time('mysql', 1);
1270 $commentdata = wp_filter_comment($commentdata);
1272 $commentdata['comment_approved'] = wp_allow_comment($commentdata);
1274 $comment_ID = wp_insert_comment($commentdata);
1276 do_action('comment_post', $comment_ID, $commentdata['comment_approved']);
1278 if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
1279 if ( '0' == $commentdata['comment_approved'] )
1280 wp_notify_moderator($comment_ID);
1282 $post = &get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment
1284 if ( get_option('comments_notify') && $commentdata['comment_approved'] && ( ! isset( $commentdata['user_id'] ) || $post->post_author != $commentdata['user_id'] ) )
1285 wp_notify_postauthor($comment_ID, empty( $commentdata['comment_type'] ) ? $commentdata['comment_type'] : '' );
1292 * Sets the status of a comment.
1294 * The 'wp_set_comment_status' action is called after the comment is handled and
1295 * will only be called, if the comment status is either 'hold', 'approve', or
1296 * 'spam'. If the comment status is not in the list, then false is returned and
1297 * if the status is 'delete', then the comment is deleted without calling the
1301 * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
1303 * @param int $comment_id Comment ID.
1304 * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'delete'.
1305 * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
1306 * @return bool False on failure or deletion and true on success.
1308 function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
1312 switch ( $comment_status ) {
1320 if ( get_option('comments_notify') ) {
1321 $comment = get_comment($comment_id);
1322 wp_notify_postauthor($comment_id, $comment->comment_type);
1335 $comment_old = wp_clone(get_comment($comment_id));
1337 if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
1339 return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
1344 clean_comment_cache($comment_id);
1346 $comment = get_comment($comment_id);
1348 do_action('wp_set_comment_status', $comment_id, $comment_status);
1349 wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
1351 wp_update_comment_count($comment->comment_post_ID);
1357 * Updates an existing comment in the database.
1359 * Filters the comment and makes sure certain fields are valid before updating.
1363 * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
1365 * @param array $commentarr Contains information on the comment.
1366 * @return int Comment was updated if value is 1, or was not updated if value is 0.
1368 function wp_update_comment($commentarr) {
1371 // First, get all of the original fields
1372 $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
1374 // Escape data pulled from DB.
1375 $comment = esc_sql($comment);
1377 $old_status = $comment['comment_approved'];
1379 // Merge old and new fields with new fields overwriting old ones.
1380 $commentarr = array_merge($comment, $commentarr);
1382 $commentarr = wp_filter_comment( $commentarr );
1384 // Now extract the merged array.
1385 extract(stripslashes_deep($commentarr), EXTR_SKIP);
1387 $comment_content = apply_filters('comment_save_pre', $comment_content);
1389 $comment_date_gmt = get_gmt_from_date($comment_date);
1391 if ( !isset($comment_approved) )
1392 $comment_approved = 1;
1393 else if ( 'hold' == $comment_approved )
1394 $comment_approved = 0;
1395 else if ( 'approve' == $comment_approved )
1396 $comment_approved = 1;
1398 $data = compact('comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt');
1399 $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
1401 clean_comment_cache($comment_ID);
1402 wp_update_comment_count($comment_post_ID);
1403 do_action('edit_comment', $comment_ID);
1404 $comment = get_comment($comment_ID);
1405 wp_transition_comment_status($comment->comment_approved, $old_status, $comment);
1410 * Whether to defer comment counting.
1412 * When setting $defer to true, all post comment counts will not be updated
1413 * until $defer is set to false. When $defer is set to false, then all
1414 * previously deferred updated post comment counts will then be automatically
1415 * updated without having to call wp_update_comment_count() after.
1418 * @staticvar bool $_defer
1420 * @param bool $defer
1423 function wp_defer_comment_counting($defer=null) {
1424 static $_defer = false;
1426 if ( is_bool($defer) ) {
1428 // flush any deferred counts
1430 wp_update_comment_count( null, true );
1437 * Updates the comment count for post(s).
1439 * When $do_deferred is false (is by default) and the comments have been set to
1440 * be deferred, the post_id will be added to a queue, which will be updated at a
1441 * later date and only updated once per post ID.
1443 * If the comments have not be set up to be deferred, then the post will be
1444 * updated. When $do_deferred is set to true, then all previous deferred post
1445 * IDs will be updated along with the current $post_id.
1448 * @see wp_update_comment_count_now() For what could cause a false return value
1450 * @param int $post_id Post ID
1451 * @param bool $do_deferred Whether to process previously deferred post comment counts
1452 * @return bool True on success, false on failure
1454 function wp_update_comment_count($post_id, $do_deferred=false) {
1455 static $_deferred = array();
1457 if ( $do_deferred ) {
1458 $_deferred = array_unique($_deferred);
1459 foreach ( $_deferred as $i => $_post_id ) {
1460 wp_update_comment_count_now($_post_id);
1461 unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
1465 if ( wp_defer_comment_counting() ) {
1466 $_deferred[] = $post_id;
1469 elseif ( $post_id ) {
1470 return wp_update_comment_count_now($post_id);
1476 * Updates the comment count for the post.
1480 * @uses do_action() Calls 'wp_update_comment_count' hook on $post_id, $new, and $old
1481 * @uses do_action() Calls 'edit_posts' hook on $post_id and $post
1483 * @param int $post_id Post ID
1484 * @return bool False on '0' $post_id or if post with ID does not exist. True on success.
1486 function wp_update_comment_count_now($post_id) {
1488 $post_id = (int) $post_id;
1491 if ( !$post = get_post($post_id) )
1494 $old = (int) $post->comment_count;
1495 $new = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id) );
1496 $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) );
1498 if ( 'page' == $post->post_type )
1499 clean_page_cache( $post_id );
1501 clean_post_cache( $post_id );
1503 do_action('wp_update_comment_count', $post_id, $new, $old);
1504 do_action('edit_post', $post_id, $post);
1510 // Ping and trackback functions.
1514 * Finds a pingback server URI based on the given URL.
1516 * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
1517 * a check for the x-pingback headers first and returns that, if available. The
1518 * check for the rel="pingback" has more overhead than just the header.
1522 * @param string $url URL to ping.
1523 * @param int $deprecated Not Used.
1524 * @return bool|string False on failure, string containing URI on success.
1526 function discover_pingback_server_uri( $url, $deprecated = '' ) {
1527 if ( !empty( $deprecated ) )
1528 _deprecated_argument( __FUNCTION__, '2.7' );
1530 $pingback_str_dquote = 'rel="pingback"';
1531 $pingback_str_squote = 'rel=\'pingback\'';
1533 /** @todo Should use Filter Extension or custom preg_match instead. */
1534 $parsed_url = parse_url($url);
1536 if ( ! isset( $parsed_url['host'] ) ) // Not an URL. This should never happen.
1539 //Do not search for a pingback server on our own uploads
1540 $uploads_dir = wp_upload_dir();
1541 if ( 0 === strpos($url, $uploads_dir['baseurl']) )
1544 $response = wp_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
1546 if ( is_wp_error( $response ) )
1549 if ( isset( $response['headers']['x-pingback'] ) )
1550 return $response['headers']['x-pingback'];
1552 // Not an (x)html, sgml, or xml page, no use going further.
1553 if ( isset( $response['headers']['content-type'] ) && preg_match('#(image|audio|video|model)/#is', $response['headers']['content-type']) )
1556 // Now do a GET since we're going to look in the html headers (and we're sure its not a binary file)
1557 $response = wp_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
1559 if ( is_wp_error( $response ) )
1562 $contents = $response['body'];
1564 $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
1565 $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
1566 if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
1567 $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
1568 $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
1569 $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
1570 $pingback_href_start = $pingback_href_pos+6;
1571 $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
1572 $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
1573 $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
1575 // We may find rel="pingback" but an incomplete pingback URL
1576 if ( $pingback_server_url_len > 0 ) { // We got it!
1577 return $pingback_server_url;
1585 * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
1590 function do_all_pings() {
1594 while ($ping = $wpdb->get_row("SELECT * FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_pingme' LIMIT 1")) {
1595 $mid = $wpdb->get_var( "SELECT meta_id FROM {$wpdb->postmeta} WHERE post_id = {$ping->ID} AND meta_key = '_pingme' LIMIT 1");
1596 do_action( 'delete_postmeta', $mid );
1597 $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->postmeta} WHERE meta_id = %d", $mid ) );
1598 do_action( 'deleted_postmeta', $mid );
1599 pingback($ping->post_content, $ping->ID);
1603 while ($enclosure = $wpdb->get_row("SELECT * FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_encloseme' LIMIT 1")) {
1604 $mid = $wpdb->get_var( $wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_encloseme'", $enclosure->ID) );
1605 do_action( 'delete_postmeta', $mid );
1606 $wpdb->query( $wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE meta_id = %d", $mid) );
1607 do_action( 'deleted_postmeta', $mid );
1608 do_enclose($enclosure->post_content, $enclosure->ID);
1612 $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'");
1613 if ( is_array($trackbacks) )
1614 foreach ( $trackbacks as $trackback )
1615 do_trackbacks($trackback);
1617 //Do Update Services/Generic Pings
1622 * Perform trackbacks.
1627 * @param int $post_id Post ID to do trackbacks on.
1629 function do_trackbacks($post_id) {
1632 $post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) );
1633 $to_ping = get_to_ping($post_id);
1634 $pinged = get_pung($post_id);
1635 if ( empty($to_ping) ) {
1636 $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) );
1640 if ( empty($post->post_excerpt) )
1641 $excerpt = apply_filters('the_content', $post->post_content);
1643 $excerpt = apply_filters('the_excerpt', $post->post_excerpt);
1644 $excerpt = str_replace(']]>', ']]>', $excerpt);
1645 $excerpt = wp_html_excerpt($excerpt, 252) . '...';
1647 $post_title = apply_filters('the_title', $post->post_title);
1648 $post_title = strip_tags($post_title);
1651 foreach ( (array) $to_ping as $tb_ping ) {
1652 $tb_ping = trim($tb_ping);
1653 if ( !in_array($tb_ping, $pinged) ) {
1654 trackback($tb_ping, $post_title, $excerpt, $post_id);
1655 $pinged[] = $tb_ping;
1657 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_ping', '')) WHERE ID = %d", $post_id) );
1664 * Sends pings to all of the ping site services.
1668 * @param int $post_id Post ID. Not actually used.
1669 * @return int Same as Post ID from parameter
1671 function generic_ping($post_id = 0) {
1672 $services = get_option('ping_sites');
1674 $services = explode("\n", $services);
1675 foreach ( (array) $services as $service ) {
1676 $service = trim($service);
1677 if ( '' != $service )
1678 weblog_ping($service);
1685 * Pings back the links found in a post.
1691 * @param string $content Post content to check for links.
1692 * @param int $post_ID Post ID.
1694 function pingback($content, $post_ID) {
1696 include_once(ABSPATH . WPINC . '/class-IXR.php');
1698 // original code by Mort (http://mort.mine.nu:8080)
1699 $post_links = array();
1701 $pung = get_pung($post_ID);
1705 $gunk = '/#~:.?+=&%@!\-';
1707 $any = $ltrs . $gunk . $punc;
1710 // Parsing the post, external links (if any) are stored in the $post_links array
1711 // This regexp comes straight from phpfreaks.com
1712 // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
1713 preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
1716 // Walking thru the links array
1717 // first we get rid of links pointing to sites, not to specific files
1719 // http://dummy-weblog.org
1720 // http://dummy-weblog.org/
1721 // http://dummy-weblog.org/post.php
1722 // We don't wanna ping first and second types, even if they have a valid <link/>
1724 foreach ( (array) $post_links_temp[0] as $link_test ) :
1725 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
1726 && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
1727 if ( $test = @parse_url($link_test) ) {
1728 if ( isset($test['query']) )
1729 $post_links[] = $link_test;
1730 elseif ( ($test['path'] != '/') && ($test['path'] != '') )
1731 $post_links[] = $link_test;
1736 do_action_ref_array('pre_ping', array(&$post_links, &$pung));
1738 foreach ( (array) $post_links as $pagelinkedto ) {
1739 $pingback_server_url = discover_pingback_server_uri($pagelinkedto, 2048);
1741 if ( $pingback_server_url ) {
1742 @ set_time_limit( 60 );
1743 // Now, the RPC call
1744 $pagelinkedfrom = get_permalink($post_ID);
1746 // using a timeout of 3 seconds should be enough to cover slow servers
1747 $client = new IXR_Client($pingback_server_url);
1748 $client->timeout = 3;
1749 $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . $wp_version, $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom);
1750 // when set to true, this outputs debug messages by itself
1751 $client->debug = false;
1753 if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
1754 add_ping( $post_ID, $pagelinkedto );
1760 * Check whether blog is public before returning sites.
1764 * @param mixed $sites Will return if blog is public, will not return if not public.
1765 * @return mixed Empty string if blog is not public, returns $sites, if site is public.
1767 function privacy_ping_filter($sites) {
1768 if ( '0' != get_option('blog_public') )
1777 * Updates database when sending trackback to prevent duplicates.
1782 * @param string $trackback_url URL to send trackbacks.
1783 * @param string $title Title of post.
1784 * @param string $excerpt Excerpt of post.
1785 * @param int $ID Post ID.
1786 * @return mixed Database query from update.
1788 function trackback($trackback_url, $title, $excerpt, $ID) {
1791 if ( empty($trackback_url) )
1795 $options['timeout'] = 4;
1796 $options['body'] = array(
1798 'url' => get_permalink($ID),
1799 'blog_name' => get_option('blogname'),
1800 'excerpt' => $excerpt
1803 $response = wp_remote_post($trackback_url, $options);
1805 if ( is_wp_error( $response ) )
1808 $tb_url = addslashes( $trackback_url );
1809 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', '$tb_url') WHERE ID = %d", $ID) );
1810 return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_url', '')) WHERE ID = %d", $ID) );
1820 * @param string $server Host of blog to connect to.
1821 * @param string $path Path to send the ping.
1823 function weblog_ping($server = '', $path = '') {
1825 include_once(ABSPATH . WPINC . '/class-IXR.php');
1827 // using a timeout of 3 seconds should be enough to cover slow servers
1828 $client = new IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
1829 $client->timeout = 3;
1830 $client->useragent .= ' -- WordPress/'.$wp_version;
1832 // when set to true, this outputs debug messages by itself
1833 $client->debug = false;
1834 $home = trailingslashit( home_url() );
1835 if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
1836 $client->query('weblogUpdates.ping', get_option('blogname'), $home);
1844 * Removes comment ID from the comment cache.
1847 * @package WordPress
1850 * @param int|array $id Comment ID or array of comment IDs to remove from cache
1852 function clean_comment_cache($ids) {
1853 foreach ( (array) $ids as $id )
1854 wp_cache_delete($id, 'comment');
1858 * Updates the comment cache of given comments.
1860 * Will add the comments in $comments to the cache. If comment ID already exists
1861 * in the comment cache then it will not be updated. The comment is added to the
1862 * cache using the comment group with the key using the ID of the comments.
1865 * @package WordPress
1868 * @param array $comments Array of comment row objects
1870 function update_comment_cache($comments) {
1871 foreach ( (array) $comments as $comment )
1872 wp_cache_add($comment->comment_ID, $comment, 'comment');
1880 * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
1885 * @param object $posts Post data object.
1888 function _close_comments_for_old_posts( $posts ) {
1889 if ( empty($posts) || !is_singular() || !get_option('close_comments_for_old_posts') )
1892 $days_old = (int) get_option('close_comments_days_old');
1896 if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * 24 * 60 * 60 ) ) {
1897 $posts[0]->comment_status = 'closed';
1898 $posts[0]->ping_status = 'closed';
1905 * Close comments on an old post. Hooked to comments_open and pings_open.
1910 * @param bool $open Comments open or closed
1911 * @param int $post_id Post ID
1912 * @return bool $open
1914 function _close_comments_for_old_post( $open, $post_id ) {
1918 if ( !get_option('close_comments_for_old_posts') )
1921 $days_old = (int) get_option('close_comments_days_old');
1925 $post = get_post($post_id);
1927 if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * 24 * 60 * 60 ) )