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