3 * Manages WordPress comments
9 * check_comment() - Checks whether a comment passes internal checks to be allowed to add
11 * {@internal Missing Long Description}}
16 * @param string $author {@internal Missing Description }}
17 * @param string $email {@internal Missing Description }}
18 * @param string $url {@internal Missing Description }}
19 * @param string $comment {@internal Missing Description }}
20 * @param string $user_ip {@internal Missing Description }}
21 * @param string $user_agent {@internal Missing Description }}
22 * @param string $comment_type {@internal Missing Description }}
23 * @return bool {@internal Missing Description }}
25 function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
28 if ( 1 == get_option('comment_moderation') )
29 return false; // If moderation is set to manual
31 if ( preg_match_all("|(href\t*?=\t*?['\"]?)?(https?:)?//|i", $comment, $out) >= get_option('comment_max_links') )
32 return false; // Check # of external links
34 $mod_keys = trim(get_option('moderation_keys'));
35 if ( !empty($mod_keys) ) {
36 $words = explode("\n", $mod_keys );
38 foreach ($words as $word) {
45 // Do some escaping magic so that '#' chars in the
46 // spam words don't break things:
47 $word = preg_quote($word, '#');
49 $pattern = "#$word#i";
50 if ( preg_match($pattern, $author) ) return false;
51 if ( preg_match($pattern, $email) ) return false;
52 if ( preg_match($pattern, $url) ) return false;
53 if ( preg_match($pattern, $comment) ) return false;
54 if ( preg_match($pattern, $user_ip) ) return false;
55 if ( preg_match($pattern, $user_agent) ) return false;
59 // Comment whitelisting:
60 if ( 1 == get_option('comment_whitelist')) {
61 if ( 'trackback' == $comment_type || 'pingback' == $comment_type ) { // check if domain is in blogroll
62 $uri = parse_url($url);
63 $domain = $uri['host'];
64 $uri = parse_url( get_option('home') );
65 $home_domain = $uri['host'];
66 if ( $wpdb->get_var($wpdb->prepare("SELECT link_id FROM $wpdb->links WHERE link_url LIKE (%s) LIMIT 1", '%'.$domain.'%')) || $domain == $home_domain )
70 } elseif ( $author != '' && $email != '' ) {
71 // expected_slashed ($author, $email)
72 $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");
73 if ( ( 1 == $ok_to_comment ) &&
74 ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
86 * get_approved_comments() - Returns the approved comments for post $post_id
91 * @param int $post_id The ID of the post
92 * @return array $comments The approved comments
94 function get_approved_comments($post_id) {
96 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));
100 * get_comment() - Retrieves comment data given a comment ID or comment object.
102 * {@internal Missing Long Description}}
107 * @param object|string|int $comment {@internal Missing Description}}
108 * @param string $output OBJECT or ARRAY_A or ARRAY_N constants
109 * @return object|array|null Depends on $output value.
111 function &get_comment(&$comment, $output = OBJECT) {
114 if ( empty($comment) ) {
115 if ( isset($GLOBALS['comment']) )
116 $_comment = & $GLOBALS['comment'];
119 } elseif ( is_object($comment) ) {
120 wp_cache_add($comment->comment_ID, $comment, 'comment');
121 $_comment = $comment;
123 if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
124 $_comment = & $GLOBALS['comment'];
125 } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
126 $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
127 wp_cache_add($_comment->comment_ID, $_comment, 'comment');
131 $_comment = apply_filters('get_comment', $_comment);
133 if ( $output == OBJECT ) {
135 } elseif ( $output == ARRAY_A ) {
136 return get_object_vars($_comment);
137 } elseif ( $output == ARRAY_N ) {
138 return array_values(get_object_vars($_comment));
145 * get_commentdata() - Returns an array of comment data about comment $comment_ID
147 * get_comment() technically does the same thing as this function. This function also
148 * appears to reference variables and then not use them or not update them when needed.
149 * It is advised to switch to get_comment(), since this function might be deprecated in
150 * favor of using get_comment().
152 * @deprecated Use get_comment()
156 * @uses $postc Comment cache, might not be used any more
158 * @uses $wpdb Database Object
160 * @param int $comment_ID The ID of the comment
161 * @param int $no_cache Whether to use the cache or not (casted to bool)
162 * @param bool $include_unapproved Whether to include unapproved comments or not
163 * @return array The comment data
165 function get_commentdata( $comment_ID, $no_cache = 0, $include_unapproved = false ) { // less flexible, but saves DB queries
166 global $postc, $wpdb;
168 $query = $wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d", $comment_ID);
169 if ( false == $include_unapproved )
170 $query .= " AND comment_approved = '1'";
171 $myrow = $wpdb->get_row($query, ARRAY_A);
173 $myrow['comment_ID'] = $postc->comment_ID;
174 $myrow['comment_post_ID'] = $postc->comment_post_ID;
175 $myrow['comment_author'] = $postc->comment_author;
176 $myrow['comment_author_email'] = $postc->comment_author_email;
177 $myrow['comment_author_url'] = $postc->comment_author_url;
178 $myrow['comment_author_IP'] = $postc->comment_author_IP;
179 $myrow['comment_date'] = $postc->comment_date;
180 $myrow['comment_content'] = $postc->comment_content;
181 $myrow['comment_karma'] = $postc->comment_karma;
182 $myrow['comment_approved'] = $postc->comment_approved;
183 $myrow['comment_type'] = $postc->comment_type;
189 * get_lastcommentmodified() - The date the last comment was modified
191 * {@internal Missing Long Description}}
195 * @global array $cache_lastcommentmodified
197 * @param string $timezone Which timezone to use in reference to 'gmt', 'blog', or 'server' locations
198 * @return string Last comment modified date
200 function get_lastcommentmodified($timezone = 'server') {
201 global $cache_lastcommentmodified, $wpdb;
203 if ( isset($cache_lastcommentmodified[$timezone]) )
204 return $cache_lastcommentmodified[$timezone];
206 $add_seconds_server = date('Z');
208 switch ( strtolower($timezone)) {
210 $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
213 $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
216 $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));
220 $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
222 return $lastcommentmodified;
226 * get_comment_count() - The amount of comments in a post or total comments
228 * {@internal Missing Long Description}}
233 * @param int $post_id Optional. Comment amount in post if > 0, else total com
235 * @return array The amount of spam, approved, awaiting moderation, and total
237 function get_comment_count( $post_id = 0 ) {
240 $post_id = (int) $post_id;
243 if ( $post_id > 0 ) {
244 $where = "WHERE comment_post_ID = {$post_id}";
247 $totals = (array) $wpdb->get_results("
248 SELECT comment_approved, COUNT( * ) AS total
249 FROM {$wpdb->comments}
251 GROUP BY comment_approved
254 $comment_count = array(
256 "awaiting_moderation" => 0,
258 "total_comments" => 0
261 foreach ( $totals as $row ) {
262 switch ( $row['comment_approved'] ) {
264 $comment_count['spam'] = $row['total'];
265 $comment_count["total_comments"] += $row['total'];
268 $comment_count['approved'] = $row['total'];
269 $comment_count['total_comments'] += $row['total'];
272 $comment_count['awaiting_moderation'] = $row['total'];
273 $comment_count['total_comments'] += $row['total'];
280 return $comment_count;
284 * sanitize_comment_cookies() - {@internal Missing Short Description}}
286 * {@internal Missing Long Description}}
291 function sanitize_comment_cookies() {
292 if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) {
293 $comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]);
294 $comment_author = stripslashes($comment_author);
295 $comment_author = attribute_escape($comment_author);
296 $_COOKIE['comment_author_'.COOKIEHASH] = $comment_author;
299 if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) {
300 $comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]);
301 $comment_author_email = stripslashes($comment_author_email);
302 $comment_author_email = attribute_escape($comment_author_email);
303 $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
306 if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) {
307 $comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]);
308 $comment_author_url = stripslashes($comment_author_url);
309 $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
314 * wp_allow_comment() - Validates whether this comment is allowed to be made or not
316 * {@internal Missing Long Description}}
320 * @uses apply_filters() Calls 'pre_comment_approved' hook on the type of comment
321 * @uses do_action() Calls 'check_comment_flood' hook on $comment_author_IP, $comment_author_email, and $comment_date_gmt
323 * @param array $commentdata Contains information on the comment
324 * @return mixed Signifies the approval status (0|1|'spam')
326 function wp_allow_comment($commentdata) {
328 extract($commentdata, EXTR_SKIP);
330 // Simple duplicate check
331 // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
332 $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' ";
333 if ( $comment_author_email )
334 $dupe .= "OR comment_author_email = '$comment_author_email' ";
335 $dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
336 if ( $wpdb->get_var($dupe) )
337 wp_die( __('Duplicate comment detected; it looks as though you\'ve already said that!') );
339 do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt );
342 $userdata = get_userdata($user_id);
343 $user = new WP_User($user_id);
344 $post_author = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", $comment_post_ID));
347 if ( $userdata && ( $user_id == $post_author || $user->has_cap('level_9') ) ) {
348 // The author and the admins get respect.
351 // Everyone else's comments will be checked.
352 if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) )
356 if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) )
360 $approved = apply_filters('pre_comment_approved', $approved);
365 * check_comment_flood_db() - {@internal Missing Short Description}}
367 * {@internal Missing Long Description}}
371 * @uses apply_filters() {@internal Missing Description}}
372 * @uses do_action() {@internal Missing Description}}
374 * @param string $ip {@internal Missing Description}}
375 * @param string $email {@internal Missing Description}}
376 * @param unknown_type $date {@internal Missing Description}}
378 function check_comment_flood_db( $ip, $email, $date ) {
380 if ( current_user_can( 'manage_options' ) )
381 return; // don't throttle admins
382 if ( $lasttime = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_author_IP = '$ip' OR comment_author_email = '$email' ORDER BY comment_date DESC LIMIT 1") ) {
383 $time_lastcomment = mysql2date('U', $lasttime);
384 $time_newcomment = mysql2date('U', $date);
385 $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
387 do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment);
388 wp_die( __('You are posting comments too quickly. Slow down.') );
394 * wp_blacklist_check() - Does comment contain blacklisted characters or words
396 * {@internal Missing Long Description}}
399 * @uses do_action() Calls 'wp_blacklist_check' hook for all parameters
401 * @param string $author The author of the comment
402 * @param string $email The email of the comment
403 * @param string $url The url used in the comment
404 * @param string $comment The comment content
405 * @param string $user_ip The comment author IP address
406 * @param string $user_agent The author's browser user agent
407 * @return bool True if comment contains blacklisted content, false if comment does not
409 function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
410 do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent);
412 if ( preg_match_all('/&#(\d+);/', $comment . $author . $url, $chars) ) {
413 foreach ( (array) $chars[1] as $char ) {
414 // If it's an encoded char in the normal ASCII set, reject
416 continue; // Unless it's &
422 $mod_keys = trim( get_option('blacklist_keys') );
423 if ( '' == $mod_keys )
424 return false; // If moderation keys are empty
425 $words = explode("\n", $mod_keys );
427 foreach ( (array) $words as $word ) {
431 if ( empty($word) ) { continue; }
433 // Do some escaping magic so that '#' chars in the
434 // spam words don't break things:
435 $word = preg_quote($word, '#');
437 $pattern = "#$word#i";
439 preg_match($pattern, $author)
440 || preg_match($pattern, $email)
441 || preg_match($pattern, $url)
442 || preg_match($pattern, $comment)
443 || preg_match($pattern, $user_ip)
444 || preg_match($pattern, $user_agent)
451 function wp_count_comments() {
454 $count = wp_cache_get('comments', 'counts');
456 if ( false !== $count )
459 $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} GROUP BY comment_approved", ARRAY_A );
462 $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam');
463 foreach( (array) $count as $row_num => $row ) {
464 $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
467 foreach ( $approved as $key ) {
468 if ( empty($stats[$key]) )
472 $stats = (object) $stats;
473 wp_cache_set('comments', $stats, 'counts');
479 * wp_delete_comment() - Removes comment ID and maybe updates post comment count
481 * The post comment count will be updated if the comment was approved and has a post
486 * @uses do_action() Calls 'delete_comment' hook on comment ID
487 * @uses do_action() Calls 'wp_set_comment_status' hook on comment ID with 'delete' set for the second parameter
489 * @param int $comment_id Comment ID
490 * @return bool False if delete comment query failure, true on success
492 function wp_delete_comment($comment_id) {
494 do_action('delete_comment', $comment_id);
496 $comment = get_comment($comment_id);
498 if ( ! $wpdb->query("DELETE FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1") )
501 $post_id = $comment->comment_post_ID;
502 if ( $post_id && $comment->comment_approved == 1 )
503 wp_update_comment_count($post_id);
505 clean_comment_cache($comment_id);
507 do_action('wp_set_comment_status', $comment_id, 'delete');
512 * wp_get_comment_status() - The status of a comment by ID
516 * @param int $comment_id Comment ID
517 * @return string|bool Status might be 'deleted', 'approved', 'unapproved', 'spam'. False on failure
519 function wp_get_comment_status($comment_id) {
520 $comment = get_comment($comment_id);
524 $approved = $comment->comment_approved;
526 if ( $approved == NULL )
528 elseif ( $approved == '1' )
530 elseif ( $approved == '0' )
532 elseif ( $approved == 'spam' )
539 * wp_get_current_commenter() - Get current commenter's name, email, and URL
541 * Expects cookies content to already be sanitized. User of this function
542 * might wish to recheck the returned array for validity.
544 * @see sanitize_comment_cookies() Use to sanitize cookies
548 * @return array Comment author, email, url respectively
550 function wp_get_current_commenter() {
551 // Cookies should already be sanitized.
553 $comment_author = '';
554 if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
555 $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
557 $comment_author_email = '';
558 if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
559 $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
561 $comment_author_url = '';
562 if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
563 $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
565 return compact('comment_author', 'comment_author_email', 'comment_author_url');
569 * wp_insert_comment() - Inserts a comment to the database
571 * {@internal Missing Long Description}}
576 * @param array $commentdata Contains information on the comment
577 * @return int The new comment's id
579 function wp_insert_comment($commentdata) {
581 extract($commentdata, EXTR_SKIP);
583 if ( ! isset($comment_author_IP) )
584 $comment_author_IP = '';
585 if ( ! isset($comment_date) )
586 $comment_date = current_time('mysql');
587 if ( ! isset($comment_date_gmt) )
588 $comment_date_gmt = get_gmt_from_date($comment_date);
589 if ( ! isset($comment_parent) )
591 if ( ! isset($comment_approved) )
592 $comment_approved = 1;
593 if ( ! isset($user_id) )
596 $result = $wpdb->query("INSERT INTO $wpdb->comments
597 (comment_post_ID, comment_author, comment_author_email, comment_author_url, comment_author_IP, comment_date, comment_date_gmt, comment_content, comment_approved, comment_agent, comment_type, comment_parent, user_id)
599 ('$comment_post_ID', '$comment_author', '$comment_author_email', '$comment_author_url', '$comment_author_IP', '$comment_date', '$comment_date_gmt', '$comment_content', '$comment_approved', '$comment_agent', '$comment_type', '$comment_parent', '$user_id')
602 $id = (int) $wpdb->insert_id;
604 if ( $comment_approved == 1)
605 wp_update_comment_count($comment_post_ID);
611 * wp_filter_comment() - Parses and returns comment information
613 * Sets the comment data 'filtered' field to true when finished. This
614 * can be checked as to whether the comment should be filtered and to
615 * keep from filtering the same comment more than once.
618 * @uses apply_filters() Calls 'pre_user_id' hook on comment author's user ID
619 * @uses apply_filters() Calls 'pre_comment_user_agent' hook on comment author's user agent
620 * @uses apply_filters() Calls 'pre_comment_author_name' hook on comment author's name
621 * @uses apply_filters() Calls 'pre_comment_content' hook on the comment's content
622 * @uses apply_filters() Calls 'pre_comment_user_ip' hook on comment author's IP
623 * @uses apply_filters() Calls 'pre_comment_author_url' hook on comment author's URL
624 * @uses apply_filters() Calls 'pre_comment_author_email' hook on comment author's email address
626 * @param array $commentdata Contains information on the comment
627 * @return array Parsed comment information
629 function wp_filter_comment($commentdata) {
630 $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_ID']);
631 $commentdata['comment_agent'] = apply_filters('pre_comment_user_agent', $commentdata['comment_agent']);
632 $commentdata['comment_author'] = apply_filters('pre_comment_author_name', $commentdata['comment_author']);
633 $commentdata['comment_content'] = apply_filters('pre_comment_content', $commentdata['comment_content']);
634 $commentdata['comment_author_IP'] = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']);
635 $commentdata['comment_author_url'] = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']);
636 $commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']);
637 $commentdata['filtered'] = true;
642 * wp_throttle_comment_flood() - {@internal Missing Short Description}}
644 * {@internal Missing Long Description}}
648 * @param unknown_type $block {@internal Missing Description}}
649 * @param unknown_type $time_lastcomment {@internal Missing Description}}
650 * @param unknown_type $time_newcomment {@internal Missing Description}}
651 * @return unknown {@internal Missing Description}}
653 function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
654 if ( $block ) // a plugin has already blocked... we'll let that decision stand
656 if ( ($time_newcomment - $time_lastcomment) < 15 )
662 * wp_new_comment() - Parses and adds a new comment to the database
664 * {@internal Missing Long Description}}
667 * @uses apply_filters() Calls 'preprocess_comment' hook on $commentdata parameter array before processing
668 * @uses do_action() Calls 'comment_post' hook on $comment_ID returned from adding the comment and if the comment was approved.
669 * @uses wp_filter_comment() Used to filter comment before adding comment
670 * @uses wp_allow_comment() checks to see if comment is approved.
671 * @uses wp_insert_comment() Does the actual comment insertion to the database
673 * @param array $commentdata Contains information on the comment
674 * @return int The ID of the comment after adding.
676 function wp_new_comment( $commentdata ) {
677 $commentdata = apply_filters('preprocess_comment', $commentdata);
679 $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
680 $commentdata['user_ID'] = (int) $commentdata['user_ID'];
682 $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
683 $commentdata['comment_agent'] = $_SERVER['HTTP_USER_AGENT'];
685 $commentdata['comment_date'] = current_time('mysql');
686 $commentdata['comment_date_gmt'] = current_time('mysql', 1);
688 $commentdata = wp_filter_comment($commentdata);
690 $commentdata['comment_approved'] = wp_allow_comment($commentdata);
692 $comment_ID = wp_insert_comment($commentdata);
694 do_action('comment_post', $comment_ID, $commentdata['comment_approved']);
696 if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
697 if ( '0' == $commentdata['comment_approved'] )
698 wp_notify_moderator($comment_ID);
700 $post = &get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment
702 if ( get_option('comments_notify') && $commentdata['comment_approved'] && $post->post_author != $commentdata['user_ID'] )
703 wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
710 * wp_set_comment_status() - Sets the status of comment ID
712 * {@internal Missing Long Description}}
716 * @param int $comment_id Comment ID
717 * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'delete'
718 * @return bool False on failure or deletion and true on success.
720 function wp_set_comment_status($comment_id, $comment_status) {
723 switch ( $comment_status ) {
725 $query = "UPDATE $wpdb->comments SET comment_approved='0' WHERE comment_ID='$comment_id' LIMIT 1";
728 $query = "UPDATE $wpdb->comments SET comment_approved='1' WHERE comment_ID='$comment_id' LIMIT 1";
731 $query = "UPDATE $wpdb->comments SET comment_approved='spam' WHERE comment_ID='$comment_id' LIMIT 1";
734 return wp_delete_comment($comment_id);
740 if ( !$wpdb->query($query) )
743 clean_comment_cache($comment_id);
745 do_action('wp_set_comment_status', $comment_id, $comment_status);
746 $comment = get_comment($comment_id);
747 wp_update_comment_count($comment->comment_post_ID);
753 * wp_update_comment() - Parses and updates an existing comment in the database
755 * {@internal Missing Long Description}}
760 * @param array $commentarr Contains information on the comment
761 * @return int Comment was updated if value is 1, or was not updated if value is 0.
763 function wp_update_comment($commentarr) {
766 // First, get all of the original fields
767 $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
769 // Escape data pulled from DB.
770 foreach ( (array) $comment as $key => $value )
771 $comment[$key] = $wpdb->escape($value);
773 // Merge old and new fields with new fields overwriting old ones.
774 $commentarr = array_merge($comment, $commentarr);
776 $commentarr = wp_filter_comment( $commentarr );
778 // Now extract the merged array.
779 extract($commentarr, EXTR_SKIP);
781 $comment_content = apply_filters('comment_save_pre', $comment_content);
783 $comment_date_gmt = get_gmt_from_date($comment_date);
786 "UPDATE $wpdb->comments SET
787 comment_content = '$comment_content',
788 comment_author = '$comment_author',
789 comment_author_email = '$comment_author_email',
790 comment_approved = '$comment_approved',
791 comment_author_url = '$comment_author_url',
792 comment_date = '$comment_date',
793 comment_date_gmt = '$comment_date_gmt'
794 WHERE comment_ID = $comment_ID" );
796 $rval = $wpdb->rows_affected;
798 clean_comment_cache($comment_ID);
799 wp_update_comment_count($comment_post_ID);
800 do_action('edit_comment', $comment_ID);
805 * wp_defer_comment_counting() - Whether to defer comment counting
807 * When setting $defer to true, all post comment counts will not be updated
808 * until $defer is set to false. When $defer is set to false, then all
809 * previously deferred updated post comment counts will then be automatically
810 * updated without having to call wp_update_comment_count() after.
813 * @staticvar bool $_defer
818 function wp_defer_comment_counting($defer=null) {
819 static $_defer = false;
821 if ( is_bool($defer) ) {
823 // flush any deferred counts
825 wp_update_comment_count( null, true );
832 * wp_update_comment_count() - Updates the comment count for post(s)
834 * When $do_deferred is false (is by default) and the comments have been
835 * set to be deferred, the post_id will be added to a queue, which will
836 * be updated at a later date and only updated once per post ID.
838 * If the comments have not be set up to be deferred, then the post will
839 * be updated. When $do_deferred is set to true, then all previous deferred
840 * post IDs will be updated along with the current $post_id.
843 * @see wp_update_comment_count_now() For what could cause a false return value
845 * @param int $post_id Post ID
846 * @param bool $do_deferred Whether to process previously deferred post comment counts
847 * @return bool True on success, false on failure
849 function wp_update_comment_count($post_id, $do_deferred=false) {
850 static $_deferred = array();
852 if ( $do_deferred ) {
853 $_deferred = array_unique($_deferred);
854 foreach ( $_deferred as $i => $_post_id ) {
855 wp_update_comment_count_now($_post_id);
856 unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
860 if ( wp_defer_comment_counting() ) {
861 $_deferred[] = $post_id;
864 elseif ( $post_id ) {
865 return wp_update_comment_count_now($post_id);
871 * wp_update_comment_count_now() - Updates the comment count for the post
875 * @uses do_action() Calls 'wp_update_comment_count' hook on $post_id, $new, and $old
876 * @uses do_action() Calls 'edit_posts' hook on $post_id and $post
878 * @param int $post_id Post ID
879 * @return bool False on '0' $post_id or if post with ID does not exist. True on success.
881 function wp_update_comment_count_now($post_id) {
883 $post_id = (int) $post_id;
886 if ( !$post = get_post($post_id) )
889 $old = (int) $post->comment_count;
890 $new = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = '$post_id' AND comment_approved = '1'");
891 $wpdb->query("UPDATE $wpdb->posts SET comment_count = '$new' WHERE ID = '$post_id'");
893 if ( 'page' == $post->post_type )
894 clean_page_cache( $post_id );
896 clean_post_cache( $post_id );
898 do_action('wp_update_comment_count', $post_id, $new, $old);
899 do_action('edit_post', $post_id, $post);
905 // Ping and trackback functions.
909 * discover_pingback_server_uri() - Finds a pingback server URI based on the given URL
911 * {@internal Missing Long Description}}
916 * @param string $url URL to ping
917 * @param int $timeout_bytes Number of bytes to timeout at. Prevents big file downloads, default is 2048.
918 * @return bool|string False on failure, string containing URI on success.
920 function discover_pingback_server_uri($url, $timeout_bytes = 2048) {
926 $pingback_str_dquote = 'rel="pingback"';
927 $pingback_str_squote = 'rel=\'pingback\'';
928 $x_pingback_str = 'x-pingback: ';
930 extract(parse_url($url), EXTR_SKIP);
932 if ( !isset($host) ) // Not an URL. This should never happen.
935 $path = ( !isset($path) ) ? '/' : $path;
936 $path .= ( isset($query) ) ? '?' . $query : '';
937 $port = ( isset($port) ) ? $port : 80;
939 // Try to connect to the server at $host
940 $fp = @fsockopen($host, $port, $errno, $errstr, 2);
941 if ( !$fp ) // Couldn't open a connection to $host
944 // Send the GET request
945 $request = "GET $path HTTP/1.1\r\nHost: $host\r\nUser-Agent: WordPress/$wp_version \r\n\r\n";
947 fputs($fp, $request);
949 // Let's check for an X-Pingback header first
950 while ( !feof($fp) ) {
951 $line = fgets($fp, 512);
952 if ( trim($line) == '' )
954 $headers .= trim($line)."\n";
955 $x_pingback_header_offset = strpos(strtolower($headers), $x_pingback_str);
956 if ( $x_pingback_header_offset ) {
958 preg_match('#x-pingback: (.+)#is', $headers, $matches);
959 $pingback_server_url = trim($matches[1]);
960 return $pingback_server_url;
962 if ( strpos(strtolower($headers), 'content-type: ') ) {
963 preg_match('#content-type: (.+)#is', $headers, $matches);
964 $content_type = trim($matches[1]);
968 if ( preg_match('#(image|audio|video|model)/#is', $content_type) ) // Not an (x)html, sgml, or xml page, no use going further
971 while ( !feof($fp) ) {
972 $line = fgets($fp, 1024);
973 $contents .= trim($line);
974 $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
975 $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
976 if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
977 $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
978 $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
979 $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
980 $pingback_href_start = $pingback_href_pos+6;
981 $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
982 $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
983 $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
984 // We may find rel="pingback" but an incomplete pingback URL
985 if ( $pingback_server_url_len > 0 ) // We got it!
986 return $pingback_server_url;
988 $byte_count += strlen($line);
989 if ( $byte_count > $timeout_bytes ) {
990 // It's no use going further, there probably isn't any pingback
991 // server to find in this file. (Prevents loading large files.)
996 // We didn't find anything.
1001 * do_all_pings() - {@internal Missing Short Description}}
1003 * {@internal Missing Long Description}}
1008 function do_all_pings() {
1012 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")) {
1013 $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = {$ping->ID} AND meta_key = '_pingme';");
1014 pingback($ping->post_content, $ping->ID);
1018 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")) {
1019 $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = {$enclosure->ID} AND meta_key = '_encloseme';");
1020 do_enclose($enclosure->post_content, $enclosure->ID);
1024 $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'");
1025 if ( is_array($trackbacks) )
1026 foreach ( $trackbacks as $trackback )
1027 do_trackbacks($trackback);
1029 //Do Update Services/Generic Pings
1034 * do_trackbacks() - {@internal Missing Short Description}}
1036 * {@internal Missing Long Description}}
1041 * @param int $post_id Post ID to do trackbacks on
1043 function do_trackbacks($post_id) {
1046 $post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = $post_id");
1047 $to_ping = get_to_ping($post_id);
1048 $pinged = get_pung($post_id);
1049 if ( empty($to_ping) ) {
1050 $wpdb->query("UPDATE $wpdb->posts SET to_ping = '' WHERE ID = '$post_id'");
1054 if ( empty($post->post_excerpt) )
1055 $excerpt = apply_filters('the_content', $post->post_content);
1057 $excerpt = apply_filters('the_excerpt', $post->post_excerpt);
1058 $excerpt = str_replace(']]>', ']]>', $excerpt);
1059 $excerpt = wp_html_excerpt($excerpt, 252) . '...';
1061 $post_title = apply_filters('the_title', $post->post_title);
1062 $post_title = strip_tags($post_title);
1065 foreach ( (array) $to_ping as $tb_ping ) {
1066 $tb_ping = trim($tb_ping);
1067 if ( !in_array($tb_ping, $pinged) ) {
1068 trackback($tb_ping, $post_title, $excerpt, $post_id);
1069 $pinged[] = $tb_ping;
1071 $wpdb->query("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_ping', '')) WHERE ID = '$post_id'");
1078 * generic_ping() - {@internal Missing Short Description}}
1080 * {@internal Missing Long Description}}
1084 * @param int $post_id Post ID. Not actually used.
1085 * @return int Same as Post ID from parameter
1087 function generic_ping($post_id = 0) {
1088 $services = get_option('ping_sites');
1090 $services = explode("\n", $services);
1091 foreach ( (array) $services as $service ) {
1092 $service = trim($service);
1093 if ( '' != $service )
1094 weblog_ping($service);
1101 * pingback() - Pings back the links found in a post
1103 * {@internal Missing Long Description}}
1109 * @param string $content {@internal Missing Description}}
1110 * @param int $post_ID {@internal Missing Description}}
1112 function pingback($content, $post_ID) {
1114 include_once(ABSPATH . WPINC . '/class-IXR.php');
1116 // original code by Mort (http://mort.mine.nu:8080)
1117 $post_links = array();
1119 $pung = get_pung($post_ID);
1123 $gunk = '/#~:.?+=&%@!\-';
1125 $any = $ltrs . $gunk . $punc;
1128 // Parsing the post, external links (if any) are stored in the $post_links array
1129 // This regexp comes straight from phpfreaks.com
1130 // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
1131 preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
1134 // Walking thru the links array
1135 // first we get rid of links pointing to sites, not to specific files
1137 // http://dummy-weblog.org
1138 // http://dummy-weblog.org/
1139 // http://dummy-weblog.org/post.php
1140 // We don't wanna ping first and second types, even if they have a valid <link/>
1142 foreach ( $post_links_temp[0] as $link_test ) :
1143 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
1144 && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
1145 $test = parse_url($link_test);
1146 if ( isset($test['query']) )
1147 $post_links[] = $link_test;
1148 elseif ( ($test['path'] != '/') && ($test['path'] != '') )
1149 $post_links[] = $link_test;
1153 do_action_ref_array('pre_ping', array(&$post_links, &$pung));
1155 foreach ( (array) $post_links as $pagelinkedto ) {
1156 $pingback_server_url = discover_pingback_server_uri($pagelinkedto, 2048);
1158 if ( $pingback_server_url ) {
1159 @ set_time_limit( 60 );
1160 // Now, the RPC call
1161 $pagelinkedfrom = get_permalink($post_ID);
1163 // using a timeout of 3 seconds should be enough to cover slow servers
1164 $client = new IXR_Client($pingback_server_url);
1165 $client->timeout = 3;
1166 $client->useragent .= ' -- WordPress/' . $wp_version;
1168 // when set to true, this outputs debug messages by itself
1169 $client->debug = false;
1171 if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
1172 add_ping( $post_ID, $pagelinkedto );
1178 * privacy_ping_filter() - {@internal Missing Short Description}}
1180 * {@internal Missing Long Description}}
1184 * @param unknown_type $sites {@internal Missing Description}}
1185 * @return unknown {@internal Missing Description}}
1187 function privacy_ping_filter($sites) {
1188 if ( '0' != get_option('blog_public') )
1195 * trackback() - Send a Trackback
1197 * {@internal Missing Long Description}}
1201 * @uses $wp_version WordPress version
1203 * @param string $trackback_url {@internal Missing Description}}
1204 * @param string $title {@internal Missing Description}}
1205 * @param string $excerpt {@internal Missing Description}}
1206 * @param int $ID {@internal Missing Description}}
1207 * @return unknown {@internal Missing Description}}
1209 function trackback($trackback_url, $title, $excerpt, $ID) {
1210 global $wpdb, $wp_version;
1212 if ( empty($trackback_url) )
1215 $title = urlencode($title);
1216 $excerpt = urlencode($excerpt);
1217 $blog_name = urlencode(get_option('blogname'));
1218 $tb_url = $trackback_url;
1219 $url = urlencode(get_permalink($ID));
1220 $query_string = "title=$title&url=$url&blog_name=$blog_name&excerpt=$excerpt";
1221 $trackback_url = parse_url($trackback_url);
1222 $http_request = 'POST ' . $trackback_url['path'] . ($trackback_url['query'] ? '?'.$trackback_url['query'] : '') . " HTTP/1.0\r\n";
1223 $http_request .= 'Host: '.$trackback_url['host']."\r\n";
1224 $http_request .= 'Content-Type: application/x-www-form-urlencoded; charset='.get_option('blog_charset')."\r\n";
1225 $http_request .= 'Content-Length: '.strlen($query_string)."\r\n";
1226 $http_request .= "User-Agent: WordPress/" . $wp_version;
1227 $http_request .= "\r\n\r\n";
1228 $http_request .= $query_string;
1229 if ( '' == $trackback_url['port'] )
1230 $trackback_url['port'] = 80;
1231 $fs = @fsockopen($trackback_url['host'], $trackback_url['port'], $errno, $errstr, 4);
1232 @fputs($fs, $http_request);
1235 $tb_url = addslashes( $tb_url );
1236 $wpdb->query("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', '$tb_url') WHERE ID = '$ID'");
1237 return $wpdb->query("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_url', '')) WHERE ID = '$ID'");
1241 * weblog_ping() - {@internal Missing Short Description}}
1243 * {@internal Missing Long Description}}
1249 * @param unknown_type $server
1250 * @param unknown_type $path
1252 function weblog_ping($server = '', $path = '') {
1254 include_once(ABSPATH . WPINC . '/class-IXR.php');
1256 // using a timeout of 3 seconds should be enough to cover slow servers
1257 $client = new IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
1258 $client->timeout = 3;
1259 $client->useragent .= ' -- WordPress/'.$wp_version;
1261 // when set to true, this outputs debug messages by itself
1262 $client->debug = false;
1263 $home = trailingslashit( get_option('home') );
1264 if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
1265 $client->query('weblogUpdates.ping', get_option('blogname'), $home);
1273 * clean_comment_cache() - Removes comment ID from the comment cache
1276 * @package WordPress
1279 * @param int $id Comment ID to remove from cache
1281 function clean_comment_cache($id) {
1282 wp_cache_delete($id, 'comment');
1286 * update_comment_cache() - Updates the comment cache of given comments
1288 * Will add the comments in $comments to the cache. If comment ID already
1289 * exists in the comment cache then it will not be updated.
1291 * The comment is added to the cache using the comment group with the key
1292 * using the ID of the comments.
1296 * @param array $comments Array of comment row objects
1298 function update_comment_cache($comments) {
1299 foreach ( (array) $comments as $comment )
1300 wp_cache_add($comment->comment_ID, $comment, 'comment');