]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/comment.php
WordPress 4.2.1
[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  * Check whether a comment passes internal checks to be allowed to add.
11  *
12  * If manual comment moderation is set in the administration, then all checks,
13  * regardless of their type and whitelist, will fail and the function will
14  * return false.
15  *
16  * If the number of links exceeds the amount in the administration, then the
17  * check fails. If any of the parameter contents match the blacklist of words,
18  * then the check fails.
19  *
20  * If the comment author was approved before, then the comment is automatically
21  * whitelisted.
22  *
23  * If all checks pass, the function will return true.
24  *
25  * @since 1.2.0
26  *
27  * @global wpdb $wpdb WordPress database abstraction object.
28  *
29  * @param string $author       Comment author name.
30  * @param string $email        Comment author email.
31  * @param string $url          Comment author URL.
32  * @param string $comment      Content of the comment.
33  * @param string $user_ip      Comment author IP address.
34  * @param string $user_agent   Comment author User-Agent.
35  * @param string $comment_type Comment type, either user-submitted comment,
36  *                                     trackback, or pingback.
37  * @return bool If all checks pass, true, otherwise false.
38  */
39 function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
40         global $wpdb;
41
42         // If manual moderation is enabled, skip all checks and return false.
43         if ( 1 == get_option('comment_moderation') )
44                 return false;
45
46         /** This filter is documented in wp-includes/comment-template.php */
47         $comment = apply_filters( 'comment_text', $comment );
48
49         // Check for the number of external links if a max allowed number is set.
50         if ( $max_links = get_option( 'comment_max_links' ) ) {
51                 $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out );
52
53                 /**
54                  * Filter the maximum number of links allowed in a comment.
55                  *
56                  * @since 3.0.0
57                  *
58                  * @param int    $num_links The number of links allowed.
59                  * @param string $url       Comment author's URL. Included in allowed links total.
60                  */
61                 $num_links = apply_filters( 'comment_max_links_url', $num_links, $url );
62
63                 /*
64                  * If the number of links in the comment exceeds the allowed amount,
65                  * fail the check by returning false.
66                  */
67                 if ( $num_links >= $max_links )
68                         return false;
69         }
70
71         $mod_keys = trim(get_option('moderation_keys'));
72
73         // If moderation 'keys' (keywords) are set, process them.
74         if ( !empty($mod_keys) ) {
75                 $words = explode("\n", $mod_keys );
76
77                 foreach ( (array) $words as $word) {
78                         $word = trim($word);
79
80                         // Skip empty lines.
81                         if ( empty($word) )
82                                 continue;
83
84                         /*
85                          * Do some escaping magic so that '#' (number of) characters in the spam
86                          * words don't break things:
87                          */
88                         $word = preg_quote($word, '#');
89
90                         /*
91                          * Check the comment fields for moderation keywords. If any are found,
92                          * fail the check for the given field by returning false.
93                          */
94                         $pattern = "#$word#i";
95                         if ( preg_match($pattern, $author) ) return false;
96                         if ( preg_match($pattern, $email) ) return false;
97                         if ( preg_match($pattern, $url) ) return false;
98                         if ( preg_match($pattern, $comment) ) return false;
99                         if ( preg_match($pattern, $user_ip) ) return false;
100                         if ( preg_match($pattern, $user_agent) ) return false;
101                 }
102         }
103
104         /*
105          * Check if the option to approve comments by previously-approved authors is enabled.
106          *
107          * If it is enabled, check whether the comment author has a previously-approved comment,
108          * as well as whether there are any moderation keywords (if set) present in the author
109          * email address. If both checks pass, return true. Otherwise, return false.
110          */
111         if ( 1 == get_option('comment_whitelist')) {
112                 if ( 'trackback' != $comment_type && 'pingback' != $comment_type && $author != '' && $email != '' ) {
113                         // expected_slashed ($author, $email)
114                         $ok_to_comment = $wpdb->get_var("SELECT comment_approved FROM $wpdb->comments WHERE comment_author = '$author' AND comment_author_email = '$email' and comment_approved = '1' LIMIT 1");
115                         if ( ( 1 == $ok_to_comment ) &&
116                                 ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
117                                         return true;
118                         else
119                                 return false;
120                 } else {
121                         return false;
122                 }
123         }
124         return true;
125 }
126
127 /**
128  * Retrieve the approved comments for post $post_id.
129  *
130  * @since 2.0.0
131  * @since 4.1.0 Refactored to leverage {@see WP_Comment_Query} over a direct query.
132  *
133  * @param  int   $post_id The ID of the post.
134  * @param  array $args    Optional. See {@see WP_Comment_Query::query()} for information
135  *                        on accepted arguments.
136  * @return int|array $comments The approved comments, or number of comments if `$count`
137  *                             argument is true.
138  */
139 function get_approved_comments( $post_id, $args = array() ) {
140         if ( ! $post_id ) {
141                 return array();
142         }
143
144         $defaults = array(
145                 'status'  => 1,
146                 'post_id' => $post_id,
147                 'order'   => 'ASC',
148         );
149         $r = wp_parse_args( $args, $defaults );
150
151         $query = new WP_Comment_Query;
152         return $query->query( $r );
153 }
154
155 /**
156  * Retrieves comment data given a comment ID or comment object.
157  *
158  * If an object is passed then the comment data will be cached and then returned
159  * after being passed through a filter. If the comment is empty, then the global
160  * comment variable will be used, if it is set.
161  *
162  * @since 2.0.0
163  *
164  * @global wpdb $wpdb WordPress database abstraction object.
165  *
166  * @param object|string|int $comment Comment to retrieve.
167  * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
168  * @return object|array|null Depends on $output value.
169  */
170 function get_comment(&$comment, $output = OBJECT) {
171         global $wpdb;
172
173         if ( empty($comment) ) {
174                 if ( isset($GLOBALS['comment']) )
175                         $_comment = & $GLOBALS['comment'];
176                 else
177                         $_comment = null;
178         } elseif ( is_object($comment) ) {
179                 wp_cache_add($comment->comment_ID, $comment, 'comment');
180                 $_comment = $comment;
181         } else {
182                 if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
183                         $_comment = & $GLOBALS['comment'];
184                 } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
185                         $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
186                         if ( ! $_comment )
187                                 return null;
188                         wp_cache_add($_comment->comment_ID, $_comment, 'comment');
189                 }
190         }
191
192         /**
193          * Fires after a comment is retrieved.
194          *
195          * @since 2.3.0
196          *
197          * @param mixed $_comment Comment data.
198          */
199         $_comment = apply_filters( 'get_comment', $_comment );
200
201         if ( $output == OBJECT ) {
202                 return $_comment;
203         } elseif ( $output == ARRAY_A ) {
204                 $__comment = get_object_vars($_comment);
205                 return $__comment;
206         } elseif ( $output == ARRAY_N ) {
207                 $__comment = array_values(get_object_vars($_comment));
208                 return $__comment;
209         } else {
210                 return $_comment;
211         }
212 }
213
214 /**
215  * Retrieve a list of comments.
216  *
217  * The comment list can be for the blog as a whole or for an individual post.
218  *
219  * @since 2.7.0
220  *
221  * @param string|array $args Optional. Array or string of arguments. See {@see WP_Comment_Query::parse_query()}
222  *                           for information on accepted arguments. Default empty.
223  * @return int|array List of comments or number of found comments if `$count` argument is true.
224  */
225 function get_comments( $args = '' ) {
226         $query = new WP_Comment_Query;
227         return $query->query( $args );
228 }
229
230 /**
231  * WordPress Comment Query class.
232  *
233  * See WP_Comment_Query::__construct() for accepted arguments.
234  *
235  * @since 3.1.0
236  */
237 class WP_Comment_Query {
238         /**
239          * SQL for database query.
240          *
241          * @since 4.0.1
242          * @access public
243          * @var string
244          */
245         public $request;
246
247         /**
248          * Metadata query container
249          *
250          * @since 3.5.0
251          * @access public
252          * @var object WP_Meta_Query
253          */
254         public $meta_query = false;
255
256         /**
257          * Date query container
258          *
259          * @since 3.7.0
260          * @access public
261          * @var object WP_Date_Query
262          */
263         public $date_query = false;
264
265         /**
266          * Query vars set by the user.
267          *
268          * @since 3.1.0
269          * @access public
270          * @var array
271          */
272         public $query_vars;
273
274         /**
275          * Default values for query vars.
276          *
277          * @since 4.2.0
278          * @access public
279          * @var array
280          */
281         public $query_var_defaults;
282
283         /**
284          * List of comments located by the query.
285          *
286          * @since 4.0.0
287          * @access public
288          * @var array
289          */
290         public $comments;
291
292         /**
293          * Make private/protected methods readable for backwards compatibility.
294          *
295          * @since 4.0.0
296          * @access public
297          *
298          * @param callable $name      Method to call.
299          * @param array    $arguments Arguments to pass when calling.
300          * @return mixed|bool Return value of the callback, false otherwise.
301          */
302         public function __call( $name, $arguments ) {
303                 if ( 'get_search_sql' === $name ) {
304                         return call_user_func_array( array( $this, $name ), $arguments );
305                 }
306                 return false;
307         }
308
309         /**
310          * Constructor.
311          *
312          * Sets up the comment query, based on the query vars passed.
313          *
314          * @since  4.2.0
315          * @access public
316          *
317          * @param string|array $query {
318          *     Optional. Array or query string of comment query parameters. Default empty.
319          *
320          *     @type string       $author_email        Comment author email address. Default empty.
321          *     @type array        $author__in          Array of author IDs to include comments for. Default empty.
322          *     @type array        $author__not_in      Array of author IDs to exclude comments for. Default empty.
323          *     @type array        $comment__in         Array of comment IDs to include. Default empty.
324          *     @type array        $comment__not_in     Array of comment IDs to exclude. Default empty.
325          *     @type bool         $count               Whether to return a comment count (true) or array of comment
326          *                                             objects (false). Default false.
327          *     @type array        $date_query          Date query clauses to limit comments by. See WP_Date_Query.
328          *                                             Default null.
329          *     @type string       $fields              Comment fields to return. Accepts 'ids' for comment IDs only or
330          *                                             empty for all fields. Default empty.
331          *     @type int          $ID                  Currently unused.
332          *     @type array        $include_unapproved  Array of IDs or email addresses of users whose unapproved comments
333          *                                             will be returned by the query regardless of `$status`. Default empty.
334          *     @type int          $karma               Karma score to retrieve matching comments for. Default empty.
335          *     @type string       $meta_key            Include comments with a matching comment meta key. Default empty.
336          *     @type string       $meta_value          Include comments with a matching comment meta value. Requires
337          *                                             `$meta_key` to be set. Default empty.
338          *     @type array        $meta_query          Meta query clauses to limit retrieved comments by.
339          *                                             See WP_Meta_Query. Default empty.
340          *     @type int          $number              Maximum number of comments to retrieve. Default null (no limit).
341          *     @type int          $offset              Number of comments to offset the query. Used to build LIMIT clause.
342          *                                             Default 0.
343          *     @type string|array $orderby             Comment status or array of statuses. To use 'meta_value' or
344          *                                             'meta_value_num', `$meta_key` must also be defined. To sort by
345          *                                             a specific `$meta_query` clause, use that clause's array key.
346          *                                             Accepts 'comment_agent', 'comment_approved', 'comment_author',
347          *                                             'comment_author_email', 'comment_author_IP',
348          *                                             'comment_author_url', 'comment_content', 'comment_date',
349          *                                             'comment_date_gmt', 'comment_ID', 'comment_karma',
350          *                                             'comment_parent', 'comment_post_ID', 'comment_type', 'user_id',
351          *                                             'meta_value', 'meta_value_num', the value of $meta_key, and the
352          *                                             array keys of `$meta_query`. Also accepts false, an empty array,
353          *                                             or 'none' to disable `ORDER BY` clause.
354          *                                             Default: 'comment_date_gmt'.
355          *     @type string       $order               How to order retrieved comments. Accepts 'ASC', 'DESC'.
356          *                                             Default: 'DESC'.
357          *     @type int          $parent              Parent ID of comment to retrieve children of. Default empty.
358          *     @type array        $post_author__in     Array of author IDs to retrieve comments for. Default empty.
359          *     @type array        $post_author__not_in Array of author IDs *not* to retrieve comments for. Default empty.
360          *     @type int          $post_ID             Currently unused.
361          *     @type int          $post_id             Limit results to those affiliated with a given post ID. Default 0.
362          *     @type array        $post__in            Array of post IDs to include affiliated comments for. Default empty.
363          *     @type array        $post__not_in        Array of post IDs to exclude affiliated comments for. Default empty.
364          *     @type int          $post_author         Comment author ID to limit results by. Default empty.
365          *     @type string       $post_status         Post status to retrieve affiliated comments for. Default empty.
366          *     @type string       $post_type           Post type to retrieve affiliated comments for. Default empty.
367          *     @type string       $post_name           Post name to retrieve affiliated comments for. Default empty.
368          *     @type int          $post_parent         Post parent ID to retrieve affiliated comments for. Default empty.
369          *     @type string       $search              Search term(s) to retrieve matching comments for. Default empty.
370          *     @type string       $status              Comment status to limit results by. Accepts 'hold'
371          *                                             (`comment_status=0`), 'approve' (`comment_status=1`), 'all', or a
372          *                                             custom comment status. Default 'all'.
373          *     @type string|array $type                Include comments of a given type, or array of types. Accepts
374          *                                             'comment', 'pings' (includes 'pingback' and 'trackback'), or any
375          *                                             custom type string. Default empty.
376          *     @type array        $type__in            Include comments from a given array of comment types. Default empty.
377          *     @type array        $type__not_in        Exclude comments from a given array of comment types. Default empty.
378          *     @type int          $user_id             Include comments for a specific user ID. Default empty.
379          * }
380          * @return WP_Comment_Query WP_Comment_Query instance.
381          */
382         public function __construct( $query = '' ) {
383                 $this->query_var_defaults = array(
384                         'author_email' => '',
385                         'author__in' => '',
386                         'author__not_in' => '',
387                         'include_unapproved' => '',
388                         'fields' => '',
389                         'ID' => '',
390                         'comment__in' => '',
391                         'comment__not_in' => '',
392                         'karma' => '',
393                         'number' => '',
394                         'offset' => '',
395                         'orderby' => '',
396                         'order' => 'DESC',
397                         'parent' => '',
398                         'post_author__in' => '',
399                         'post_author__not_in' => '',
400                         'post_ID' => '',
401                         'post_id' => 0,
402                         'post__in' => '',
403                         'post__not_in' => '',
404                         'post_author' => '',
405                         'post_name' => '',
406                         'post_parent' => '',
407                         'post_status' => '',
408                         'post_type' => '',
409                         'status' => 'all',
410                         'type' => '',
411                         'type__in' => '',
412                         'type__not_in' => '',
413                         'user_id' => '',
414                         'search' => '',
415                         'count' => false,
416                         'meta_key' => '',
417                         'meta_value' => '',
418                         'meta_query' => '',
419                         'date_query' => null, // See WP_Date_Query
420                 );
421
422                 if ( ! empty( $query ) ) {
423                         $this->query( $query );
424                 }
425         }
426
427         /**
428          * Parse arguments passed to the comment query with default query parameters.
429          *
430          * @since  4.2.0 Extracted from WP_Comment_Query::query().
431          *
432          * @access public
433          *
434          * @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct()
435          */
436         public function parse_query( $query = '' ) {
437                 if ( empty( $query ) ) {
438                         $query = $this->query_vars;
439                 }
440
441                 $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
442                 do_action_ref_array( 'parse_comment_query', array( &$this ) );
443         }
444
445         /**
446          * Sets up the WordPress query for retrieving comments.
447          *
448          * @since 3.1.0
449          * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in',
450          *              'post_author__not_in', 'author__in', 'author__not_in', 'post__in',
451          *              'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in'
452          *              arguments to $query_vars.
453          * @since 4.2.0 Moved parsing to WP_Comment_Query::parse_query().
454          * @access public
455          *
456          * @param string|array $query Array or URL query string of parameters.
457          * @return array List of comments.
458          */
459         public function query( $query ) {
460                 $this->query_vars = wp_parse_args( $query );
461                 return $this->get_comments();
462         }
463
464         /**
465          * Get a list of comments matching the query vars.
466          *
467          * @since 4.2.0
468          * @access public
469          *
470          * @global wpdb $wpdb WordPress database abstraction object.
471          *
472          * @return array The list of comments.
473          */
474         public function get_comments() {
475                 global $wpdb;
476
477                 $groupby = '';
478
479                 $this->parse_query();
480
481                 // Parse meta query
482                 $this->meta_query = new WP_Meta_Query();
483                 $this->meta_query->parse_query_vars( $this->query_vars );
484
485                 if ( ! empty( $this->meta_query->queries ) ) {
486                         $meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
487                 }
488
489                 /**
490                  * Fires before comments are retrieved.
491                  *
492                  * @since 3.1.0
493                  *
494                  * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
495                  */
496                 do_action_ref_array( 'pre_get_comments', array( &$this ) );
497
498                 // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
499                 $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
500                 $last_changed = wp_cache_get( 'last_changed', 'comment' );
501                 if ( ! $last_changed ) {
502                         $last_changed = microtime();
503                         wp_cache_set( 'last_changed', $last_changed, 'comment' );
504                 }
505                 $cache_key = "get_comments:$key:$last_changed";
506
507                 if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) {
508                         $this->comments = $cache;
509                         return $this->comments;
510                 }
511
512                 $where = array();
513
514                 // Assemble clauses related to 'comment_approved'.
515                 $approved_clauses = array();
516
517                 // 'status' accepts an array or a comma-separated string.
518                 $status_clauses = array();
519                 $statuses = $this->query_vars['status'];
520                 if ( ! is_array( $statuses ) ) {
521                         $statuses = preg_split( '/[\s,]+/', $statuses );
522                 }
523
524                 // 'any' overrides other statuses.
525                 if ( ! in_array( 'any', $statuses ) ) {
526                         foreach ( $statuses as $status ) {
527                                 switch ( $status ) {
528                                         case 'hold' :
529                                                 $status_clauses[] = "comment_approved = '0'";
530                                                 break;
531
532                                         case 'approve' :
533                                                 $status_clauses[] = "comment_approved = '1'";
534                                                 break;
535
536                                         case 'all' :
537                                         case '' :
538                                                 $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
539                                                 break;
540
541                                         default :
542                                                 $status_clauses[] = $wpdb->prepare( "comment_approved = %s", $status );
543                                                 break;
544                                 }
545                         }
546
547                         if ( ! empty( $status_clauses ) ) {
548                                 $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
549                         }
550                 }
551
552                 // User IDs or emails whose unapproved comments are included, regardless of $status.
553                 if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
554                         $include_unapproved = $this->query_vars['include_unapproved'];
555
556                         // Accepts arrays or comma-separated strings.
557                         if ( ! is_array( $include_unapproved ) ) {
558                                 $include_unapproved = preg_split( '/[\s,]+/', $include_unapproved );
559                         }
560
561                         $unapproved_ids = $unapproved_emails = array();
562                         foreach ( $include_unapproved as $unapproved_identifier ) {
563                                 // Numeric values are assumed to be user ids.
564                                 if ( is_numeric( $unapproved_identifier ) ) {
565                                         $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
566
567                                 // Otherwise we match against email addresses.
568                                 } else {
569                                         $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
570                                 }
571                         }
572                 }
573
574                 // Collapse comment_approved clauses into a single OR-separated clause.
575                 if ( ! empty( $approved_clauses ) ) {
576                         if ( 1 === count( $approved_clauses ) ) {
577                                 $where[] = $approved_clauses[0];
578                         } else {
579                                 $where[] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
580                         }
581                 }
582
583                 $order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
584
585                 // Disable ORDER BY with 'none', an empty array, or boolean false.
586                 if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
587                         $orderby = '';
588                 } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
589                         $ordersby = is_array( $this->query_vars['orderby'] ) ?
590                                 $this->query_vars['orderby'] :
591                                 preg_split( '/[,\s]/', $this->query_vars['orderby'] );
592
593                         $orderby_array = array();
594                         $found_orderby_comment_ID = false;
595                         foreach ( $ordersby as $_key => $_value ) {
596                                 if ( ! $_value ) {
597                                         continue;
598                                 }
599
600                                 if ( is_int( $_key ) ) {
601                                         $_orderby = $_value;
602                                         $_order = $order;
603                                 } else {
604                                         $_orderby = $_key;
605                                         $_order = $_value;
606                                 }
607
608                                 if ( ! $found_orderby_comment_ID && 'comment_ID' === $_orderby ) {
609                                         $found_orderby_comment_ID = true;
610                                 }
611
612                                 $parsed = $this->parse_orderby( $_orderby );
613
614                                 if ( ! $parsed ) {
615                                         continue;
616                                 }
617
618                                 $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
619                         }
620
621                         // If no valid clauses were found, order by comment_date_gmt.
622                         if ( empty( $orderby_array ) ) {
623                                 $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
624                         }
625
626                         // To ensure determinate sorting, always include a comment_ID clause.
627                         if ( ! $found_orderby_comment_ID ) {
628                                 $comment_ID_order = '';
629
630                                 // Inherit order from comment_date or comment_date_gmt, if available.
631                                 foreach ( $orderby_array as $orderby_clause ) {
632                                         if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
633                                                 $comment_ID_order = $match[1];
634                                                 break;
635                                         }
636                                 }
637
638                                 // If no date-related order is available, use the date from the first available clause.
639                                 if ( ! $comment_ID_order ) {
640                                         foreach ( $orderby_array as $orderby_clause ) {
641                                                 if ( false !== strpos( 'ASC', $orderby_clause ) ) {
642                                                         $comment_ID_order = 'ASC';
643                                                 } else {
644                                                         $comment_ID_order = 'DESC';
645                                                 }
646
647                                                 break;
648                                         }
649                                 }
650
651                                 // Default to DESC.
652                                 if ( ! $comment_ID_order ) {
653                                         $comment_ID_order = 'DESC';
654                                 }
655
656                                 $orderby_array[] = "$wpdb->comments.comment_ID $comment_ID_order";
657                         }
658
659                         $orderby = implode( ', ', $orderby_array );
660                 } else {
661                         $orderby = "$wpdb->comments.comment_date_gmt $order";
662                 }
663
664                 $number = absint( $this->query_vars['number'] );
665                 $offset = absint( $this->query_vars['offset'] );
666
667                 if ( ! empty( $number ) ) {
668                         if ( $offset ) {
669                                 $limits = 'LIMIT ' . $offset . ',' . $number;
670                         } else {
671                                 $limits = 'LIMIT ' . $number;
672                         }
673                 } else {
674                         $limits = '';
675                 }
676
677                 if ( $this->query_vars['count'] ) {
678                         $fields = 'COUNT(*)';
679                 } else {
680                         switch ( strtolower( $this->query_vars['fields'] ) ) {
681                                 case 'ids':
682                                         $fields = "$wpdb->comments.comment_ID";
683                                         break;
684                                 default:
685                                         $fields = "*";
686                                         break;
687                         }
688                 }
689
690                 $join = '';
691
692                 $post_id = absint( $this->query_vars['post_id'] );
693                 if ( ! empty( $post_id ) ) {
694                         $where[] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
695                 }
696
697                 // Parse comment IDs for an IN clause.
698                 if ( ! empty( $this->query_vars['comment__in'] ) ) {
699                         $where[] = 'comment_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
700                 }
701
702                 // Parse comment IDs for a NOT IN clause.
703                 if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
704                         $where[] = 'comment_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
705                 }
706
707                 // Parse comment post IDs for an IN clause.
708                 if ( ! empty( $this->query_vars['post__in'] ) ) {
709                         $where[] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
710                 }
711
712                 // Parse comment post IDs for a NOT IN clause.
713                 if ( ! empty( $this->query_vars['post__not_in'] ) ) {
714                         $where[] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
715                 }
716
717                 if ( '' !== $this->query_vars['author_email'] ) {
718                         $where[] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
719                 }
720
721                 if ( '' !== $this->query_vars['karma'] ) {
722                         $where[] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
723                 }
724
725                 // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
726                 $raw_types = array(
727                         'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
728                         'NOT IN' => (array) $this->query_vars['type__not_in'],
729                 );
730
731                 $comment_types = array();
732                 foreach ( $raw_types as $operator => $_raw_types ) {
733                         $_raw_types = array_unique( $_raw_types );
734
735                         foreach ( $_raw_types as $type ) {
736                                 switch ( $type ) {
737                                         // An empty translates to 'all', for backward compatibility
738                                         case '':
739                                         case 'all' :
740                                                 break;
741
742                                         case 'comment':
743                                         case 'comments':
744                                                 $comment_types[ $operator ][] = "''";
745                                                 break;
746
747                                         case 'pings':
748                                                 $comment_types[ $operator ][] = "'pingback'";
749                                                 $comment_types[ $operator ][] = "'trackback'";
750                                                 break;
751
752                                         default:
753                                                 $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
754                                                 break;
755                                 }
756                         }
757
758                         if ( ! empty( $comment_types[ $operator ] ) ) {
759                                 $types_sql = implode( ', ', $comment_types[ $operator ] );
760                                 $where[] = "comment_type $operator ($types_sql)";
761                         }
762                 }
763
764                 if ( '' !== $this->query_vars['parent'] ) {
765                         $where[] = $wpdb->prepare( 'comment_parent = %d', $this->query_vars['parent'] );
766                 }
767
768                 if ( is_array( $this->query_vars['user_id'] ) ) {
769                         $where[] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
770                 } elseif ( '' !== $this->query_vars['user_id'] ) {
771                         $where[] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
772                 }
773
774                 if ( '' !== $this->query_vars['search'] ) {
775                         $search_sql = $this->get_search_sql(
776                                 $this->query_vars['search'],
777                                 array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
778                         );
779
780                         // Strip leading 'AND'.
781                         $where[] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
782                 }
783
784                 // If any post-related query vars are passed, join the posts table.
785                 $join_posts_table = false;
786                 $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type' ) );
787                 $post_fields = array_filter( $plucked );
788
789                 if ( ! empty( $post_fields ) ) {
790                         $join_posts_table = true;
791                         foreach ( $post_fields as $field_name => $field_value ) {
792                                 // $field_value may be an array.
793                                 $esses = array_fill( 0, count( (array) $field_value ), '%s' );
794                                 $where[] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
795                         }
796                 }
797
798                 // Comment author IDs for an IN clause.
799                 if ( ! empty( $this->query_vars['author__in'] ) ) {
800                         $where[] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
801                 }
802
803                 // Comment author IDs for a NOT IN clause.
804                 if ( ! empty( $this->query_vars['author__not_in'] ) ) {
805                         $where[] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
806                 }
807
808                 // Post author IDs for an IN clause.
809                 if ( ! empty( $this->query_vars['post_author__in'] ) ) {
810                         $join_posts_table = true;
811                         $where[] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
812                 }
813
814                 // Post author IDs for a NOT IN clause.
815                 if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
816                         $join_posts_table = true;
817                         $where[] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
818                 }
819
820                 if ( $join_posts_table ) {
821                         $join = "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
822                 }
823
824                 if ( ! empty( $meta_query_clauses ) ) {
825                         $join .= $meta_query_clauses['join'];
826
827                         // Strip leading 'AND'.
828                         $where[] = preg_replace( '/^\s*AND\s*/', '', $meta_query_clauses['where'] );
829
830                         if ( ! $this->query_vars['count'] ) {
831                                 $groupby = "{$wpdb->comments}.comment_ID";
832                         }
833                 }
834
835                 $date_query = $this->query_vars['date_query'];
836                 if ( ! empty( $date_query ) && is_array( $date_query ) ) {
837                         $date_query_object = new WP_Date_Query( $date_query, 'comment_date' );
838                         $where[] = preg_replace( '/^\s*AND\s*/', '', $date_query_object->get_sql() );
839                 }
840
841                 $where = implode( ' AND ', $where );
842
843                 $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
844                 /**
845                  * Filter the comment query clauses.
846                  *
847                  * @since 3.1.0
848                  *
849                  * @param array            $pieces A compacted array of comment query clauses.
850                  * @param WP_Comment_Query &$this  Current instance of WP_Comment_Query, passed by reference.
851                  */
852                 $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
853
854                 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
855                 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
856                 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
857                 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
858                 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
859                 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
860
861                 if ( $where ) {
862                         $where = 'WHERE ' . $where;
863                 }
864
865                 if ( $groupby ) {
866                         $groupby = 'GROUP BY ' . $groupby;
867                 }
868
869                 if ( $orderby ) {
870                         $orderby = "ORDER BY $orderby";
871                 }
872
873                 $this->request = "SELECT $fields FROM $wpdb->comments $join $where $groupby $orderby $limits";
874
875                 if ( $this->query_vars['count'] ) {
876                         return $wpdb->get_var( $this->request );
877                 }
878
879                 if ( 'ids' == $this->query_vars['fields'] ) {
880                         $this->comments = $wpdb->get_col( $this->request );
881                         return array_map( 'intval', $this->comments );
882                 }
883
884                 $results = $wpdb->get_results( $this->request );
885                 /**
886                  * Filter the comment query results.
887                  *
888                  * @since 3.1.0
889                  *
890                  * @param array            $results  An array of comments.
891                  * @param WP_Comment_Query &$this    Current instance of WP_Comment_Query, passed by reference.
892                  */
893                 $comments = apply_filters_ref_array( 'the_comments', array( $results, &$this ) );
894
895                 wp_cache_add( $cache_key, $comments, 'comment' );
896
897                 $this->comments = $comments;
898                 return $this->comments;
899         }
900
901         /**
902          * Used internally to generate an SQL string for searching across multiple columns
903          *
904          * @access protected
905          * @since 3.1.0
906          *
907          * @param string $string
908          * @param array $cols
909          * @return string
910          */
911         protected function get_search_sql( $string, $cols ) {
912                 global $wpdb;
913
914                 $like = '%' . $wpdb->esc_like( $string ) . '%';
915
916                 $searches = array();
917                 foreach ( $cols as $col ) {
918                         $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
919                 }
920
921                 return ' AND (' . implode(' OR ', $searches) . ')';
922         }
923
924         /**
925          * Parse and sanitize 'orderby' keys passed to the comment query.
926          *
927          * @since 4.2.0
928          * @access protected
929          *
930          * @global wpdb $wpdb WordPress database abstraction object.
931          *
932          * @param string $orderby Alias for the field to order by.
933          * @return string|bool Value to used in the ORDER clause. False otherwise.
934          */
935         protected function parse_orderby( $orderby ) {
936                 global $wpdb;
937
938                 $allowed_keys = array(
939                         'comment_agent',
940                         'comment_approved',
941                         'comment_author',
942                         'comment_author_email',
943                         'comment_author_IP',
944                         'comment_author_url',
945                         'comment_content',
946                         'comment_date',
947                         'comment_date_gmt',
948                         'comment_ID',
949                         'comment_karma',
950                         'comment_parent',
951                         'comment_post_ID',
952                         'comment_type',
953                         'user_id',
954                 );
955
956                 if ( ! empty( $this->query_vars['meta_key'] ) ) {
957                         $allowed_keys[] = $this->query_vars['meta_key'];
958                         $allowed_keys[] = 'meta_value';
959                         $allowed_keys[] = 'meta_value_num';
960                 }
961
962                 $meta_query_clauses = $this->meta_query->get_clauses();
963                 if ( $meta_query_clauses ) {
964                         $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
965                 }
966
967                 $parsed = false;
968                 if ( $orderby == $this->query_vars['meta_key'] || $orderby == 'meta_value' ) {
969                         $parsed = "$wpdb->commentmeta.meta_value";
970                 } else if ( $orderby == 'meta_value_num' ) {
971                         $parsed = "$wpdb->commentmeta.meta_value+0";
972                 } else if ( in_array( $orderby, $allowed_keys ) ) {
973
974                         if ( isset( $meta_query_clauses[ $orderby ] ) ) {
975                                 $meta_clause = $meta_query_clauses[ $orderby ];
976                                 $parsed = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
977                         } else {
978                                 $parsed = "$wpdb->comments.$orderby";
979                         }
980                 }
981
982                 return $parsed;
983         }
984
985         /**
986          * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
987          *
988          * @since 4.2.0
989          * @access protected
990          *
991          * @param string $order The 'order' query variable.
992          * @return string The sanitized 'order' query variable.
993          */
994         protected function parse_order( $order ) {
995                 if ( ! is_string( $order ) || empty( $order ) ) {
996                         return 'DESC';
997                 }
998
999                 if ( 'ASC' === strtoupper( $order ) ) {
1000                         return 'ASC';
1001                 } else {
1002                         return 'DESC';
1003                 }
1004         }
1005 }
1006
1007 /**
1008  * Retrieve all of the WordPress supported comment statuses.
1009  *
1010  * Comments have a limited set of valid status values, this provides the comment
1011  * status values and descriptions.
1012  *
1013  * @since 2.7.0
1014  *
1015  * @return array List of comment statuses.
1016  */
1017 function get_comment_statuses() {
1018         $status = array(
1019                 'hold'          => __('Unapproved'),
1020                 /* translators: comment status  */
1021                 'approve'       => _x('Approved', 'adjective'),
1022                 /* translators: comment status */
1023                 'spam'          => _x('Spam', 'adjective'),
1024         );
1025
1026         return $status;
1027 }
1028
1029 /**
1030  * The date the last comment was modified.
1031  *
1032  * @since 1.5.0
1033  *
1034  * @global wpdb $wpdb WordPress database abstraction object.
1035  *
1036  * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
1037  *              or 'server' locations.
1038  * @return string Last comment modified date.
1039  */
1040 function get_lastcommentmodified($timezone = 'server') {
1041         global $wpdb;
1042         static $cache_lastcommentmodified = array();
1043
1044         if ( isset($cache_lastcommentmodified[$timezone]) )
1045                 return $cache_lastcommentmodified[$timezone];
1046
1047         $add_seconds_server = date('Z');
1048
1049         switch ( strtolower($timezone)) {
1050                 case 'gmt':
1051                         $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
1052                         break;
1053                 case 'blog':
1054                         $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
1055                         break;
1056                 case 'server':
1057                         $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));
1058                         break;
1059         }
1060
1061         $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
1062
1063         return $lastcommentmodified;
1064 }
1065
1066 /**
1067  * The amount of comments in a post or total comments.
1068  *
1069  * A lot like {@link wp_count_comments()}, in that they both return comment
1070  * stats (albeit with different types). The {@link wp_count_comments()} actual
1071  * caches, but this function does not.
1072  *
1073  * @since 2.0.0
1074  *
1075  * @global wpdb $wpdb WordPress database abstraction object.
1076  *
1077  * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
1078  * @return array The amount of spam, approved, awaiting moderation, and total comments.
1079  */
1080 function get_comment_count( $post_id = 0 ) {
1081         global $wpdb;
1082
1083         $post_id = (int) $post_id;
1084
1085         $where = '';
1086         if ( $post_id > 0 ) {
1087                 $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
1088         }
1089
1090         $totals = (array) $wpdb->get_results("
1091                 SELECT comment_approved, COUNT( * ) AS total
1092                 FROM {$wpdb->comments}
1093                 {$where}
1094                 GROUP BY comment_approved
1095         ", ARRAY_A);
1096
1097         $comment_count = array(
1098                 "approved"              => 0,
1099                 "awaiting_moderation"   => 0,
1100                 "spam"                  => 0,
1101                 "total_comments"        => 0
1102         );
1103
1104         foreach ( $totals as $row ) {
1105                 switch ( $row['comment_approved'] ) {
1106                         case 'spam':
1107                                 $comment_count['spam'] = $row['total'];
1108                                 $comment_count["total_comments"] += $row['total'];
1109                                 break;
1110                         case 1:
1111                                 $comment_count['approved'] = $row['total'];
1112                                 $comment_count['total_comments'] += $row['total'];
1113                                 break;
1114                         case 0:
1115                                 $comment_count['awaiting_moderation'] = $row['total'];
1116                                 $comment_count['total_comments'] += $row['total'];
1117                                 break;
1118                         default:
1119                                 break;
1120                 }
1121         }
1122
1123         return $comment_count;
1124 }
1125
1126 //
1127 // Comment meta functions
1128 //
1129
1130 /**
1131  * Add meta data field to a comment.
1132  *
1133  * @since 2.9.0
1134  * @link https://codex.wordpress.org/Function_Reference/add_comment_meta
1135  *
1136  * @param int $comment_id Comment ID.
1137  * @param string $meta_key Metadata name.
1138  * @param mixed $meta_value Metadata value.
1139  * @param bool $unique Optional, default is false. Whether the same key should not be added.
1140  * @return int|bool Meta ID on success, false on failure.
1141  */
1142 function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
1143         return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
1144 }
1145
1146 /**
1147  * Remove metadata matching criteria from a comment.
1148  *
1149  * You can match based on the key, or key and value. Removing based on key and
1150  * value, will keep from removing duplicate metadata with the same key. It also
1151  * allows removing all metadata matching key, if needed.
1152  *
1153  * @since 2.9.0
1154  * @link https://codex.wordpress.org/Function_Reference/delete_comment_meta
1155  *
1156  * @param int $comment_id comment ID
1157  * @param string $meta_key Metadata name.
1158  * @param mixed $meta_value Optional. Metadata value.
1159  * @return bool True on success, false on failure.
1160  */
1161 function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
1162         return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
1163 }
1164
1165 /**
1166  * Retrieve comment meta field for a comment.
1167  *
1168  * @since 2.9.0
1169  * @link https://codex.wordpress.org/Function_Reference/get_comment_meta
1170  *
1171  * @param int $comment_id Comment ID.
1172  * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
1173  * @param bool $single Whether to return a single value.
1174  * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
1175  *  is true.
1176  */
1177 function get_comment_meta($comment_id, $key = '', $single = false) {
1178         return get_metadata('comment', $comment_id, $key, $single);
1179 }
1180
1181 /**
1182  * Update comment meta field based on comment ID.
1183  *
1184  * Use the $prev_value parameter to differentiate between meta fields with the
1185  * same key and comment ID.
1186  *
1187  * If the meta field for the comment does not exist, it will be added.
1188  *
1189  * @since 2.9.0
1190  * @link https://codex.wordpress.org/Function_Reference/update_comment_meta
1191  *
1192  * @param int $comment_id Comment ID.
1193  * @param string $meta_key Metadata key.
1194  * @param mixed $meta_value Metadata value.
1195  * @param mixed $prev_value Optional. Previous value to check before removing.
1196  * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
1197  */
1198 function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
1199         return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
1200 }
1201
1202 /**
1203  * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
1204  * to recall previous comments by this commentator that are still held in moderation.
1205  *
1206  * @param object $comment Comment object.
1207  * @param object $user Comment author's object.
1208  *
1209  * @since 3.4.0
1210  */
1211 function wp_set_comment_cookies($comment, $user) {
1212         if ( $user->exists() )
1213                 return;
1214
1215         /**
1216          * Filter the lifetime of the comment cookie in seconds.
1217          *
1218          * @since 2.8.0
1219          *
1220          * @param int $seconds Comment cookie lifetime. Default 30000000.
1221          */
1222         $comment_cookie_lifetime = apply_filters( 'comment_cookie_lifetime', 30000000 );
1223         $secure = ( 'https' === parse_url( home_url(), PHP_URL_SCHEME ) );
1224         setcookie( 'comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
1225         setcookie( 'comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
1226         setcookie( 'comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
1227 }
1228
1229 /**
1230  * Sanitizes the cookies sent to the user already.
1231  *
1232  * Will only do anything if the cookies have already been created for the user.
1233  * Mostly used after cookies had been sent to use elsewhere.
1234  *
1235  * @since 2.0.4
1236  */
1237 function sanitize_comment_cookies() {
1238         if ( isset( $_COOKIE['comment_author_' . COOKIEHASH] ) ) {
1239                 /**
1240                  * Filter the comment author's name cookie before it is set.
1241                  *
1242                  * When this filter hook is evaluated in wp_filter_comment(),
1243                  * the comment author's name string is passed.
1244                  *
1245                  * @since 1.5.0
1246                  *
1247                  * @param string $author_cookie The comment author name cookie.
1248                  */
1249                 $comment_author = apply_filters( 'pre_comment_author_name', $_COOKIE['comment_author_' . COOKIEHASH] );
1250                 $comment_author = wp_unslash($comment_author);
1251                 $comment_author = esc_attr($comment_author);
1252                 $_COOKIE['comment_author_' . COOKIEHASH] = $comment_author;
1253         }
1254
1255         if ( isset( $_COOKIE['comment_author_email_' . COOKIEHASH] ) ) {
1256                 /**
1257                  * Filter the comment author's email cookie before it is set.
1258                  *
1259                  * When this filter hook is evaluated in wp_filter_comment(),
1260                  * the comment author's email string is passed.
1261                  *
1262                  * @since 1.5.0
1263                  *
1264                  * @param string $author_email_cookie The comment author email cookie.
1265                  */
1266                 $comment_author_email = apply_filters( 'pre_comment_author_email', $_COOKIE['comment_author_email_' . COOKIEHASH] );
1267                 $comment_author_email = wp_unslash($comment_author_email);
1268                 $comment_author_email = esc_attr($comment_author_email);
1269                 $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
1270         }
1271
1272         if ( isset( $_COOKIE['comment_author_url_' . COOKIEHASH] ) ) {
1273                 /**
1274                  * Filter the comment author's URL cookie before it is set.
1275                  *
1276                  * When this filter hook is evaluated in wp_filter_comment(),
1277                  * the comment author's URL string is passed.
1278                  *
1279                  * @since 1.5.0
1280                  *
1281                  * @param string $author_url_cookie The comment author URL cookie.
1282                  */
1283                 $comment_author_url = apply_filters( 'pre_comment_author_url', $_COOKIE['comment_author_url_' . COOKIEHASH] );
1284                 $comment_author_url = wp_unslash($comment_author_url);
1285                 $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
1286         }
1287 }
1288
1289 /**
1290  * Validates whether this comment is allowed to be made.
1291  *
1292  * @since 2.0.0
1293  *
1294  * @global wpdb $wpdb WordPress database abstraction object.
1295  *
1296  * @param array $commentdata Contains information on the comment
1297  * @return mixed Signifies the approval status (0|1|'spam')
1298  */
1299 function wp_allow_comment( $commentdata ) {
1300         global $wpdb;
1301
1302         // Simple duplicate check
1303         // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
1304         $dupe = $wpdb->prepare(
1305                 "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ",
1306                 wp_unslash( $commentdata['comment_post_ID'] ),
1307                 wp_unslash( $commentdata['comment_parent'] ),
1308                 wp_unslash( $commentdata['comment_author'] )
1309         );
1310         if ( $commentdata['comment_author_email'] ) {
1311                 $dupe .= $wpdb->prepare(
1312                         "OR comment_author_email = %s ",
1313                         wp_unslash( $commentdata['comment_author_email'] )
1314                 );
1315         }
1316         $dupe .= $wpdb->prepare(
1317                 ") AND comment_content = %s LIMIT 1",
1318                 wp_unslash( $commentdata['comment_content'] )
1319         );
1320         if ( $wpdb->get_var( $dupe ) ) {
1321                 /**
1322                  * Fires immediately after a duplicate comment is detected.
1323                  *
1324                  * @since 3.0.0
1325                  *
1326                  * @param array $commentdata Comment data.
1327                  */
1328                 do_action( 'comment_duplicate_trigger', $commentdata );
1329                 if ( defined( 'DOING_AJAX' ) ) {
1330                         die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
1331                 }
1332                 wp_die( __( 'Duplicate comment detected; it looks as though you&#8217;ve already said that!' ), 409 );
1333         }
1334
1335         /**
1336          * Fires immediately before a comment is marked approved.
1337          *
1338          * Allows checking for comment flooding.
1339          *
1340          * @since 2.3.0
1341          *
1342          * @param string $comment_author_IP    Comment author's IP address.
1343          * @param string $comment_author_email Comment author's email.
1344          * @param string $comment_date_gmt     GMT date the comment was posted.
1345          */
1346         do_action(
1347                 'check_comment_flood',
1348                 $commentdata['comment_author_IP'],
1349                 $commentdata['comment_author_email'],
1350                 $commentdata['comment_date_gmt']
1351         );
1352
1353         if ( ! empty( $commentdata['user_id'] ) ) {
1354                 $user = get_userdata( $commentdata['user_id'] );
1355                 $post_author = $wpdb->get_var( $wpdb->prepare(
1356                         "SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1",
1357                         $commentdata['comment_post_ID']
1358                 ) );
1359         }
1360
1361         if ( isset( $user ) && ( $commentdata['user_id'] == $post_author || $user->has_cap( 'moderate_comments' ) ) ) {
1362                 // The author and the admins get respect.
1363                 $approved = 1;
1364         } else {
1365                 // Everyone else's comments will be checked.
1366                 if ( check_comment(
1367                         $commentdata['comment_author'],
1368                         $commentdata['comment_author_email'],
1369                         $commentdata['comment_author_url'],
1370                         $commentdata['comment_content'],
1371                         $commentdata['comment_author_IP'],
1372                         $commentdata['comment_agent'],
1373                         $commentdata['comment_type']
1374                 ) ) {
1375                         $approved = 1;
1376                 } else {
1377                         $approved = 0;
1378                 }
1379
1380                 if ( wp_blacklist_check(
1381                         $commentdata['comment_author'],
1382                         $commentdata['comment_author_email'],
1383                         $commentdata['comment_author_url'],
1384                         $commentdata['comment_content'],
1385                         $commentdata['comment_author_IP'],
1386                         $commentdata['comment_agent']
1387                 ) ) {
1388                         $approved = 'spam';
1389                 }
1390         }
1391
1392         /**
1393          * Filter a comment's approval status before it is set.
1394          *
1395          * @since 2.1.0
1396          *
1397          * @param bool|string $approved    The approval status. Accepts 1, 0, or 'spam'.
1398          * @param array       $commentdata Comment data.
1399          */
1400         $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
1401         return $approved;
1402 }
1403
1404 /**
1405  * Check whether comment flooding is occurring.
1406  *
1407  * Won't run, if current user can manage options, so to not block
1408  * administrators.
1409  *
1410  * @since 2.3.0
1411  *
1412  * @global wpdb $wpdb WordPress database abstraction object.
1413  *
1414  * @param string $ip Comment IP.
1415  * @param string $email Comment author email address.
1416  * @param string $date MySQL time string.
1417  */
1418 function check_comment_flood_db( $ip, $email, $date ) {
1419         global $wpdb;
1420         if ( current_user_can( 'manage_options' ) )
1421                 return; // don't throttle admins
1422         $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
1423         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 ) ) ) {
1424                 $time_lastcomment = mysql2date('U', $lasttime, false);
1425                 $time_newcomment  = mysql2date('U', $date, false);
1426                 /**
1427                  * Filter the comment flood status.
1428                  *
1429                  * @since 2.1.0
1430                  *
1431                  * @param bool $bool             Whether a comment flood is occurring. Default false.
1432                  * @param int  $time_lastcomment Timestamp of when the last comment was posted.
1433                  * @param int  $time_newcomment  Timestamp of when the new comment was posted.
1434                  */
1435                 $flood_die = apply_filters( 'comment_flood_filter', false, $time_lastcomment, $time_newcomment );
1436                 if ( $flood_die ) {
1437                         /**
1438                          * Fires before the comment flood message is triggered.
1439                          *
1440                          * @since 1.5.0
1441                          *
1442                          * @param int $time_lastcomment Timestamp of when the last comment was posted.
1443                          * @param int $time_newcomment  Timestamp of when the new comment was posted.
1444                          */
1445                         do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment );
1446
1447                         if ( defined('DOING_AJAX') )
1448                                 die( __('You are posting comments too quickly. Slow down.') );
1449
1450                         wp_die( __( 'You are posting comments too quickly. Slow down.' ), 429 );
1451                 }
1452         }
1453 }
1454
1455 /**
1456  * Separates an array of comments into an array keyed by comment_type.
1457  *
1458  * @since 2.7.0
1459  *
1460  * @param array $comments Array of comments
1461  * @return array Array of comments keyed by comment_type.
1462  */
1463 function separate_comments(&$comments) {
1464         $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
1465         $count = count($comments);
1466         for ( $i = 0; $i < $count; $i++ ) {
1467                 $type = $comments[$i]->comment_type;
1468                 if ( empty($type) )
1469                         $type = 'comment';
1470                 $comments_by_type[$type][] = &$comments[$i];
1471                 if ( 'trackback' == $type || 'pingback' == $type )
1472                         $comments_by_type['pings'][] = &$comments[$i];
1473         }
1474
1475         return $comments_by_type;
1476 }
1477
1478 /**
1479  * Calculate the total number of comment pages.
1480  *
1481  * @since 2.7.0
1482  *
1483  * @uses Walker_Comment
1484  *
1485  * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
1486  * @param int $per_page Optional comments per page.
1487  * @param boolean $threaded Optional control over flat or threaded comments.
1488  * @return int Number of comment pages.
1489  */
1490 function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
1491         global $wp_query;
1492
1493         if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
1494                 return $wp_query->max_num_comment_pages;
1495
1496         if ( ( ! $comments || ! is_array( $comments ) ) && ! empty( $wp_query->comments )  )
1497                 $comments = $wp_query->comments;
1498
1499         if ( empty($comments) )
1500                 return 0;
1501
1502         if ( ! get_option( 'page_comments' ) )
1503                 return 1;
1504
1505         if ( !isset($per_page) )
1506                 $per_page = (int) get_query_var('comments_per_page');
1507         if ( 0 === $per_page )
1508                 $per_page = (int) get_option('comments_per_page');
1509         if ( 0 === $per_page )
1510                 return 1;
1511
1512         if ( !isset($threaded) )
1513                 $threaded = get_option('thread_comments');
1514
1515         if ( $threaded ) {
1516                 $walker = new Walker_Comment;
1517                 $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
1518         } else {
1519                 $count = ceil( count( $comments ) / $per_page );
1520         }
1521
1522         return $count;
1523 }
1524
1525 /**
1526  * Calculate what page number a comment will appear on for comment paging.
1527  *
1528  * @since 2.7.0
1529  *
1530  * @param int $comment_ID Comment ID.
1531  * @param array $args Optional args.
1532  * @return int|null Comment page number or null on error.
1533  */
1534 function get_page_of_comment( $comment_ID, $args = array() ) {
1535         global $wpdb;
1536
1537         if ( !$comment = get_comment( $comment_ID ) )
1538                 return;
1539
1540         $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
1541         $args = wp_parse_args( $args, $defaults );
1542
1543         if ( '' === $args['per_page'] && get_option('page_comments') )
1544                 $args['per_page'] = get_query_var('comments_per_page');
1545         if ( empty($args['per_page']) ) {
1546                 $args['per_page'] = 0;
1547                 $args['page'] = 0;
1548         }
1549         if ( $args['per_page'] < 1 )
1550                 return 1;
1551
1552         if ( '' === $args['max_depth'] ) {
1553                 if ( get_option('thread_comments') )
1554                         $args['max_depth'] = get_option('thread_comments_depth');
1555                 else
1556                         $args['max_depth'] = -1;
1557         }
1558
1559         // Find this comment's top level parent if threading is enabled
1560         if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
1561                 return get_page_of_comment( $comment->comment_parent, $args );
1562
1563         $allowedtypes = array(
1564                 'comment' => '',
1565                 'pingback' => 'pingback',
1566                 'trackback' => 'trackback',
1567         );
1568
1569         $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
1570
1571         // Count comments older than this one
1572         $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 ) );
1573
1574         // No older comments? Then it's page #1.
1575         if ( 0 == $oldercoms )
1576                 return 1;
1577
1578         // Divide comments older than this one by comments per page to get this comment's page number
1579         return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
1580 }
1581
1582 /**
1583  * Does comment contain blacklisted characters or words.
1584  *
1585  * @since 1.5.0
1586  *
1587  * @param string $author The author of the comment
1588  * @param string $email The email of the comment
1589  * @param string $url The url used in the comment
1590  * @param string $comment The comment content
1591  * @param string $user_ip The comment author IP address
1592  * @param string $user_agent The author's browser user agent
1593  * @return bool True if comment contains blacklisted content, false if comment does not
1594  */
1595 function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
1596         /**
1597          * Fires before the comment is tested for blacklisted characters or words.
1598          *
1599          * @since 1.5.0
1600          *
1601          * @param string $author     Comment author.
1602          * @param string $email      Comment author's email.
1603          * @param string $url        Comment author's URL.
1604          * @param string $comment    Comment content.
1605          * @param string $user_ip    Comment author's IP address.
1606          * @param string $user_agent Comment author's browser user agent.
1607          */
1608         do_action( 'wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent );
1609
1610         $mod_keys = trim( get_option('blacklist_keys') );
1611         if ( '' == $mod_keys )
1612                 return false; // If moderation keys are empty
1613         $words = explode("\n", $mod_keys );
1614
1615         foreach ( (array) $words as $word ) {
1616                 $word = trim($word);
1617
1618                 // Skip empty lines
1619                 if ( empty($word) ) { continue; }
1620
1621                 // Do some escaping magic so that '#' chars in the
1622                 // spam words don't break things:
1623                 $word = preg_quote($word, '#');
1624
1625                 $pattern = "#$word#i";
1626                 if (
1627                            preg_match($pattern, $author)
1628                         || preg_match($pattern, $email)
1629                         || preg_match($pattern, $url)
1630                         || preg_match($pattern, $comment)
1631                         || preg_match($pattern, $user_ip)
1632                         || preg_match($pattern, $user_agent)
1633                  )
1634                         return true;
1635         }
1636         return false;
1637 }
1638
1639 /**
1640  * Retrieve total comments for blog or single post.
1641  *
1642  * The properties of the returned object contain the 'moderated', 'approved',
1643  * and spam comments for either the entire blog or single post. Those properties
1644  * contain the amount of comments that match the status. The 'total_comments'
1645  * property contains the integer of total comments.
1646  *
1647  * The comment stats are cached and then retrieved, if they already exist in the
1648  * cache.
1649  *
1650  * @since 2.5.0
1651  *
1652  * @param int $post_id Optional. Post ID.
1653  * @return object Comment stats.
1654  */
1655 function wp_count_comments( $post_id = 0 ) {
1656         global $wpdb;
1657
1658         $post_id = (int) $post_id;
1659
1660         /**
1661          * Filter the comments count for a given post.
1662          *
1663          * @since 2.7.0
1664          *
1665          * @param array $count   An empty array.
1666          * @param int   $post_id The post ID.
1667          */
1668         $stats = apply_filters( 'wp_count_comments', array(), $post_id );
1669         if ( !empty($stats) )
1670                 return $stats;
1671
1672         $count = wp_cache_get("comments-{$post_id}", 'counts');
1673
1674         if ( false !== $count )
1675                 return $count;
1676
1677         $where = '';
1678         if ( $post_id > 0 )
1679                 $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
1680
1681         $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
1682
1683         $total = 0;
1684         $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
1685         foreach ( (array) $count as $row ) {
1686                 // Don't count post-trashed toward totals
1687                 if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
1688                         $total += $row['num_comments'];
1689                 if ( isset( $approved[$row['comment_approved']] ) )
1690                         $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
1691         }
1692
1693         $stats['total_comments'] = $total;
1694         foreach ( $approved as $key ) {
1695                 if ( empty($stats[$key]) )
1696                         $stats[$key] = 0;
1697         }
1698
1699         $stats = (object) $stats;
1700         wp_cache_set("comments-{$post_id}", $stats, 'counts');
1701
1702         return $stats;
1703 }
1704
1705 /**
1706  * Trashes or deletes a comment.
1707  *
1708  * The comment is moved to trash instead of permanently deleted unless trash is
1709  * disabled, item is already in the trash, or $force_delete is true.
1710  *
1711  * The post comment count will be updated if the comment was approved and has a
1712  * post ID available.
1713  *
1714  * @since 2.0.0
1715  *
1716  * @global wpdb $wpdb WordPress database abstraction object.
1717  *
1718  * @param int $comment_id Comment ID
1719  * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
1720  * @return bool True on success, false on failure.
1721  */
1722 function wp_delete_comment($comment_id, $force_delete = false) {
1723         global $wpdb;
1724         if (!$comment = get_comment($comment_id))
1725                 return false;
1726
1727         if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) )
1728                 return wp_trash_comment($comment_id);
1729
1730         /**
1731          * Fires immediately before a comment is deleted from the database.
1732          *
1733          * @since 1.2.0
1734          *
1735          * @param int $comment_id The comment ID.
1736          */
1737         do_action( 'delete_comment', $comment_id );
1738
1739         // Move children up a level.
1740         $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
1741         if ( !empty($children) ) {
1742                 $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
1743                 clean_comment_cache($children);
1744         }
1745
1746         // Delete metadata
1747         $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment_id ) );
1748         foreach ( $meta_ids as $mid )
1749                 delete_metadata_by_mid( 'comment', $mid );
1750
1751         if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment_id ) ) )
1752                 return false;
1753
1754         /**
1755          * Fires immediately after a comment is deleted from the database.
1756          *
1757          * @since 2.9.0
1758          *
1759          * @param int $comment_id The comment ID.
1760          */
1761         do_action( 'deleted_comment', $comment_id );
1762
1763         $post_id = $comment->comment_post_ID;
1764         if ( $post_id && $comment->comment_approved == 1 )
1765                 wp_update_comment_count($post_id);
1766
1767         clean_comment_cache($comment_id);
1768
1769         /** This action is documented in wp-includes/comment.php */
1770         do_action( 'wp_set_comment_status', $comment_id, 'delete' );
1771
1772         wp_transition_comment_status('delete', $comment->comment_approved, $comment);
1773         return true;
1774 }
1775
1776 /**
1777  * Moves a comment to the Trash
1778  *
1779  * If trash is disabled, comment is permanently deleted.
1780  *
1781  * @since 2.9.0
1782  *
1783  * @param int $comment_id Comment ID.
1784  * @return bool True on success, false on failure.
1785  */
1786 function wp_trash_comment($comment_id) {
1787         if ( !EMPTY_TRASH_DAYS )
1788                 return wp_delete_comment($comment_id, true);
1789
1790         if ( !$comment = get_comment($comment_id) )
1791                 return false;
1792
1793         /**
1794          * Fires immediately before a comment is sent to the Trash.
1795          *
1796          * @since 2.9.0
1797          *
1798          * @param int $comment_id The comment ID.
1799          */
1800         do_action( 'trash_comment', $comment_id );
1801
1802         if ( wp_set_comment_status($comment_id, 'trash') ) {
1803                 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
1804                 add_comment_meta($comment_id, '_wp_trash_meta_time', time() );
1805
1806                 /**
1807                  * Fires immediately after a comment is sent to Trash.
1808                  *
1809                  * @since 2.9.0
1810                  *
1811                  * @param int $comment_id The comment ID.
1812                  */
1813                 do_action( 'trashed_comment', $comment_id );
1814                 return true;
1815         }
1816
1817         return false;
1818 }
1819
1820 /**
1821  * Removes a comment from the Trash
1822  *
1823  * @since 2.9.0
1824  *
1825  * @param int $comment_id Comment ID.
1826  * @return bool True on success, false on failure.
1827  */
1828 function wp_untrash_comment($comment_id) {
1829         if ( ! (int)$comment_id )
1830                 return false;
1831
1832         /**
1833          * Fires immediately before a comment is restored from the Trash.
1834          *
1835          * @since 2.9.0
1836          *
1837          * @param int $comment_id The comment ID.
1838          */
1839         do_action( 'untrash_comment', $comment_id );
1840
1841         $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
1842         if ( empty($status) )
1843                 $status = '0';
1844
1845         if ( wp_set_comment_status($comment_id, $status) ) {
1846                 delete_comment_meta($comment_id, '_wp_trash_meta_time');
1847                 delete_comment_meta($comment_id, '_wp_trash_meta_status');
1848                 /**
1849                  * Fires immediately after a comment is restored from the Trash.
1850                  *
1851                  * @since 2.9.0
1852                  *
1853                  * @param int $comment_id The comment ID.
1854                  */
1855                 do_action( 'untrashed_comment', $comment_id );
1856                 return true;
1857         }
1858
1859         return false;
1860 }
1861
1862 /**
1863  * Marks a comment as Spam
1864  *
1865  * @since 2.9.0
1866  *
1867  * @param int $comment_id Comment ID.
1868  * @return bool True on success, false on failure.
1869  */
1870 function wp_spam_comment($comment_id) {
1871         if ( !$comment = get_comment($comment_id) )
1872                 return false;
1873
1874         /**
1875          * Fires immediately before a comment is marked as Spam.
1876          *
1877          * @since 2.9.0
1878          *
1879          * @param int $comment_id The comment ID.
1880          */
1881         do_action( 'spam_comment', $comment_id );
1882
1883         if ( wp_set_comment_status($comment_id, 'spam') ) {
1884                 add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
1885                 /**
1886                  * Fires immediately after a comment is marked as Spam.
1887                  *
1888                  * @since 2.9.0
1889                  *
1890                  * @param int $comment_id The comment ID.
1891                  */
1892                 do_action( 'spammed_comment', $comment_id );
1893                 return true;
1894         }
1895
1896         return false;
1897 }
1898
1899 /**
1900  * Removes a comment from the Spam
1901  *
1902  * @since 2.9.0
1903  *
1904  * @param int $comment_id Comment ID.
1905  * @return bool True on success, false on failure.
1906  */
1907 function wp_unspam_comment($comment_id) {
1908         if ( ! (int)$comment_id )
1909                 return false;
1910
1911         /**
1912          * Fires immediately before a comment is unmarked as Spam.
1913          *
1914          * @since 2.9.0
1915          *
1916          * @param int $comment_id The comment ID.
1917          */
1918         do_action( 'unspam_comment', $comment_id );
1919
1920         $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
1921         if ( empty($status) )
1922                 $status = '0';
1923
1924         if ( wp_set_comment_status($comment_id, $status) ) {
1925                 delete_comment_meta($comment_id, '_wp_trash_meta_status');
1926                 /**
1927                  * Fires immediately after a comment is unmarked as Spam.
1928                  *
1929                  * @since 2.9.0
1930                  *
1931                  * @param int $comment_id The comment ID.
1932                  */
1933                 do_action( 'unspammed_comment', $comment_id );
1934                 return true;
1935         }
1936
1937         return false;
1938 }
1939
1940 /**
1941  * The status of a comment by ID.
1942  *
1943  * @since 1.0.0
1944  *
1945  * @param int $comment_id Comment ID
1946  * @return false|string Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
1947  */
1948 function wp_get_comment_status($comment_id) {
1949         $comment = get_comment($comment_id);
1950         if ( !$comment )
1951                 return false;
1952
1953         $approved = $comment->comment_approved;
1954
1955         if ( $approved == null )
1956                 return false;
1957         elseif ( $approved == '1' )
1958                 return 'approved';
1959         elseif ( $approved == '0' )
1960                 return 'unapproved';
1961         elseif ( $approved == 'spam' )
1962                 return 'spam';
1963         elseif ( $approved == 'trash' )
1964                 return 'trash';
1965         else
1966                 return false;
1967 }
1968
1969 /**
1970  * Call hooks for when a comment status transition occurs.
1971  *
1972  * Calls hooks for comment status transitions. If the new comment status is not the same
1973  * as the previous comment status, then two hooks will be ran, the first is
1974  * 'transition_comment_status' with new status, old status, and comment data. The
1975  * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
1976  * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
1977  * comment data.
1978  *
1979  * The final action will run whether or not the comment statuses are the same. The
1980  * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
1981  * parameter and COMMENTTYPE is comment_type comment data.
1982  *
1983  * @since 2.7.0
1984  *
1985  * @param string $new_status New comment status.
1986  * @param string $old_status Previous comment status.
1987  * @param object $comment Comment data.
1988  */
1989 function wp_transition_comment_status($new_status, $old_status, $comment) {
1990         /*
1991          * Translate raw statuses to human readable formats for the hooks.
1992          * This is not a complete list of comment status, it's only the ones
1993          * that need to be renamed
1994          */
1995         $comment_statuses = array(
1996                 0         => 'unapproved',
1997                 'hold'    => 'unapproved', // wp_set_comment_status() uses "hold"
1998                 1         => 'approved',
1999                 'approve' => 'approved', // wp_set_comment_status() uses "approve"
2000         );
2001         if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
2002         if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
2003
2004         // Call the hooks
2005         if ( $new_status != $old_status ) {
2006                 /**
2007                  * Fires when the comment status is in transition.
2008                  *
2009                  * @since 2.7.0
2010                  *
2011                  * @param int|string $new_status The new comment status.
2012                  * @param int|string $old_status The old comment status.
2013                  * @param object     $comment    The comment data.
2014                  */
2015                 do_action( 'transition_comment_status', $new_status, $old_status, $comment );
2016                 /**
2017                  * Fires when the comment status is in transition from one specific status to another.
2018                  *
2019                  * The dynamic portions of the hook name, `$old_status`, and `$new_status`,
2020                  * refer to the old and new comment statuses, respectively.
2021                  *
2022                  * @since 2.7.0
2023                  *
2024                  * @param object $comment Comment object.
2025                  */
2026                 do_action( "comment_{$old_status}_to_{$new_status}", $comment );
2027         }
2028         /**
2029          * Fires when the status of a specific comment type is in transition.
2030          *
2031          * The dynamic portions of the hook name, `$new_status`, and `$comment->comment_type`,
2032          * refer to the new comment status, and the type of comment, respectively.
2033          *
2034          * Typical comment types include an empty string (standard comment), 'pingback',
2035          * or 'trackback'.
2036          *
2037          * @since 2.7.0
2038          *
2039          * @param int $comment_ID The comment ID.
2040          * @param obj $comment    Comment object.
2041          */
2042         do_action( "comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment );
2043 }
2044
2045 /**
2046  * Get current commenter's name, email, and URL.
2047  *
2048  * Expects cookies content to already be sanitized. User of this function might
2049  * wish to recheck the returned array for validity.
2050  *
2051  * @see sanitize_comment_cookies() Use to sanitize cookies
2052  *
2053  * @since 2.0.4
2054  *
2055  * @return array Comment author, email, url respectively.
2056  */
2057 function wp_get_current_commenter() {
2058         // Cookies should already be sanitized.
2059
2060         $comment_author = '';
2061         if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
2062                 $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
2063
2064         $comment_author_email = '';
2065         if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
2066                 $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
2067
2068         $comment_author_url = '';
2069         if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
2070                 $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
2071
2072         /**
2073          * Filter the current commenter's name, email, and URL.
2074          *
2075          * @since 3.1.0
2076          *
2077          * @param string $comment_author       Comment author's name.
2078          * @param string $comment_author_email Comment author's email.
2079          * @param string $comment_author_url   Comment author's URL.
2080          */
2081         return apply_filters( 'wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url') );
2082 }
2083
2084 /**
2085  * Inserts a comment to the database.
2086  *
2087  * The available comment data key names are 'comment_author_IP', 'comment_date',
2088  * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'.
2089  *
2090  * @since 2.0.0
2091  *
2092  * @global wpdb $wpdb WordPress database abstraction object.
2093  *
2094  * @param array $commentdata Contains information on the comment.
2095  * @return int|bool The new comment's ID on success, false on failure.
2096  */
2097 function wp_insert_comment( $commentdata ) {
2098         global $wpdb;
2099         $data = wp_unslash( $commentdata );
2100
2101         $comment_author       = ! isset( $data['comment_author'] )       ? '' : $data['comment_author'];
2102         $comment_author_email = ! isset( $data['comment_author_email'] ) ? '' : $data['comment_author_email'];
2103         $comment_author_url   = ! isset( $data['comment_author_url'] )   ? '' : $data['comment_author_url'];
2104         $comment_author_IP    = ! isset( $data['comment_author_IP'] )    ? '' : $data['comment_author_IP'];
2105
2106         $comment_date     = ! isset( $data['comment_date'] )     ? current_time( 'mysql' )            : $data['comment_date'];
2107         $comment_date_gmt = ! isset( $data['comment_date_gmt'] ) ? get_gmt_from_date( $comment_date ) : $data['comment_date_gmt'];
2108
2109         $comment_post_ID  = ! isset( $data['comment_post_ID'] )  ? '' : $data['comment_post_ID'];
2110         $comment_content  = ! isset( $data['comment_content'] )  ? '' : $data['comment_content'];
2111         $comment_karma    = ! isset( $data['comment_karma'] )    ? 0  : $data['comment_karma'];
2112         $comment_approved = ! isset( $data['comment_approved'] ) ? 1  : $data['comment_approved'];
2113         $comment_agent    = ! isset( $data['comment_agent'] )    ? '' : $data['comment_agent'];
2114         $comment_type     = ! isset( $data['comment_type'] )     ? '' : $data['comment_type'];
2115         $comment_parent   = ! isset( $data['comment_parent'] )   ? 0  : $data['comment_parent'];
2116
2117         $user_id  = ! isset( $data['user_id'] ) ? 0 : $data['user_id'];
2118
2119         $compacted = compact( 'comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_karma', 'comment_approved', 'comment_agent', 'comment_type', 'comment_parent', 'user_id' );
2120         if ( ! $wpdb->insert( $wpdb->comments, $compacted ) ) {
2121                 $fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' );
2122
2123                 foreach( $fields as $field ) {
2124                         if ( isset( $compacted[ $field ] ) ) {
2125                                 $compacted[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $compacted[ $field ] );
2126                         }
2127                 }
2128
2129                 if ( ! $wpdb->insert( $wpdb->comments, $compacted ) ) {
2130                         return false;
2131                 }
2132         }
2133
2134         $id = (int) $wpdb->insert_id;
2135
2136         if ( $comment_approved == 1 ) {
2137                 wp_update_comment_count( $comment_post_ID );
2138         }
2139         $comment = get_comment( $id );
2140
2141         /**
2142          * Fires immediately after a comment is inserted into the database.
2143          *
2144          * @since 2.8.0
2145          *
2146          * @param int $id      The comment ID.
2147          * @param obj $comment Comment object.
2148          */
2149         do_action( 'wp_insert_comment', $id, $comment );
2150
2151         wp_cache_set( 'last_changed', microtime(), 'comment' );
2152
2153         return $id;
2154 }
2155
2156 /**
2157  * Filters and sanitizes comment data.
2158  *
2159  * Sets the comment data 'filtered' field to true when finished. This can be
2160  * checked as to whether the comment should be filtered and to keep from
2161  * filtering the same comment more than once.
2162  *
2163  * @since 2.0.0
2164  *
2165  * @param array $commentdata Contains information on the comment.
2166  * @return array Parsed comment information.
2167  */
2168 function wp_filter_comment($commentdata) {
2169         if ( isset( $commentdata['user_ID'] ) ) {
2170                 /**
2171                  * Filter the comment author's user id before it is set.
2172                  *
2173                  * The first time this filter is evaluated, 'user_ID' is checked
2174                  * (for back-compat), followed by the standard 'user_id' value.
2175                  *
2176                  * @since 1.5.0
2177                  *
2178                  * @param int $user_ID The comment author's user ID.
2179                  */
2180                 $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_ID'] );
2181         } elseif ( isset( $commentdata['user_id'] ) ) {
2182                 /** This filter is documented in wp-includes/comment.php */
2183                 $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_id'] );
2184         }
2185
2186         /**
2187          * Filter the comment author's browser user agent before it is set.
2188          *
2189          * @since 1.5.0
2190          *
2191          * @param int $comment_agent The comment author's browser user agent.
2192          */
2193         $commentdata['comment_agent'] = apply_filters( 'pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
2194         /** This filter is documented in wp-includes/comment.php */
2195         $commentdata['comment_author'] = apply_filters( 'pre_comment_author_name', $commentdata['comment_author'] );
2196         /**
2197          * Filter the comment content before it is set.
2198          *
2199          * @since 1.5.0
2200          *
2201          * @param int $comment_content The comment content.
2202          */
2203         $commentdata['comment_content'] = apply_filters( 'pre_comment_content', $commentdata['comment_content'] );
2204         /**
2205          * Filter the comment author's IP before it is set.
2206          *
2207          * @since 1.5.0
2208          *
2209          * @param int $comment_author_ip The comment author's IP.
2210          */
2211         $commentdata['comment_author_IP'] = apply_filters( 'pre_comment_user_ip', $commentdata['comment_author_IP'] );
2212         /** This filter is documented in wp-includes/comment.php */
2213         $commentdata['comment_author_url'] = apply_filters( 'pre_comment_author_url', $commentdata['comment_author_url'] );
2214         /** This filter is documented in wp-includes/comment.php */
2215         $commentdata['comment_author_email'] = apply_filters( 'pre_comment_author_email', $commentdata['comment_author_email'] );
2216         $commentdata['filtered'] = true;
2217         return $commentdata;
2218 }
2219
2220 /**
2221  * Whether a comment should be blocked because of comment flood.
2222  *
2223  * @since 2.1.0
2224  *
2225  * @param bool $block Whether plugin has already blocked comment.
2226  * @param int $time_lastcomment Timestamp for last comment.
2227  * @param int $time_newcomment Timestamp for new comment.
2228  * @return bool Whether comment should be blocked.
2229  */
2230 function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
2231         if ( $block ) // a plugin has already blocked... we'll let that decision stand
2232                 return $block;
2233         if ( ($time_newcomment - $time_lastcomment) < 15 )
2234                 return true;
2235         return false;
2236 }
2237
2238 /**
2239  * Adds a new comment to the database.
2240  *
2241  * Filters new comment to ensure that the fields are sanitized and valid before
2242  * inserting comment into database. Calls 'comment_post' action with comment ID
2243  * and whether comment is approved by WordPress. Also has 'preprocess_comment'
2244  * filter for processing the comment data before the function handles it.
2245  *
2246  * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure
2247  * that it is properly set, such as in wp-config.php, for your environment.
2248  * See {@link https://core.trac.wordpress.org/ticket/9235}
2249  *
2250  * @since 1.5.0
2251  * @param array $commentdata Contains information on the comment.
2252  * @return int|bool The ID of the comment on success, false on failure.
2253  */
2254 function wp_new_comment( $commentdata ) {
2255         if ( isset( $commentdata['user_ID'] ) ) {
2256                 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
2257         }
2258
2259         $prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0;
2260
2261         /**
2262          * Filter a comment's data before it is sanitized and inserted into the database.
2263          *
2264          * @since 1.5.0
2265          *
2266          * @param array $commentdata Comment data.
2267          */
2268         $commentdata = apply_filters( 'preprocess_comment', $commentdata );
2269
2270         $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
2271         if ( isset( $commentdata['user_ID'] ) && $prefiltered_user_id !== (int) $commentdata['user_ID'] ) {
2272                 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
2273         } elseif ( isset( $commentdata['user_id'] ) ) {
2274                 $commentdata['user_id'] = (int) $commentdata['user_id'];
2275         }
2276
2277         $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
2278         $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
2279         $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
2280
2281         $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
2282         $commentdata['comment_agent']     = isset( $_SERVER['HTTP_USER_AGENT'] ) ? substr( $_SERVER['HTTP_USER_AGENT'], 0, 254 ) : '';
2283
2284         if ( empty( $commentdata['comment_date'] ) ) {
2285                 $commentdata['comment_date'] = current_time('mysql');
2286         }
2287
2288         if ( empty( $commentdata['comment_date_gmt'] ) ) {
2289                 $commentdata['comment_date_gmt'] = current_time( 'mysql', 1 );
2290         }
2291
2292         $commentdata = wp_filter_comment($commentdata);
2293
2294         $commentdata['comment_approved'] = wp_allow_comment($commentdata);
2295
2296         $comment_ID = wp_insert_comment($commentdata);
2297         if ( ! $comment_ID ) {
2298                 return false;
2299         }
2300
2301         /**
2302          * Fires immediately after a comment is inserted into the database.
2303          *
2304          * @since 1.2.0
2305          *
2306          * @param int $comment_ID       The comment ID.
2307          * @param int $comment_approved 1 (true) if the comment is approved, 0 (false) if not.
2308          */
2309         do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'] );
2310
2311         if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
2312                 if ( '0' == $commentdata['comment_approved'] ) {
2313                         wp_notify_moderator( $comment_ID );
2314                 }
2315
2316                 // wp_notify_postauthor() checks if notifying the author of their own comment.
2317                 // By default, it won't, but filters can override this.
2318                 if ( get_option( 'comments_notify' ) && $commentdata['comment_approved'] ) {
2319                         wp_notify_postauthor( $comment_ID );
2320                 }
2321         }
2322
2323         return $comment_ID;
2324 }
2325
2326 /**
2327  * Sets the status of a comment.
2328  *
2329  * The 'wp_set_comment_status' action is called after the comment is handled.
2330  * If the comment status is not in the list, then false is returned.
2331  *
2332  * @since 1.0.0
2333  *
2334  * @param int $comment_id Comment ID.
2335  * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
2336  * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
2337  * @return bool|WP_Error True on success, false or WP_Error on failure.
2338  */
2339 function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
2340         global $wpdb;
2341
2342         switch ( $comment_status ) {
2343                 case 'hold':
2344                 case '0':
2345                         $status = '0';
2346                         break;
2347                 case 'approve':
2348                 case '1':
2349                         $status = '1';
2350                         if ( get_option('comments_notify') ) {
2351                                 wp_notify_postauthor( $comment_id );
2352                         }
2353                         break;
2354                 case 'spam':
2355                         $status = 'spam';
2356                         break;
2357                 case 'trash':
2358                         $status = 'trash';
2359                         break;
2360                 default:
2361                         return false;
2362         }
2363
2364         $comment_old = clone get_comment($comment_id);
2365
2366         if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
2367                 if ( $wp_error )
2368                         return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
2369                 else
2370                         return false;
2371         }
2372
2373         clean_comment_cache($comment_id);
2374
2375         $comment = get_comment($comment_id);
2376
2377         /**
2378          * Fires immediately before transitioning a comment's status from one to another
2379          * in the database.
2380          *
2381          * @since 1.5.0
2382          *
2383          * @param int         $comment_id     Comment ID.
2384          * @param string|bool $comment_status Current comment status. Possible values include
2385          *                                    'hold', 'approve', 'spam', 'trash', or false.
2386          */
2387         do_action( 'wp_set_comment_status', $comment_id, $comment_status );
2388
2389         wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
2390
2391         wp_update_comment_count($comment->comment_post_ID);
2392
2393         return true;
2394 }
2395
2396 /**
2397  * Updates an existing comment in the database.
2398  *
2399  * Filters the comment and makes sure certain fields are valid before updating.
2400  *
2401  * @since 2.0.0
2402  *
2403  * @global wpdb $wpdb WordPress database abstraction object.
2404  *
2405  * @param array $commentarr Contains information on the comment.
2406  * @return int Comment was updated if value is 1, or was not updated if value is 0.
2407  */
2408 function wp_update_comment($commentarr) {
2409         global $wpdb;
2410
2411         // First, get all of the original fields
2412         $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
2413         if ( empty( $comment ) ) {
2414                 return 0;
2415         }
2416
2417         // Make sure that the comment post ID is valid (if specified).
2418         if ( isset( $commentarr['comment_post_ID'] ) && ! get_post( $commentarr['comment_post_ID'] ) ) {
2419                 return 0;
2420         }
2421
2422         // Escape data pulled from DB.
2423         $comment = wp_slash($comment);
2424
2425         $old_status = $comment['comment_approved'];
2426
2427         // Merge old and new fields with new fields overwriting old ones.
2428         $commentarr = array_merge($comment, $commentarr);
2429
2430         $commentarr = wp_filter_comment( $commentarr );
2431
2432         // Now extract the merged array.
2433         $data = wp_unslash( $commentarr );
2434
2435         /**
2436          * Filter the comment content before it is updated in the database.
2437          *
2438          * @since 1.5.0
2439          *
2440          * @param string $comment_content The comment data.
2441          */
2442         $data['comment_content'] = apply_filters( 'comment_save_pre', $data['comment_content'] );
2443
2444         $data['comment_date_gmt'] = get_gmt_from_date( $data['comment_date'] );
2445
2446         if ( ! isset( $data['comment_approved'] ) ) {
2447                 $data['comment_approved'] = 1;
2448         } elseif ( 'hold' == $data['comment_approved'] ) {
2449                 $data['comment_approved'] = 0;
2450         } elseif ( 'approve' == $data['comment_approved'] ) {
2451                 $data['comment_approved'] = 1;
2452         }
2453
2454         $comment_ID = $data['comment_ID'];
2455         $comment_post_ID = $data['comment_post_ID'];
2456         $keys = array( 'comment_post_ID', 'comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt', 'comment_type', 'comment_parent', 'user_id' );
2457         $data = wp_array_slice_assoc( $data, $keys );
2458         $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
2459
2460         clean_comment_cache( $comment_ID );
2461         wp_update_comment_count( $comment_post_ID );
2462         /**
2463          * Fires immediately after a comment is updated in the database.
2464          *
2465          * The hook also fires immediately before comment status transition hooks are fired.
2466          *
2467          * @since 1.2.0
2468          *
2469          * @param int $comment_ID The comment ID.
2470          */
2471         do_action( 'edit_comment', $comment_ID );
2472         $comment = get_comment($comment_ID);
2473         wp_transition_comment_status($comment->comment_approved, $old_status, $comment);
2474         return $rval;
2475 }
2476
2477 /**
2478  * Whether to defer comment counting.
2479  *
2480  * When setting $defer to true, all post comment counts will not be updated
2481  * until $defer is set to false. When $defer is set to false, then all
2482  * previously deferred updated post comment counts will then be automatically
2483  * updated without having to call wp_update_comment_count() after.
2484  *
2485  * @since 2.5.0
2486  * @staticvar bool $_defer
2487  *
2488  * @param bool $defer
2489  * @return bool
2490  */
2491 function wp_defer_comment_counting($defer=null) {
2492         static $_defer = false;
2493
2494         if ( is_bool($defer) ) {
2495                 $_defer = $defer;
2496                 // flush any deferred counts
2497                 if ( !$defer )
2498                         wp_update_comment_count( null, true );
2499         }
2500
2501         return $_defer;
2502 }
2503
2504 /**
2505  * Updates the comment count for post(s).
2506  *
2507  * When $do_deferred is false (is by default) and the comments have been set to
2508  * be deferred, the post_id will be added to a queue, which will be updated at a
2509  * later date and only updated once per post ID.
2510  *
2511  * If the comments have not be set up to be deferred, then the post will be
2512  * updated. When $do_deferred is set to true, then all previous deferred post
2513  * IDs will be updated along with the current $post_id.
2514  *
2515  * @since 2.1.0
2516  * @see wp_update_comment_count_now() For what could cause a false return value
2517  *
2518  * @param int $post_id Post ID
2519  * @param bool $do_deferred Whether to process previously deferred post comment counts
2520  * @return bool|null True on success, false on failure
2521  */
2522 function wp_update_comment_count($post_id, $do_deferred=false) {
2523         static $_deferred = array();
2524
2525         if ( $do_deferred ) {
2526                 $_deferred = array_unique($_deferred);
2527                 foreach ( $_deferred as $i => $_post_id ) {
2528                         wp_update_comment_count_now($_post_id);
2529                         unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
2530                 }
2531         }
2532
2533         if ( wp_defer_comment_counting() ) {
2534                 $_deferred[] = $post_id;
2535                 return true;
2536         }
2537         elseif ( $post_id ) {
2538                 return wp_update_comment_count_now($post_id);
2539         }
2540
2541 }
2542
2543 /**
2544  * Updates the comment count for the post.
2545  *
2546  * @since 2.5.0
2547  *
2548  * @global wpdb $wpdb WordPress database abstraction object.
2549  *
2550  * @param int $post_id Post ID
2551  * @return bool True on success, false on '0' $post_id or if post with ID does not exist.
2552  */
2553 function wp_update_comment_count_now($post_id) {
2554         global $wpdb;
2555         $post_id = (int) $post_id;
2556         if ( !$post_id )
2557                 return false;
2558         if ( !$post = get_post($post_id) )
2559                 return false;
2560
2561         $old = (int) $post->comment_count;
2562         $new = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id) );
2563         $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) );
2564
2565         clean_post_cache( $post );
2566
2567         /**
2568          * Fires immediately after a post's comment count is updated in the database.
2569          *
2570          * @since 2.3.0
2571          *
2572          * @param int $post_id Post ID.
2573          * @param int $new     The new comment count.
2574          * @param int $old     The old comment count.
2575          */
2576         do_action( 'wp_update_comment_count', $post_id, $new, $old );
2577         /** This action is documented in wp-includes/post.php */
2578         do_action( 'edit_post', $post_id, $post );
2579
2580         return true;
2581 }
2582
2583 //
2584 // Ping and trackback functions.
2585 //
2586
2587 /**
2588  * Finds a pingback server URI based on the given URL.
2589  *
2590  * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
2591  * a check for the x-pingback headers first and returns that, if available. The
2592  * check for the rel="pingback" has more overhead than just the header.
2593  *
2594  * @since 1.5.0
2595  *
2596  * @param string $url URL to ping.
2597  * @param int $deprecated Not Used.
2598  * @return false|string False on failure, string containing URI on success.
2599  */
2600 function discover_pingback_server_uri( $url, $deprecated = '' ) {
2601         if ( !empty( $deprecated ) )
2602                 _deprecated_argument( __FUNCTION__, '2.7' );
2603
2604         $pingback_str_dquote = 'rel="pingback"';
2605         $pingback_str_squote = 'rel=\'pingback\'';
2606
2607         /** @todo Should use Filter Extension or custom preg_match instead. */
2608         $parsed_url = parse_url($url);
2609
2610         if ( ! isset( $parsed_url['host'] ) ) // Not an URL. This should never happen.
2611                 return false;
2612
2613         //Do not search for a pingback server on our own uploads
2614         $uploads_dir = wp_upload_dir();
2615         if ( 0 === strpos($url, $uploads_dir['baseurl']) )
2616                 return false;
2617
2618         $response = wp_safe_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
2619
2620         if ( is_wp_error( $response ) )
2621                 return false;
2622
2623         if ( wp_remote_retrieve_header( $response, 'x-pingback' ) )
2624                 return wp_remote_retrieve_header( $response, 'x-pingback' );
2625
2626         // Not an (x)html, sgml, or xml page, no use going further.
2627         if ( preg_match('#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'content-type' )) )
2628                 return false;
2629
2630         // Now do a GET since we're going to look in the html headers (and we're sure it's not a binary file)
2631         $response = wp_safe_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
2632
2633         if ( is_wp_error( $response ) )
2634                 return false;
2635
2636         $contents = wp_remote_retrieve_body( $response );
2637
2638         $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
2639         $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
2640         if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
2641                 $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
2642                 $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
2643                 $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
2644                 $pingback_href_start = $pingback_href_pos+6;
2645                 $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
2646                 $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
2647                 $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
2648
2649                 // We may find rel="pingback" but an incomplete pingback URL
2650                 if ( $pingback_server_url_len > 0 ) { // We got it!
2651                         return $pingback_server_url;
2652                 }
2653         }
2654
2655         return false;
2656 }
2657
2658 /**
2659  * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
2660  *
2661  * @since 2.1.0
2662  *
2663  * @global wpdb $wpdb WordPress database abstraction object.
2664  */
2665 function do_all_pings() {
2666         global $wpdb;
2667
2668         // Do pingbacks
2669         while ($ping = $wpdb->get_row("SELECT ID, post_content, meta_id FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_pingme' LIMIT 1")) {
2670                 delete_metadata_by_mid( 'post', $ping->meta_id );
2671                 pingback( $ping->post_content, $ping->ID );
2672         }
2673
2674         // Do Enclosures
2675         while ($enclosure = $wpdb->get_row("SELECT ID, post_content, meta_id FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_encloseme' LIMIT 1")) {
2676                 delete_metadata_by_mid( 'post', $enclosure->meta_id );
2677                 do_enclose( $enclosure->post_content, $enclosure->ID );
2678         }
2679
2680         // Do Trackbacks
2681         $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'");
2682         if ( is_array($trackbacks) )
2683                 foreach ( $trackbacks as $trackback )
2684                         do_trackbacks($trackback);
2685
2686         //Do Update Services/Generic Pings
2687         generic_ping();
2688 }
2689
2690 /**
2691  * Perform trackbacks.
2692  *
2693  * @since 1.5.0
2694  *
2695  * @global wpdb $wpdb WordPress database abstraction object.
2696  *
2697  * @param int $post_id Post ID to do trackbacks on.
2698  */
2699 function do_trackbacks($post_id) {
2700         global $wpdb;
2701
2702         $post = get_post( $post_id );
2703         $to_ping = get_to_ping($post_id);
2704         $pinged  = get_pung($post_id);
2705         if ( empty($to_ping) ) {
2706                 $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) );
2707                 return;
2708         }
2709
2710         if ( empty($post->post_excerpt) ) {
2711                 /** This filter is documented in wp-includes/post-template.php */
2712                 $excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
2713         } else {
2714                 /** This filter is documented in wp-includes/post-template.php */
2715                 $excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );
2716         }
2717
2718         $excerpt = str_replace(']]>', ']]&gt;', $excerpt);
2719         $excerpt = wp_html_excerpt($excerpt, 252, '&#8230;');
2720
2721         /** This filter is documented in wp-includes/post-template.php */
2722         $post_title = apply_filters( 'the_title', $post->post_title, $post->ID );
2723         $post_title = strip_tags($post_title);
2724
2725         if ( $to_ping ) {
2726                 foreach ( (array) $to_ping as $tb_ping ) {
2727                         $tb_ping = trim($tb_ping);
2728                         if ( !in_array($tb_ping, $pinged) ) {
2729                                 trackback($tb_ping, $post_title, $excerpt, $post_id);
2730                                 $pinged[] = $tb_ping;
2731                         } else {
2732                                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post_id) );
2733                         }
2734                 }
2735         }
2736 }
2737
2738 /**
2739  * Sends pings to all of the ping site services.
2740  *
2741  * @since 1.2.0
2742  *
2743  * @param int $post_id Post ID.
2744  * @return int Same as Post ID from parameter
2745  */
2746 function generic_ping( $post_id = 0 ) {
2747         $services = get_option('ping_sites');
2748
2749         $services = explode("\n", $services);
2750         foreach ( (array) $services as $service ) {
2751                 $service = trim($service);
2752                 if ( '' != $service )
2753                         weblog_ping($service);
2754         }
2755
2756         return $post_id;
2757 }
2758
2759 /**
2760  * Pings back the links found in a post.
2761  *
2762  * @since 0.71
2763  * @uses $wp_version
2764  *
2765  * @param string $content Post content to check for links.
2766  * @param int $post_ID Post ID.
2767  */
2768 function pingback($content, $post_ID) {
2769         global $wp_version;
2770         include_once(ABSPATH . WPINC . '/class-IXR.php');
2771         include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
2772
2773         // original code by Mort (http://mort.mine.nu:8080)
2774         $post_links = array();
2775
2776         $pung = get_pung($post_ID);
2777
2778         // Step 1
2779         // Parsing the post, external links (if any) are stored in the $post_links array
2780         $post_links_temp = wp_extract_urls( $content );
2781
2782         // Step 2.
2783         // Walking thru the links array
2784         // first we get rid of links pointing to sites, not to specific files
2785         // Example:
2786         // http://dummy-weblog.org
2787         // http://dummy-weblog.org/
2788         // http://dummy-weblog.org/post.php
2789         // We don't wanna ping first and second types, even if they have a valid <link/>
2790
2791         foreach ( (array) $post_links_temp as $link_test ) :
2792                 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
2793                                 && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
2794                         if ( $test = @parse_url($link_test) ) {
2795                                 if ( isset($test['query']) )
2796                                         $post_links[] = $link_test;
2797                                 elseif ( isset( $test['path'] ) && ( $test['path'] != '/' ) && ( $test['path'] != '' ) )
2798                                         $post_links[] = $link_test;
2799                         }
2800                 endif;
2801         endforeach;
2802
2803         $post_links = array_unique( $post_links );
2804         /**
2805          * Fires just before pinging back links found in a post.
2806          *
2807          * @since 2.0.0
2808          *
2809          * @param array &$post_links An array of post links to be checked, passed by reference.
2810          * @param array &$pung       Whether a link has already been pinged, passed by reference.
2811          * @param int   $post_ID     The post ID.
2812          */
2813         do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post_ID ) );
2814
2815         foreach ( (array) $post_links as $pagelinkedto ) {
2816                 $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
2817
2818                 if ( $pingback_server_url ) {
2819                         @ set_time_limit( 60 );
2820                         // Now, the RPC call
2821                         $pagelinkedfrom = get_permalink($post_ID);
2822
2823                         // using a timeout of 3 seconds should be enough to cover slow servers
2824                         $client = new WP_HTTP_IXR_Client($pingback_server_url);
2825                         $client->timeout = 3;
2826                         /**
2827                          * Filter the user agent sent when pinging-back a URL.
2828                          *
2829                          * @since 2.9.0
2830                          *
2831                          * @param string $concat_useragent    The user agent concatenated with ' -- WordPress/'
2832                          *                                    and the WordPress version.
2833                          * @param string $useragent           The useragent.
2834                          * @param string $pingback_server_url The server URL being linked to.
2835                          * @param string $pagelinkedto        URL of page linked to.
2836                          * @param string $pagelinkedfrom      URL of page linked from.
2837                          */
2838                         $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . $wp_version, $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom );
2839                         // when set to true, this outputs debug messages by itself
2840                         $client->debug = false;
2841
2842                         if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
2843                                 add_ping( $post_ID, $pagelinkedto );
2844                 }
2845         }
2846 }
2847
2848 /**
2849  * Check whether blog is public before returning sites.
2850  *
2851  * @since 2.1.0
2852  *
2853  * @param mixed $sites Will return if blog is public, will not return if not public.
2854  * @return mixed Empty string if blog is not public, returns $sites, if site is public.
2855  */
2856 function privacy_ping_filter($sites) {
2857         if ( '0' != get_option('blog_public') )
2858                 return $sites;
2859         else
2860                 return '';
2861 }
2862
2863 /**
2864  * Send a Trackback.
2865  *
2866  * Updates database when sending trackback to prevent duplicates.
2867  *
2868  * @since 0.71
2869  *
2870  * @global wpdb $wpdb WordPress database abstraction object.
2871  *
2872  * @param string $trackback_url URL to send trackbacks.
2873  * @param string $title Title of post.
2874  * @param string $excerpt Excerpt of post.
2875  * @param int $ID Post ID.
2876  * @return mixed Database query from update.
2877  */
2878 function trackback($trackback_url, $title, $excerpt, $ID) {
2879         global $wpdb;
2880
2881         if ( empty($trackback_url) )
2882                 return;
2883
2884         $options = array();
2885         $options['timeout'] = 4;
2886         $options['body'] = array(
2887                 'title' => $title,
2888                 'url' => get_permalink($ID),
2889                 'blog_name' => get_option('blogname'),
2890                 'excerpt' => $excerpt
2891         );
2892
2893         $response = wp_safe_remote_post( $trackback_url, $options );
2894
2895         if ( is_wp_error( $response ) )
2896                 return;
2897
2898         $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID) );
2899         return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID) );
2900 }
2901
2902 /**
2903  * Send a pingback.
2904  *
2905  * @since 1.2.0
2906  * @uses $wp_version
2907  *
2908  * @param string $server Host of blog to connect to.
2909  * @param string $path Path to send the ping.
2910  */
2911 function weblog_ping($server = '', $path = '') {
2912         global $wp_version;
2913         include_once(ABSPATH . WPINC . '/class-IXR.php');
2914         include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
2915
2916         // using a timeout of 3 seconds should be enough to cover slow servers
2917         $client = new WP_HTTP_IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
2918         $client->timeout = 3;
2919         $client->useragent .= ' -- WordPress/'.$wp_version;
2920
2921         // when set to true, this outputs debug messages by itself
2922         $client->debug = false;
2923         $home = trailingslashit( home_url() );
2924         if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
2925                 $client->query('weblogUpdates.ping', get_option('blogname'), $home);
2926 }
2927
2928 /**
2929  * Default filter attached to pingback_ping_source_uri to validate the pingback's Source URI
2930  *
2931  * @since 3.5.1
2932  * @see wp_http_validate_url()
2933  *
2934  * @param string $source_uri
2935  * @return string
2936  */
2937 function pingback_ping_source_uri( $source_uri ) {
2938         return (string) wp_http_validate_url( $source_uri );
2939 }
2940
2941 /**
2942  * Default filter attached to xmlrpc_pingback_error.
2943  *
2944  * Returns a generic pingback error code unless the error code is 48,
2945  * which reports that the pingback is already registered.
2946  *
2947  * @since 3.5.1
2948  * @link http://www.hixie.ch/specs/pingback/pingback#TOC3
2949  *
2950  * @param IXR_Error $ixr_error
2951  * @return IXR_Error
2952  */
2953 function xmlrpc_pingback_error( $ixr_error ) {
2954         if ( $ixr_error->code === 48 )
2955                 return $ixr_error;
2956         return new IXR_Error( 0, '' );
2957 }
2958
2959 //
2960 // Cache
2961 //
2962
2963 /**
2964  * Removes comment ID from the comment cache.
2965  *
2966  * @since 2.3.0
2967  *
2968  * @param int|array $ids Comment ID or array of comment IDs to remove from cache
2969  */
2970 function clean_comment_cache($ids) {
2971         foreach ( (array) $ids as $id )
2972                 wp_cache_delete($id, 'comment');
2973
2974         wp_cache_set( 'last_changed', microtime(), 'comment' );
2975 }
2976
2977 /**
2978  * Updates the comment cache of given comments.
2979  *
2980  * Will add the comments in $comments to the cache. If comment ID already exists
2981  * in the comment cache then it will not be updated. The comment is added to the
2982  * cache using the comment group with the key using the ID of the comments.
2983  *
2984  * @since 2.3.0
2985  *
2986  * @param array $comments Array of comment row objects
2987  */
2988 function update_comment_cache($comments) {
2989         foreach ( (array) $comments as $comment )
2990                 wp_cache_add($comment->comment_ID, $comment, 'comment');
2991 }
2992
2993 //
2994 // Internal
2995 //
2996
2997 /**
2998  * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
2999  *
3000  * @access private
3001  * @since 2.7.0
3002  *
3003  * @param object $posts Post data object.
3004  * @param object $query Query object.
3005  * @return object
3006  */
3007 function _close_comments_for_old_posts( $posts, $query ) {
3008         if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) )
3009                 return $posts;
3010
3011         /**
3012          * Filter the list of post types to automatically close comments for.
3013          *
3014          * @since 3.2.0
3015          *
3016          * @param array $post_types An array of registered post types. Default array with 'post'.
3017          */
3018         $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
3019         if ( ! in_array( $posts[0]->post_type, $post_types ) )
3020                 return $posts;
3021
3022         $days_old = (int) get_option( 'close_comments_days_old' );
3023         if ( ! $days_old )
3024                 return $posts;
3025
3026         if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
3027                 $posts[0]->comment_status = 'closed';
3028                 $posts[0]->ping_status = 'closed';
3029         }
3030
3031         return $posts;
3032 }
3033
3034 /**
3035  * Close comments on an old post. Hooked to comments_open and pings_open.
3036  *
3037  * @access private
3038  * @since 2.7.0
3039  *
3040  * @param bool $open Comments open or closed
3041  * @param int $post_id Post ID
3042  * @return bool $open
3043  */
3044 function _close_comments_for_old_post( $open, $post_id ) {
3045         if ( ! $open )
3046                 return $open;
3047
3048         if ( !get_option('close_comments_for_old_posts') )
3049                 return $open;
3050
3051         $days_old = (int) get_option('close_comments_days_old');
3052         if ( !$days_old )
3053                 return $open;
3054
3055         $post = get_post($post_id);
3056
3057         /** This filter is documented in wp-includes/comment.php */
3058         $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
3059         if ( ! in_array( $post->post_type, $post_types ) )
3060                 return $open;
3061
3062         if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) )
3063                 return false;
3064
3065         return $open;
3066 }