10 * Check whether a comment passes internal checks to be allowed to add.
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
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.
20 * If the comment author was approved before, then the comment is automatically
23 * If all checks pass, the function will return true.
27 * @global wpdb $wpdb WordPress database abstraction object.
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.
39 function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
42 // If manual moderation is enabled, skip all checks and return false.
43 if ( 1 == get_option('comment_moderation') )
46 /** This filter is documented in wp-includes/comment-template.php */
47 $comment = apply_filters( 'comment_text', $comment );
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 );
54 * Filters the number of links found in a comment.
57 * @since 4.7.0 Added the `$comment` parameter.
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.
63 $num_links = apply_filters( 'comment_max_links_url', $num_links, $url, $comment );
66 * If the number of links in the comment exceeds the allowed amount,
67 * fail the check by returning false.
69 if ( $num_links >= $max_links )
73 $mod_keys = trim(get_option('moderation_keys'));
75 // If moderation 'keys' (keywords) are set, process them.
76 if ( !empty($mod_keys) ) {
77 $words = explode("\n", $mod_keys );
79 foreach ( (array) $words as $word) {
87 * Do some escaping magic so that '#' (number of) characters in the spam
88 * words don't break things:
90 $word = preg_quote($word, '#');
93 * Check the comment fields for moderation keywords. If any are found,
94 * fail the check for the given field by returning false.
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;
107 * Check if the option to approve comments by previously-approved authors is enabled.
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.
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 ) );
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 ) );
122 if ( ( 1 == $ok_to_comment ) &&
123 ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
135 * Retrieve the approved comments for post $post_id.
138 * @since 4.1.0 Refactored to leverage WP_Comment_Query over a direct query.
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`
145 function get_approved_comments( $post_id, $args = array() ) {
152 'post_id' => $post_id,
155 $r = wp_parse_args( $args, $defaults );
157 $query = new WP_Comment_Query;
158 return $query->query( $r );
162 * Retrieves comment data given a comment ID or comment object.
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.
170 * @global WP_Comment $comment
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.
177 function get_comment( &$comment = null, $output = OBJECT ) {
178 if ( empty( $comment ) && isset( $GLOBALS['comment'] ) ) {
179 $comment = $GLOBALS['comment'];
182 if ( $comment instanceof WP_Comment ) {
183 $_comment = $comment;
184 } elseif ( is_object( $comment ) ) {
185 $_comment = new WP_Comment( $comment );
187 $_comment = WP_Comment::get_instance( $comment );
195 * Fires after a comment is retrieved.
199 * @param mixed $_comment Comment data.
201 $_comment = apply_filters( 'get_comment', $_comment );
203 if ( $output == OBJECT ) {
205 } elseif ( $output == ARRAY_A ) {
206 return $_comment->to_array();
207 } elseif ( $output == ARRAY_N ) {
208 return array_values( $_comment->to_array() );
214 * Retrieve a list of comments.
216 * The comment list can be for the blog as a whole or for an individual post.
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.
224 function get_comments( $args = '' ) {
225 $query = new WP_Comment_Query;
226 return $query->query( $args );
230 * Retrieve all of the WordPress supported comment statuses.
232 * Comments have a limited set of valid status values, this provides the comment
233 * status values and descriptions.
237 * @return array List of comment statuses.
239 function get_comment_statuses() {
241 'hold' => __( 'Unapproved' ),
242 'approve' => _x( 'Approved', 'comment status' ),
243 'spam' => _x( 'Spam', 'comment status' ),
244 'trash' => _x( 'Trash', 'comment status' ),
251 * Gets the default comment status for a post type.
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'.
259 function get_default_comment_status( $post_type = 'post', $comment_type = 'comment' ) {
260 switch ( $comment_type ) {
263 $supports = 'trackbacks';
267 $supports = 'comments';
272 if ( 'page' === $post_type ) {
274 } elseif ( post_type_supports( $post_type, $supports ) ) {
275 $status = get_option( "default_{$option}_status" );
281 * Filters the default comment status for the given post type.
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`.
290 return apply_filters( 'get_default_comment_status' , $status, $post_type, $comment_type );
294 * The date the last comment was modified.
297 * @since 4.7.0 Replaced caching the modified date in a local static variable
298 * with the Object Cache API.
300 * @global wpdb $wpdb WordPress database abstraction object.
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.
305 function get_lastcommentmodified( $timezone = 'server' ) {
308 $timezone = strtolower( $timezone );
309 $key = "lastcommentmodified:$timezone";
311 $comment_modified_date = wp_cache_get( $key, 'timeinfo' );
312 if ( false !== $comment_modified_date ) {
313 return $comment_modified_date;
316 switch ( $timezone ) {
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" );
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" );
324 $add_seconds_server = date( 'Z' );
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 ) );
330 if ( $comment_modified_date ) {
331 wp_cache_set( $key, $comment_modified_date, 'timeinfo' );
333 return $comment_modified_date;
340 * The amount of comments in a post or total comments.
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.
347 * @global wpdb $wpdb WordPress database abstraction object.
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.
352 function get_comment_count( $post_id = 0 ) {
355 $post_id = (int) $post_id;
358 if ( $post_id > 0 ) {
359 $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
362 $totals = (array) $wpdb->get_results("
363 SELECT comment_approved, COUNT( * ) AS total
364 FROM {$wpdb->comments}
366 GROUP BY comment_approved
369 $comment_count = array(
371 'awaiting_moderation' => 0,
375 'total_comments' => 0,
379 foreach ( $totals as $row ) {
380 switch ( $row['comment_approved'] ) {
382 $comment_count['trash'] = $row['total'];
385 $comment_count['post-trashed'] = $row['total'];
388 $comment_count['spam'] = $row['total'];
389 $comment_count['total_comments'] += $row['total'];
392 $comment_count['approved'] = $row['total'];
393 $comment_count['total_comments'] += $row['total'];
394 $comment_count['all'] += $row['total'];
397 $comment_count['awaiting_moderation'] = $row['total'];
398 $comment_count['total_comments'] += $row['total'];
399 $comment_count['all'] += $row['total'];
406 return $comment_count;
410 // Comment meta functions
414 * Add meta data field to a comment.
417 * @link https://codex.wordpress.org/Function_Reference/add_comment_meta
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.
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);
430 * Remove metadata matching criteria from a comment.
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.
437 * @link https://codex.wordpress.org/Function_Reference/delete_comment_meta
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.
444 function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
445 return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
449 * Retrieve comment meta field for a comment.
452 * @link https://codex.wordpress.org/Function_Reference/get_comment_meta
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
460 function get_comment_meta($comment_id, $key = '', $single = false) {
461 return get_metadata('comment', $comment_id, $key, $single);
465 * Update comment meta field based on comment ID.
467 * Use the $prev_value parameter to differentiate between meta fields with the
468 * same key and comment ID.
470 * If the meta field for the comment does not exist, it will be added.
473 * @link https://codex.wordpress.org/Function_Reference/update_comment_meta
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.
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);
486 * Queues comments for metadata lazy-loading.
490 * @param array $comments Array of comment objects.
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;
503 if ( $comment_ids ) {
504 $lazyloader = wp_metadata_lazyloader();
505 $lazyloader->queue_objects( 'comment', $comment_ids );
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.
513 * @param WP_Comment $comment Comment object.
514 * @param object $user Comment author's object.
518 function wp_set_comment_cookies($comment, $user) {
519 if ( $user->exists() )
523 * Filters the lifetime of the comment cookie in seconds.
527 * @param int $seconds Comment cookie lifetime. Default 30000000.
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 );
537 * Sanitizes the cookies sent to the user already.
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.
544 function sanitize_comment_cookies() {
545 if ( isset( $_COOKIE['comment_author_' . COOKIEHASH] ) ) {
547 * Filters the comment author's name cookie before it is set.
549 * When this filter hook is evaluated in wp_filter_comment(),
550 * the comment author's name string is passed.
554 * @param string $author_cookie The comment author name cookie.
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;
562 if ( isset( $_COOKIE['comment_author_email_' . COOKIEHASH] ) ) {
564 * Filters the comment author's email cookie before it is set.
566 * When this filter hook is evaluated in wp_filter_comment(),
567 * the comment author's email string is passed.
571 * @param string $author_email_cookie The comment author email cookie.
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;
579 if ( isset( $_COOKIE['comment_author_url_' . COOKIEHASH] ) ) {
581 * Filters the comment author's URL cookie before it is set.
583 * When this filter hook is evaluated in wp_filter_comment(),
584 * the comment author's URL string is passed.
588 * @param string $author_url_cookie The comment author URL cookie.
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;
597 * Validates whether this comment is allowed to be made.
600 * @since 4.7.0 The `$avoid_die` parameter was added, allowing the function to
601 * return a WP_Error object instead of dying.
603 * @global wpdb $wpdb WordPress database abstraction object.
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().
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.
612 function wp_allow_comment( $commentdata, $avoid_die = false ) {
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'] )
623 if ( $commentdata['comment_author_email'] ) {
624 $dupe .= $wpdb->prepare(
625 "AND comment_author_email = %s ",
626 wp_unslash( $commentdata['comment_author_email'] )
629 $dupe .= $wpdb->prepare(
630 ") AND comment_content = %s LIMIT 1",
631 wp_unslash( $commentdata['comment_content'] )
634 $dupe_id = $wpdb->get_var( $dupe );
637 * Filters the ID, if any, of the duplicate comment found when creating a new comment.
639 * Return an empty value from this filter to allow what WP considers a duplicate comment.
643 * @param int $dupe_id ID of the comment identified as a duplicate.
644 * @param array $commentdata Data for the comment being created.
646 $dupe_id = apply_filters( 'duplicate_comment_id', $dupe_id, $commentdata );
650 * Fires immediately after a duplicate comment is detected.
654 * @param array $commentdata Comment data.
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’ve already said that!' ), 409 );
660 if ( wp_doing_ajax() ) {
661 die( __('Duplicate comment detected; it looks as though you’ve already said that!') );
664 wp_die( __( 'Duplicate comment detected; it looks as though you’ve already said that!' ), 409 );
669 * Fires immediately before a comment is marked approved.
671 * Allows checking for comment flooding.
674 * @since 4.7.0 The `$avoid_die` parameter was added.
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.
683 'check_comment_flood',
684 $commentdata['comment_author_IP'],
685 $commentdata['comment_author_email'],
686 $commentdata['comment_date_gmt'],
691 * Filters whether a comment is part of a comment flood.
693 * The default check is wp_check_comment_flood(). See check_comment_flood_db().
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.
704 $is_flood = apply_filters(
705 'wp_is_comment_flood',
707 $commentdata['comment_author_IP'],
708 $commentdata['comment_author_email'],
709 $commentdata['comment_date_gmt'],
714 return new WP_Error( 'comment_flood', __( 'You are posting comments too quickly. Slow down.' ), 429 );
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']
725 if ( isset( $user ) && ( $commentdata['user_id'] == $post_author || $user->has_cap( 'moderate_comments' ) ) ) {
726 // The author and the admins get respect.
729 // Everyone else's comments will be checked.
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']
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']
752 $approved = EMPTY_TRASH_DAYS ? 'trash' : 'spam';
757 * Filters a comment's approval status before it is set.
761 * @param bool|string $approved The approval status. Accepts 1, 0, or 'spam'.
762 * @param array $commentdata Comment data.
764 $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
769 * Hooks WP's native database-based comment-flood check.
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().
776 * @since 4.7.0 Converted to be an add_filter() wrapper.
778 function check_comment_flood_db() {
779 add_filter( 'wp_is_comment_flood', 'wp_check_comment_flood', 10, 5 );
783 * Checks whether comment flooding is occurring.
785 * Won't run, if current user can manage options, so to not block
790 * @global wpdb $wpdb WordPress database abstraction object.
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().
799 * @return bool Whether comment flooding is occurring.
801 function wp_check_comment_flood( $is_flood, $ip, $email, $date, $avoid_die = false ) {
805 // Another callback has declared a flood. Trust it.
806 if ( true === $is_flood ) {
810 // don't throttle admins or moderators
811 if ( current_user_can( 'manage_options' ) || current_user_can( 'moderate_comments' ) ) {
814 $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
816 if ( is_user_logged_in() ) {
817 $user = get_current_user_id();
818 $check_column = '`user_id`';
821 $check_column = '`comment_author_IP`';
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",
830 $lasttime = $wpdb->get_var( $sql );
832 $time_lastcomment = mysql2date('U', $lasttime, false);
833 $time_newcomment = mysql2date('U', $date, false);
835 * Filters the comment flood status.
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.
843 $flood_die = apply_filters( 'comment_flood_filter', false, $time_lastcomment, $time_newcomment );
846 * Fires before the comment flood message is triggered.
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.
853 do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment );
854 if ( true === $avoid_die ) {
857 if ( wp_doing_ajax() ) {
858 die( __('You are posting comments too quickly. Slow down.') );
861 wp_die( __( 'You are posting comments too quickly. Slow down.' ), 429 );
870 * Separates an array of comments into an array keyed by comment_type.
874 * @param array $comments Array of comments
875 * @return array Array of comments keyed by comment_type.
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;
884 $comments_by_type[$type][] = &$comments[$i];
885 if ( 'trackback' == $type || 'pingback' == $type )
886 $comments_by_type['pings'][] = &$comments[$i];
889 return $comments_by_type;
893 * Calculate the total number of comment pages.
897 * @uses Walker_Comment
899 * @global WP_Query $wp_query
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.
906 function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
909 if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
910 return $wp_query->max_num_comment_pages;
912 if ( ( ! $comments || ! is_array( $comments ) ) && ! empty( $wp_query->comments ) )
913 $comments = $wp_query->comments;
915 if ( empty($comments) )
918 if ( ! get_option( 'page_comments' ) ) {
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 )
929 if ( !isset($threaded) )
930 $threaded = get_option('thread_comments');
933 $walker = new Walker_Comment;
934 $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
936 $count = ceil( count( $comments ) / $per_page );
943 * Calculate what page number a comment will appear on for comment paging.
947 * @global wpdb $wpdb WordPress database abstraction object.
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'.
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.
960 * @return int|null Comment page number or null on error.
962 function get_page_of_comment( $comment_ID, $args = array() ) {
967 if ( !$comment = get_comment( $comment_ID ) )
970 $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
971 $args = wp_parse_args( $args, $defaults );
972 $original_args = $args;
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' );
980 if ( '' === $args['per_page'] ) {
981 $args['per_page'] = get_option( 'comments_per_page' );
985 if ( empty($args['per_page']) ) {
986 $args['per_page'] = 0;
990 if ( $args['per_page'] < 1 ) {
994 if ( null === $page ) {
995 if ( '' === $args['max_depth'] ) {
996 if ( get_option('thread_comments') )
997 $args['max_depth'] = get_option('thread_comments_depth');
999 $args['max_depth'] = -1;
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 );
1006 if ( 'desc' === get_option( 'comment_order' ) ) {
1009 $compare = 'before';
1012 $comment_args = array(
1013 'type' => $args['type'],
1014 'post_id' => $comment->comment_post_ID,
1017 'status' => 'approve',
1019 'date_query' => array(
1021 'column' => "$wpdb->comments.comment_date_gmt",
1022 $compare => $comment->comment_date_gmt,
1027 $comment_query = new WP_Comment_Query();
1028 $older_comment_count = $comment_query->query( $comment_args );
1030 // No older comments? Then it's page #1.
1031 if ( 0 == $older_comment_count ) {
1034 // Divide comments older than this one by comments per page to get this comment's page number
1036 $page = ceil( ( $older_comment_count + 1 ) / $args['per_page'] );
1041 * Filters the calculated page on which a comment appears.
1044 * @since 4.7.0 Introduced the `$comment_ID` parameter.
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`.
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.
1057 * @param array $original_args {
1058 * Array of arguments passed to the function. Some or all of these may not be set.
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.
1065 * @param int $comment_ID ID of the comment.
1067 return apply_filters( 'get_page_of_comment', (int) $page, $args, $original_args, $comment_ID );
1071 * Retrieves the maximum character lengths for the comment form fields.
1075 * @global wpdb $wpdb WordPress database abstraction object.
1077 * @return array Maximum character length for the comment form fields.
1079 function wp_get_comment_fields_max_lengths() {
1083 'comment_author' => 245,
1084 'comment_author_email' => 100,
1085 'comment_author_url' => 200,
1086 'comment_content' => 65525,
1089 if ( $wpdb->is_mysql ) {
1090 foreach ( $lengths as $column => $length ) {
1091 $col_length = $wpdb->get_col_length( $wpdb->comments, $column );
1094 // No point if we can't get the DB column lengths
1095 if ( is_wp_error( $col_length ) ) {
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'];
1104 if ( ! empty( $col_length['type'] ) && 'byte' === $col_length['type'] ) {
1105 $max_length = $max_length - 10;
1109 if ( $max_length > 0 ) {
1110 $lengths[ $column ] = $max_length;
1116 * Filters the lengths for the comment form fields.
1120 * @param array $lengths Associative array `'field_name' => 'maximum length'`.
1122 return apply_filters( 'wp_get_comment_fields_max_lengths', $lengths );
1126 * Compares the lengths of comment data against the maximum character limits.
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,
1134 function wp_check_comment_data_max_lengths( $comment_data ) {
1135 $max_lengths = wp_get_comment_fields_max_lengths();
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 );
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 );
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 );
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 );
1157 * Does comment contain blacklisted characters or words.
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
1169 function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
1171 * Fires before the comment is tested for blacklisted characters or words.
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.
1182 do_action( 'wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent );
1184 $mod_keys = trim( get_option('blacklist_keys') );
1185 if ( '' == $mod_keys )
1186 return false; // If moderation keys are empty
1188 // Ensure HTML tags are not being used to bypass the blacklist.
1189 $comment_without_html = wp_strip_all_tags( $comment );
1191 $words = explode("\n", $mod_keys );
1193 foreach ( (array) $words as $word ) {
1194 $word = trim($word);
1197 if ( empty($word) ) { continue; }
1199 // Do some escaping magic so that '#' chars in the
1200 // spam words don't break things:
1201 $word = preg_quote($word, '#');
1203 $pattern = "#$word#i";
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)
1219 * Retrieve total comments for blog or single post.
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.
1226 * The comment stats are cached and then retrieved, if they already exist in the
1231 * @param int $post_id Optional. Post ID.
1232 * @return object|array Comment stats.
1234 function wp_count_comments( $post_id = 0 ) {
1235 $post_id = (int) $post_id;
1238 * Filters the comments count for a given post.
1242 * @param array $count An empty array.
1243 * @param int $post_id The post ID.
1245 $filtered = apply_filters( 'wp_count_comments', array(), $post_id );
1246 if ( ! empty( $filtered ) ) {
1250 $count = wp_cache_get( "comments-{$post_id}", 'counts' );
1251 if ( false !== $count ) {
1255 $stats = get_comment_count( $post_id );
1256 $stats['moderated'] = $stats['awaiting_moderation'];
1257 unset( $stats['awaiting_moderation'] );
1259 $stats_object = (object) $stats;
1260 wp_cache_set( "comments-{$post_id}", $stats_object, 'counts' );
1262 return $stats_object;
1266 * Trashes or deletes a comment.
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.
1271 * The post comment count will be updated if the comment was approved and has a
1272 * post ID available.
1276 * @global wpdb $wpdb WordPress database abstraction object.
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.
1282 function wp_delete_comment($comment_id, $force_delete = false) {
1284 if (!$comment = get_comment($comment_id))
1287 if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status( $comment ), array( 'trash', 'spam' ) ) )
1288 return wp_trash_comment($comment_id);
1291 * Fires immediately before a comment is deleted from the database.
1295 * @param int $comment_id The comment ID.
1297 do_action( 'delete_comment', $comment->comment_ID );
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);
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 );
1311 if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment->comment_ID ) ) )
1315 * Fires immediately after a comment is deleted from the database.
1319 * @param int $comment_id The comment ID.
1321 do_action( 'deleted_comment', $comment->comment_ID );
1323 $post_id = $comment->comment_post_ID;
1324 if ( $post_id && $comment->comment_approved == 1 )
1325 wp_update_comment_count($post_id);
1327 clean_comment_cache( $comment->comment_ID );
1329 /** This action is documented in wp-includes/comment.php */
1330 do_action( 'wp_set_comment_status', $comment->comment_ID, 'delete' );
1332 wp_transition_comment_status('delete', $comment->comment_approved, $comment);
1337 * Moves a comment to the Trash
1339 * If trash is disabled, comment is permanently deleted.
1343 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
1344 * @return bool True on success, false on failure.
1346 function wp_trash_comment($comment_id) {
1347 if ( !EMPTY_TRASH_DAYS )
1348 return wp_delete_comment($comment_id, true);
1350 if ( !$comment = get_comment($comment_id) )
1354 * Fires immediately before a comment is sent to the Trash.
1358 * @param int $comment_id The comment ID.
1360 do_action( 'trash_comment', $comment->comment_ID );
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() );
1369 * Fires immediately after a comment is sent to Trash.
1373 * @param int $comment_id The comment ID.
1375 do_action( 'trashed_comment', $comment->comment_ID );
1383 * Removes a comment from the Trash
1387 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
1388 * @return bool True on success, false on failure.
1390 function wp_untrash_comment($comment_id) {
1391 $comment = get_comment( $comment_id );
1397 * Fires immediately before a comment is restored from the Trash.
1401 * @param int $comment_id The comment ID.
1403 do_action( 'untrash_comment', $comment->comment_ID );
1405 $status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true );
1406 if ( empty($status) )
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' );
1413 * Fires immediately after a comment is restored from the Trash.
1417 * @param int $comment_id The comment ID.
1419 do_action( 'untrashed_comment', $comment->comment_ID );
1427 * Marks a comment as Spam
1431 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
1432 * @return bool True on success, false on failure.
1434 function wp_spam_comment( $comment_id ) {
1435 $comment = get_comment( $comment_id );
1441 * Fires immediately before a comment is marked as Spam.
1445 * @param int $comment_id The comment ID.
1447 do_action( 'spam_comment', $comment->comment_ID );
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() );
1455 * Fires immediately after a comment is marked as Spam.
1459 * @param int $comment_id The comment ID.
1461 do_action( 'spammed_comment', $comment->comment_ID );
1469 * Removes a comment from the Spam
1473 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
1474 * @return bool True on success, false on failure.
1476 function wp_unspam_comment( $comment_id ) {
1477 $comment = get_comment( $comment_id );
1483 * Fires immediately before a comment is unmarked as Spam.
1487 * @param int $comment_id The comment ID.
1489 do_action( 'unspam_comment', $comment->comment_ID );
1491 $status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true );
1492 if ( empty($status) )
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' );
1499 * Fires immediately after a comment is unmarked as Spam.
1503 * @param int $comment_id The comment ID.
1505 do_action( 'unspammed_comment', $comment->comment_ID );
1513 * The status of a comment by ID.
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.
1520 function wp_get_comment_status($comment_id) {
1521 $comment = get_comment($comment_id);
1525 $approved = $comment->comment_approved;
1527 if ( $approved == null )
1529 elseif ( $approved == '1' )
1531 elseif ( $approved == '0' )
1532 return 'unapproved';
1533 elseif ( $approved == 'spam' )
1535 elseif ( $approved == 'trash' )
1542 * Call hooks for when a comment status transition occurs.
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
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'}.
1555 * @param string $new_status New comment status.
1556 * @param string $old_status Previous comment status.
1557 * @param object $comment Comment data.
1559 function wp_transition_comment_status($new_status, $old_status, $comment) {
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
1565 $comment_statuses = array(
1567 'hold' => 'unapproved', // wp_set_comment_status() uses "hold"
1569 'approve' => 'approved', // wp_set_comment_status() uses "approve"
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];
1575 if ( $new_status != $old_status ) {
1577 * Fires when the comment status is in transition.
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.
1585 do_action( 'transition_comment_status', $new_status, $old_status, $comment );
1587 * Fires when the comment status is in transition from one specific status to another.
1589 * The dynamic portions of the hook name, `$old_status`, and `$new_status`,
1590 * refer to the old and new comment statuses, respectively.
1594 * @param WP_Comment $comment Comment object.
1596 do_action( "comment_{$old_status}_to_{$new_status}", $comment );
1599 * Fires when the status of a specific comment type is in transition.
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.
1604 * Typical comment types include an empty string (standard comment), 'pingback',
1609 * @param int $comment_ID The comment ID.
1610 * @param WP_Comment $comment Comment object.
1612 do_action( "comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment );
1616 * Clear the lastcommentmodified cached value when a comment status is changed.
1618 * Deletes the lastcommentmodified cache key when a comment enters or leaves
1619 * 'approved' status.
1624 * @param string $new_status The new comment status.
1625 * @param string $old_status The old comment status.
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' );
1636 * Get current commenter's name, email, and URL.
1638 * Expects cookies content to already be sanitized. User of this function might
1639 * wish to recheck the returned array for validity.
1641 * @see sanitize_comment_cookies() Use to sanitize cookies
1645 * @return array Comment author, email, url respectively.
1647 function wp_get_current_commenter() {
1648 // Cookies should already be sanitized.
1650 $comment_author = '';
1651 if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
1652 $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
1654 $comment_author_email = '';
1655 if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
1656 $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
1658 $comment_author_url = '';
1659 if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
1660 $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
1663 * Filters the current commenter's name, email, and URL.
1667 * @param array $comment_author_data {
1668 * An array of current commenter variables.
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.
1675 return apply_filters( 'wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url') );
1679 * Inserts a comment into the database.
1682 * @since 4.4.0 Introduced `$comment_meta` argument.
1684 * @global wpdb $wpdb WordPress database abstraction object.
1686 * @param array $commentdata {
1687 * Array of arguments for inserting a new comment.
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.
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
1709 * @type int $user_id ID of the user who submitted the comment. Default 0.
1711 * @return int|false The new comment's ID on success, false on failure.
1713 function wp_insert_comment( $commentdata ) {
1715 $data = wp_unslash( $commentdata );
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'];
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'];
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'];
1733 $user_id = ! isset( $data['user_id'] ) ? 0 : $data['user_id'];
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 ) ) {
1740 $id = (int) $wpdb->insert_id;
1742 if ( $comment_approved == 1 ) {
1743 wp_update_comment_count( $comment_post_ID );
1745 foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
1746 wp_cache_delete( "lastcommentmodified:$timezone", 'timeinfo' );
1750 clean_comment_cache( $id );
1752 $comment = get_comment( $id );
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 );
1762 * Fires immediately after a comment is inserted into the database.
1766 * @param int $id The comment ID.
1767 * @param WP_Comment $comment Comment object.
1769 do_action( 'wp_insert_comment', $id, $comment );
1775 * Filters and sanitizes comment data.
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.
1783 * @param array $commentdata Contains information on the comment.
1784 * @return array Parsed comment information.
1786 function wp_filter_comment($commentdata) {
1787 if ( isset( $commentdata['user_ID'] ) ) {
1789 * Filters the comment author's user id before it is set.
1791 * The first time this filter is evaluated, 'user_ID' is checked
1792 * (for back-compat), followed by the standard 'user_id' value.
1796 * @param int $user_ID The comment author's user ID.
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'] );
1805 * Filters the comment author's browser user agent before it is set.
1809 * @param string $comment_agent The comment author's browser user agent.
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'] );
1815 * Filters the comment content before it is set.
1819 * @param string $comment_content The comment content.
1821 $commentdata['comment_content'] = apply_filters( 'pre_comment_content', $commentdata['comment_content'] );
1823 * Filters the comment author's IP before it is set.
1827 * @param string $comment_author_ip The comment author's IP.
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;
1839 * Whether a comment should be blocked because of comment flood.
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.
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
1851 if ( ($time_newcomment - $time_lastcomment) < 15 )
1857 * Adds a new comment to the database.
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.
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.
1867 * See {@link https://core.trac.wordpress.org/ticket/9235}
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.
1874 * @see wp_insert_comment()
1875 * @global wpdb $wpdb WordPress database abstraction object.
1877 * @param array $commentdata {
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.
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.
1900 function wp_new_comment( $commentdata, $avoid_die = false ) {
1903 if ( isset( $commentdata['user_ID'] ) ) {
1904 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
1907 $prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0;
1910 * Filters a comment's data before it is sanitized and inserted into the database.
1914 * @param array $commentdata Comment data.
1916 $commentdata = apply_filters( 'preprocess_comment', $commentdata );
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'];
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;
1929 if ( ! isset( $commentdata['comment_author_IP'] ) ) {
1930 $commentdata['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
1932 $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '', $commentdata['comment_author_IP'] );
1934 if ( ! isset( $commentdata['comment_agent'] ) ) {
1935 $commentdata['comment_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT']: '';
1937 $commentdata['comment_agent'] = substr( $commentdata['comment_agent'], 0, 254 );
1939 if ( empty( $commentdata['comment_date'] ) ) {
1940 $commentdata['comment_date'] = current_time('mysql');
1943 if ( empty( $commentdata['comment_date_gmt'] ) ) {
1944 $commentdata['comment_date_gmt'] = current_time( 'mysql', 1 );
1947 $commentdata = wp_filter_comment($commentdata);
1949 $commentdata['comment_approved'] = wp_allow_comment( $commentdata, $avoid_die );
1950 if ( is_wp_error( $commentdata['comment_approved'] ) ) {
1951 return $commentdata['comment_approved'];
1954 $comment_ID = wp_insert_comment($commentdata);
1955 if ( ! $comment_ID ) {
1956 $fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' );
1958 foreach ( $fields as $field ) {
1959 if ( isset( $commentdata[ $field ] ) ) {
1960 $commentdata[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $commentdata[ $field ] );
1964 $commentdata = wp_filter_comment( $commentdata );
1966 $commentdata['comment_approved'] = wp_allow_comment( $commentdata, $avoid_die );
1967 if ( is_wp_error( $commentdata['comment_approved'] ) ) {
1968 return $commentdata['comment_approved'];
1971 $comment_ID = wp_insert_comment( $commentdata );
1972 if ( ! $comment_ID ) {
1978 * Fires immediately after a comment is inserted into the database.
1981 * @since 4.5.0 The `$commentdata` parameter was added.
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.
1987 do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'], $commentdata );
1993 * Send a comment moderation notification to the comment moderator.
1997 * @param int $comment_ID ID of the comment.
1998 * @return bool True on success, false on failure.
2000 function wp_new_comment_notify_moderator( $comment_ID ) {
2001 $comment = get_comment( $comment_ID );
2003 // Only send notifications for pending comments.
2004 $maybe_notify = ( '0' == $comment->comment_approved );
2006 /** This filter is documented in wp-includes/comment.php */
2007 $maybe_notify = apply_filters( 'notify_moderator', $maybe_notify, $comment_ID );
2009 if ( ! $maybe_notify ) {
2013 return wp_notify_moderator( $comment_ID );
2017 * Send a notification of a new comment to the post author.
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.
2024 * @param int $comment_ID Comment ID.
2025 * @return bool True on success, false on failure.
2027 function wp_new_comment_notify_postauthor( $comment_ID ) {
2028 $comment = get_comment( $comment_ID );
2030 $maybe_notify = get_option( 'comments_notify' );
2033 * Filters whether to send the post author new comment notification emails,
2034 * overriding the site setting.
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.
2041 $maybe_notify = apply_filters( 'notify_post_author', $maybe_notify, $comment_ID );
2044 * wp_notify_postauthor() checks if notifying the author of their own comment.
2045 * By default, it won't, but filters can override this.
2047 if ( ! $maybe_notify ) {
2051 // Only send notifications for approved comments.
2052 if ( ! isset( $comment->comment_approved ) || '1' != $comment->comment_approved ) {
2056 return wp_notify_postauthor( $comment_ID );
2060 * Sets the status of a comment.
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.
2067 * @global wpdb $wpdb WordPress database abstraction object.
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.
2074 function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
2077 switch ( $comment_status ) {
2085 add_action( 'wp_set_comment_status', 'wp_new_comment_notify_postauthor' );
2097 $comment_old = clone get_comment($comment_id);
2099 if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array( 'comment_ID' => $comment_old->comment_ID ) ) ) {
2101 return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
2106 clean_comment_cache( $comment_old->comment_ID );
2108 $comment = get_comment( $comment_old->comment_ID );
2111 * Fires immediately before transitioning a comment's status from one to another
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.
2120 do_action( 'wp_set_comment_status', $comment->comment_ID, $comment_status );
2122 wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
2124 wp_update_comment_count($comment->comment_post_ID);
2130 * Updates an existing comment in the database.
2132 * Filters the comment and makes sure certain fields are valid before updating.
2136 * @global wpdb $wpdb WordPress database abstraction object.
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.
2141 function wp_update_comment($commentarr) {
2144 // First, get all of the original fields
2145 $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
2146 if ( empty( $comment ) ) {
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'] ) ) {
2155 // Escape data pulled from DB.
2156 $comment = wp_slash($comment);
2158 $old_status = $comment['comment_approved'];
2160 // Merge old and new fields with new fields overwriting old ones.
2161 $commentarr = array_merge($comment, $commentarr);
2163 $commentarr = wp_filter_comment( $commentarr );
2165 // Now extract the merged array.
2166 $data = wp_unslash( $commentarr );
2169 * Filters the comment content before it is updated in the database.
2173 * @param string $comment_content The comment data.
2175 $data['comment_content'] = apply_filters( 'comment_save_pre', $data['comment_content'] );
2177 $data['comment_date_gmt'] = get_gmt_from_date( $data['comment_date'] );
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;
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 );
2193 * Filters the comment data immediately before it is updated in the database.
2195 * Note: data being passed to the filter is already unslashed.
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.
2203 $data = apply_filters( 'wp_update_comment_data', $data, $comment, $commentarr );
2205 $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
2207 clean_comment_cache( $comment_ID );
2208 wp_update_comment_count( $comment_post_ID );
2210 * Fires immediately after a comment is updated in the database.
2212 * The hook also fires immediately before comment status transition hooks are fired.
2215 * @since 4.6.0 Added the `$data` parameter.
2217 * @param int $comment_ID The comment ID.
2218 * @param array $data Comment data.
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);
2227 * Whether to defer comment counting.
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.
2235 * @staticvar bool $_defer
2237 * @param bool $defer
2240 function wp_defer_comment_counting($defer=null) {
2241 static $_defer = false;
2243 if ( is_bool($defer) ) {
2245 // flush any deferred counts
2247 wp_update_comment_count( null, true );
2254 * Updates the comment count for post(s).
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.
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.
2265 * @see wp_update_comment_count_now() For what could cause a false return value
2267 * @staticvar array $_deferred
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
2275 function wp_update_comment_count($post_id, $do_deferred=false) {
2276 static $_deferred = array();
2278 if ( empty( $post_id ) && ! $do_deferred ) {
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 */
2290 if ( wp_defer_comment_counting() ) {
2291 $_deferred[] = $post_id;
2294 elseif ( $post_id ) {
2295 return wp_update_comment_count_now($post_id);
2301 * Updates the comment count for the post.
2305 * @global wpdb $wpdb WordPress database abstraction object.
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.
2310 function wp_update_comment_count_now($post_id) {
2312 $post_id = (int) $post_id;
2316 wp_cache_delete( 'comments-0', 'counts' );
2317 wp_cache_delete( "comments-{$post_id}", 'counts' );
2319 if ( !$post = get_post($post_id) )
2322 $old = (int) $post->comment_count;
2325 * Filters a post's comment count before it is updated in the database.
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.
2333 $new = apply_filters( 'pre_wp_update_comment_count_now', null, $old, $post_id );
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 ) );
2341 $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) );
2343 clean_post_cache( $post );
2346 * Fires immediately after a post's comment count is updated in the database.
2350 * @param int $post_id Post ID.
2351 * @param int $new The new comment count.
2352 * @param int $old The old comment count.
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 );
2362 // Ping and trackback functions.
2366 * Finds a pingback server URI based on the given URL.
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.
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.
2378 function discover_pingback_server_uri( $url, $deprecated = '' ) {
2379 if ( !empty( $deprecated ) )
2380 _deprecated_argument( __FUNCTION__, '2.7.0' );
2382 $pingback_str_dquote = 'rel="pingback"';
2383 $pingback_str_squote = 'rel=\'pingback\'';
2385 /** @todo Should use Filter Extension or custom preg_match instead. */
2386 $parsed_url = parse_url($url);
2388 if ( ! isset( $parsed_url['host'] ) ) // Not a URL. This should never happen.
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']) )
2396 $response = wp_safe_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
2398 if ( is_wp_error( $response ) )
2401 if ( wp_remote_retrieve_header( $response, 'x-pingback' ) )
2402 return wp_remote_retrieve_header( $response, 'x-pingback' );
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' )) )
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' ) );
2411 if ( is_wp_error( $response ) )
2414 $contents = wp_remote_retrieve_body( $response );
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);
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;
2437 * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
2441 * @global wpdb $wpdb WordPress database abstraction object.
2443 function do_all_pings() {
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 );
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 );
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);
2464 //Do Update Services/Generic Pings
2469 * Perform trackbacks.
2472 * @since 4.7.0 $post_id can be a WP_Post object.
2474 * @global wpdb $wpdb WordPress database abstraction object.
2476 * @param int|WP_Post $post_id Post object or ID to do trackbacks on.
2478 function do_trackbacks( $post_id ) {
2480 $post = get_post( $post_id );
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 ) );
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 );
2496 /** This filter is documented in wp-includes/post-template.php */
2497 $excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );
2500 $excerpt = str_replace(']]>', ']]>', $excerpt);
2501 $excerpt = wp_html_excerpt($excerpt, 252, '…');
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);
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;
2514 $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s,
2515 '')) WHERE ID = %d", $tb_ping, $post->ID ) );
2522 * Sends pings to all of the ping site services.
2526 * @param int $post_id Post ID.
2527 * @return int Same as Post ID from parameter
2529 function generic_ping( $post_id = 0 ) {
2530 $services = get_option('ping_sites');
2532 $services = explode("\n", $services);
2533 foreach ( (array) $services as $service ) {
2534 $service = trim($service);
2535 if ( '' != $service )
2536 weblog_ping($service);
2543 * Pings back the links found in a post.
2546 * @since 4.7.0 $post_id can be a WP_Post object.
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.
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' );
2555 // original code by Mort (http://mort.mine.nu:8080)
2556 $post_links = array();
2558 $post = get_post( $post_id );
2563 $pung = get_pung( $post );
2565 if ( empty( $content ) ) {
2566 $content = $post->post_content;
2570 // Parsing the post, external links (if any) are stored in the $post_links array
2571 $post_links_temp = wp_extract_urls( $content );
2574 // Walking thru the links array
2575 // first we get rid of links pointing to sites, not to specific files
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/>
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;
2594 $post_links = array_unique( $post_links );
2596 * Fires just before pinging back links found in a post.
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.
2604 do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post->ID ) );
2606 foreach ( (array) $post_links as $pagelinkedto ) {
2607 $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
2609 if ( $pingback_server_url ) {
2610 @ set_time_limit( 60 );
2611 // Now, the RPC call
2612 $pagelinkedfrom = get_permalink( $post );
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;
2618 * Filters the user agent sent when pinging-back a URL.
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.
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;
2633 if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
2634 add_ping( $post, $pagelinkedto );
2640 * Check whether blog is public before returning sites.
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.
2647 function privacy_ping_filter($sites) {
2648 if ( '0' != get_option('blog_public') )
2657 * Updates database when sending trackback to prevent duplicates.
2661 * @global wpdb $wpdb WordPress database abstraction object.
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.
2669 function trackback($trackback_url, $title, $excerpt, $ID) {
2672 if ( empty($trackback_url) )
2676 $options['timeout'] = 10;
2677 $options['body'] = array(
2679 'url' => get_permalink($ID),
2680 'blog_name' => get_option('blogname'),
2681 'excerpt' => $excerpt
2684 $response = wp_safe_remote_post( $trackback_url, $options );
2686 if ( is_wp_error( $response ) )
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) );
2698 * @param string $server Host of blog to connect to.
2699 * @param string $path Path to send the ping.
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' );
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' );
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);
2718 * Default filter attached to pingback_ping_source_uri to validate the pingback's Source URI
2721 * @see wp_http_validate_url()
2723 * @param string $source_uri
2726 function pingback_ping_source_uri( $source_uri ) {
2727 return (string) wp_http_validate_url( $source_uri );
2731 * Default filter attached to xmlrpc_pingback_error.
2733 * Returns a generic pingback error code unless the error code is 48,
2734 * which reports that the pingback is already registered.
2737 * @link https://www.hixie.ch/specs/pingback/pingback#TOC3
2739 * @param IXR_Error $ixr_error
2742 function xmlrpc_pingback_error( $ixr_error ) {
2743 if ( $ixr_error->code === 48 )
2745 return new IXR_Error( 0, '' );
2753 * Removes a comment from the object cache.
2757 * @param int|array $ids Comment ID or an array of comment IDs to remove from cache.
2759 function clean_comment_cache($ids) {
2760 foreach ( (array) $ids as $id ) {
2761 wp_cache_delete( $id, 'comment' );
2764 * Fires immediately after a comment has been removed from the object cache.
2768 * @param int $id Comment ID.
2770 do_action( 'clean_comment_cache', $id );
2773 wp_cache_set( 'last_changed', microtime(), 'comment' );
2777 * Updates the comment cache of given comments.
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.
2784 * @since 4.4.0 Introduced the `$update_meta_cache` parameter.
2786 * @param array $comments Array of comment row objects
2787 * @param bool $update_meta_cache Whether to update commentmeta cache. Default true.
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');
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;
2799 update_meta_cache( 'comment', $comment_ids );
2804 * Adds any comments from the given IDs to the cache that do not already exist in cache.
2809 * @see update_comment_cache()
2810 * @global wpdb $wpdb WordPress database abstraction object.
2812 * @param array $comment_ids Array of comment IDs.
2813 * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
2815 function _prime_comment_caches( $comment_ids, $update_meta_cache = true ) {
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 ) ) ) );
2822 update_comment_cache( $fresh_comments, $update_meta_cache );
2831 * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
2836 * @param WP_Post $posts Post data object.
2837 * @param WP_Query $query Query object.
2840 function _close_comments_for_old_posts( $posts, $query ) {
2841 if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) )
2845 * Filters the list of post types to automatically close comments for.
2849 * @param array $post_types An array of registered post types. Default array with 'post'.
2851 $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
2852 if ( ! in_array( $posts[0]->post_type, $post_types ) )
2855 $days_old = (int) get_option( 'close_comments_days_old' );
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';
2868 * Close comments on an old post. Hooked to comments_open and pings_open.
2873 * @param bool $open Comments open or closed
2874 * @param int $post_id Post ID
2875 * @return bool $open
2877 function _close_comments_for_old_post( $open, $post_id ) {
2881 if ( !get_option('close_comments_for_old_posts') )
2884 $days_old = (int) get_option('close_comments_days_old');
2888 $post = get_post($post_id);
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 ) )
2895 // Undated drafts should not show up as comments closed.
2896 if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
2900 if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) )
2907 * Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form.
2909 * This function expects unslashed data, as opposed to functions such as `wp_new_comment()` which
2910 * expect slashed data.
2914 * @param array $comment_data {
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.
2925 * @return WP_Comment|WP_Error A WP_Comment object on success, a WP_Error object on failure.
2927 function wp_handle_comment_submission( $comment_data ) {
2929 $comment_post_ID = $comment_parent = 0;
2930 $comment_author = $comment_author_email = $comment_author_url = $comment_content = null;
2932 if ( isset( $comment_data['comment_post_ID'] ) ) {
2933 $comment_post_ID = (int) $comment_data['comment_post_ID'];
2935 if ( isset( $comment_data['author'] ) && is_string( $comment_data['author'] ) ) {
2936 $comment_author = trim( strip_tags( $comment_data['author'] ) );
2938 if ( isset( $comment_data['email'] ) && is_string( $comment_data['email'] ) ) {
2939 $comment_author_email = trim( $comment_data['email'] );
2941 if ( isset( $comment_data['url'] ) && is_string( $comment_data['url'] ) ) {
2942 $comment_author_url = trim( $comment_data['url'] );
2944 if ( isset( $comment_data['comment'] ) && is_string( $comment_data['comment'] ) ) {
2945 $comment_content = trim( $comment_data['comment'] );
2947 if ( isset( $comment_data['comment_parent'] ) ) {
2948 $comment_parent = absint( $comment_data['comment_parent'] );
2951 $post = get_post( $comment_post_ID );
2953 if ( empty( $post->comment_status ) ) {
2956 * Fires when a comment is attempted on a post that does not exist.
2960 * @param int $comment_post_ID Post ID.
2962 do_action( 'comment_id_not_found', $comment_post_ID );
2964 return new WP_Error( 'comment_id_not_found' );
2968 // get_post_status() will get the parent status for attachments.
2969 $status = get_post_status( $post );
2971 if ( ( 'private' == $status ) && ! current_user_can( 'read_post', $comment_post_ID ) ) {
2972 return new WP_Error( 'comment_id_not_found' );
2975 $status_obj = get_post_status_object( $status );
2977 if ( ! comments_open( $comment_post_ID ) ) {
2980 * Fires when a comment is attempted on a post that has comments closed.
2984 * @param int $comment_post_ID Post ID.
2986 do_action( 'comment_closed', $comment_post_ID );
2988 return new WP_Error( 'comment_closed', __( 'Sorry, comments are closed for this item.' ), 403 );
2990 } elseif ( 'trash' == $status ) {
2993 * Fires when a comment is attempted on a trashed post.
2997 * @param int $comment_post_ID Post ID.
2999 do_action( 'comment_on_trash', $comment_post_ID );
3001 return new WP_Error( 'comment_on_trash' );
3003 } elseif ( ! $status_obj->public && ! $status_obj->private ) {
3006 * Fires when a comment is attempted on a post in draft mode.
3010 * @param int $comment_post_ID Post ID.
3012 do_action( 'comment_on_draft', $comment_post_ID );
3014 return new WP_Error( 'comment_on_draft' );
3016 } elseif ( post_password_required( $comment_post_ID ) ) {
3019 * Fires when a comment is attempted on a password-protected post.
3023 * @param int $comment_post_ID Post ID.
3025 do_action( 'comment_on_password_protected', $comment_post_ID );
3027 return new WP_Error( 'comment_on_password_protected' );
3032 * Fires before a comment is posted.
3036 * @param int $comment_post_ID Post ID.
3038 do_action( 'pre_comment_on_post', $comment_post_ID );
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;
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 )
3056 kses_remove_filters(); // start with a clean slate
3057 kses_init_filters(); // set up the filters
3061 if ( get_option( 'comment_registration' ) ) {
3062 return new WP_Error( 'not_logged_in', __( 'Sorry, you must be logged in to comment.' ), 403 );
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 );
3076 if ( '' == $comment_content ) {
3077 return new WP_Error( 'require_valid_comment', __( '<strong>ERROR</strong>: please type a comment.' ), 200 );
3080 $commentdata = compact(
3083 'comment_author_email',
3084 'comment_author_url',
3091 $check_max_lengths = wp_check_comment_data_max_lengths( $commentdata );
3092 if ( is_wp_error( $check_max_lengths ) ) {
3093 return $check_max_lengths;
3096 $comment_id = wp_new_comment( wp_slash( $commentdata ), true );
3097 if ( is_wp_error( $comment_id ) ) {
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 );
3105 return get_comment( $comment_id );