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 * Filter the maximum number of links allowed in a comment.
58 * @param int $num_links The number of links allowed.
59 * @param string $url Comment author's URL. Included in allowed links total.
61 $num_links = apply_filters( 'comment_max_links_url', $num_links, $url );
64 * If the number of links in the comment exceeds the allowed amount,
65 * fail the check by returning false.
67 if ( $num_links >= $max_links )
71 $mod_keys = trim(get_option('moderation_keys'));
73 // If moderation 'keys' (keywords) are set, process them.
74 if ( !empty($mod_keys) ) {
75 $words = explode("\n", $mod_keys );
77 foreach ( (array) $words as $word) {
85 * Do some escaping magic so that '#' (number of) characters in the spam
86 * words don't break things:
88 $word = preg_quote($word, '#');
91 * Check the comment fields for moderation keywords. If any are found,
92 * fail the check for the given field by returning false.
94 $pattern = "#$word#i";
95 if ( preg_match($pattern, $author) ) return false;
96 if ( preg_match($pattern, $email) ) return false;
97 if ( preg_match($pattern, $url) ) return false;
98 if ( preg_match($pattern, $comment) ) return false;
99 if ( preg_match($pattern, $user_ip) ) return false;
100 if ( preg_match($pattern, $user_agent) ) return false;
105 * Check if the option to approve comments by previously-approved authors is enabled.
107 * If it is enabled, check whether the comment author has a previously-approved comment,
108 * as well as whether there are any moderation keywords (if set) present in the author
109 * email address. If both checks pass, return true. Otherwise, return false.
111 if ( 1 == get_option('comment_whitelist')) {
112 if ( 'trackback' != $comment_type && 'pingback' != $comment_type && $author != '' && $email != '' ) {
113 // expected_slashed ($author, $email)
114 $ok_to_comment = $wpdb->get_var("SELECT comment_approved FROM $wpdb->comments WHERE comment_author = '$author' AND comment_author_email = '$email' and comment_approved = '1' LIMIT 1");
115 if ( ( 1 == $ok_to_comment ) &&
116 ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
128 * Retrieve the approved comments for post $post_id.
131 * @since 4.1.0 Refactored to leverage {@see WP_Comment_Query} over a direct query.
133 * @param int $post_id The ID of the post.
134 * @param array $args Optional. See {@see WP_Comment_Query::query()} for information
135 * on accepted arguments.
136 * @return int|array $comments The approved comments, or number of comments if `$count`
139 function get_approved_comments( $post_id, $args = array() ) {
146 'post_id' => $post_id,
149 $r = wp_parse_args( $args, $defaults );
151 $query = new WP_Comment_Query;
152 return $query->query( $r );
156 * Retrieves comment data given a comment ID or comment object.
158 * If an object is passed then the comment data will be cached and then returned
159 * after being passed through a filter. If the comment is empty, then the global
160 * comment variable will be used, if it is set.
164 * @global WP_Comment $comment
166 * @param WP_Comment|string|int $comment Comment to retrieve.
167 * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
168 * @return WP_Comment|array|null Depends on $output value.
170 function get_comment( &$comment = null, $output = OBJECT ) {
171 if ( empty( $comment ) && isset( $GLOBALS['comment'] ) ) {
172 $comment = $GLOBALS['comment'];
175 if ( $comment instanceof WP_Comment ) {
176 $_comment = $comment;
177 } elseif ( is_object( $comment ) ) {
178 $_comment = new WP_Comment( $comment );
180 $_comment = WP_Comment::get_instance( $comment );
188 * Fires after a comment is retrieved.
192 * @param mixed $_comment Comment data.
194 $_comment = apply_filters( 'get_comment', $_comment );
196 if ( $output == OBJECT ) {
198 } elseif ( $output == ARRAY_A ) {
199 return $_comment->to_array();
200 } elseif ( $output == ARRAY_N ) {
201 return array_values( $_comment->to_array() );
207 * Retrieve a list of comments.
209 * The comment list can be for the blog as a whole or for an individual post.
213 * @param string|array $args Optional. Array or string of arguments. See {@see WP_Comment_Query::parse_query()}
214 * for information on accepted arguments. Default empty.
215 * @return int|array List of comments or number of found comments if `$count` argument is true.
217 function get_comments( $args = '' ) {
218 $query = new WP_Comment_Query;
219 return $query->query( $args );
223 * Retrieve all of the WordPress supported comment statuses.
225 * Comments have a limited set of valid status values, this provides the comment
226 * status values and descriptions.
230 * @return array List of comment statuses.
232 function get_comment_statuses() {
234 'hold' => __( 'Unapproved' ),
235 'approve' => _x( 'Approved', 'comment status' ),
236 'spam' => _x( 'Spam', 'comment status' ),
237 'trash' => _x( 'Trash', 'comment status' ),
244 * Gets the default comment status for a post type.
248 * @param string $post_type Optional. Post type. Default 'post'.
249 * @param string $comment_type Optional. Comment type. Default 'comment'.
250 * @return string Expected return value is 'open' or 'closed'.
252 function get_default_comment_status( $post_type = 'post', $comment_type = 'comment' ) {
253 switch ( $comment_type ) {
256 $supports = 'trackbacks';
260 $supports = 'comments';
265 if ( 'page' === $post_type ) {
267 } elseif ( post_type_supports( $post_type, $supports ) ) {
268 $status = get_option( "default_{$option}_status" );
274 * Filter the default comment status for the given post type.
278 * @param string $status Default status for the given post type,
279 * either 'open' or 'closed'.
280 * @param string $post_type Post type. Default is `post`.
281 * @param string $comment_type Type of comment. Default is `comment`.
283 return apply_filters( 'get_default_comment_status' , $status, $post_type, $comment_type );
287 * The date the last comment was modified.
291 * @global wpdb $wpdb WordPress database abstraction object.
292 * @staticvar array $cache_lastcommentmodified
294 * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
295 * or 'server' locations.
296 * @return string Last comment modified date.
298 function get_lastcommentmodified($timezone = 'server') {
300 static $cache_lastcommentmodified = array();
302 if ( isset($cache_lastcommentmodified[$timezone]) )
303 return $cache_lastcommentmodified[$timezone];
305 $add_seconds_server = date('Z');
307 switch ( strtolower($timezone)) {
309 $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
312 $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
315 $lastcommentmodified = $wpdb->get_var($wpdb->prepare("SELECT DATE_ADD(comment_date_gmt, INTERVAL %s SECOND) FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1", $add_seconds_server));
319 $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
321 return $lastcommentmodified;
325 * The amount of comments in a post or total comments.
327 * A lot like {@link wp_count_comments()}, in that they both return comment
328 * stats (albeit with different types). The {@link wp_count_comments()} actual
329 * caches, but this function does not.
333 * @global wpdb $wpdb WordPress database abstraction object.
335 * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
336 * @return array The amount of spam, approved, awaiting moderation, and total comments.
338 function get_comment_count( $post_id = 0 ) {
341 $post_id = (int) $post_id;
344 if ( $post_id > 0 ) {
345 $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
348 $totals = (array) $wpdb->get_results("
349 SELECT comment_approved, COUNT( * ) AS total
350 FROM {$wpdb->comments}
352 GROUP BY comment_approved
355 $comment_count = array(
357 'awaiting_moderation' => 0,
361 'total_comments' => 0,
365 foreach ( $totals as $row ) {
366 switch ( $row['comment_approved'] ) {
368 $comment_count['trash'] = $row['total'];
371 $comment_count['post-trashed'] = $row['total'];
374 $comment_count['spam'] = $row['total'];
375 $comment_count['total_comments'] += $row['total'];
378 $comment_count['approved'] = $row['total'];
379 $comment_count['total_comments'] += $row['total'];
380 $comment_count['all'] += $row['total'];
383 $comment_count['awaiting_moderation'] = $row['total'];
384 $comment_count['total_comments'] += $row['total'];
385 $comment_count['all'] += $row['total'];
392 return $comment_count;
396 // Comment meta functions
400 * Add meta data field to a comment.
403 * @link https://codex.wordpress.org/Function_Reference/add_comment_meta
405 * @param int $comment_id Comment ID.
406 * @param string $meta_key Metadata name.
407 * @param mixed $meta_value Metadata value.
408 * @param bool $unique Optional, default is false. Whether the same key should not be added.
409 * @return int|bool Meta ID on success, false on failure.
411 function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
412 return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
416 * Remove metadata matching criteria from a comment.
418 * You can match based on the key, or key and value. Removing based on key and
419 * value, will keep from removing duplicate metadata with the same key. It also
420 * allows removing all metadata matching key, if needed.
423 * @link https://codex.wordpress.org/Function_Reference/delete_comment_meta
425 * @param int $comment_id comment ID
426 * @param string $meta_key Metadata name.
427 * @param mixed $meta_value Optional. Metadata value.
428 * @return bool True on success, false on failure.
430 function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
431 return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
435 * Retrieve comment meta field for a comment.
438 * @link https://codex.wordpress.org/Function_Reference/get_comment_meta
440 * @param int $comment_id Comment ID.
441 * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
442 * @param bool $single Whether to return a single value.
443 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
446 function get_comment_meta($comment_id, $key = '', $single = false) {
447 return get_metadata('comment', $comment_id, $key, $single);
451 * Update comment meta field based on comment ID.
453 * Use the $prev_value parameter to differentiate between meta fields with the
454 * same key and comment ID.
456 * If the meta field for the comment does not exist, it will be added.
459 * @link https://codex.wordpress.org/Function_Reference/update_comment_meta
461 * @param int $comment_id Comment ID.
462 * @param string $meta_key Metadata key.
463 * @param mixed $meta_value Metadata value.
464 * @param mixed $prev_value Optional. Previous value to check before removing.
465 * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
467 function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
468 return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
472 * Queues comments for metadata lazy-loading.
476 * @param array $comments Array of comment objects.
478 function wp_queue_comments_for_comment_meta_lazyload( $comments ) {
479 // Don't use `wp_list_pluck()` to avoid by-reference manipulation.
480 $comment_ids = array();
481 if ( is_array( $comments ) ) {
482 foreach ( $comments as $comment ) {
483 if ( $comment instanceof WP_Comment ) {
484 $comment_ids[] = $comment->comment_ID;
489 if ( $comment_ids ) {
490 $lazyloader = wp_metadata_lazyloader();
491 $lazyloader->queue_objects( 'comment', $comment_ids );
496 * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
497 * to recall previous comments by this commentator that are still held in moderation.
499 * @param WP_Comment $comment Comment object.
500 * @param object $user Comment author's object.
504 function wp_set_comment_cookies($comment, $user) {
505 if ( $user->exists() )
509 * Filter the lifetime of the comment cookie in seconds.
513 * @param int $seconds Comment cookie lifetime. Default 30000000.
515 $comment_cookie_lifetime = apply_filters( 'comment_cookie_lifetime', 30000000 );
516 $secure = ( 'https' === parse_url( home_url(), PHP_URL_SCHEME ) );
517 setcookie( 'comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
518 setcookie( 'comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
519 setcookie( 'comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
523 * Sanitizes the cookies sent to the user already.
525 * Will only do anything if the cookies have already been created for the user.
526 * Mostly used after cookies had been sent to use elsewhere.
530 function sanitize_comment_cookies() {
531 if ( isset( $_COOKIE['comment_author_' . COOKIEHASH] ) ) {
533 * Filter the comment author's name cookie before it is set.
535 * When this filter hook is evaluated in wp_filter_comment(),
536 * the comment author's name string is passed.
540 * @param string $author_cookie The comment author name cookie.
542 $comment_author = apply_filters( 'pre_comment_author_name', $_COOKIE['comment_author_' . COOKIEHASH] );
543 $comment_author = wp_unslash($comment_author);
544 $comment_author = esc_attr($comment_author);
545 $_COOKIE['comment_author_' . COOKIEHASH] = $comment_author;
548 if ( isset( $_COOKIE['comment_author_email_' . COOKIEHASH] ) ) {
550 * Filter the comment author's email cookie before it is set.
552 * When this filter hook is evaluated in wp_filter_comment(),
553 * the comment author's email string is passed.
557 * @param string $author_email_cookie The comment author email cookie.
559 $comment_author_email = apply_filters( 'pre_comment_author_email', $_COOKIE['comment_author_email_' . COOKIEHASH] );
560 $comment_author_email = wp_unslash($comment_author_email);
561 $comment_author_email = esc_attr($comment_author_email);
562 $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
565 if ( isset( $_COOKIE['comment_author_url_' . COOKIEHASH] ) ) {
567 * Filter the comment author's URL cookie before it is set.
569 * When this filter hook is evaluated in wp_filter_comment(),
570 * the comment author's URL string is passed.
574 * @param string $author_url_cookie The comment author URL cookie.
576 $comment_author_url = apply_filters( 'pre_comment_author_url', $_COOKIE['comment_author_url_' . COOKIEHASH] );
577 $comment_author_url = wp_unslash($comment_author_url);
578 $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
583 * Validates whether this comment is allowed to be made.
587 * @global wpdb $wpdb WordPress database abstraction object.
589 * @param array $commentdata Contains information on the comment
590 * @return int|string Signifies the approval status (0|1|'spam')
592 function wp_allow_comment( $commentdata ) {
595 // Simple duplicate check
596 // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
597 $dupe = $wpdb->prepare(
598 "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ",
599 wp_unslash( $commentdata['comment_post_ID'] ),
600 wp_unslash( $commentdata['comment_parent'] ),
601 wp_unslash( $commentdata['comment_author'] )
603 if ( $commentdata['comment_author_email'] ) {
604 $dupe .= $wpdb->prepare(
605 "OR comment_author_email = %s ",
606 wp_unslash( $commentdata['comment_author_email'] )
609 $dupe .= $wpdb->prepare(
610 ") AND comment_content = %s LIMIT 1",
611 wp_unslash( $commentdata['comment_content'] )
614 $dupe_id = $wpdb->get_var( $dupe );
617 * Filters the ID, if any, of the duplicate comment found when creating a new comment.
619 * Return an empty value from this filter to allow what WP considers a duplicate comment.
623 * @param int $dupe_id ID of the comment identified as a duplicate.
624 * @param array $commentdata Data for the comment being created.
626 $dupe_id = apply_filters( 'duplicate_comment_id', $dupe_id, $commentdata );
630 * Fires immediately after a duplicate comment is detected.
634 * @param array $commentdata Comment data.
636 do_action( 'comment_duplicate_trigger', $commentdata );
637 if ( defined( 'DOING_AJAX' ) ) {
638 die( __('Duplicate comment detected; it looks as though you’ve already said that!') );
640 wp_die( __( 'Duplicate comment detected; it looks as though you’ve already said that!' ), 409 );
644 * Fires immediately before a comment is marked approved.
646 * Allows checking for comment flooding.
650 * @param string $comment_author_IP Comment author's IP address.
651 * @param string $comment_author_email Comment author's email.
652 * @param string $comment_date_gmt GMT date the comment was posted.
655 'check_comment_flood',
656 $commentdata['comment_author_IP'],
657 $commentdata['comment_author_email'],
658 $commentdata['comment_date_gmt']
661 if ( ! empty( $commentdata['user_id'] ) ) {
662 $user = get_userdata( $commentdata['user_id'] );
663 $post_author = $wpdb->get_var( $wpdb->prepare(
664 "SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1",
665 $commentdata['comment_post_ID']
669 if ( isset( $user ) && ( $commentdata['user_id'] == $post_author || $user->has_cap( 'moderate_comments' ) ) ) {
670 // The author and the admins get respect.
673 // Everyone else's comments will be checked.
675 $commentdata['comment_author'],
676 $commentdata['comment_author_email'],
677 $commentdata['comment_author_url'],
678 $commentdata['comment_content'],
679 $commentdata['comment_author_IP'],
680 $commentdata['comment_agent'],
681 $commentdata['comment_type']
688 if ( wp_blacklist_check(
689 $commentdata['comment_author'],
690 $commentdata['comment_author_email'],
691 $commentdata['comment_author_url'],
692 $commentdata['comment_content'],
693 $commentdata['comment_author_IP'],
694 $commentdata['comment_agent']
696 $approved = EMPTY_TRASH_DAYS ? 'trash' : 'spam';
701 * Filter a comment's approval status before it is set.
705 * @param bool|string $approved The approval status. Accepts 1, 0, or 'spam'.
706 * @param array $commentdata Comment data.
708 $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
713 * Check whether comment flooding is occurring.
715 * Won't run, if current user can manage options, so to not block
720 * @global wpdb $wpdb WordPress database abstraction object.
722 * @param string $ip Comment IP.
723 * @param string $email Comment author email address.
724 * @param string $date MySQL time string.
726 function check_comment_flood_db( $ip, $email, $date ) {
728 // don't throttle admins or moderators
729 if ( current_user_can( 'manage_options' ) || current_user_can( 'moderate_comments' ) ) {
732 $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
734 if ( is_user_logged_in() ) {
735 $user = get_current_user_id();
736 $check_column = '`user_id`';
739 $check_column = '`comment_author_IP`';
742 $sql = $wpdb->prepare(
743 "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",
748 $lasttime = $wpdb->get_var( $sql );
750 $time_lastcomment = mysql2date('U', $lasttime, false);
751 $time_newcomment = mysql2date('U', $date, false);
753 * Filter the comment flood status.
757 * @param bool $bool Whether a comment flood is occurring. Default false.
758 * @param int $time_lastcomment Timestamp of when the last comment was posted.
759 * @param int $time_newcomment Timestamp of when the new comment was posted.
761 $flood_die = apply_filters( 'comment_flood_filter', false, $time_lastcomment, $time_newcomment );
764 * Fires before the comment flood message is triggered.
768 * @param int $time_lastcomment Timestamp of when the last comment was posted.
769 * @param int $time_newcomment Timestamp of when the new comment was posted.
771 do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment );
773 if ( defined('DOING_AJAX') )
774 die( __('You are posting comments too quickly. Slow down.') );
776 wp_die( __( 'You are posting comments too quickly. Slow down.' ), 429 );
782 * Separates an array of comments into an array keyed by comment_type.
786 * @param array $comments Array of comments
787 * @return array Array of comments keyed by comment_type.
789 function separate_comments(&$comments) {
790 $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
791 $count = count($comments);
792 for ( $i = 0; $i < $count; $i++ ) {
793 $type = $comments[$i]->comment_type;
796 $comments_by_type[$type][] = &$comments[$i];
797 if ( 'trackback' == $type || 'pingback' == $type )
798 $comments_by_type['pings'][] = &$comments[$i];
801 return $comments_by_type;
805 * Calculate the total number of comment pages.
809 * @uses Walker_Comment
811 * @global WP_Query $wp_query
813 * @param array $comments Optional array of WP_Comment objects. Defaults to $wp_query->comments
814 * @param int $per_page Optional comments per page.
815 * @param bool $threaded Optional control over flat or threaded comments.
816 * @return int Number of comment pages.
818 function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
821 if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
822 return $wp_query->max_num_comment_pages;
824 if ( ( ! $comments || ! is_array( $comments ) ) && ! empty( $wp_query->comments ) )
825 $comments = $wp_query->comments;
827 if ( empty($comments) )
830 if ( ! get_option( 'page_comments' ) ) {
834 if ( !isset($per_page) )
835 $per_page = (int) get_query_var('comments_per_page');
836 if ( 0 === $per_page )
837 $per_page = (int) get_option('comments_per_page');
838 if ( 0 === $per_page )
841 if ( !isset($threaded) )
842 $threaded = get_option('thread_comments');
845 $walker = new Walker_Comment;
846 $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
848 $count = ceil( count( $comments ) / $per_page );
855 * Calculate what page number a comment will appear on for comment paging.
859 * @global wpdb $wpdb WordPress database abstraction object.
861 * @param int $comment_ID Comment ID.
862 * @param array $args {
863 * Array of optional arguments.
864 * @type string $type Limit paginated comments to those matching a given type. Accepts 'comment',
865 * 'trackback', 'pingback', 'pings' (trackbacks and pingbacks), or 'all'.
867 * @type int $per_page Per-page count to use when calculating pagination. Defaults to the value of the
868 * 'comments_per_page' option.
869 * @type int|string $max_depth If greater than 1, comment page will be determined for the top-level parent of
870 * `$comment_ID`. Defaults to the value of the 'thread_comments_depth' option.
872 * @return int|null Comment page number or null on error.
874 function get_page_of_comment( $comment_ID, $args = array() ) {
879 if ( !$comment = get_comment( $comment_ID ) )
882 $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
883 $args = wp_parse_args( $args, $defaults );
884 $original_args = $args;
886 // Order of precedence: 1. `$args['per_page']`, 2. 'comments_per_page' query_var, 3. 'comments_per_page' option.
887 if ( get_option( 'page_comments' ) ) {
888 if ( '' === $args['per_page'] ) {
889 $args['per_page'] = get_query_var( 'comments_per_page' );
892 if ( '' === $args['per_page'] ) {
893 $args['per_page'] = get_option( 'comments_per_page' );
897 if ( empty($args['per_page']) ) {
898 $args['per_page'] = 0;
902 if ( $args['per_page'] < 1 ) {
906 if ( null === $page ) {
907 if ( '' === $args['max_depth'] ) {
908 if ( get_option('thread_comments') )
909 $args['max_depth'] = get_option('thread_comments_depth');
911 $args['max_depth'] = -1;
914 // Find this comment's top level parent if threading is enabled
915 if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
916 return get_page_of_comment( $comment->comment_parent, $args );
918 $comment_args = array(
919 'type' => $args['type'],
920 'post_id' => $comment->comment_post_ID,
923 'status' => 'approve',
925 'date_query' => array(
927 'column' => "$wpdb->comments.comment_date_gmt",
928 'before' => $comment->comment_date_gmt,
933 $comment_query = new WP_Comment_Query();
934 $older_comment_count = $comment_query->query( $comment_args );
936 // No older comments? Then it's page #1.
937 if ( 0 == $older_comment_count ) {
940 // Divide comments older than this one by comments per page to get this comment's page number
942 $page = ceil( ( $older_comment_count + 1 ) / $args['per_page'] );
947 * Filters the calculated page on which a comment appears.
951 * @param int $page Comment page.
952 * @param array $args {
953 * Arguments used to calculate pagination. These include arguments auto-detected by the function,
954 * based on query vars, system settings, etc. For pristine arguments passed to the function,
955 * see `$original_args`.
957 * @type string $type Type of comments to count.
958 * @type int $page Calculated current page.
959 * @type int $per_page Calculated number of comments per page.
960 * @type int $max_depth Maximum comment threading depth allowed.
962 * @param array $original_args {
963 * Array of arguments passed to the function. Some or all of these may not be set.
965 * @type string $type Type of comments to count.
966 * @type int $page Current comment page.
967 * @type int $per_page Number of comments per page.
968 * @type int $max_depth Maximum comment threading depth allowed.
971 return apply_filters( 'get_page_of_comment', (int) $page, $args, $original_args );
975 * Retrieves the maximum character lengths for the comment form fields.
979 * @global wpdb $wpdb WordPress database abstraction object.
981 * @return array Maximum character length for the comment form fields.
983 function wp_get_comment_fields_max_lengths() {
987 'comment_author' => 245,
988 'comment_author_email' => 100,
989 'comment_author_url' => 200,
990 'comment_content' => 65525,
993 if ( $wpdb->is_mysql ) {
994 foreach ( $lengths as $column => $length ) {
995 $col_length = $wpdb->get_col_length( $wpdb->comments, $column );
998 // No point if we can't get the DB column lengths
999 if ( is_wp_error( $col_length ) ) {
1003 if ( ! is_array( $col_length ) && (int) $col_length > 0 ) {
1004 $max_length = (int) $col_length;
1005 } elseif ( is_array( $col_length ) && isset( $col_length['length'] ) && intval( $col_length['length'] ) > 0 ) {
1006 $max_length = (int) $col_length['length'];
1008 if ( ! empty( $col_length['type'] ) && 'byte' === $col_length['type'] ) {
1009 $max_length = $max_length - 10;
1013 if ( $max_length > 0 ) {
1014 $lengths[ $column ] = $max_length;
1020 * Filters the lengths for the comment form fields.
1024 * @param array $lengths Associative array `'field_name' => 'maximum length'`.
1026 return apply_filters( 'wp_get_comment_fields_max_lengths', $lengths );
1030 * Does comment contain blacklisted characters or words.
1034 * @param string $author The author of the comment
1035 * @param string $email The email of the comment
1036 * @param string $url The url used in the comment
1037 * @param string $comment The comment content
1038 * @param string $user_ip The comment author IP address
1039 * @param string $user_agent The author's browser user agent
1040 * @return bool True if comment contains blacklisted content, false if comment does not
1042 function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
1044 * Fires before the comment is tested for blacklisted characters or words.
1048 * @param string $author Comment author.
1049 * @param string $email Comment author's email.
1050 * @param string $url Comment author's URL.
1051 * @param string $comment Comment content.
1052 * @param string $user_ip Comment author's IP address.
1053 * @param string $user_agent Comment author's browser user agent.
1055 do_action( 'wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent );
1057 $mod_keys = trim( get_option('blacklist_keys') );
1058 if ( '' == $mod_keys )
1059 return false; // If moderation keys are empty
1060 $words = explode("\n", $mod_keys );
1062 foreach ( (array) $words as $word ) {
1063 $word = trim($word);
1066 if ( empty($word) ) { continue; }
1068 // Do some escaping magic so that '#' chars in the
1069 // spam words don't break things:
1070 $word = preg_quote($word, '#');
1072 $pattern = "#$word#i";
1074 preg_match($pattern, $author)
1075 || preg_match($pattern, $email)
1076 || preg_match($pattern, $url)
1077 || preg_match($pattern, $comment)
1078 || preg_match($pattern, $user_ip)
1079 || preg_match($pattern, $user_agent)
1087 * Retrieve total comments for blog or single post.
1089 * The properties of the returned object contain the 'moderated', 'approved',
1090 * and spam comments for either the entire blog or single post. Those properties
1091 * contain the amount of comments that match the status. The 'total_comments'
1092 * property contains the integer of total comments.
1094 * The comment stats are cached and then retrieved, if they already exist in the
1099 * @param int $post_id Optional. Post ID.
1100 * @return object|array Comment stats.
1102 function wp_count_comments( $post_id = 0 ) {
1103 $post_id = (int) $post_id;
1106 * Filter the comments count for a given post.
1110 * @param array $count An empty array.
1111 * @param int $post_id The post ID.
1113 $filtered = apply_filters( 'wp_count_comments', array(), $post_id );
1114 if ( ! empty( $filtered ) ) {
1118 $count = wp_cache_get( "comments-{$post_id}", 'counts' );
1119 if ( false !== $count ) {
1123 $stats = get_comment_count( $post_id );
1124 $stats['moderated'] = $stats['awaiting_moderation'];
1125 unset( $stats['awaiting_moderation'] );
1127 $stats_object = (object) $stats;
1128 wp_cache_set( "comments-{$post_id}", $stats_object, 'counts' );
1130 return $stats_object;
1134 * Trashes or deletes a comment.
1136 * The comment is moved to trash instead of permanently deleted unless trash is
1137 * disabled, item is already in the trash, or $force_delete is true.
1139 * The post comment count will be updated if the comment was approved and has a
1140 * post ID available.
1144 * @global wpdb $wpdb WordPress database abstraction object.
1146 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
1147 * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
1148 * @return bool True on success, false on failure.
1150 function wp_delete_comment($comment_id, $force_delete = false) {
1152 if (!$comment = get_comment($comment_id))
1155 if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status( $comment ), array( 'trash', 'spam' ) ) )
1156 return wp_trash_comment($comment_id);
1159 * Fires immediately before a comment is deleted from the database.
1163 * @param int $comment_id The comment ID.
1165 do_action( 'delete_comment', $comment->comment_ID );
1167 // Move children up a level.
1168 $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment->comment_ID) );
1169 if ( !empty($children) ) {
1170 $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment->comment_ID));
1171 clean_comment_cache($children);
1175 $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment->comment_ID ) );
1176 foreach ( $meta_ids as $mid )
1177 delete_metadata_by_mid( 'comment', $mid );
1179 if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment->comment_ID ) ) )
1183 * Fires immediately after a comment is deleted from the database.
1187 * @param int $comment_id The comment ID.
1189 do_action( 'deleted_comment', $comment->comment_ID );
1191 $post_id = $comment->comment_post_ID;
1192 if ( $post_id && $comment->comment_approved == 1 )
1193 wp_update_comment_count($post_id);
1195 clean_comment_cache( $comment->comment_ID );
1197 /** This action is documented in wp-includes/comment.php */
1198 do_action( 'wp_set_comment_status', $comment->comment_ID, 'delete' );
1200 wp_transition_comment_status('delete', $comment->comment_approved, $comment);
1205 * Moves a comment to the Trash
1207 * If trash is disabled, comment is permanently deleted.
1211 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
1212 * @return bool True on success, false on failure.
1214 function wp_trash_comment($comment_id) {
1215 if ( !EMPTY_TRASH_DAYS )
1216 return wp_delete_comment($comment_id, true);
1218 if ( !$comment = get_comment($comment_id) )
1222 * Fires immediately before a comment is sent to the Trash.
1226 * @param int $comment_id The comment ID.
1228 do_action( 'trash_comment', $comment->comment_ID );
1230 if ( wp_set_comment_status( $comment, 'trash' ) ) {
1231 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
1232 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
1233 add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved );
1234 add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() );
1237 * Fires immediately after a comment is sent to Trash.
1241 * @param int $comment_id The comment ID.
1243 do_action( 'trashed_comment', $comment->comment_ID );
1251 * Removes a comment from the Trash
1255 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
1256 * @return bool True on success, false on failure.
1258 function wp_untrash_comment($comment_id) {
1259 $comment = get_comment( $comment_id );
1265 * Fires immediately before a comment is restored from the Trash.
1269 * @param int $comment_id The comment ID.
1271 do_action( 'untrash_comment', $comment->comment_ID );
1273 $status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true );
1274 if ( empty($status) )
1277 if ( wp_set_comment_status( $comment, $status ) ) {
1278 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
1279 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
1281 * Fires immediately after a comment is restored from the Trash.
1285 * @param int $comment_id The comment ID.
1287 do_action( 'untrashed_comment', $comment->comment_ID );
1295 * Marks a comment as Spam
1299 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
1300 * @return bool True on success, false on failure.
1302 function wp_spam_comment( $comment_id ) {
1303 $comment = get_comment( $comment_id );
1309 * Fires immediately before a comment is marked as Spam.
1313 * @param int $comment_id The comment ID.
1315 do_action( 'spam_comment', $comment->comment_ID );
1317 if ( wp_set_comment_status( $comment, 'spam' ) ) {
1318 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
1319 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
1320 add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved );
1321 add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() );
1323 * Fires immediately after a comment is marked as Spam.
1327 * @param int $comment_id The comment ID.
1329 do_action( 'spammed_comment', $comment->comment_ID );
1337 * Removes a comment from the Spam
1341 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
1342 * @return bool True on success, false on failure.
1344 function wp_unspam_comment( $comment_id ) {
1345 $comment = get_comment( $comment_id );
1351 * Fires immediately before a comment is unmarked as Spam.
1355 * @param int $comment_id The comment ID.
1357 do_action( 'unspam_comment', $comment->comment_ID );
1359 $status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true );
1360 if ( empty($status) )
1363 if ( wp_set_comment_status( $comment, $status ) ) {
1364 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
1365 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
1367 * Fires immediately after a comment is unmarked as Spam.
1371 * @param int $comment_id The comment ID.
1373 do_action( 'unspammed_comment', $comment->comment_ID );
1381 * The status of a comment by ID.
1385 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object
1386 * @return false|string Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
1388 function wp_get_comment_status($comment_id) {
1389 $comment = get_comment($comment_id);
1393 $approved = $comment->comment_approved;
1395 if ( $approved == null )
1397 elseif ( $approved == '1' )
1399 elseif ( $approved == '0' )
1400 return 'unapproved';
1401 elseif ( $approved == 'spam' )
1403 elseif ( $approved == 'trash' )
1410 * Call hooks for when a comment status transition occurs.
1412 * Calls hooks for comment status transitions. If the new comment status is not the same
1413 * as the previous comment status, then two hooks will be ran, the first is
1414 * 'transition_comment_status' with new status, old status, and comment data. The
1415 * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
1416 * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
1419 * The final action will run whether or not the comment statuses are the same. The
1420 * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
1421 * parameter and COMMENTTYPE is comment_type comment data.
1425 * @param string $new_status New comment status.
1426 * @param string $old_status Previous comment status.
1427 * @param object $comment Comment data.
1429 function wp_transition_comment_status($new_status, $old_status, $comment) {
1431 * Translate raw statuses to human readable formats for the hooks.
1432 * This is not a complete list of comment status, it's only the ones
1433 * that need to be renamed
1435 $comment_statuses = array(
1437 'hold' => 'unapproved', // wp_set_comment_status() uses "hold"
1439 'approve' => 'approved', // wp_set_comment_status() uses "approve"
1441 if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
1442 if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
1445 if ( $new_status != $old_status ) {
1447 * Fires when the comment status is in transition.
1451 * @param int|string $new_status The new comment status.
1452 * @param int|string $old_status The old comment status.
1453 * @param object $comment The comment data.
1455 do_action( 'transition_comment_status', $new_status, $old_status, $comment );
1457 * Fires when the comment status is in transition from one specific status to another.
1459 * The dynamic portions of the hook name, `$old_status`, and `$new_status`,
1460 * refer to the old and new comment statuses, respectively.
1464 * @param WP_Comment $comment Comment object.
1466 do_action( "comment_{$old_status}_to_{$new_status}", $comment );
1469 * Fires when the status of a specific comment type is in transition.
1471 * The dynamic portions of the hook name, `$new_status`, and `$comment->comment_type`,
1472 * refer to the new comment status, and the type of comment, respectively.
1474 * Typical comment types include an empty string (standard comment), 'pingback',
1479 * @param int $comment_ID The comment ID.
1480 * @param WP_Comment $comment Comment object.
1482 do_action( "comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment );
1486 * Get current commenter's name, email, and URL.
1488 * Expects cookies content to already be sanitized. User of this function might
1489 * wish to recheck the returned array for validity.
1491 * @see sanitize_comment_cookies() Use to sanitize cookies
1495 * @return array Comment author, email, url respectively.
1497 function wp_get_current_commenter() {
1498 // Cookies should already be sanitized.
1500 $comment_author = '';
1501 if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
1502 $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
1504 $comment_author_email = '';
1505 if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
1506 $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
1508 $comment_author_url = '';
1509 if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
1510 $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
1513 * Filter the current commenter's name, email, and URL.
1517 * @param array $comment_author_data {
1518 * An array of current commenter variables.
1520 * @type string $comment_author The name of the author of the comment. Default empty.
1521 * @type string $comment_author_email The email address of the `$comment_author`. Default empty.
1522 * @type string $comment_author_url The URL address of the `$comment_author`. Default empty.
1525 return apply_filters( 'wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url') );
1529 * Inserts a comment into the database.
1532 * @since 4.4.0 Introduced `$comment_meta` argument.
1534 * @global wpdb $wpdb WordPress database abstraction object.
1536 * @param array $commentdata {
1537 * Array of arguments for inserting a new comment.
1539 * @type string $comment_agent The HTTP user agent of the `$comment_author` when
1540 * the comment was submitted. Default empty.
1541 * @type int|string $comment_approved Whether the comment has been approved. Default 1.
1542 * @type string $comment_author The name of the author of the comment. Default empty.
1543 * @type string $comment_author_email The email address of the `$comment_author`. Default empty.
1544 * @type string $comment_author_IP The IP address of the `$comment_author`. Default empty.
1545 * @type string $comment_author_url The URL address of the `$comment_author`. Default empty.
1546 * @type string $comment_content The content of the comment. Default empty.
1547 * @type string $comment_date The date the comment was submitted. To set the date
1548 * manually, `$comment_date_gmt` must also be specified.
1549 * Default is the current time.
1550 * @type string $comment_date_gmt The date the comment was submitted in the GMT timezone.
1551 * Default is `$comment_date` in the site's GMT timezone.
1552 * @type int $comment_karma The karma of the comment. Default 0.
1553 * @type int $comment_parent ID of this comment's parent, if any. Default 0.
1554 * @type int $comment_post_ID ID of the post that relates to the comment, if any.
1556 * @type string $comment_type Comment type. Default empty.
1557 * @type array $comment_meta Optional. Array of key/value pairs to be stored in commentmeta for the
1559 * @type int $user_id ID of the user who submitted the comment. Default 0.
1561 * @return int|false The new comment's ID on success, false on failure.
1563 function wp_insert_comment( $commentdata ) {
1565 $data = wp_unslash( $commentdata );
1567 $comment_author = ! isset( $data['comment_author'] ) ? '' : $data['comment_author'];
1568 $comment_author_email = ! isset( $data['comment_author_email'] ) ? '' : $data['comment_author_email'];
1569 $comment_author_url = ! isset( $data['comment_author_url'] ) ? '' : $data['comment_author_url'];
1570 $comment_author_IP = ! isset( $data['comment_author_IP'] ) ? '' : $data['comment_author_IP'];
1572 $comment_date = ! isset( $data['comment_date'] ) ? current_time( 'mysql' ) : $data['comment_date'];
1573 $comment_date_gmt = ! isset( $data['comment_date_gmt'] ) ? get_gmt_from_date( $comment_date ) : $data['comment_date_gmt'];
1575 $comment_post_ID = ! isset( $data['comment_post_ID'] ) ? 0 : $data['comment_post_ID'];
1576 $comment_content = ! isset( $data['comment_content'] ) ? '' : $data['comment_content'];
1577 $comment_karma = ! isset( $data['comment_karma'] ) ? 0 : $data['comment_karma'];
1578 $comment_approved = ! isset( $data['comment_approved'] ) ? 1 : $data['comment_approved'];
1579 $comment_agent = ! isset( $data['comment_agent'] ) ? '' : $data['comment_agent'];
1580 $comment_type = ! isset( $data['comment_type'] ) ? '' : $data['comment_type'];
1581 $comment_parent = ! isset( $data['comment_parent'] ) ? 0 : $data['comment_parent'];
1583 $user_id = ! isset( $data['user_id'] ) ? 0 : $data['user_id'];
1585 $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' );
1586 if ( ! $wpdb->insert( $wpdb->comments, $compacted ) ) {
1590 $id = (int) $wpdb->insert_id;
1592 if ( $comment_approved == 1 ) {
1593 wp_update_comment_count( $comment_post_ID );
1595 $comment = get_comment( $id );
1597 // If metadata is provided, store it.
1598 if ( isset( $commentdata['comment_meta'] ) && is_array( $commentdata['comment_meta'] ) ) {
1599 foreach ( $commentdata['comment_meta'] as $meta_key => $meta_value ) {
1600 add_comment_meta( $comment->comment_ID, $meta_key, $meta_value, true );
1605 * Fires immediately after a comment is inserted into the database.
1609 * @param int $id The comment ID.
1610 * @param WP_Comment $comment Comment object.
1612 do_action( 'wp_insert_comment', $id, $comment );
1614 wp_cache_set( 'last_changed', microtime(), 'comment' );
1620 * Filters and sanitizes comment data.
1622 * Sets the comment data 'filtered' field to true when finished. This can be
1623 * checked as to whether the comment should be filtered and to keep from
1624 * filtering the same comment more than once.
1628 * @param array $commentdata Contains information on the comment.
1629 * @return array Parsed comment information.
1631 function wp_filter_comment($commentdata) {
1632 if ( isset( $commentdata['user_ID'] ) ) {
1634 * Filter the comment author's user id before it is set.
1636 * The first time this filter is evaluated, 'user_ID' is checked
1637 * (for back-compat), followed by the standard 'user_id' value.
1641 * @param int $user_ID The comment author's user ID.
1643 $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_ID'] );
1644 } elseif ( isset( $commentdata['user_id'] ) ) {
1645 /** This filter is documented in wp-includes/comment.php */
1646 $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_id'] );
1650 * Filter the comment author's browser user agent before it is set.
1654 * @param string $comment_agent The comment author's browser user agent.
1656 $commentdata['comment_agent'] = apply_filters( 'pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
1657 /** This filter is documented in wp-includes/comment.php */
1658 $commentdata['comment_author'] = apply_filters( 'pre_comment_author_name', $commentdata['comment_author'] );
1660 * Filter the comment content before it is set.
1664 * @param string $comment_content The comment content.
1666 $commentdata['comment_content'] = apply_filters( 'pre_comment_content', $commentdata['comment_content'] );
1668 * Filter the comment author's IP before it is set.
1672 * @param string $comment_author_ip The comment author's IP.
1674 $commentdata['comment_author_IP'] = apply_filters( 'pre_comment_user_ip', $commentdata['comment_author_IP'] );
1675 /** This filter is documented in wp-includes/comment.php */
1676 $commentdata['comment_author_url'] = apply_filters( 'pre_comment_author_url', $commentdata['comment_author_url'] );
1677 /** This filter is documented in wp-includes/comment.php */
1678 $commentdata['comment_author_email'] = apply_filters( 'pre_comment_author_email', $commentdata['comment_author_email'] );
1679 $commentdata['filtered'] = true;
1680 return $commentdata;
1684 * Whether a comment should be blocked because of comment flood.
1688 * @param bool $block Whether plugin has already blocked comment.
1689 * @param int $time_lastcomment Timestamp for last comment.
1690 * @param int $time_newcomment Timestamp for new comment.
1691 * @return bool Whether comment should be blocked.
1693 function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
1694 if ( $block ) // a plugin has already blocked... we'll let that decision stand
1696 if ( ($time_newcomment - $time_lastcomment) < 15 )
1702 * Adds a new comment to the database.
1704 * Filters new comment to ensure that the fields are sanitized and valid before
1705 * inserting comment into database. Calls 'comment_post' action with comment ID
1706 * and whether comment is approved by WordPress. Also has 'preprocess_comment'
1707 * filter for processing the comment data before the function handles it.
1709 * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure
1710 * that it is properly set, such as in wp-config.php, for your environment.
1711 * See {@link https://core.trac.wordpress.org/ticket/9235}
1714 * @since 4.3.0 'comment_agent' and 'comment_author_IP' can be set via `$commentdata`.
1716 * @see wp_insert_comment()
1717 * @global wpdb $wpdb WordPress database abstraction object.
1719 * @param array $commentdata {
1722 * @type string $comment_author The name of the comment author.
1723 * @type string $comment_author_email The comment author email address.
1724 * @type string $comment_author_url The comment author URL.
1725 * @type string $comment_content The content of the comment.
1726 * @type string $comment_date The date the comment was submitted. Default is the current time.
1727 * @type string $comment_date_gmt The date the comment was submitted in the GMT timezone.
1728 * Default is `$comment_date` in the GMT timezone.
1729 * @type int $comment_parent The ID of this comment's parent, if any. Default 0.
1730 * @type int $comment_post_ID The ID of the post that relates to the comment.
1731 * @type int $user_id The ID of the user who submitted the comment. Default 0.
1732 * @type int $user_ID Kept for backward-compatibility. Use `$user_id` instead.
1733 * @type string $comment_agent Comment author user agent. Default is the value of 'HTTP_USER_AGENT'
1734 * in the `$_SERVER` superglobal sent in the original request.
1735 * @type string $comment_author_IP Comment author IP address in IPv4 format. Default is the value of
1736 * 'REMOTE_ADDR' in the `$_SERVER` superglobal sent in the original request.
1738 * @return int|false The ID of the comment on success, false on failure.
1740 function wp_new_comment( $commentdata ) {
1743 if ( isset( $commentdata['user_ID'] ) ) {
1744 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
1747 $prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0;
1750 * Filter a comment's data before it is sanitized and inserted into the database.
1754 * @param array $commentdata Comment data.
1756 $commentdata = apply_filters( 'preprocess_comment', $commentdata );
1758 $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
1759 if ( isset( $commentdata['user_ID'] ) && $prefiltered_user_id !== (int) $commentdata['user_ID'] ) {
1760 $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
1761 } elseif ( isset( $commentdata['user_id'] ) ) {
1762 $commentdata['user_id'] = (int) $commentdata['user_id'];
1765 $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
1766 $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
1767 $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
1769 if ( ! isset( $commentdata['comment_author_IP'] ) ) {
1770 $commentdata['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
1772 $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '', $commentdata['comment_author_IP'] );
1774 if ( ! isset( $commentdata['comment_agent'] ) ) {
1775 $commentdata['comment_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT']: '';
1777 $commentdata['comment_agent'] = substr( $commentdata['comment_agent'], 0, 254 );
1779 if ( empty( $commentdata['comment_date'] ) ) {
1780 $commentdata['comment_date'] = current_time('mysql');
1783 if ( empty( $commentdata['comment_date_gmt'] ) ) {
1784 $commentdata['comment_date_gmt'] = current_time( 'mysql', 1 );
1787 $commentdata = wp_filter_comment($commentdata);
1789 $commentdata['comment_approved'] = wp_allow_comment($commentdata);
1791 $comment_ID = wp_insert_comment($commentdata);
1792 if ( ! $comment_ID ) {
1793 $fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' );
1795 foreach ( $fields as $field ) {
1796 if ( isset( $commentdata[ $field ] ) ) {
1797 $commentdata[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $commentdata[ $field ] );
1801 $commentdata = wp_filter_comment( $commentdata );
1803 $commentdata['comment_approved'] = wp_allow_comment( $commentdata );
1805 $comment_ID = wp_insert_comment( $commentdata );
1806 if ( ! $comment_ID ) {
1812 * Fires immediately after a comment is inserted into the database.
1815 * @since 4.5.0 The `$commentdata` parameter was added.
1817 * @param int $comment_ID The comment ID.
1818 * @param int|string $comment_approved 1 if the comment is approved, 0 if not, 'spam' if spam.
1819 * @param array $commentdata Comment data.
1821 do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'], $commentdata );
1827 * Send a comment moderation notification to the comment moderator.
1831 * @param int $comment_ID ID of the comment.
1832 * @return bool True on success, false on failure.
1834 function wp_new_comment_notify_moderator( $comment_ID ) {
1835 $comment = get_comment( $comment_ID );
1837 // Only send notifications for pending comments.
1838 $maybe_notify = ( '0' == $comment->comment_approved );
1840 /** This filter is documented in wp-includes/comment.php */
1841 $maybe_notify = apply_filters( 'notify_moderator', $maybe_notify, $comment_ID );
1843 if ( ! $maybe_notify ) {
1847 return wp_notify_moderator( $comment_ID );
1851 * Send a notification of a new comment to the post author.
1855 * Uses the {@see 'notify_post_author'} filter to determine whether the post author
1856 * should be notified when a new comment is added, overriding site setting.
1858 * @param int $comment_ID Comment ID.
1859 * @return bool True on success, false on failure.
1861 function wp_new_comment_notify_postauthor( $comment_ID ) {
1862 $comment = get_comment( $comment_ID );
1864 $maybe_notify = get_option( 'comments_notify' );
1867 * Filter whether to send the post author new comment notification emails,
1868 * overriding the site setting.
1872 * @param bool $maybe_notify Whether to notify the post author about the new comment.
1873 * @param int $comment_ID The ID of the comment for the notification.
1875 $maybe_notify = apply_filters( 'notify_post_author', $maybe_notify, $comment_ID );
1878 * wp_notify_postauthor() checks if notifying the author of their own comment.
1879 * By default, it won't, but filters can override this.
1881 if ( ! $maybe_notify ) {
1885 // Only send notifications for approved comments.
1886 if ( ! isset( $comment->comment_approved ) || '1' != $comment->comment_approved ) {
1890 return wp_notify_postauthor( $comment_ID );
1894 * Sets the status of a comment.
1896 * The 'wp_set_comment_status' action is called after the comment is handled.
1897 * If the comment status is not in the list, then false is returned.
1901 * @global wpdb $wpdb WordPress database abstraction object.
1903 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
1904 * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
1905 * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
1906 * @return bool|WP_Error True on success, false or WP_Error on failure.
1908 function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
1911 switch ( $comment_status ) {
1919 add_action( 'wp_set_comment_status', 'wp_new_comment_notify_postauthor' );
1931 $comment_old = clone get_comment($comment_id);
1933 if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array( 'comment_ID' => $comment_old->comment_ID ) ) ) {
1935 return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
1940 clean_comment_cache( $comment_old->comment_ID );
1942 $comment = get_comment( $comment_old->comment_ID );
1945 * Fires immediately before transitioning a comment's status from one to another
1950 * @param int $comment_id Comment ID.
1951 * @param string|bool $comment_status Current comment status. Possible values include
1952 * 'hold', 'approve', 'spam', 'trash', or false.
1954 do_action( 'wp_set_comment_status', $comment->comment_ID, $comment_status );
1956 wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
1958 wp_update_comment_count($comment->comment_post_ID);
1964 * Updates an existing comment in the database.
1966 * Filters the comment and makes sure certain fields are valid before updating.
1970 * @global wpdb $wpdb WordPress database abstraction object.
1972 * @param array $commentarr Contains information on the comment.
1973 * @return int Comment was updated if value is 1, or was not updated if value is 0.
1975 function wp_update_comment($commentarr) {
1978 // First, get all of the original fields
1979 $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
1980 if ( empty( $comment ) ) {
1984 // Make sure that the comment post ID is valid (if specified).
1985 if ( ! empty( $commentarr['comment_post_ID'] ) && ! get_post( $commentarr['comment_post_ID'] ) ) {
1989 // Escape data pulled from DB.
1990 $comment = wp_slash($comment);
1992 $old_status = $comment['comment_approved'];
1994 // Merge old and new fields with new fields overwriting old ones.
1995 $commentarr = array_merge($comment, $commentarr);
1997 $commentarr = wp_filter_comment( $commentarr );
1999 // Now extract the merged array.
2000 $data = wp_unslash( $commentarr );
2003 * Filter the comment content before it is updated in the database.
2007 * @param string $comment_content The comment data.
2009 $data['comment_content'] = apply_filters( 'comment_save_pre', $data['comment_content'] );
2011 $data['comment_date_gmt'] = get_gmt_from_date( $data['comment_date'] );
2013 if ( ! isset( $data['comment_approved'] ) ) {
2014 $data['comment_approved'] = 1;
2015 } elseif ( 'hold' == $data['comment_approved'] ) {
2016 $data['comment_approved'] = 0;
2017 } elseif ( 'approve' == $data['comment_approved'] ) {
2018 $data['comment_approved'] = 1;
2021 $comment_ID = $data['comment_ID'];
2022 $comment_post_ID = $data['comment_post_ID'];
2023 $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' );
2024 $data = wp_array_slice_assoc( $data, $keys );
2025 $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
2027 clean_comment_cache( $comment_ID );
2028 wp_update_comment_count( $comment_post_ID );
2030 * Fires immediately after a comment is updated in the database.
2032 * The hook also fires immediately before comment status transition hooks are fired.
2036 * @param int $comment_ID The comment ID.
2038 do_action( 'edit_comment', $comment_ID );
2039 $comment = get_comment($comment_ID);
2040 wp_transition_comment_status($comment->comment_approved, $old_status, $comment);
2045 * Whether to defer comment counting.
2047 * When setting $defer to true, all post comment counts will not be updated
2048 * until $defer is set to false. When $defer is set to false, then all
2049 * previously deferred updated post comment counts will then be automatically
2050 * updated without having to call wp_update_comment_count() after.
2053 * @staticvar bool $_defer
2055 * @param bool $defer
2058 function wp_defer_comment_counting($defer=null) {
2059 static $_defer = false;
2061 if ( is_bool($defer) ) {
2063 // flush any deferred counts
2065 wp_update_comment_count( null, true );
2072 * Updates the comment count for post(s).
2074 * When $do_deferred is false (is by default) and the comments have been set to
2075 * be deferred, the post_id will be added to a queue, which will be updated at a
2076 * later date and only updated once per post ID.
2078 * If the comments have not be set up to be deferred, then the post will be
2079 * updated. When $do_deferred is set to true, then all previous deferred post
2080 * IDs will be updated along with the current $post_id.
2083 * @see wp_update_comment_count_now() For what could cause a false return value
2085 * @staticvar array $_deferred
2087 * @param int|null $post_id Post ID.
2088 * @param bool $do_deferred Optional. Whether to process previously deferred
2089 * post comment counts. Default false.
2090 * @return bool|void True on success, false on failure or if post with ID does
2093 function wp_update_comment_count($post_id, $do_deferred=false) {
2094 static $_deferred = array();
2096 if ( empty( $post_id ) && ! $do_deferred ) {
2100 if ( $do_deferred ) {
2101 $_deferred = array_unique($_deferred);
2102 foreach ( $_deferred as $i => $_post_id ) {
2103 wp_update_comment_count_now($_post_id);
2104 unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
2108 if ( wp_defer_comment_counting() ) {
2109 $_deferred[] = $post_id;
2112 elseif ( $post_id ) {
2113 return wp_update_comment_count_now($post_id);
2119 * Updates the comment count for the post.
2123 * @global wpdb $wpdb WordPress database abstraction object.
2125 * @param int $post_id Post ID
2126 * @return bool True on success, false on '0' $post_id or if post with ID does not exist.
2128 function wp_update_comment_count_now($post_id) {
2130 $post_id = (int) $post_id;
2134 wp_cache_delete( 'comments-0', 'counts' );
2135 wp_cache_delete( "comments-{$post_id}", 'counts' );
2137 if ( !$post = get_post($post_id) )
2140 $old = (int) $post->comment_count;
2143 * Filters a post's comment count before it is updated in the database.
2147 * @param int $new The new comment count. Default null.
2148 * @param int $old The old comment count.
2149 * @param int $post_id Post ID.
2151 $new = apply_filters( 'pre_wp_update_comment_count_now', null, $old, $post_id );
2153 if ( is_null( $new ) ) {
2154 $new = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id ) );
2159 $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) );
2161 clean_post_cache( $post );
2164 * Fires immediately after a post's comment count is updated in the database.
2168 * @param int $post_id Post ID.
2169 * @param int $new The new comment count.
2170 * @param int $old The old comment count.
2172 do_action( 'wp_update_comment_count', $post_id, $new, $old );
2173 /** This action is documented in wp-includes/post.php */
2174 do_action( 'edit_post', $post_id, $post );
2180 // Ping and trackback functions.
2184 * Finds a pingback server URI based on the given URL.
2186 * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
2187 * a check for the x-pingback headers first and returns that, if available. The
2188 * check for the rel="pingback" has more overhead than just the header.
2192 * @param string $url URL to ping.
2193 * @param int $deprecated Not Used.
2194 * @return false|string False on failure, string containing URI on success.
2196 function discover_pingback_server_uri( $url, $deprecated = '' ) {
2197 if ( !empty( $deprecated ) )
2198 _deprecated_argument( __FUNCTION__, '2.7' );
2200 $pingback_str_dquote = 'rel="pingback"';
2201 $pingback_str_squote = 'rel=\'pingback\'';
2203 /** @todo Should use Filter Extension or custom preg_match instead. */
2204 $parsed_url = parse_url($url);
2206 if ( ! isset( $parsed_url['host'] ) ) // Not a URL. This should never happen.
2209 //Do not search for a pingback server on our own uploads
2210 $uploads_dir = wp_get_upload_dir();
2211 if ( 0 === strpos($url, $uploads_dir['baseurl']) )
2214 $response = wp_safe_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
2216 if ( is_wp_error( $response ) )
2219 if ( wp_remote_retrieve_header( $response, 'x-pingback' ) )
2220 return wp_remote_retrieve_header( $response, 'x-pingback' );
2222 // Not an (x)html, sgml, or xml page, no use going further.
2223 if ( preg_match('#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'content-type' )) )
2226 // Now do a GET since we're going to look in the html headers (and we're sure it's not a binary file)
2227 $response = wp_safe_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
2229 if ( is_wp_error( $response ) )
2232 $contents = wp_remote_retrieve_body( $response );
2234 $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
2235 $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
2236 if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
2237 $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
2238 $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
2239 $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
2240 $pingback_href_start = $pingback_href_pos+6;
2241 $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
2242 $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
2243 $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
2245 // We may find rel="pingback" but an incomplete pingback URL
2246 if ( $pingback_server_url_len > 0 ) { // We got it!
2247 return $pingback_server_url;
2255 * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
2259 * @global wpdb $wpdb WordPress database abstraction object.
2261 function do_all_pings() {
2265 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")) {
2266 delete_metadata_by_mid( 'post', $ping->meta_id );
2267 pingback( $ping->post_content, $ping->ID );
2271 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")) {
2272 delete_metadata_by_mid( 'post', $enclosure->meta_id );
2273 do_enclose( $enclosure->post_content, $enclosure->ID );
2277 $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'");
2278 if ( is_array($trackbacks) )
2279 foreach ( $trackbacks as $trackback )
2280 do_trackbacks($trackback);
2282 //Do Update Services/Generic Pings
2287 * Perform trackbacks.
2291 * @global wpdb $wpdb WordPress database abstraction object.
2293 * @param int $post_id Post ID to do trackbacks on.
2295 function do_trackbacks($post_id) {
2298 $post = get_post( $post_id );
2299 $to_ping = get_to_ping($post_id);
2300 $pinged = get_pung($post_id);
2301 if ( empty($to_ping) ) {
2302 $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) );
2306 if ( empty($post->post_excerpt) ) {
2307 /** This filter is documented in wp-includes/post-template.php */
2308 $excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
2310 /** This filter is documented in wp-includes/post-template.php */
2311 $excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );
2314 $excerpt = str_replace(']]>', ']]>', $excerpt);
2315 $excerpt = wp_html_excerpt($excerpt, 252, '…');
2317 /** This filter is documented in wp-includes/post-template.php */
2318 $post_title = apply_filters( 'the_title', $post->post_title, $post->ID );
2319 $post_title = strip_tags($post_title);
2322 foreach ( (array) $to_ping as $tb_ping ) {
2323 $tb_ping = trim($tb_ping);
2324 if ( !in_array($tb_ping, $pinged) ) {
2325 trackback($tb_ping, $post_title, $excerpt, $post_id);
2326 $pinged[] = $tb_ping;
2328 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post_id) );
2335 * Sends pings to all of the ping site services.
2339 * @param int $post_id Post ID.
2340 * @return int Same as Post ID from parameter
2342 function generic_ping( $post_id = 0 ) {
2343 $services = get_option('ping_sites');
2345 $services = explode("\n", $services);
2346 foreach ( (array) $services as $service ) {
2347 $service = trim($service);
2348 if ( '' != $service )
2349 weblog_ping($service);
2356 * Pings back the links found in a post.
2360 * @global string $wp_version
2362 * @param string $content Post content to check for links.
2363 * @param int $post_ID Post ID.
2365 function pingback($content, $post_ID) {
2367 include_once(ABSPATH . WPINC . '/class-IXR.php');
2368 include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
2370 // original code by Mort (http://mort.mine.nu:8080)
2371 $post_links = array();
2373 $pung = get_pung($post_ID);
2376 // Parsing the post, external links (if any) are stored in the $post_links array
2377 $post_links_temp = wp_extract_urls( $content );
2380 // Walking thru the links array
2381 // first we get rid of links pointing to sites, not to specific files
2383 // http://dummy-weblog.org
2384 // http://dummy-weblog.org/
2385 // http://dummy-weblog.org/post.php
2386 // We don't wanna ping first and second types, even if they have a valid <link/>
2388 foreach ( (array) $post_links_temp as $link_test ) :
2389 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
2390 && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
2391 if ( $test = @parse_url($link_test) ) {
2392 if ( isset($test['query']) )
2393 $post_links[] = $link_test;
2394 elseif ( isset( $test['path'] ) && ( $test['path'] != '/' ) && ( $test['path'] != '' ) )
2395 $post_links[] = $link_test;
2400 $post_links = array_unique( $post_links );
2402 * Fires just before pinging back links found in a post.
2406 * @param array &$post_links An array of post links to be checked, passed by reference.
2407 * @param array &$pung Whether a link has already been pinged, passed by reference.
2408 * @param int $post_ID The post ID.
2410 do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post_ID ) );
2412 foreach ( (array) $post_links as $pagelinkedto ) {
2413 $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
2415 if ( $pingback_server_url ) {
2416 @ set_time_limit( 60 );
2417 // Now, the RPC call
2418 $pagelinkedfrom = get_permalink($post_ID);
2420 // using a timeout of 3 seconds should be enough to cover slow servers
2421 $client = new WP_HTTP_IXR_Client($pingback_server_url);
2422 $client->timeout = 3;
2424 * Filter the user agent sent when pinging-back a URL.
2428 * @param string $concat_useragent The user agent concatenated with ' -- WordPress/'
2429 * and the WordPress version.
2430 * @param string $useragent The useragent.
2431 * @param string $pingback_server_url The server URL being linked to.
2432 * @param string $pagelinkedto URL of page linked to.
2433 * @param string $pagelinkedfrom URL of page linked from.
2435 $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . $wp_version, $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom );
2436 // when set to true, this outputs debug messages by itself
2437 $client->debug = false;
2439 if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
2440 add_ping( $post_ID, $pagelinkedto );
2446 * Check whether blog is public before returning sites.
2450 * @param mixed $sites Will return if blog is public, will not return if not public.
2451 * @return mixed Empty string if blog is not public, returns $sites, if site is public.
2453 function privacy_ping_filter($sites) {
2454 if ( '0' != get_option('blog_public') )
2463 * Updates database when sending trackback to prevent duplicates.
2467 * @global wpdb $wpdb WordPress database abstraction object.
2469 * @param string $trackback_url URL to send trackbacks.
2470 * @param string $title Title of post.
2471 * @param string $excerpt Excerpt of post.
2472 * @param int $ID Post ID.
2473 * @return int|false|void Database query from update.
2475 function trackback($trackback_url, $title, $excerpt, $ID) {
2478 if ( empty($trackback_url) )
2482 $options['timeout'] = 10;
2483 $options['body'] = array(
2485 'url' => get_permalink($ID),
2486 'blog_name' => get_option('blogname'),
2487 'excerpt' => $excerpt
2490 $response = wp_safe_remote_post( $trackback_url, $options );
2492 if ( is_wp_error( $response ) )
2495 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID) );
2496 return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID) );
2504 * @global string $wp_version
2506 * @param string $server Host of blog to connect to.
2507 * @param string $path Path to send the ping.
2509 function weblog_ping($server = '', $path = '') {
2511 include_once(ABSPATH . WPINC . '/class-IXR.php');
2512 include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
2514 // using a timeout of 3 seconds should be enough to cover slow servers
2515 $client = new WP_HTTP_IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
2516 $client->timeout = 3;
2517 $client->useragent .= ' -- WordPress/'.$wp_version;
2519 // when set to true, this outputs debug messages by itself
2520 $client->debug = false;
2521 $home = trailingslashit( home_url() );
2522 if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
2523 $client->query('weblogUpdates.ping', get_option('blogname'), $home);
2527 * Default filter attached to pingback_ping_source_uri to validate the pingback's Source URI
2530 * @see wp_http_validate_url()
2532 * @param string $source_uri
2535 function pingback_ping_source_uri( $source_uri ) {
2536 return (string) wp_http_validate_url( $source_uri );
2540 * Default filter attached to xmlrpc_pingback_error.
2542 * Returns a generic pingback error code unless the error code is 48,
2543 * which reports that the pingback is already registered.
2546 * @link http://www.hixie.ch/specs/pingback/pingback#TOC3
2548 * @param IXR_Error $ixr_error
2551 function xmlrpc_pingback_error( $ixr_error ) {
2552 if ( $ixr_error->code === 48 )
2554 return new IXR_Error( 0, '' );
2562 * Removes a comment from the object cache.
2566 * @param int|array $ids Comment ID or an array of comment IDs to remove from cache.
2568 function clean_comment_cache($ids) {
2569 foreach ( (array) $ids as $id ) {
2570 wp_cache_delete( $id, 'comment' );
2573 * Fires immediately after a comment has been removed from the object cache.
2577 * @param int $id Comment ID.
2579 do_action( 'clean_comment_cache', $id );
2582 wp_cache_set( 'last_changed', microtime(), 'comment' );
2586 * Updates the comment cache of given comments.
2588 * Will add the comments in $comments to the cache. If comment ID already exists
2589 * in the comment cache then it will not be updated. The comment is added to the
2590 * cache using the comment group with the key using the ID of the comments.
2593 * @since 4.4.0 Introduced the `$update_meta_cache` parameter.
2595 * @param array $comments Array of comment row objects
2596 * @param bool $update_meta_cache Whether to update commentmeta cache. Default true.
2598 function update_comment_cache( $comments, $update_meta_cache = true ) {
2599 foreach ( (array) $comments as $comment )
2600 wp_cache_add($comment->comment_ID, $comment, 'comment');
2602 if ( $update_meta_cache ) {
2603 // Avoid `wp_list_pluck()` in case `$comments` is passed by reference.
2604 $comment_ids = array();
2605 foreach ( $comments as $comment ) {
2606 $comment_ids[] = $comment->comment_ID;
2608 update_meta_cache( 'comment', $comment_ids );
2613 * Adds any comments from the given IDs to the cache that do not already exist in cache.
2618 * @see update_comment_cache()
2619 * @global wpdb $wpdb WordPress database abstraction object.
2621 * @param array $comment_ids Array of comment IDs.
2622 * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
2624 function _prime_comment_caches( $comment_ids, $update_meta_cache = true ) {
2627 $non_cached_ids = _get_non_cached_ids( $comment_ids, 'comment' );
2628 if ( !empty( $non_cached_ids ) ) {
2629 $fresh_comments = $wpdb->get_results( sprintf( "SELECT $wpdb->comments.* FROM $wpdb->comments WHERE comment_ID IN (%s)", join( ",", array_map( 'intval', $non_cached_ids ) ) ) );
2631 update_comment_cache( $fresh_comments, $update_meta_cache );
2640 * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
2645 * @param WP_Post $posts Post data object.
2646 * @param WP_Query $query Query object.
2649 function _close_comments_for_old_posts( $posts, $query ) {
2650 if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) )
2654 * Filter the list of post types to automatically close comments for.
2658 * @param array $post_types An array of registered post types. Default array with 'post'.
2660 $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
2661 if ( ! in_array( $posts[0]->post_type, $post_types ) )
2664 $days_old = (int) get_option( 'close_comments_days_old' );
2668 if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
2669 $posts[0]->comment_status = 'closed';
2670 $posts[0]->ping_status = 'closed';
2677 * Close comments on an old post. Hooked to comments_open and pings_open.
2682 * @param bool $open Comments open or closed
2683 * @param int $post_id Post ID
2684 * @return bool $open
2686 function _close_comments_for_old_post( $open, $post_id ) {
2690 if ( !get_option('close_comments_for_old_posts') )
2693 $days_old = (int) get_option('close_comments_days_old');
2697 $post = get_post($post_id);
2699 /** This filter is documented in wp-includes/comment.php */
2700 $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
2701 if ( ! in_array( $post->post_type, $post_types ) )
2704 // Undated drafts should not show up as comments closed.
2705 if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
2709 if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) )
2716 * Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form.
2718 * This function expects unslashed data, as opposed to functions such as `wp_new_comment()` which
2719 * expect slashed data.
2723 * @param array $comment_data {
2726 * @type string|int $comment_post_ID The ID of the post that relates to the comment.
2727 * @type string $author The name of the comment author.
2728 * @type string $email The comment author email address.
2729 * @type string $url The comment author URL.
2730 * @type string $comment The content of the comment.
2731 * @type string|int $comment_parent The ID of this comment's parent, if any. Default 0.
2732 * @type string $_wp_unfiltered_html_comment The nonce value for allowing unfiltered HTML.
2734 * @return WP_Comment|WP_Error A WP_Comment object on success, a WP_Error object on failure.
2736 function wp_handle_comment_submission( $comment_data ) {
2738 $comment_post_ID = $comment_parent = 0;
2739 $comment_author = $comment_author_email = $comment_author_url = $comment_content = $_wp_unfiltered_html_comment = null;
2741 if ( isset( $comment_data['comment_post_ID'] ) ) {
2742 $comment_post_ID = (int) $comment_data['comment_post_ID'];
2744 if ( isset( $comment_data['author'] ) && is_string( $comment_data['author'] ) ) {
2745 $comment_author = trim( strip_tags( $comment_data['author'] ) );
2747 if ( isset( $comment_data['email'] ) && is_string( $comment_data['email'] ) ) {
2748 $comment_author_email = trim( $comment_data['email'] );
2750 if ( isset( $comment_data['url'] ) && is_string( $comment_data['url'] ) ) {
2751 $comment_author_url = trim( $comment_data['url'] );
2753 if ( isset( $comment_data['comment'] ) && is_string( $comment_data['comment'] ) ) {
2754 $comment_content = trim( $comment_data['comment'] );
2756 if ( isset( $comment_data['comment_parent'] ) ) {
2757 $comment_parent = absint( $comment_data['comment_parent'] );
2759 if ( isset( $comment_data['_wp_unfiltered_html_comment'] ) && is_string( $comment_data['_wp_unfiltered_html_comment'] ) ) {
2760 $_wp_unfiltered_html_comment = trim( $comment_data['_wp_unfiltered_html_comment'] );
2763 $post = get_post( $comment_post_ID );
2765 if ( empty( $post->comment_status ) ) {
2768 * Fires when a comment is attempted on a post that does not exist.
2772 * @param int $comment_post_ID Post ID.
2774 do_action( 'comment_id_not_found', $comment_post_ID );
2776 return new WP_Error( 'comment_id_not_found' );
2780 // get_post_status() will get the parent status for attachments.
2781 $status = get_post_status( $post );
2783 if ( ( 'private' == $status ) && ! current_user_can( 'read_post', $comment_post_ID ) ) {
2784 return new WP_Error( 'comment_id_not_found' );
2787 $status_obj = get_post_status_object( $status );
2789 if ( ! comments_open( $comment_post_ID ) ) {
2792 * Fires when a comment is attempted on a post that has comments closed.
2796 * @param int $comment_post_ID Post ID.
2798 do_action( 'comment_closed', $comment_post_ID );
2800 return new WP_Error( 'comment_closed', __( 'Sorry, comments are closed for this item.' ), 403 );
2802 } elseif ( 'trash' == $status ) {
2805 * Fires when a comment is attempted on a trashed post.
2809 * @param int $comment_post_ID Post ID.
2811 do_action( 'comment_on_trash', $comment_post_ID );
2813 return new WP_Error( 'comment_on_trash' );
2815 } elseif ( ! $status_obj->public && ! $status_obj->private ) {
2818 * Fires when a comment is attempted on a post in draft mode.
2822 * @param int $comment_post_ID Post ID.
2824 do_action( 'comment_on_draft', $comment_post_ID );
2826 return new WP_Error( 'comment_on_draft' );
2828 } elseif ( post_password_required( $comment_post_ID ) ) {
2831 * Fires when a comment is attempted on a password-protected post.
2835 * @param int $comment_post_ID Post ID.
2837 do_action( 'comment_on_password_protected', $comment_post_ID );
2839 return new WP_Error( 'comment_on_password_protected' );
2844 * Fires before a comment is posted.
2848 * @param int $comment_post_ID Post ID.
2850 do_action( 'pre_comment_on_post', $comment_post_ID );
2854 // If the user is logged in
2855 $user = wp_get_current_user();
2856 if ( $user->exists() ) {
2857 if ( empty( $user->display_name ) ) {
2858 $user->display_name=$user->user_login;
2860 $comment_author = $user->display_name;
2861 $comment_author_email = $user->user_email;
2862 $comment_author_url = $user->user_url;
2863 $user_ID = $user->ID;
2864 if ( current_user_can( 'unfiltered_html' ) ) {
2865 if ( ! isset( $comment_data['_wp_unfiltered_html_comment'] )
2866 || ! wp_verify_nonce( $comment_data['_wp_unfiltered_html_comment'], 'unfiltered-html-comment_' . $comment_post_ID )
2868 kses_remove_filters(); // start with a clean slate
2869 kses_init_filters(); // set up the filters
2873 if ( get_option( 'comment_registration' ) ) {
2874 return new WP_Error( 'not_logged_in', __( 'Sorry, you must be logged in to post a comment.' ), 403 );
2879 $max_lengths = wp_get_comment_fields_max_lengths();
2881 if ( get_option( 'require_name_email' ) && ! $user->exists() ) {
2882 if ( 6 > strlen( $comment_author_email ) || '' == $comment_author ) {
2883 return new WP_Error( 'require_name_email', __( '<strong>ERROR</strong>: please fill the required fields (name, email).' ), 200 );
2884 } elseif ( ! is_email( $comment_author_email ) ) {
2885 return new WP_Error( 'require_valid_email', __( '<strong>ERROR</strong>: please enter a valid email address.' ), 200 );
2889 if ( isset( $comment_author ) && $max_lengths['comment_author'] < mb_strlen( $comment_author, '8bit' ) ) {
2890 return new WP_Error( 'comment_author_column_length', __( '<strong>ERROR</strong>: your name is too long.' ), 200 );
2893 if ( isset( $comment_author_email ) && $max_lengths['comment_author_email'] < strlen( $comment_author_email ) ) {
2894 return new WP_Error( 'comment_author_email_column_length', __( '<strong>ERROR</strong>: your email address is too long.' ), 200 );
2897 if ( isset( $comment_author_url ) && $max_lengths['comment_author_url'] < strlen( $comment_author_url ) ) {
2898 return new WP_Error( 'comment_author_url_column_length', __( '<strong>ERROR</strong>: your url is too long.' ), 200 );
2901 if ( '' == $comment_content ) {
2902 return new WP_Error( 'require_valid_comment', __( '<strong>ERROR</strong>: please type a comment.' ), 200 );
2903 } elseif ( $max_lengths['comment_content'] < mb_strlen( $comment_content, '8bit' ) ) {
2904 return new WP_Error( 'comment_content_column_length', __( '<strong>ERROR</strong>: your comment is too long.' ), 200 );
2907 $commentdata = compact(
2910 'comment_author_email',
2911 'comment_author_url',
2918 $comment_id = wp_new_comment( wp_slash( $commentdata ) );
2919 if ( ! $comment_id ) {
2920 return new WP_Error( 'comment_save_error', __( '<strong>ERROR</strong>: The comment could not be saved. Please try again later.' ), 500 );
2923 return get_comment( $comment_id );