]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/comment.php
Wordpress 3.1.2-scripts
[autoinstalls/wordpress.git] / wp-includes / comment.php
1 <?php
2 /**
3  * Manages WordPress comments
4  *
5  * @package WordPress
6  * @subpackage Comment
7  */
8
9 /**
10  * Checks whether a comment passes internal checks to be allowed to add.
11  *
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.
16  *
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.
20  *
21  * If the comment author was approved before, then the comment is
22  * automatically whitelisted.
23  *
24  * If none of the checks fail, then the failback is to set the check to pass
25  * (return true).
26  *
27  * @since 1.2.0
28  * @uses $wpdb
29  *
30  * @param string $author Comment Author's name
31  * @param string $email Comment Author's email
32  * @param string $url Comment Author's URL
33  * @param string $comment Comment contents
34  * @param string $user_ip Comment Author's IP address
35  * @param string $user_agent Comment Author's User Agent
36  * @param string $comment_type Comment type, either user submitted comment,
37  *              trackback, or pingback
38  * @return bool Whether the checks passed (true) and the comments should be
39  *              displayed or set to moderated
40  */
41 function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
42         global $wpdb;
43
44         if ( 1 == get_option('comment_moderation') )
45                 return false; // If moderation is set to manual
46
47         $comment = apply_filters( 'comment_text', $comment );
48
49         // Check # of external links
50         if ( $max_links = get_option( 'comment_max_links' ) ) {
51                 $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out );
52                 $num_links = apply_filters( 'comment_max_links_url', $num_links, $url ); // provide for counting of $url as a link
53                 if ( $num_links >= $max_links )
54                         return false;
55         }
56
57         $mod_keys = trim(get_option('moderation_keys'));
58         if ( !empty($mod_keys) ) {
59                 $words = explode("\n", $mod_keys );
60
61                 foreach ( (array) $words as $word) {
62                         $word = trim($word);
63
64                         // Skip empty lines
65                         if ( empty($word) )
66                                 continue;
67
68                         // Do some escaping magic so that '#' chars in the
69                         // spam words don't break things:
70                         $word = preg_quote($word, '#');
71
72                         $pattern = "#$word#i";
73                         if ( preg_match($pattern, $author) ) return false;
74                         if ( preg_match($pattern, $email) ) return false;
75                         if ( preg_match($pattern, $url) ) return false;
76                         if ( preg_match($pattern, $comment) ) return false;
77                         if ( preg_match($pattern, $user_ip) ) return false;
78                         if ( preg_match($pattern, $user_agent) ) return false;
79                 }
80         }
81
82         // Comment whitelisting:
83         if ( 1 == get_option('comment_whitelist')) {
84                 if ( 'trackback' != $comment_type && 'pingback' != $comment_type && $author != '' && $email != '' ) {
85                         // expected_slashed ($author, $email)
86                         $ok_to_comment = $wpdb->get_var("SELECT comment_approved FROM $wpdb->comments WHERE comment_author = '$author' AND comment_author_email = '$email' and comment_approved = '1' LIMIT 1");
87                         if ( ( 1 == $ok_to_comment ) &&
88                                 ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
89                                         return true;
90                         else
91                                 return false;
92                 } else {
93                         return false;
94                 }
95         }
96         return true;
97 }
98
99 /**
100  * Retrieve the approved comments for post $post_id.
101  *
102  * @since 2.0.0
103  * @uses $wpdb
104  *
105  * @param int $post_id The ID of the post
106  * @return array $comments The approved comments
107  */
108 function get_approved_comments($post_id) {
109         global $wpdb;
110         return $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1' ORDER BY comment_date", $post_id));
111 }
112
113 /**
114  * Retrieves comment data given a comment ID or comment object.
115  *
116  * If an object is passed then the comment data will be cached and then returned
117  * after being passed through a filter. If the comment is empty, then the global
118  * comment variable will be used, if it is set.
119  *
120  * If the comment is empty, then the global comment variable will be used, if it
121  * is set.
122  *
123  * @since 2.0.0
124  * @uses $wpdb
125  *
126  * @param object|string|int $comment Comment to retrieve.
127  * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
128  * @return object|array|null Depends on $output value.
129  */
130 function &get_comment(&$comment, $output = OBJECT) {
131         global $wpdb;
132         $null = null;
133
134         if ( empty($comment) ) {
135                 if ( isset($GLOBALS['comment']) )
136                         $_comment = & $GLOBALS['comment'];
137                 else
138                         $_comment = null;
139         } elseif ( is_object($comment) ) {
140                 wp_cache_add($comment->comment_ID, $comment, 'comment');
141                 $_comment = $comment;
142         } else {
143                 if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
144                         $_comment = & $GLOBALS['comment'];
145                 } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
146                         $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
147                         if ( ! $_comment )
148                                 return $null;
149                         wp_cache_add($_comment->comment_ID, $_comment, 'comment');
150                 }
151         }
152
153         $_comment = apply_filters('get_comment', $_comment);
154
155         if ( $output == OBJECT ) {
156                 return $_comment;
157         } elseif ( $output == ARRAY_A ) {
158                 $__comment = get_object_vars($_comment);
159                 return $__comment;
160         } elseif ( $output == ARRAY_N ) {
161                 $__comment = array_values(get_object_vars($_comment));
162                 return $__comment;
163         } else {
164                 return $_comment;
165         }
166 }
167
168 /**
169  * Retrieve a list of comments.
170  *
171  * The comment list can be for the blog as a whole or for an individual post.
172  *
173  * The list of comment arguments are 'status', 'orderby', 'comment_date_gmt',
174  * 'order', 'number', 'offset', and 'post_id'.
175  *
176  * @since 2.7.0
177  * @uses $wpdb
178  *
179  * @param mixed $args Optional. Array or string of options to override defaults.
180  * @return array List of comments.
181  */
182 function get_comments( $args = '' ) {
183         $query = new WP_Comment_Query;
184         return $query->query( $args );
185 }
186
187 /**
188  * WordPress Comment Query class.
189  *
190  * @since 3.1.0
191  */
192 class WP_Comment_Query {
193
194         /**
195          * Execute the query
196          *
197          * @since 3.1.0
198          *
199          * @param string|array $query_vars
200          * @return int|array
201          */
202         function query( $query_vars ) {
203                 global $wpdb;
204
205                 $defaults = array(
206                         'author_email' => '',
207                         'ID' => '',
208                         'karma' => '',
209                         'number' => '',
210                         'offset' => '',
211                         'orderby' => '',
212                         'order' => 'DESC',
213                         'parent' => '',
214                         'post_ID' => '',
215                         'post_id' => 0,
216                         'status' => '',
217                         'type' => '',
218                         'user_id' => '',
219                         'search' => '',
220                         'count' => false
221                 );
222
223                 $this->query_vars = wp_parse_args( $query_vars, $defaults );
224                 do_action_ref_array( 'pre_get_comments', array( &$this ) );
225                 extract( $this->query_vars, EXTR_SKIP );
226
227                 // $args can be whatever, only use the args defined in defaults to compute the key
228                 $key = md5( serialize( compact(array_keys($defaults)) )  );
229                 $last_changed = wp_cache_get('last_changed', 'comment');
230                 if ( !$last_changed ) {
231                         $last_changed = time();
232                         wp_cache_set('last_changed', $last_changed, 'comment');
233                 }
234                 $cache_key = "get_comments:$key:$last_changed";
235
236                 if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) {
237                         return $cache;
238                 }
239
240                 $post_id = absint($post_id);
241
242                 if ( 'hold' == $status )
243                         $approved = "comment_approved = '0'";
244                 elseif ( 'approve' == $status )
245                         $approved = "comment_approved = '1'";
246                 elseif ( 'spam' == $status )
247                         $approved = "comment_approved = 'spam'";
248                 elseif ( 'trash' == $status )
249                         $approved = "comment_approved = 'trash'";
250                 else
251                         $approved = "( comment_approved = '0' OR comment_approved = '1' )";
252
253                 $order = ( 'ASC' == strtoupper($order) ) ? 'ASC' : 'DESC';
254
255                 if ( ! empty( $orderby ) ) {
256                         $ordersby = is_array($orderby) ? $orderby : preg_split('/[,\s]/', $orderby);
257                         $ordersby = array_intersect(
258                                 $ordersby,
259                                 array(
260                                         'comment_agent',
261                                         'comment_approved',
262                                         'comment_author',
263                                         'comment_author_email',
264                                         'comment_author_IP',
265                                         'comment_author_url',
266                                         'comment_content',
267                                         'comment_date',
268                                         'comment_date_gmt',
269                                         'comment_ID',
270                                         'comment_karma',
271                                         'comment_parent',
272                                         'comment_post_ID',
273                                         'comment_type',
274                                         'user_id',
275                                 )
276                         );
277                         $orderby = empty( $ordersby ) ? 'comment_date_gmt' : implode(', ', $ordersby);
278                 } else {
279                         $orderby = 'comment_date_gmt';
280                 }
281
282                 $number = absint($number);
283                 $offset = absint($offset);
284
285                 if ( !empty($number) ) {
286                         if ( $offset )
287                                 $limits = 'LIMIT ' . $offset . ',' . $number;
288                         else
289                                 $limits = 'LIMIT ' . $number;
290                 } else {
291                         $limits = '';
292                 }
293
294                 if ( $count )
295                         $fields = 'COUNT(*)';
296                 else
297                         $fields = '*';
298
299                 $join = '';
300                 $where = $approved;
301
302                 if ( ! empty($post_id) )
303                         $where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
304                 if ( '' !== $author_email )
305                         $where .= $wpdb->prepare( ' AND comment_author_email = %s', $author_email );
306                 if ( '' !== $karma )
307                         $where .= $wpdb->prepare( ' AND comment_karma = %d', $karma );
308                 if ( 'comment' == $type ) {
309                         $where .= " AND comment_type = ''";
310                 } elseif( 'pings' == $type ) {
311                         $where .= ' AND comment_type IN ("pingback", "trackback")';
312                 } elseif ( ! empty( $type ) ) {
313                         $where .= $wpdb->prepare( ' AND comment_type = %s', $type );
314                 }
315                 if ( '' !== $parent )
316                         $where .= $wpdb->prepare( ' AND comment_parent = %d', $parent );
317                 if ( '' !== $user_id )
318                         $where .= $wpdb->prepare( ' AND user_id = %d', $user_id );
319                 if ( '' !== $search )
320                         $where .= $this->get_search_sql( $search, array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' ) );
321
322                 $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
323                 $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
324                 foreach ( $pieces as $piece )
325                         $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
326
327                 $query = "SELECT $fields FROM $wpdb->comments $join WHERE $where ORDER BY $orderby $order $limits";
328
329                 if ( $count )
330                         return $wpdb->get_var( $query );
331
332                 $comments = $wpdb->get_results( $query );
333                 $comments = apply_filters_ref_array( 'the_comments', array( $comments, &$this ) );
334
335                 wp_cache_add( $cache_key, $comments, 'comment' );
336
337                 return $comments;
338         }
339
340         /*
341          * Used internally to generate an SQL string for searching across multiple columns
342          *
343          * @access protected
344          * @since 3.1.0
345          *
346          * @param string $string
347          * @param array $cols
348          * @return string
349          */
350         function get_search_sql( $string, $cols ) {
351                 $string = esc_sql( like_escape( $string ) );
352
353                 $searches = array();
354                 foreach ( $cols as $col )
355                         $searches[] = "$col LIKE '%$string%'";
356
357                 return ' AND (' . implode(' OR ', $searches) . ')';
358         }
359 }
360
361 /**
362  * Retrieve all of the WordPress supported comment statuses.
363  *
364  * Comments have a limited set of valid status values, this provides the comment
365  * status values and descriptions.
366  *
367  * @package WordPress
368  * @subpackage Post
369  * @since 2.7.0
370  *
371  * @return array List of comment statuses.
372  */
373 function get_comment_statuses( ) {
374         $status = array(
375                 'hold'          => __('Unapproved'),
376                 /* translators: comment status  */
377                 'approve'       => _x('Approved', 'adjective'),
378                 /* translators: comment status */
379                 'spam'          => _x('Spam', 'adjective'),
380         );
381
382         return $status;
383 }
384
385
386 /**
387  * The date the last comment was modified.
388  *
389  * @since 1.5.0
390  * @uses $wpdb
391  * @global array $cache_lastcommentmodified
392  *
393  * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
394  *              or 'server' locations.
395  * @return string Last comment modified date.
396  */
397 function get_lastcommentmodified($timezone = 'server') {
398         global $cache_lastcommentmodified, $wpdb;
399
400         if ( isset($cache_lastcommentmodified[$timezone]) )
401                 return $cache_lastcommentmodified[$timezone];
402
403         $add_seconds_server = date('Z');
404
405         switch ( strtolower($timezone)) {
406                 case 'gmt':
407                         $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
408                         break;
409                 case 'blog':
410                         $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
411                         break;
412                 case 'server':
413                         $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));
414                         break;
415         }
416
417         $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
418
419         return $lastcommentmodified;
420 }
421
422 /**
423  * The amount of comments in a post or total comments.
424  *
425  * A lot like {@link wp_count_comments()}, in that they both return comment
426  * stats (albeit with different types). The {@link wp_count_comments()} actual
427  * caches, but this function does not.
428  *
429  * @since 2.0.0
430  * @uses $wpdb
431  *
432  * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
433  * @return array The amount of spam, approved, awaiting moderation, and total comments.
434  */
435 function get_comment_count( $post_id = 0 ) {
436         global $wpdb;
437
438         $post_id = (int) $post_id;
439
440         $where = '';
441         if ( $post_id > 0 ) {
442                 $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
443         }
444
445         $totals = (array) $wpdb->get_results("
446                 SELECT comment_approved, COUNT( * ) AS total
447                 FROM {$wpdb->comments}
448                 {$where}
449                 GROUP BY comment_approved
450         ", ARRAY_A);
451
452         $comment_count = array(
453                 "approved"              => 0,
454                 "awaiting_moderation"   => 0,
455                 "spam"                  => 0,
456                 "total_comments"        => 0
457         );
458
459         foreach ( $totals as $row ) {
460                 switch ( $row['comment_approved'] ) {
461                         case 'spam':
462                                 $comment_count['spam'] = $row['total'];
463                                 $comment_count["total_comments"] += $row['total'];
464                                 break;
465                         case 1:
466                                 $comment_count['approved'] = $row['total'];
467                                 $comment_count['total_comments'] += $row['total'];
468                                 break;
469                         case 0:
470                                 $comment_count['awaiting_moderation'] = $row['total'];
471                                 $comment_count['total_comments'] += $row['total'];
472                                 break;
473                         default:
474                                 break;
475                 }
476         }
477
478         return $comment_count;
479 }
480
481 //
482 // Comment meta functions
483 //
484
485 /**
486  * Add meta data field to a comment.
487  *
488  * @since 2.9.0
489  * @uses add_metadata
490  * @link http://codex.wordpress.org/Function_Reference/add_comment_meta
491  *
492  * @param int $comment_id Comment ID.
493  * @param string $meta_key Metadata name.
494  * @param mixed $meta_value Metadata value.
495  * @param bool $unique Optional, default is false. Whether the same key should not be added.
496  * @return bool False for failure. True for success.
497  */
498 function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
499         return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
500 }
501
502 /**
503  * Remove metadata matching criteria from a comment.
504  *
505  * You can match based on the key, or key and value. Removing based on key and
506  * value, will keep from removing duplicate metadata with the same key. It also
507  * allows removing all metadata matching key, if needed.
508  *
509  * @since 2.9.0
510  * @uses delete_metadata
511  * @link http://codex.wordpress.org/Function_Reference/delete_comment_meta
512  *
513  * @param int $comment_id comment ID
514  * @param string $meta_key Metadata name.
515  * @param mixed $meta_value Optional. Metadata value.
516  * @return bool False for failure. True for success.
517  */
518 function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
519         return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
520 }
521
522 /**
523  * Retrieve comment meta field for a comment.
524  *
525  * @since 2.9.0
526  * @uses get_metadata
527  * @link http://codex.wordpress.org/Function_Reference/get_comment_meta
528  *
529  * @param int $comment_id Comment ID.
530  * @param string $key The meta key to retrieve.
531  * @param bool $single Whether to return a single value.
532  * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
533  *  is true.
534  */
535 function get_comment_meta($comment_id, $key, $single = false) {
536         return get_metadata('comment', $comment_id, $key, $single);
537 }
538
539 /**
540  * Update comment meta field based on comment ID.
541  *
542  * Use the $prev_value parameter to differentiate between meta fields with the
543  * same key and comment ID.
544  *
545  * If the meta field for the comment does not exist, it will be added.
546  *
547  * @since 2.9.0
548  * @uses update_metadata
549  * @link http://codex.wordpress.org/Function_Reference/update_comment_meta
550  *
551  * @param int $comment_id Comment ID.
552  * @param string $meta_key Metadata key.
553  * @param mixed $meta_value Metadata value.
554  * @param mixed $prev_value Optional. Previous value to check before removing.
555  * @return bool False on failure, true if success.
556  */
557 function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
558         return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
559 }
560
561 /**
562  * Sanitizes the cookies sent to the user already.
563  *
564  * Will only do anything if the cookies have already been created for the user.
565  * Mostly used after cookies had been sent to use elsewhere.
566  *
567  * @since 2.0.4
568  */
569 function sanitize_comment_cookies() {
570         if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) {
571                 $comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]);
572                 $comment_author = stripslashes($comment_author);
573                 $comment_author = esc_attr($comment_author);
574                 $_COOKIE['comment_author_'.COOKIEHASH] = $comment_author;
575         }
576
577         if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) {
578                 $comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]);
579                 $comment_author_email = stripslashes($comment_author_email);
580                 $comment_author_email = esc_attr($comment_author_email);
581                 $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
582         }
583
584         if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) {
585                 $comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]);
586                 $comment_author_url = stripslashes($comment_author_url);
587                 $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
588         }
589 }
590
591 /**
592  * Validates whether this comment is allowed to be made.
593  *
594  * @since 2.0.0
595  * @uses $wpdb
596  * @uses apply_filters() Calls 'pre_comment_approved' hook on the type of comment
597  * @uses apply_filters() Calls 'comment_duplicate_trigger' hook on commentdata.
598  * @uses do_action() Calls 'check_comment_flood' hook on $comment_author_IP, $comment_author_email, and $comment_date_gmt
599  *
600  * @param array $commentdata Contains information on the comment
601  * @return mixed Signifies the approval status (0|1|'spam')
602  */
603 function wp_allow_comment($commentdata) {
604         global $wpdb;
605         extract($commentdata, EXTR_SKIP);
606
607         // Simple duplicate check
608         // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
609         $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND comment_approved != 'trash' AND ( comment_author = '$comment_author' ";
610         if ( $comment_author_email )
611                 $dupe .= "OR comment_author_email = '$comment_author_email' ";
612         $dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
613         if ( $wpdb->get_var($dupe) ) {
614                 do_action( 'comment_duplicate_trigger', $commentdata );
615                 if ( defined('DOING_AJAX') )
616                         die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
617
618                 wp_die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
619         }
620
621         do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt );
622
623         if ( isset($user_id) && $user_id) {
624                 $userdata = get_userdata($user_id);
625                 $user = new WP_User($user_id);
626                 $post_author = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", $comment_post_ID));
627         }
628
629         if ( isset($userdata) && ( $user_id == $post_author || $user->has_cap('moderate_comments') ) ) {
630                 // The author and the admins get respect.
631                 $approved = 1;
632          } else {
633                 // Everyone else's comments will be checked.
634                 if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) )
635                         $approved = 1;
636                 else
637                         $approved = 0;
638                 if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) )
639                         $approved = 'spam';
640         }
641
642         $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
643         return $approved;
644 }
645
646 /**
647  * Check whether comment flooding is occurring.
648  *
649  * Won't run, if current user can manage options, so to not block
650  * administrators.
651  *
652  * @since 2.3.0
653  * @uses $wpdb
654  * @uses apply_filters() Calls 'comment_flood_filter' filter with first
655  *              parameter false, last comment timestamp, new comment timestamp.
656  * @uses do_action() Calls 'comment_flood_trigger' action with parameters with
657  *              last comment timestamp and new comment timestamp.
658  *
659  * @param string $ip Comment IP.
660  * @param string $email Comment author email address.
661  * @param string $date MySQL time string.
662  */
663 function check_comment_flood_db( $ip, $email, $date ) {
664         global $wpdb;
665         if ( current_user_can( 'manage_options' ) )
666                 return; // don't throttle admins
667         $hour_ago = gmdate( 'Y-m-d H:i:s', time() - 3600 );
668         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 ) ) ) {
669                 $time_lastcomment = mysql2date('U', $lasttime, false);
670                 $time_newcomment  = mysql2date('U', $date, false);
671                 $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
672                 if ( $flood_die ) {
673                         do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment);
674
675                         if ( defined('DOING_AJAX') )
676                                 die( __('You are posting comments too quickly.  Slow down.') );
677
678                         wp_die( __('You are posting comments too quickly.  Slow down.'), '', array('response' => 403) );
679                 }
680         }
681 }
682
683 /**
684  * Separates an array of comments into an array keyed by comment_type.
685  *
686  * @since 2.7.0
687  *
688  * @param array $comments Array of comments
689  * @return array Array of comments keyed by comment_type.
690  */
691 function &separate_comments(&$comments) {
692         $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
693         $count = count($comments);
694         for ( $i = 0; $i < $count; $i++ ) {
695                 $type = $comments[$i]->comment_type;
696                 if ( empty($type) )
697                         $type = 'comment';
698                 $comments_by_type[$type][] = &$comments[$i];
699                 if ( 'trackback' == $type || 'pingback' == $type )
700                         $comments_by_type['pings'][] = &$comments[$i];
701         }
702
703         return $comments_by_type;
704 }
705
706 /**
707  * Calculate the total number of comment pages.
708  *
709  * @since 2.7.0
710  * @uses get_query_var() Used to fill in the default for $per_page parameter.
711  * @uses get_option() Used to fill in defaults for parameters.
712  * @uses Walker_Comment
713  *
714  * @param array $comments Optional array of comment objects.  Defaults to $wp_query->comments
715  * @param int $per_page Optional comments per page.
716  * @param boolean $threaded Optional control over flat or threaded comments.
717  * @return int Number of comment pages.
718  */
719 function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
720         global $wp_query;
721
722         if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
723                 return $wp_query->max_num_comment_pages;
724
725         if ( !$comments || !is_array($comments) )
726                 $comments = $wp_query->comments;
727
728         if ( empty($comments) )
729                 return 0;
730
731         if ( !isset($per_page) )
732                 $per_page = (int) get_query_var('comments_per_page');
733         if ( 0 === $per_page )
734                 $per_page = (int) get_option('comments_per_page');
735         if ( 0 === $per_page )
736                 return 1;
737
738         if ( !isset($threaded) )
739                 $threaded = get_option('thread_comments');
740
741         if ( $threaded ) {
742                 $walker = new Walker_Comment;
743                 $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
744         } else {
745                 $count = ceil( count( $comments ) / $per_page );
746         }
747
748         return $count;
749 }
750
751 /**
752  * Calculate what page number a comment will appear on for comment paging.
753  *
754  * @since 2.7.0
755  * @uses get_comment() Gets the full comment of the $comment_ID parameter.
756  * @uses get_option() Get various settings to control function and defaults.
757  * @uses get_page_of_comment() Used to loop up to top level comment.
758  *
759  * @param int $comment_ID Comment ID.
760  * @param array $args Optional args.
761  * @return int|null Comment page number or null on error.
762  */
763 function get_page_of_comment( $comment_ID, $args = array() ) {
764         global $wpdb;
765
766         if ( !$comment = get_comment( $comment_ID ) )
767                 return;
768
769         $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
770         $args = wp_parse_args( $args, $defaults );
771
772         if ( '' === $args['per_page'] && get_option('page_comments') )
773                 $args['per_page'] = get_query_var('comments_per_page');
774         if ( empty($args['per_page']) ) {
775                 $args['per_page'] = 0;
776                 $args['page'] = 0;
777         }
778         if ( $args['per_page'] < 1 )
779                 return 1;
780
781         if ( '' === $args['max_depth'] ) {
782                 if ( get_option('thread_comments') )
783                         $args['max_depth'] = get_option('thread_comments_depth');
784                 else
785                         $args['max_depth'] = -1;
786         }
787
788         // Find this comment's top level parent if threading is enabled
789         if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
790                 return get_page_of_comment( $comment->comment_parent, $args );
791
792         $allowedtypes = array(
793                 'comment' => '',
794                 'pingback' => 'pingback',
795                 'trackback' => 'trackback',
796         );
797
798         $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
799
800         // Count comments older than this one
801         $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 ) );
802
803         // No older comments? Then it's page #1.
804         if ( 0 == $oldercoms )
805                 return 1;
806
807         // Divide comments older than this one by comments per page to get this comment's page number
808         return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
809 }
810
811 /**
812  * Does comment contain blacklisted characters or words.
813  *
814  * @since 1.5.0
815  * @uses do_action() Calls 'wp_blacklist_check' hook for all parameters.
816  *
817  * @param string $author The author of the comment
818  * @param string $email The email of the comment
819  * @param string $url The url used in the comment
820  * @param string $comment The comment content
821  * @param string $user_ip The comment author IP address
822  * @param string $user_agent The author's browser user agent
823  * @return bool True if comment contains blacklisted content, false if comment does not
824  */
825 function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
826         do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent);
827
828         $mod_keys = trim( get_option('blacklist_keys') );
829         if ( '' == $mod_keys )
830                 return false; // If moderation keys are empty
831         $words = explode("\n", $mod_keys );
832
833         foreach ( (array) $words as $word ) {
834                 $word = trim($word);
835
836                 // Skip empty lines
837                 if ( empty($word) ) { continue; }
838
839                 // Do some escaping magic so that '#' chars in the
840                 // spam words don't break things:
841                 $word = preg_quote($word, '#');
842
843                 $pattern = "#$word#i";
844                 if (
845                            preg_match($pattern, $author)
846                         || preg_match($pattern, $email)
847                         || preg_match($pattern, $url)
848                         || preg_match($pattern, $comment)
849                         || preg_match($pattern, $user_ip)
850                         || preg_match($pattern, $user_agent)
851                  )
852                         return true;
853         }
854         return false;
855 }
856
857 /**
858  * Retrieve total comments for blog or single post.
859  *
860  * The properties of the returned object contain the 'moderated', 'approved',
861  * and spam comments for either the entire blog or single post. Those properties
862  * contain the amount of comments that match the status. The 'total_comments'
863  * property contains the integer of total comments.
864  *
865  * The comment stats are cached and then retrieved, if they already exist in the
866  * cache.
867  *
868  * @since 2.5.0
869  *
870  * @param int $post_id Optional. Post ID.
871  * @return object Comment stats.
872  */
873 function wp_count_comments( $post_id = 0 ) {
874         global $wpdb;
875
876         $post_id = (int) $post_id;
877
878         $stats = apply_filters('wp_count_comments', array(), $post_id);
879         if ( !empty($stats) )
880                 return $stats;
881
882         $count = wp_cache_get("comments-{$post_id}", 'counts');
883
884         if ( false !== $count )
885                 return $count;
886
887         $where = '';
888         if ( $post_id > 0 )
889                 $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
890
891         $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
892
893         $total = 0;
894         $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
895         $known_types = array_keys( $approved );
896         foreach ( (array) $count as $row ) {
897                 // Don't count post-trashed toward totals
898                 if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
899                         $total += $row['num_comments'];
900                 if ( in_array( $row['comment_approved'], $known_types ) )
901                         $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
902         }
903
904         $stats['total_comments'] = $total;
905         foreach ( $approved as $key ) {
906                 if ( empty($stats[$key]) )
907                         $stats[$key] = 0;
908         }
909
910         $stats = (object) $stats;
911         wp_cache_set("comments-{$post_id}", $stats, 'counts');
912
913         return $stats;
914 }
915
916 /**
917  * Trashes or deletes a comment.
918  *
919  * The comment is moved to trash instead of permanently deleted unless trash is
920  * disabled, item is already in the trash, or $force_delete is true.
921  *
922  * The post comment count will be updated if the comment was approved and has a
923  * post ID available.
924  *
925  * @since 2.0.0
926  * @uses $wpdb
927  * @uses do_action() Calls 'delete_comment' hook on comment ID
928  * @uses do_action() Calls 'deleted_comment' hook on comment ID after deletion, on success
929  * @uses do_action() Calls 'wp_set_comment_status' hook on comment ID with 'delete' set for the second parameter
930  * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
931  *
932  * @param int $comment_id Comment ID
933  * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
934  * @return bool False if delete comment query failure, true on success.
935  */
936 function wp_delete_comment($comment_id, $force_delete = false) {
937         global $wpdb;
938         if (!$comment = get_comment($comment_id))
939                 return false;
940
941         if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) )
942                 return wp_trash_comment($comment_id);
943
944         do_action('delete_comment', $comment_id);
945
946         // Move children up a level.
947         $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
948         if ( !empty($children) ) {
949                 $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
950                 clean_comment_cache($children);
951         }
952
953         // Delete metadata
954         $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d ", $comment_id ) );
955         if ( !empty($meta_ids) ) {
956                 do_action( 'delete_commentmeta', $meta_ids );
957                 $in_meta_ids = "'" . implode("', '", $meta_ids) . "'";
958                 $wpdb->query( "DELETE FROM $wpdb->commentmeta WHERE meta_id IN ($in_meta_ids)" );
959                 do_action( 'deleted_commentmeta', $meta_ids );
960         }
961
962         if ( ! $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment_id) ) )
963                 return false;
964         do_action('deleted_comment', $comment_id);
965
966         $post_id = $comment->comment_post_ID;
967         if ( $post_id && $comment->comment_approved == 1 )
968                 wp_update_comment_count($post_id);
969
970         clean_comment_cache($comment_id);
971
972         do_action('wp_set_comment_status', $comment_id, 'delete');
973         wp_transition_comment_status('delete', $comment->comment_approved, $comment);
974         return true;
975 }
976
977 /**
978  * Moves a comment to the Trash
979  *
980  * If trash is disabled, comment is permanently deleted.
981  *
982  * @since 2.9.0
983  * @uses do_action() on 'trash_comment' before trashing
984  * @uses do_action() on 'trashed_comment' after trashing
985  * @uses wp_delete_comment() if trash is disabled
986  *
987  * @param int $comment_id Comment ID.
988  * @return mixed False on failure
989  */
990 function wp_trash_comment($comment_id) {
991         if ( !EMPTY_TRASH_DAYS )
992                 return wp_delete_comment($comment_id, true);
993
994         if ( !$comment = get_comment($comment_id) )
995                 return false;
996
997         do_action('trash_comment', $comment_id);
998
999         if ( wp_set_comment_status($comment_id, 'trash') ) {
1000                 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
1001                 add_comment_meta($comment_id, '_wp_trash_meta_time', time() );
1002                 do_action('trashed_comment', $comment_id);
1003                 return true;
1004         }
1005
1006         return false;
1007 }
1008
1009 /**
1010  * Removes a comment from the Trash
1011  *
1012  * @since 2.9.0
1013  * @uses do_action() on 'untrash_comment' before untrashing
1014  * @uses do_action() on 'untrashed_comment' after untrashing
1015  *
1016  * @param int $comment_id Comment ID.
1017  * @return mixed False on failure
1018  */
1019 function wp_untrash_comment($comment_id) {
1020         if ( ! (int)$comment_id )
1021                 return false;
1022
1023         do_action('untrash_comment', $comment_id);
1024
1025         $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
1026         if ( empty($status) )
1027                 $status = '0';
1028
1029         if ( wp_set_comment_status($comment_id, $status) ) {
1030                 delete_comment_meta($comment_id, '_wp_trash_meta_time');
1031                 delete_comment_meta($comment_id, '_wp_trash_meta_status');
1032                 do_action('untrashed_comment', $comment_id);
1033                 return true;
1034         }
1035
1036         return false;
1037 }
1038
1039 /**
1040  * Marks a comment as Spam
1041  *
1042  * @since 2.9.0
1043  * @uses do_action() on 'spam_comment' before spamming
1044  * @uses do_action() on 'spammed_comment' after spamming
1045  *
1046  * @param int $comment_id Comment ID.
1047  * @return mixed False on failure
1048  */
1049 function wp_spam_comment($comment_id) {
1050         if ( !$comment = get_comment($comment_id) )
1051                 return false;
1052
1053         do_action('spam_comment', $comment_id);
1054
1055         if ( wp_set_comment_status($comment_id, 'spam') ) {
1056                 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
1057                 do_action('spammed_comment', $comment_id);
1058                 return true;
1059         }
1060
1061         return false;
1062 }
1063
1064 /**
1065  * Removes a comment from the Spam
1066  *
1067  * @since 2.9.0
1068  * @uses do_action() on 'unspam_comment' before unspamming
1069  * @uses do_action() on 'unspammed_comment' after unspamming
1070  *
1071  * @param int $comment_id Comment ID.
1072  * @return mixed False on failure
1073  */
1074 function wp_unspam_comment($comment_id) {
1075         if ( ! (int)$comment_id )
1076                 return false;
1077
1078         do_action('unspam_comment', $comment_id);
1079
1080         $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
1081         if ( empty($status) )
1082                 $status = '0';
1083
1084         if ( wp_set_comment_status($comment_id, $status) ) {
1085                 delete_comment_meta($comment_id, '_wp_trash_meta_status');
1086                 do_action('unspammed_comment', $comment_id);
1087                 return true;
1088         }
1089
1090         return false;
1091 }
1092
1093 /**
1094  * The status of a comment by ID.
1095  *
1096  * @since 1.0.0
1097  *
1098  * @param int $comment_id Comment ID
1099  * @return string|bool Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
1100  */
1101 function wp_get_comment_status($comment_id) {
1102         $comment = get_comment($comment_id);
1103         if ( !$comment )
1104                 return false;
1105
1106         $approved = $comment->comment_approved;
1107
1108         if ( $approved == NULL )
1109                 return false;
1110         elseif ( $approved == '1' )
1111                 return 'approved';
1112         elseif ( $approved == '0' )
1113                 return 'unapproved';
1114         elseif ( $approved == 'spam' )
1115                 return 'spam';
1116         elseif ( $approved == 'trash' )
1117                 return 'trash';
1118         else
1119                 return false;
1120 }
1121
1122 /**
1123  * Call hooks for when a comment status transition occurs.
1124  *
1125  * Calls hooks for comment status transitions. If the new comment status is not the same
1126  * as the previous comment status, then two hooks will be ran, the first is
1127  * 'transition_comment_status' with new status, old status, and comment data. The
1128  * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
1129  * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
1130  * comment data.
1131  *
1132  * The final action will run whether or not the comment statuses are the same. The
1133  * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
1134  * parameter and COMMENTTYPE is comment_type comment data.
1135  *
1136  * @since 2.7.0
1137  *
1138  * @param string $new_status New comment status.
1139  * @param string $old_status Previous comment status.
1140  * @param object $comment Comment data.
1141  */
1142 function wp_transition_comment_status($new_status, $old_status, $comment) {
1143         // Translate raw statuses to human readable formats for the hooks
1144         // This is not a complete list of comment status, it's only the ones that need to be renamed
1145         $comment_statuses = array(
1146                 0         => 'unapproved',
1147                 'hold'    => 'unapproved', // wp_set_comment_status() uses "hold"
1148                 1         => 'approved',
1149                 'approve' => 'approved', // wp_set_comment_status() uses "approve"
1150         );
1151         if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
1152         if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
1153
1154         // Call the hooks
1155         if ( $new_status != $old_status ) {
1156                 do_action('transition_comment_status', $new_status, $old_status, $comment);
1157                 do_action("comment_{$old_status}_to_{$new_status}", $comment);
1158         }
1159         do_action("comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment);
1160 }
1161
1162 /**
1163  * Get current commenter's name, email, and URL.
1164  *
1165  * Expects cookies content to already be sanitized. User of this function might
1166  * wish to recheck the returned array for validity.
1167  *
1168  * @see sanitize_comment_cookies() Use to sanitize cookies
1169  *
1170  * @since 2.0.4
1171  *
1172  * @return array Comment author, email, url respectively.
1173  */
1174 function wp_get_current_commenter() {
1175         // Cookies should already be sanitized.
1176
1177         $comment_author = '';
1178         if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
1179                 $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
1180
1181         $comment_author_email = '';
1182         if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
1183                 $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
1184
1185         $comment_author_url = '';
1186         if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
1187                 $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
1188
1189         return apply_filters('wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url'));
1190 }
1191
1192 /**
1193  * Inserts a comment to the database.
1194  *
1195  * The available comment data key names are 'comment_author_IP', 'comment_date',
1196  * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'.
1197  *
1198  * @since 2.0.0
1199  * @uses $wpdb
1200  *
1201  * @param array $commentdata Contains information on the comment.
1202  * @return int The new comment's ID.
1203  */
1204 function wp_insert_comment($commentdata) {
1205         global $wpdb;
1206         extract(stripslashes_deep($commentdata), EXTR_SKIP);
1207
1208         if ( ! isset($comment_author_IP) )
1209                 $comment_author_IP = '';
1210         if ( ! isset($comment_date) )
1211                 $comment_date = current_time('mysql');
1212         if ( ! isset($comment_date_gmt) )
1213                 $comment_date_gmt = get_gmt_from_date($comment_date);
1214         if ( ! isset($comment_parent) )
1215                 $comment_parent = 0;
1216         if ( ! isset($comment_approved) )
1217                 $comment_approved = 1;
1218         if ( ! isset($comment_karma) )
1219                 $comment_karma = 0;
1220         if ( ! isset($user_id) )
1221                 $user_id = 0;
1222         if ( ! isset($comment_type) )
1223                 $comment_type = '';
1224
1225         $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');
1226         $wpdb->insert($wpdb->comments, $data);
1227
1228         $id = (int) $wpdb->insert_id;
1229
1230         if ( $comment_approved == 1 )
1231                 wp_update_comment_count($comment_post_ID);
1232
1233         $comment = get_comment($id);
1234         do_action('wp_insert_comment', $id, $comment);
1235
1236         return $id;
1237 }
1238
1239 /**
1240  * Filters and sanitizes comment data.
1241  *
1242  * Sets the comment data 'filtered' field to true when finished. This can be
1243  * checked as to whether the comment should be filtered and to keep from
1244  * filtering the same comment more than once.
1245  *
1246  * @since 2.0.0
1247  * @uses apply_filters() Calls 'pre_user_id' hook on comment author's user ID
1248  * @uses apply_filters() Calls 'pre_comment_user_agent' hook on comment author's user agent
1249  * @uses apply_filters() Calls 'pre_comment_author_name' hook on comment author's name
1250  * @uses apply_filters() Calls 'pre_comment_content' hook on the comment's content
1251  * @uses apply_filters() Calls 'pre_comment_user_ip' hook on comment author's IP
1252  * @uses apply_filters() Calls 'pre_comment_author_url' hook on comment author's URL
1253  * @uses apply_filters() Calls 'pre_comment_author_email' hook on comment author's email address
1254  *
1255  * @param array $commentdata Contains information on the comment.
1256  * @return array Parsed comment information.
1257  */
1258 function wp_filter_comment($commentdata) {
1259         if ( isset($commentdata['user_ID']) )
1260                 $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_ID']);
1261         elseif ( isset($commentdata['user_id']) )
1262                 $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_id']);
1263         $commentdata['comment_agent']        = apply_filters('pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
1264         $commentdata['comment_author']       = apply_filters('pre_comment_author_name', $commentdata['comment_author']);
1265         $commentdata['comment_content']      = apply_filters('pre_comment_content', $commentdata['comment_content']);
1266         $commentdata['comment_author_IP']    = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']);
1267         $commentdata['comment_author_url']   = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']);
1268         $commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']);
1269         $commentdata['filtered'] = true;
1270         return $commentdata;
1271 }
1272
1273 /**
1274  * Whether comment should be blocked because of comment flood.
1275  *
1276  * @since 2.1.0
1277  *
1278  * @param bool $block Whether plugin has already blocked comment.
1279  * @param int $time_lastcomment Timestamp for last comment.
1280  * @param int $time_newcomment Timestamp for new comment.
1281  * @return bool Whether comment should be blocked.
1282  */
1283 function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
1284         if ( $block ) // a plugin has already blocked... we'll let that decision stand
1285                 return $block;
1286         if ( ($time_newcomment - $time_lastcomment) < 15 )
1287                 return true;
1288         return false;
1289 }
1290
1291 /**
1292  * Adds a new comment to the database.
1293  *
1294  * Filters new comment to ensure that the fields are sanitized and valid before
1295  * inserting comment into database. Calls 'comment_post' action with comment ID
1296  * and whether comment is approved by WordPress. Also has 'preprocess_comment'
1297  * filter for processing the comment data before the function handles it.
1298  *
1299  * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure
1300  * that it is properly set, such as in wp-config.php, for your environment.
1301  * See {@link http://core.trac.wordpress.org/ticket/9235}
1302  *
1303  * @since 1.5.0
1304  * @uses apply_filters() Calls 'preprocess_comment' hook on $commentdata parameter array before processing
1305  * @uses do_action() Calls 'comment_post' hook on $comment_ID returned from adding the comment and if the comment was approved.
1306  * @uses wp_filter_comment() Used to filter comment before adding comment.
1307  * @uses wp_allow_comment() checks to see if comment is approved.
1308  * @uses wp_insert_comment() Does the actual comment insertion to the database.
1309  *
1310  * @param array $commentdata Contains information on the comment.
1311  * @return int The ID of the comment after adding.
1312  */
1313 function wp_new_comment( $commentdata ) {
1314         $commentdata = apply_filters('preprocess_comment', $commentdata);
1315
1316         $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
1317         if ( isset($commentdata['user_ID']) )
1318                 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
1319         elseif ( isset($commentdata['user_id']) )
1320                 $commentdata['user_id'] = (int) $commentdata['user_id'];
1321
1322         $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
1323         $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
1324         $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
1325
1326         $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
1327         $commentdata['comment_agent']     = substr($_SERVER['HTTP_USER_AGENT'], 0, 254);
1328
1329         $commentdata['comment_date']     = current_time('mysql');
1330         $commentdata['comment_date_gmt'] = current_time('mysql', 1);
1331
1332         $commentdata = wp_filter_comment($commentdata);
1333
1334         $commentdata['comment_approved'] = wp_allow_comment($commentdata);
1335
1336         $comment_ID = wp_insert_comment($commentdata);
1337
1338         do_action('comment_post', $comment_ID, $commentdata['comment_approved']);
1339
1340         if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
1341                 if ( '0' == $commentdata['comment_approved'] )
1342                         wp_notify_moderator($comment_ID);
1343
1344                 $post = &get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment
1345
1346                 if ( get_option('comments_notify') && $commentdata['comment_approved'] && ( ! isset( $commentdata['user_id'] ) || $post->post_author != $commentdata['user_id'] ) )
1347                         wp_notify_postauthor($comment_ID, isset( $commentdata['comment_type'] ) ? $commentdata['comment_type'] : '' );
1348         }
1349
1350         return $comment_ID;
1351 }
1352
1353 /**
1354  * Sets the status of a comment.
1355  *
1356  * The 'wp_set_comment_status' action is called after the comment is handled and
1357  * will only be called, if the comment status is either 'hold', 'approve', or
1358  * 'spam'. If the comment status is not in the list, then false is returned and
1359  * if the status is 'delete', then the comment is deleted without calling the
1360  * action.
1361  *
1362  * @since 1.0.0
1363  * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
1364  *
1365  * @param int $comment_id Comment ID.
1366  * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'delete'.
1367  * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
1368  * @return bool False on failure or deletion and true on success.
1369  */
1370 function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
1371         global $wpdb;
1372
1373         $status = '0';
1374         switch ( $comment_status ) {
1375                 case 'hold':
1376                 case '0':
1377                         $status = '0';
1378                         break;
1379                 case 'approve':
1380                 case '1':
1381                         $status = '1';
1382                         if ( get_option('comments_notify') ) {
1383                                 $comment = get_comment($comment_id);
1384                                 wp_notify_postauthor($comment_id, $comment->comment_type);
1385                         }
1386                         break;
1387                 case 'spam':
1388                         $status = 'spam';
1389                         break;
1390                 case 'trash':
1391                         $status = 'trash';
1392                         break;
1393                 default:
1394                         return false;
1395         }
1396
1397         $comment_old = wp_clone(get_comment($comment_id));
1398
1399         if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
1400                 if ( $wp_error )
1401                         return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
1402                 else
1403                         return false;
1404         }
1405
1406         clean_comment_cache($comment_id);
1407
1408         $comment = get_comment($comment_id);
1409
1410         do_action('wp_set_comment_status', $comment_id, $comment_status);
1411         wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
1412
1413         wp_update_comment_count($comment->comment_post_ID);
1414
1415         return true;
1416 }
1417
1418 /**
1419  * Updates an existing comment in the database.
1420  *
1421  * Filters the comment and makes sure certain fields are valid before updating.
1422  *
1423  * @since 2.0.0
1424  * @uses $wpdb
1425  * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
1426  *
1427  * @param array $commentarr Contains information on the comment.
1428  * @return int Comment was updated if value is 1, or was not updated if value is 0.
1429  */
1430 function wp_update_comment($commentarr) {
1431         global $wpdb;
1432
1433         // First, get all of the original fields
1434         $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
1435
1436         // Escape data pulled from DB.
1437         $comment = esc_sql($comment);
1438
1439         $old_status = $comment['comment_approved'];
1440
1441         // Merge old and new fields with new fields overwriting old ones.
1442         $commentarr = array_merge($comment, $commentarr);
1443
1444         $commentarr = wp_filter_comment( $commentarr );
1445
1446         // Now extract the merged array.
1447         extract(stripslashes_deep($commentarr), EXTR_SKIP);
1448
1449         $comment_content = apply_filters('comment_save_pre', $comment_content);
1450
1451         $comment_date_gmt = get_gmt_from_date($comment_date);
1452
1453         if ( !isset($comment_approved) )
1454                 $comment_approved = 1;
1455         else if ( 'hold' == $comment_approved )
1456                 $comment_approved = 0;
1457         else if ( 'approve' == $comment_approved )
1458                 $comment_approved = 1;
1459
1460         $data = compact('comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt');
1461         $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
1462
1463         clean_comment_cache($comment_ID);
1464         wp_update_comment_count($comment_post_ID);
1465         do_action('edit_comment', $comment_ID);
1466         $comment = get_comment($comment_ID);
1467         wp_transition_comment_status($comment->comment_approved, $old_status, $comment);
1468         return $rval;
1469 }
1470
1471 /**
1472  * Whether to defer comment counting.
1473  *
1474  * When setting $defer to true, all post comment counts will not be updated
1475  * until $defer is set to false. When $defer is set to false, then all
1476  * previously deferred updated post comment counts will then be automatically
1477  * updated without having to call wp_update_comment_count() after.
1478  *
1479  * @since 2.5.0
1480  * @staticvar bool $_defer
1481  *
1482  * @param bool $defer
1483  * @return unknown
1484  */
1485 function wp_defer_comment_counting($defer=null) {
1486         static $_defer = false;
1487
1488         if ( is_bool($defer) ) {
1489                 $_defer = $defer;
1490                 // flush any deferred counts
1491                 if ( !$defer )
1492                         wp_update_comment_count( null, true );
1493         }
1494
1495         return $_defer;
1496 }
1497
1498 /**
1499  * Updates the comment count for post(s).
1500  *
1501  * When $do_deferred is false (is by default) and the comments have been set to
1502  * be deferred, the post_id will be added to a queue, which will be updated at a
1503  * later date and only updated once per post ID.
1504  *
1505  * If the comments have not be set up to be deferred, then the post will be
1506  * updated. When $do_deferred is set to true, then all previous deferred post
1507  * IDs will be updated along with the current $post_id.
1508  *
1509  * @since 2.1.0
1510  * @see wp_update_comment_count_now() For what could cause a false return value
1511  *
1512  * @param int $post_id Post ID
1513  * @param bool $do_deferred Whether to process previously deferred post comment counts
1514  * @return bool True on success, false on failure
1515  */
1516 function wp_update_comment_count($post_id, $do_deferred=false) {
1517         static $_deferred = array();
1518
1519         if ( $do_deferred ) {
1520                 $_deferred = array_unique($_deferred);
1521                 foreach ( $_deferred as $i => $_post_id ) {
1522                         wp_update_comment_count_now($_post_id);
1523                         unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
1524                 }
1525         }
1526
1527         if ( wp_defer_comment_counting() ) {
1528                 $_deferred[] = $post_id;
1529                 return true;
1530         }
1531         elseif ( $post_id ) {
1532                 return wp_update_comment_count_now($post_id);
1533         }
1534
1535 }
1536
1537 /**
1538  * Updates the comment count for the post.
1539  *
1540  * @since 2.5.0
1541  * @uses $wpdb
1542  * @uses do_action() Calls 'wp_update_comment_count' hook on $post_id, $new, and $old
1543  * @uses do_action() Calls 'edit_posts' hook on $post_id and $post
1544  *
1545  * @param int $post_id Post ID
1546  * @return bool False on '0' $post_id or if post with ID does not exist. True on success.
1547  */
1548 function wp_update_comment_count_now($post_id) {
1549         global $wpdb;
1550         $post_id = (int) $post_id;
1551         if ( !$post_id )
1552                 return false;
1553         if ( !$post = get_post($post_id) )
1554                 return false;
1555
1556         $old = (int) $post->comment_count;
1557         $new = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id) );
1558         $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) );
1559
1560         if ( 'page' == $post->post_type )
1561                 clean_page_cache( $post_id );
1562         else
1563                 clean_post_cache( $post_id );
1564
1565         do_action('wp_update_comment_count', $post_id, $new, $old);
1566         do_action('edit_post', $post_id, $post);
1567
1568         return true;
1569 }
1570
1571 //
1572 // Ping and trackback functions.
1573 //
1574
1575 /**
1576  * Finds a pingback server URI based on the given URL.
1577  *
1578  * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
1579  * a check for the x-pingback headers first and returns that, if available. The
1580  * check for the rel="pingback" has more overhead than just the header.
1581  *
1582  * @since 1.5.0
1583  *
1584  * @param string $url URL to ping.
1585  * @param int $deprecated Not Used.
1586  * @return bool|string False on failure, string containing URI on success.
1587  */
1588 function discover_pingback_server_uri( $url, $deprecated = '' ) {
1589         if ( !empty( $deprecated ) )
1590                 _deprecated_argument( __FUNCTION__, '2.7' );
1591
1592         $pingback_str_dquote = 'rel="pingback"';
1593         $pingback_str_squote = 'rel=\'pingback\'';
1594
1595         /** @todo Should use Filter Extension or custom preg_match instead. */
1596         $parsed_url = parse_url($url);
1597
1598         if ( ! isset( $parsed_url['host'] ) ) // Not an URL. This should never happen.
1599                 return false;
1600
1601         //Do not search for a pingback server on our own uploads
1602         $uploads_dir = wp_upload_dir();
1603         if ( 0 === strpos($url, $uploads_dir['baseurl']) )
1604                 return false;
1605
1606         $response = wp_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
1607
1608         if ( is_wp_error( $response ) )
1609                 return false;
1610
1611         if ( isset( $response['headers']['x-pingback'] ) )
1612                 return $response['headers']['x-pingback'];
1613
1614         // Not an (x)html, sgml, or xml page, no use going further.
1615         if ( isset( $response['headers']['content-type'] ) && preg_match('#(image|audio|video|model)/#is', $response['headers']['content-type']) )
1616                 return false;
1617
1618         // Now do a GET since we're going to look in the html headers (and we're sure its not a binary file)
1619         $response = wp_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
1620
1621         if ( is_wp_error( $response ) )
1622                 return false;
1623
1624         $contents = $response['body'];
1625
1626         $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
1627         $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
1628         if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
1629                 $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
1630                 $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
1631                 $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
1632                 $pingback_href_start = $pingback_href_pos+6;
1633                 $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
1634                 $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
1635                 $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
1636
1637                 // We may find rel="pingback" but an incomplete pingback URL
1638                 if ( $pingback_server_url_len > 0 ) { // We got it!
1639                         return $pingback_server_url;
1640                 }
1641         }
1642
1643         return false;
1644 }
1645
1646 /**
1647  * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
1648  *
1649  * @since 2.1.0
1650  * @uses $wpdb
1651  */
1652 function do_all_pings() {
1653         global $wpdb;
1654
1655         // Do pingbacks
1656         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")) {
1657                 $mid = $wpdb->get_var( "SELECT meta_id FROM {$wpdb->postmeta} WHERE post_id = {$ping->ID} AND meta_key = '_pingme' LIMIT 1");
1658                 do_action( 'delete_postmeta', $mid );
1659                 $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->postmeta} WHERE meta_id = %d", $mid ) );
1660                 do_action( 'deleted_postmeta', $mid );
1661                 pingback($ping->post_content, $ping->ID);
1662         }
1663
1664         // Do Enclosures
1665         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")) {
1666                 $mid = $wpdb->get_var( $wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_encloseme'", $enclosure->ID) );
1667                 do_action( 'delete_postmeta', $mid );
1668                 $wpdb->query( $wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE meta_id =  %d", $mid) );
1669                 do_action( 'deleted_postmeta', $mid );
1670                 do_enclose($enclosure->post_content, $enclosure->ID);
1671         }
1672
1673         // Do Trackbacks
1674         $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'");
1675         if ( is_array($trackbacks) )
1676                 foreach ( $trackbacks as $trackback )
1677                         do_trackbacks($trackback);
1678
1679         //Do Update Services/Generic Pings
1680         generic_ping();
1681 }
1682
1683 /**
1684  * Perform trackbacks.
1685  *
1686  * @since 1.5.0
1687  * @uses $wpdb
1688  *
1689  * @param int $post_id Post ID to do trackbacks on.
1690  */
1691 function do_trackbacks($post_id) {
1692         global $wpdb;
1693
1694         $post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) );
1695         $to_ping = get_to_ping($post_id);
1696         $pinged  = get_pung($post_id);
1697         if ( empty($to_ping) ) {
1698                 $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) );
1699                 return;
1700         }
1701
1702         if ( empty($post->post_excerpt) )
1703                 $excerpt = apply_filters('the_content', $post->post_content);
1704         else
1705                 $excerpt = apply_filters('the_excerpt', $post->post_excerpt);
1706         $excerpt = str_replace(']]>', ']]&gt;', $excerpt);
1707         $excerpt = wp_html_excerpt($excerpt, 252) . '...';
1708
1709         $post_title = apply_filters('the_title', $post->post_title);
1710         $post_title = strip_tags($post_title);
1711
1712         if ( $to_ping ) {
1713                 foreach ( (array) $to_ping as $tb_ping ) {
1714                         $tb_ping = trim($tb_ping);
1715                         if ( !in_array($tb_ping, $pinged) ) {
1716                                 trackback($tb_ping, $post_title, $excerpt, $post_id);
1717                                 $pinged[] = $tb_ping;
1718                         } else {
1719                                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post_id) );
1720                         }
1721                 }
1722         }
1723 }
1724
1725 /**
1726  * Sends pings to all of the ping site services.
1727  *
1728  * @since 1.2.0
1729  *
1730  * @param int $post_id Post ID. Not actually used.
1731  * @return int Same as Post ID from parameter
1732  */
1733 function generic_ping($post_id = 0) {
1734         $services = get_option('ping_sites');
1735
1736         $services = explode("\n", $services);
1737         foreach ( (array) $services as $service ) {
1738                 $service = trim($service);
1739                 if ( '' != $service )
1740                         weblog_ping($service);
1741         }
1742
1743         return $post_id;
1744 }
1745
1746 /**
1747  * Pings back the links found in a post.
1748  *
1749  * @since 0.71
1750  * @uses $wp_version
1751  * @uses IXR_Client
1752  *
1753  * @param string $content Post content to check for links.
1754  * @param int $post_ID Post ID.
1755  */
1756 function pingback($content, $post_ID) {
1757         global $wp_version;
1758         include_once(ABSPATH . WPINC . '/class-IXR.php');
1759         include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
1760
1761         // original code by Mort (http://mort.mine.nu:8080)
1762         $post_links = array();
1763
1764         $pung = get_pung($post_ID);
1765
1766         // Variables
1767         $ltrs = '\w';
1768         $gunk = '/#~:.?+=&%@!\-';
1769         $punc = '.:?\-';
1770         $any = $ltrs . $gunk . $punc;
1771
1772         // Step 1
1773         // Parsing the post, external links (if any) are stored in the $post_links array
1774         // This regexp comes straight from phpfreaks.com
1775         // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
1776         preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
1777
1778         // Step 2.
1779         // Walking thru the links array
1780         // first we get rid of links pointing to sites, not to specific files
1781         // Example:
1782         // http://dummy-weblog.org
1783         // http://dummy-weblog.org/
1784         // http://dummy-weblog.org/post.php
1785         // We don't wanna ping first and second types, even if they have a valid <link/>
1786
1787         foreach ( (array) $post_links_temp[0] as $link_test ) :
1788                 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
1789                                 && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
1790                         if ( $test = @parse_url($link_test) ) {
1791                                 if ( isset($test['query']) )
1792                                         $post_links[] = $link_test;
1793                                 elseif ( isset( $test['path'] ) && ( $test['path'] != '/' ) && ( $test['path'] != '' ) )
1794                                         $post_links[] = $link_test;
1795                         }
1796                 endif;
1797         endforeach;
1798
1799         do_action_ref_array('pre_ping', array(&$post_links, &$pung));
1800
1801         foreach ( (array) $post_links as $pagelinkedto ) {
1802                 $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
1803
1804                 if ( $pingback_server_url ) {
1805                         @ set_time_limit( 60 );
1806                          // Now, the RPC call
1807                         $pagelinkedfrom = get_permalink($post_ID);
1808
1809                         // using a timeout of 3 seconds should be enough to cover slow servers
1810                         $client = new WP_HTTP_IXR_Client($pingback_server_url);
1811                         $client->timeout = 3;
1812                         $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . $wp_version, $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom);
1813                         // when set to true, this outputs debug messages by itself
1814                         $client->debug = false;
1815
1816                         if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
1817                                 add_ping( $post_ID, $pagelinkedto );
1818                 }
1819         }
1820 }
1821
1822 /**
1823  * Check whether blog is public before returning sites.
1824  *
1825  * @since 2.1.0
1826  *
1827  * @param mixed $sites Will return if blog is public, will not return if not public.
1828  * @return mixed Empty string if blog is not public, returns $sites, if site is public.
1829  */
1830 function privacy_ping_filter($sites) {
1831         if ( '0' != get_option('blog_public') )
1832                 return $sites;
1833         else
1834                 return '';
1835 }
1836
1837 /**
1838  * Send a Trackback.
1839  *
1840  * Updates database when sending trackback to prevent duplicates.
1841  *
1842  * @since 0.71
1843  * @uses $wpdb
1844  *
1845  * @param string $trackback_url URL to send trackbacks.
1846  * @param string $title Title of post.
1847  * @param string $excerpt Excerpt of post.
1848  * @param int $ID Post ID.
1849  * @return mixed Database query from update.
1850  */
1851 function trackback($trackback_url, $title, $excerpt, $ID) {
1852         global $wpdb;
1853
1854         if ( empty($trackback_url) )
1855                 return;
1856
1857         $options = array();
1858         $options['timeout'] = 4;
1859         $options['body'] = array(
1860                 'title' => $title,
1861                 'url' => get_permalink($ID),
1862                 'blog_name' => get_option('blogname'),
1863                 'excerpt' => $excerpt
1864         );
1865
1866         $response = wp_remote_post($trackback_url, $options);
1867
1868         if ( is_wp_error( $response ) )
1869                 return;
1870
1871         $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID) );
1872         return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID) );
1873 }
1874
1875 /**
1876  * Send a pingback.
1877  *
1878  * @since 1.2.0
1879  * @uses $wp_version
1880  * @uses IXR_Client
1881  *
1882  * @param string $server Host of blog to connect to.
1883  * @param string $path Path to send the ping.
1884  */
1885 function weblog_ping($server = '', $path = '') {
1886         global $wp_version;
1887         include_once(ABSPATH . WPINC . '/class-IXR.php');
1888         include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
1889
1890         // using a timeout of 3 seconds should be enough to cover slow servers
1891         $client = new WP_HTTP_IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
1892         $client->timeout = 3;
1893         $client->useragent .= ' -- WordPress/'.$wp_version;
1894
1895         // when set to true, this outputs debug messages by itself
1896         $client->debug = false;
1897         $home = trailingslashit( home_url() );
1898         if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
1899                 $client->query('weblogUpdates.ping', get_option('blogname'), $home);
1900 }
1901
1902 //
1903 // Cache
1904 //
1905
1906 /**
1907  * Removes comment ID from the comment cache.
1908  *
1909  * @since 2.3.0
1910  * @package WordPress
1911  * @subpackage Cache
1912  *
1913  * @param int|array $ids Comment ID or array of comment IDs to remove from cache
1914  */
1915 function clean_comment_cache($ids) {
1916         foreach ( (array) $ids as $id )
1917                 wp_cache_delete($id, 'comment');
1918
1919         wp_cache_set('last_changed', time(), 'comment');
1920 }
1921
1922 /**
1923  * Updates the comment cache of given comments.
1924  *
1925  * Will add the comments in $comments to the cache. If comment ID already exists
1926  * in the comment cache then it will not be updated. The comment is added to the
1927  * cache using the comment group with the key using the ID of the comments.
1928  *
1929  * @since 2.3.0
1930  * @package WordPress
1931  * @subpackage Cache
1932  *
1933  * @param array $comments Array of comment row objects
1934  */
1935 function update_comment_cache($comments) {
1936         foreach ( (array) $comments as $comment )
1937                 wp_cache_add($comment->comment_ID, $comment, 'comment');
1938 }
1939
1940 //
1941 // Internal
1942 //
1943
1944 /**
1945  * Close comments on old posts on the fly, without any extra DB queries.  Hooked to the_posts.
1946  *
1947  * @access private
1948  * @since 2.7.0
1949  *
1950  * @param object $posts Post data object.
1951  * @return object
1952  */
1953 function _close_comments_for_old_posts( $posts ) {
1954         if ( empty($posts) || !is_singular() || !get_option('close_comments_for_old_posts') )
1955                 return $posts;
1956
1957         $days_old = (int) get_option('close_comments_days_old');
1958         if ( !$days_old )
1959                 return $posts;
1960
1961         if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * 24 * 60 * 60 ) ) {
1962                 $posts[0]->comment_status = 'closed';
1963                 $posts[0]->ping_status = 'closed';
1964         }
1965
1966         return $posts;
1967 }
1968
1969 /**
1970  * Close comments on an old post.  Hooked to comments_open and pings_open.
1971  *
1972  * @access private
1973  * @since 2.7.0
1974  *
1975  * @param bool $open Comments open or closed
1976  * @param int $post_id Post ID
1977  * @return bool $open
1978  */
1979 function _close_comments_for_old_post( $open, $post_id ) {
1980         if ( ! $open )
1981                 return $open;
1982
1983         if ( !get_option('close_comments_for_old_posts') )
1984                 return $open;
1985
1986         $days_old = (int) get_option('close_comments_days_old');
1987         if ( !$days_old )
1988                 return $open;
1989
1990         $post = get_post($post_id);
1991
1992         if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * 24 * 60 * 60 ) )
1993                 return false;
1994
1995         return $open;
1996 }
1997
1998 ?>