| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * Core Comment API 4 * 5 * @package WordPress 6 * @subpackage Comment 7 */ 8 9 /** 10 * Checks whether a comment passes internal checks to be allowed to add. 11 * 12 * If manual comment moderation is set in the administration, then all checks, 13 * regardless of their type and substance, will fail and the function will 14 * return false. 15 * 16 * If the number of links exceeds the amount in the administration, then the 17 * check fails. If any of the parameter contents contain any disallowed words, 18 * then the check fails. 19 * 20 * If the comment author was approved before, then the comment is automatically 21 * approved. 22 * 23 * Pingbacks originating from the same site are automatically approved, as the 24 * link they report was created by someone who can already publish here. 25 * 26 * If all checks pass, the function will return true. 27 * 28 * @since 1.2.0 29 * @since 7.1.0 Pingbacks from the same site are no longer held for moderation. 30 * 31 * @global wpdb $wpdb WordPress database abstraction object. 32 * 33 * @param string $author Comment author name. 34 * @param string $email Comment author email. 35 * @param string $url Comment author URL. 36 * @param string $comment Content of the comment. 37 * @param string $user_ip Comment author IP address. 38 * @param string $user_agent Comment author User-Agent. 39 * @param string $comment_type Comment type, either user-submitted comment, 40 * trackback, or pingback. 41 * @return bool If all checks pass, true, otherwise false. 42 */ 43 function check_comment( $author, $email, $url, $comment, $user_ip, $user_agent, $comment_type ) { 44 global $wpdb; 45 46 // If manual moderation is enabled, skip all checks and return false. 47 if ( '1' === get_option( 'comment_moderation' ) ) { 48 return false; 49 } 50 51 /** This filter is documented in wp-includes/comment-template.php */ 52 $comment = apply_filters( 'comment_text', $comment, null, array() ); 53 54 // Check for the number of external links if a max allowed number is set. 55 $max_links = get_option( 'comment_max_links' ); 56 if ( $max_links ) { 57 $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out ); 58 59 /** 60 * Filters the number of links found in a comment. 61 * 62 * @since 3.0.0 63 * @since 4.7.0 Added the `$comment` parameter. 64 * 65 * @param int $num_links The number of links found. 66 * @param string $url Comment author's URL. Included in allowed links total. 67 * @param string $comment Content of the comment. 68 */ 69 $num_links = apply_filters( 'comment_max_links_url', $num_links, $url, $comment ); 70 71 /* 72 * If the number of links in the comment exceeds the allowed amount, 73 * fail the check by returning false. 74 */ 75 if ( $num_links >= $max_links ) { 76 return false; 77 } 78 } 79 80 $mod_keys = trim( get_option( 'moderation_keys' ) ); 81 82 // If moderation 'keys' (keywords) are set, process them. 83 if ( ! empty( $mod_keys ) ) { 84 $words = explode( "\n", $mod_keys ); 85 86 foreach ( (array) $words as $word ) { 87 $word = trim( $word ); 88 89 // Skip empty lines. 90 if ( empty( $word ) ) { 91 continue; 92 } 93 94 /* 95 * Do some escaping magic so that '#' (number of) characters in the spam 96 * words don't break things: 97 */ 98 $word = preg_quote( $word, '#' ); 99 100 /* 101 * Check the comment fields for moderation keywords. If any are found, 102 * fail the check for the given field by returning false. 103 */ 104 $pattern = "#$word#iu"; 105 if ( preg_match( $pattern, $author ) ) { 106 return false; 107 } 108 if ( preg_match( $pattern, $email ) ) { 109 return false; 110 } 111 if ( preg_match( $pattern, $url ) ) { 112 return false; 113 } 114 if ( preg_match( $pattern, $comment ) ) { 115 return false; 116 } 117 if ( preg_match( $pattern, $user_ip ) ) { 118 return false; 119 } 120 if ( preg_match( $pattern, $user_agent ) ) { 121 return false; 122 } 123 } 124 } 125 126 /* 127 * Check if the option to approve comments by previously-approved authors is enabled. 128 * 129 * If it is enabled, check whether the comment author has a previously-approved comment, 130 * as well as whether there are any moderation keywords (if set) present in the author 131 * email address. If both checks pass, return true. Otherwise, return false. 132 */ 133 if ( '1' === get_option( 'comment_previously_approved' ) ) { 134 if ( 'trackback' !== $comment_type && 'pingback' !== $comment_type && '' !== $author && '' !== $email ) { 135 $comment_user = get_user_by( 'email', wp_unslash( $email ) ); 136 if ( ! empty( $comment_user->ID ) ) { 137 $ok_to_comment = $wpdb->get_var( 138 $wpdb->prepare( 139 "SELECT comment_approved 140 FROM $wpdb->comments 141 WHERE user_id = %d 142 AND comment_approved = '1' 143 LIMIT 1", 144 $comment_user->ID 145 ) 146 ); 147 } else { 148 // expected_slashed ($author, $email) 149 $ok_to_comment = $wpdb->get_var( 150 $wpdb->prepare( 151 "SELECT comment_approved 152 FROM $wpdb->comments 153 WHERE comment_author = %s 154 AND comment_author_email = %s 155 AND comment_approved = '1' 156 LIMIT 1", 157 $author, 158 $email 159 ) 160 ); 161 } 162 163 if ( '1' === $ok_to_comment && ( empty( $mod_keys ) || ! str_contains( $email, $mod_keys ) ) ) { 164 return true; 165 } else { 166 return false; 167 } 168 } elseif ( 'pingback' === $comment_type ) { 169 /* 170 * Only pingbacks are considered. A pingback is verified before it reaches 171 * this point: the source page is fetched, it must link to the target, and 172 * the comment is built from that fetched page. A trackback carries no such 173 * proof. Its source URL, title, and excerpt are unverified request data, so 174 * a forged trackback naming a local post as its source would be approved. 175 */ 176 177 // url_to_postid() compares hostnames, so it returns 0 for any URL that only appears to be local. 178 $source_id = url_to_postid( wp_unslash( $url ) ); 179 180 // Approve pingbacks reporting a link that someone who can already publish here created. 181 $approve_pingback = $source_id > 0 && 'publish' === get_post_status( $source_id ); 182 183 /** 184 * Filters whether a pingback is approved without being held for moderation. 185 * 186 * Defaults to true for pingbacks originating from a published post on the same 187 * site, and false for every other pingback. Trackbacks are never considered, 188 * as they cannot be verified. 189 * 190 * @since 7.1.0 191 * 192 * @param bool $approve_pingback Whether to auto-approve the pingback. 193 * @param int $source_id ID of the post on this site the pingback 194 * originated from, or 0 if it came from elsewhere. 195 * @param string $url The URL the pingback was sent from. 196 */ 197 return (bool) apply_filters( 'wp_auto_approve_ping', $approve_pingback, $source_id, $url ); 198 } else { 199 return false; 200 } 201 } 202 return true; 203 } 204 205 /** 206 * Retrieves the approved comments for a post. 207 * 208 * @since 2.0.0 209 * @since 4.1.0 Refactored to leverage WP_Comment_Query over a direct query. 210 * 211 * @param int $post_id The ID of the post. 212 * @param array $args { 213 * Optional. See WP_Comment_Query::__construct() for information on accepted arguments. 214 * 215 * @type int $status Comment status to limit results by. Defaults to approved comments. 216 * @type int $post_id Limit results to those affiliated with a given post ID. 217 * @type string $order How to order retrieved comments. Default 'ASC'. 218 * } 219 * @return WP_Comment[]|int[]|int The approved comments, or number of comments if `$count` 220 * argument is true. An empty array is returned when `$post_id` 221 * is falsey, even when `$count` is true. 222 * @phpstan-return ( 223 * $post_id is 0 ? array{} : ( 224 * $args is array{ count: true, ... } ? non-negative-int : ( 225 * $args is array{ fields: 'ids', ... } ? non-negative-int[] : array<int, WP_Comment> 226 * ) 227 * ) 228 * ) 229 */ 230 function get_approved_comments( $post_id, $args = array() ) { 231 if ( ! $post_id ) { 232 return array(); 233 } 234 235 $defaults = array( 236 'status' => 1, 237 'post_id' => $post_id, 238 'order' => 'ASC', 239 ); 240 $parsed_args = wp_parse_args( $args, $defaults ); 241 242 $query = new WP_Comment_Query(); 243 return $query->query( $parsed_args ); 244 } 245 246 /** 247 * Retrieves comment data given a comment ID or comment object. 248 * 249 * If an object is passed then the comment data will be cached and then returned 250 * after being passed through a filter. If the comment is empty, then the global 251 * comment variable will be used, if it is set. 252 * 253 * @since 2.0.0 254 * @since 7.1.0 Only numeric values are now treated as comment IDs; other unrecognized values 255 * return null instead of being cast to an integer ID. 256 * 257 * @global WP_Comment $comment Global comment object. 258 * 259 * @param WP_Comment|string|int $comment Comment to retrieve. 260 * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which 261 * correspond to a WP_Comment object, an associative array, or a numeric array, 262 * respectively. Default OBJECT. 263 * @return WP_Comment|array|null Depends on $output value. 264 * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output 265 * @phpstan-return ( 266 * $output is 'ARRAY_A' ? non-empty-array<string, mixed>|null : ( 267 * $output is 'ARRAY_N' ? non-empty-list<mixed>|null : WP_Comment|null 268 * ) 269 * ) 270 */ 271 function get_comment( $comment = null, $output = OBJECT ) { 272 if ( empty( $comment ) && isset( $GLOBALS['comment'] ) ) { 273 $comment = $GLOBALS['comment']; 274 } 275 276 if ( $comment instanceof WP_Comment ) { 277 $_comment = $comment; 278 } elseif ( is_object( $comment ) ) { 279 $_comment = new WP_Comment( $comment ); 280 } elseif ( is_numeric( $comment ) ) { 281 $_comment = WP_Comment::get_instance( (int) $comment ); 282 } else { 283 $_comment = null; 284 } 285 286 if ( ! $_comment ) { 287 return null; 288 } 289 290 /** 291 * Fires after a comment is retrieved. 292 * 293 * @since 2.3.0 294 * 295 * @param WP_Comment|null $_comment Comment data. 296 */ 297 $_comment = apply_filters( 'get_comment', $_comment ); 298 if ( ! ( $_comment instanceof WP_Comment ) ) { 299 return null; 300 } 301 302 if ( OBJECT === $output ) { 303 return $_comment; 304 } elseif ( ARRAY_A === $output ) { 305 return $_comment->to_array(); 306 } elseif ( ARRAY_N === $output ) { 307 return array_values( $_comment->to_array() ); 308 } 309 return $_comment; 310 } 311 312 /** 313 * Retrieves a list of comments. 314 * 315 * The comment list can be for the blog as a whole or for an individual post. 316 * 317 * @since 2.7.0 318 * 319 * @param string|array $args Optional. Array or string of arguments. See WP_Comment_Query::__construct() 320 * for information on accepted arguments. Default empty string. 321 * @return WP_Comment[]|int[]|int List of comments or number of found comments if `$count` argument is true. 322 * @phpstan-return ( 323 * $args is array{ count: true, ... } ? non-negative-int : ( 324 * $args is array{ fields: 'ids', ... } ? non-negative-int[] : array<int, WP_Comment> 325 * ) 326 * ) 327 */ 328 function get_comments( $args = '' ) { 329 $query = new WP_Comment_Query(); 330 return $query->query( $args ); 331 } 332 333 /** 334 * Retrieves all of the WordPress supported comment statuses. 335 * 336 * Comments have a limited set of valid status values, this provides the comment 337 * status values and descriptions. 338 * 339 * @since 2.7.0 340 * 341 * @return string[] List of comment status labels keyed by status. 342 */ 343 function get_comment_statuses() { 344 $status = array( 345 'hold' => __( 'Unapproved' ), 346 'approve' => _x( 'Approved', 'comment status' ), 347 'spam' => _x( 'Spam', 'comment status' ), 348 'trash' => _x( 'Trash', 'comment status' ), 349 ); 350 351 return $status; 352 } 353 354 /** 355 * Gets the default comment status for a post type. 356 * 357 * @since 4.3.0 358 * 359 * @param string $post_type Optional. Post type. Default 'post'. 360 * @param string $comment_type Optional. Comment type. Default 'comment'. 361 * @return string Either 'open' or 'closed'. 362 */ 363 function get_default_comment_status( $post_type = 'post', $comment_type = 'comment' ) { 364 switch ( $comment_type ) { 365 case 'pingback': 366 case 'trackback': 367 $supports = 'trackbacks'; 368 $option = 'ping'; 369 break; 370 default: 371 $supports = 'comments'; 372 $option = 'comment'; 373 break; 374 } 375 376 // Set the status. 377 if ( 'page' === $post_type ) { 378 $status = 'closed'; 379 } elseif ( post_type_supports( $post_type, $supports ) ) { 380 $status = get_option( "default_{$option}_status" ); 381 } else { 382 $status = 'closed'; 383 } 384 385 /** 386 * Filters the default comment status for the given post type. 387 * 388 * @since 4.3.0 389 * 390 * @param string $status Default status for the given post type, 391 * either 'open' or 'closed'. 392 * @param string $post_type Post type. Default is `post`. 393 * @param string $comment_type Type of comment. Default is `comment`. 394 */ 395 return apply_filters( 'get_default_comment_status', $status, $post_type, $comment_type ); 396 } 397 398 /** 399 * Retrieves the date the last comment was modified. 400 * 401 * @since 1.5.0 402 * @since 4.7.0 Replaced caching the modified date in a local static variable 403 * with the Object Cache API. 404 * @since 7.2.0 The 'note' and 'reaction' comment types are excluded from the query. 405 * 406 * @global wpdb $wpdb WordPress database abstraction object. 407 * 408 * @param string $timezone Which timezone to use in reference to 'gmt', 'blog', or 'server' locations. 409 * @return string|false Last comment modified date on success, false on failure. 410 */ 411 function get_lastcommentmodified( $timezone = 'server' ) { 412 global $wpdb; 413 414 $timezone = strtolower( $timezone ); 415 $key = "lastcommentmodified:$timezone"; 416 417 $comment_modified_date = wp_cache_get( $key, 'timeinfo' ); 418 if ( false !== $comment_modified_date ) { 419 return $comment_modified_date; 420 } 421 422 switch ( $timezone ) { 423 case 'gmt': 424 $comment_modified_date = $wpdb->get_var( "SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' AND comment_type NOT IN ( 'note', 'reaction' ) ORDER BY comment_date_gmt DESC LIMIT 1" ); 425 break; 426 case 'blog': 427 $comment_modified_date = $wpdb->get_var( "SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' AND comment_type NOT IN ( 'note', 'reaction' ) ORDER BY comment_date_gmt DESC LIMIT 1" ); 428 break; 429 case 'server': 430 $add_seconds_server = gmdate( 'Z' ); 431 432 $comment_modified_date = $wpdb->get_var( $wpdb->prepare( "SELECT DATE_ADD(comment_date_gmt, INTERVAL %s SECOND) FROM $wpdb->comments WHERE comment_approved = '1' AND comment_type NOT IN ( 'note', 'reaction' ) ORDER BY comment_date_gmt DESC LIMIT 1", $add_seconds_server ) ); 433 break; 434 } 435 436 if ( $comment_modified_date ) { 437 wp_cache_set( $key, $comment_modified_date, 'timeinfo' ); 438 439 return $comment_modified_date; 440 } 441 442 return false; 443 } 444 445 /** 446 * Retrieves the total comment counts for the whole site or a single post. 447 * 448 * @since 2.0.0 449 * 450 * @param int $post_id Optional. Restrict the comment counts to the given post. Default 0, which indicates that 451 * comment counts for the whole site will be retrieved. 452 * @return int[] { 453 * The number of comments keyed by their status. 454 * 455 * @type int $approved The number of approved comments. 456 * @type int $awaiting_moderation The number of comments awaiting moderation (a.k.a. pending). 457 * @type int $spam The number of spam comments. 458 * @type int $trash The number of trashed comments. 459 * @type int $post-trashed The number of comments for posts that are in the trash. 460 * @type int $total_comments The total number of non-trashed comments, including spam. 461 * @type int $all The total number of pending or approved comments. 462 * } 463 */ 464 function get_comment_count( $post_id = 0 ) { 465 $post_id = (int) $post_id; 466 467 $comment_count = array( 468 'approved' => 0, 469 'awaiting_moderation' => 0, 470 'spam' => 0, 471 'trash' => 0, 472 'post-trashed' => 0, 473 'total_comments' => 0, 474 'all' => 0, 475 ); 476 477 $args = array( 478 'count' => true, 479 'update_comment_meta_cache' => false, 480 'orderby' => 'none', 481 ); 482 if ( $post_id > 0 ) { 483 $args['post_id'] = $post_id; 484 } 485 $mapping = array( 486 'approved' => 'approve', 487 'awaiting_moderation' => 'hold', 488 'spam' => 'spam', 489 'trash' => 'trash', 490 'post-trashed' => 'post-trashed', 491 ); 492 $comment_count = array(); 493 foreach ( $mapping as $key => $value ) { 494 $comment_count[ $key ] = get_comments( array_merge( $args, array( 'status' => $value ) ) ); 495 } 496 497 $comment_count['all'] = $comment_count['approved'] + $comment_count['awaiting_moderation']; 498 $comment_count['total_comments'] = $comment_count['all'] + $comment_count['spam']; 499 500 return array_map( 'intval', $comment_count ); 501 } 502 503 // 504 // Comment meta functions. 505 // 506 507 /** 508 * Adds meta data field to a comment. 509 * 510 * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input. 511 * 512 * @since 2.9.0 513 * 514 * @link https://developer.wordpress.org/reference/functions/add_comment_meta/ 515 * 516 * @param int $comment_id Comment ID. 517 * @param string $meta_key Metadata name. 518 * @param mixed $meta_value Metadata value. Arrays and objects are stored as serialized data and 519 * will be returned as the same type when retrieved. Other data types will 520 * be stored as strings in the database: 521 * - false is stored and retrieved as an empty string ('') 522 * - true is stored and retrieved as '1' 523 * - numbers (both integer and float) are stored and retrieved as strings 524 * Must be serializable if non-scalar. 525 * @param bool $unique Optional. Whether the same key should not be added. 526 * Default false. 527 * @return int|false Meta ID on success, false on failure. 528 */ 529 function add_comment_meta( $comment_id, $meta_key, $meta_value, $unique = false ) { 530 return add_metadata( 'comment', $comment_id, $meta_key, $meta_value, $unique ); 531 } 532 533 /** 534 * Removes metadata matching criteria from a comment. 535 * 536 * You can match based on the key, or key and value. Removing based on key and 537 * value, will keep from removing duplicate metadata with the same key. It also 538 * allows removing all metadata matching key, if needed. 539 * 540 * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input. 541 * 542 * @since 2.9.0 543 * 544 * @link https://developer.wordpress.org/reference/functions/delete_comment_meta/ 545 * 546 * @param int $comment_id Comment ID. 547 * @param string $meta_key Metadata name. 548 * @param mixed $meta_value Optional. Metadata value. If provided, 549 * rows will only be removed that match the value. 550 * Must be serializable if non-scalar. Default empty string. 551 * @return bool True on success, false on failure. 552 * 553 * @phpstan-param positive-int $comment_id 554 */ 555 function delete_comment_meta( $comment_id, $meta_key, $meta_value = '' ) { 556 return delete_metadata( 'comment', $comment_id, $meta_key, $meta_value ); 557 } 558 559 /** 560 * Retrieves comment meta field for a comment. 561 * 562 * @since 2.9.0 563 * 564 * @link https://developer.wordpress.org/reference/functions/get_comment_meta/ 565 * 566 * @param int $comment_id Comment ID. 567 * @param string $key Optional. The meta key to retrieve. By default, 568 * returns data for all keys. Default empty string. 569 * @param bool $single Optional. Whether to return a single value. 570 * This parameter has no effect if `$key` is not specified. 571 * Default false. 572 * @return mixed An array of values if `$single` is false. 573 * The value of meta data field if `$single` is true. 574 * False for an invalid `$comment_id` (non-numeric, zero, or negative value). 575 * An empty array if a valid but non-existing comment ID is passed and `$single` is false. 576 * An empty string if a valid but non-existing comment ID is passed and `$single` is true. 577 * Note: Non-serialized values are returned as strings: 578 * - false values are returned as empty strings ('') 579 * - true values are returned as '1' 580 * - numbers are returned as strings 581 * Arrays and objects retain their original type. 582 * These conversions apply to stored values. A default value registered 583 * with {@see register_meta()} is never stored, so it is returned with 584 * the type it was registered with, which may be an integer, float, or 585 * boolean. 586 * 587 * @phpstan-param int|decimal-int-string $comment_id 588 * @phpstan-return ( 589 * $key is ''|'0' 590 * ? array<array-key, list<string>>|false 591 * : ( $single is true 592 * ? mixed 593 * : list<mixed>|false ) 594 * ) 595 */ 596 function get_comment_meta( $comment_id, $key = '', $single = false ) { 597 return get_metadata( 'comment', $comment_id, $key, $single ); 598 } 599 600 /** 601 * Queue comment meta for lazy-loading. 602 * 603 * @since 6.3.0 604 * 605 * @param array $comment_ids List of comment IDs. 606 */ 607 function wp_lazyload_comment_meta( array $comment_ids ) { 608 if ( empty( $comment_ids ) ) { 609 return; 610 } 611 $lazyloader = wp_metadata_lazyloader(); 612 $lazyloader->queue_objects( 'comment', $comment_ids ); 613 } 614 615 /** 616 * Updates comment meta field based on comment ID. 617 * 618 * Use the $prev_value parameter to differentiate between meta fields with the 619 * same key and comment ID. 620 * 621 * If the meta field for the comment does not exist, it will be added. 622 * 623 * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input. 624 * 625 * @since 2.9.0 626 * 627 * @link https://developer.wordpress.org/reference/functions/update_comment_meta/ 628 * 629 * @param int $comment_id Comment ID. 630 * @param string $meta_key Metadata key. 631 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar. 632 * @param mixed $prev_value Optional. Previous value to check before updating. 633 * If specified, only update existing metadata entries with 634 * this value. Otherwise, update all entries. Default empty string. 635 * @return int|bool Meta ID if the key didn't exist, true on successful update, 636 * false on failure or if the value passed to the function 637 * is the same as the one that is already in the database. 638 */ 639 function update_comment_meta( $comment_id, $meta_key, $meta_value, $prev_value = '' ) { 640 return update_metadata( 'comment', $comment_id, $meta_key, $meta_value, $prev_value ); 641 } 642 643 /** 644 * Sets the cookies used to store an unauthenticated commentator's identity. Typically used 645 * to recall previous comments by this commentator that are still held in moderation. 646 * 647 * @since 3.4.0 648 * @since 4.9.6 The `$cookies_consent` parameter was added. 649 * 650 * @param WP_Comment $comment Comment object. 651 * @param WP_User $user Comment author's user object. The user may not exist. 652 * @param bool $cookies_consent Optional. Comment author's consent to store cookies. Default true. 653 */ 654 function wp_set_comment_cookies( $comment, $user, $cookies_consent = true ) { 655 // If the user already exists, or the user opted out of cookies, don't set cookies. 656 if ( $user->exists() ) { 657 return; 658 } 659 660 if ( false === $cookies_consent ) { 661 // Remove any existing cookies. 662 $past = time() - YEAR_IN_SECONDS; 663 setcookie( 'comment_author_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN ); 664 setcookie( 'comment_author_email_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN ); 665 setcookie( 'comment_author_url_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN ); 666 667 return; 668 } 669 670 /** 671 * Filters the lifetime of the comment cookie in seconds. 672 * 673 * @since 2.8.0 674 * @since 6.6.0 The default `$seconds` value changed from 30000000 to YEAR_IN_SECONDS. 675 * 676 * @param int $seconds Comment cookie lifetime. Default YEAR_IN_SECONDS. 677 */ 678 $comment_cookie_lifetime = time() + apply_filters( 'comment_cookie_lifetime', YEAR_IN_SECONDS ); 679 680 $secure = ( 'https' === parse_url( home_url(), PHP_URL_SCHEME ) ); 681 682 setcookie( 'comment_author_' . COOKIEHASH, $comment->comment_author, $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure ); 683 setcookie( 'comment_author_email_' . COOKIEHASH, $comment->comment_author_email, $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure ); 684 setcookie( 'comment_author_url_' . COOKIEHASH, esc_url( $comment->comment_author_url ), $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure ); 685 } 686 687 /** 688 * Sanitizes the cookies sent to the user already. 689 * 690 * Will only do anything if the cookies have already been created for the user. 691 * Mostly used after cookies had been sent to use elsewhere. 692 * 693 * @since 2.0.4 694 */ 695 function sanitize_comment_cookies() { 696 if ( isset( $_COOKIE[ 'comment_author_' . COOKIEHASH ] ) ) { 697 /** 698 * Filters the comment author's name cookie before it is set. 699 * 700 * When this filter hook is evaluated in wp_filter_comment(), 701 * the comment author's name string is passed. 702 * 703 * @since 1.5.0 704 * 705 * @param string $author_cookie The comment author name cookie. 706 */ 707 $comment_author = apply_filters( 'pre_comment_author_name', $_COOKIE[ 'comment_author_' . COOKIEHASH ] ); 708 $comment_author = wp_unslash( $comment_author ); 709 $comment_author = esc_attr( $comment_author ); 710 711 $_COOKIE[ 'comment_author_' . COOKIEHASH ] = $comment_author; 712 } 713 714 if ( isset( $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] ) ) { 715 /** 716 * Filters the comment author's email cookie before it is set. 717 * 718 * When this filter hook is evaluated in wp_filter_comment(), 719 * the comment author's email string is passed. 720 * 721 * @since 1.5.0 722 * 723 * @param string $author_email_cookie The comment author email cookie. 724 */ 725 $comment_author_email = apply_filters( 'pre_comment_author_email', $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] ); 726 $comment_author_email = wp_unslash( $comment_author_email ); 727 $comment_author_email = esc_attr( $comment_author_email ); 728 729 $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] = $comment_author_email; 730 } 731 732 if ( isset( $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] ) ) { 733 /** 734 * Filters the comment author's URL cookie before it is set. 735 * 736 * When this filter hook is evaluated in wp_filter_comment(), 737 * the comment author's URL string is passed. 738 * 739 * @since 1.5.0 740 * 741 * @param string $author_url_cookie The comment author URL cookie. 742 */ 743 $comment_author_url = apply_filters( 'pre_comment_author_url', $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] ); 744 $comment_author_url = wp_unslash( $comment_author_url ); 745 746 $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] = $comment_author_url; 747 } 748 } 749 750 /** 751 * Validates whether this comment is allowed to be made. 752 * 753 * @since 2.0.0 754 * @since 4.7.0 The `$avoid_die` parameter was added, allowing the function 755 * to return a WP_Error object instead of dying. 756 * @since 5.5.0 The `$avoid_die` parameter was renamed to `$wp_error`. 757 * 758 * @global wpdb $wpdb WordPress database abstraction object. 759 * 760 * @param array $commentdata Contains information on the comment. 761 * @param bool $wp_error When true, a disallowed comment will result in the function 762 * returning a WP_Error object, rather than executing wp_die(). 763 * Default false. 764 * @return int|string|WP_Error Allowed comments return the approval status (0|1|'spam'|'trash'). 765 * WP_Error if the comment is a duplicate or a flood and `$wp_error` 766 * is true, or if the {@see 'pre_comment_approved'} filter returns one. 767 */ 768 function wp_allow_comment( $commentdata, $wp_error = false ) { 769 global $wpdb; 770 771 /* 772 * Simple duplicate check. 773 * expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content) 774 */ 775 $dupe = $wpdb->prepare( 776 "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ", 777 wp_unslash( $commentdata['comment_post_ID'] ), 778 wp_unslash( $commentdata['comment_parent'] ), 779 wp_unslash( $commentdata['comment_author'] ) 780 ); 781 if ( $commentdata['comment_author_email'] ) { 782 $dupe .= $wpdb->prepare( 783 'AND comment_author_email = %s ', 784 wp_unslash( $commentdata['comment_author_email'] ) 785 ); 786 } 787 $dupe .= $wpdb->prepare( 788 ') AND comment_content = %s LIMIT 1', 789 wp_unslash( $commentdata['comment_content'] ) 790 ); 791 792 $dupe_id = $wpdb->get_var( $dupe ); 793 794 /** 795 * Filters the ID, if any, of the duplicate comment found when creating a new comment. 796 * 797 * Return an empty value from this filter to allow what WP considers a duplicate comment. 798 * 799 * @since 4.4.0 800 * 801 * @param int $dupe_id ID of the comment identified as a duplicate. 802 * @param array $commentdata Data for the comment being created. 803 */ 804 $dupe_id = apply_filters( 'duplicate_comment_id', $dupe_id, $commentdata ); 805 806 if ( $dupe_id ) { 807 /** 808 * Fires immediately after a duplicate comment is detected. 809 * 810 * @since 3.0.0 811 * 812 * @param array $commentdata Comment data. 813 */ 814 do_action( 'comment_duplicate_trigger', $commentdata ); 815 816 /** 817 * Filters duplicate comment error message. 818 * 819 * @since 5.2.0 820 * 821 * @param string $comment_duplicate_message Duplicate comment error message. 822 */ 823 $comment_duplicate_message = apply_filters( 'comment_duplicate_message', __( 'Duplicate comment detected; it looks as though you’ve already said that!' ) ); 824 825 if ( $wp_error ) { 826 return new WP_Error( 'comment_duplicate', $comment_duplicate_message, 409 ); 827 } else { 828 if ( wp_doing_ajax() ) { 829 die( $comment_duplicate_message ); 830 } 831 832 wp_die( $comment_duplicate_message, 409 ); 833 } 834 } 835 836 /** 837 * Fires immediately before a comment is marked approved. 838 * 839 * Allows checking for comment flooding. 840 * 841 * @since 2.3.0 842 * @since 4.7.0 The `$avoid_die` parameter was added. 843 * @since 5.5.0 The `$avoid_die` parameter was renamed to `$wp_error`. 844 * 845 * @param string $comment_author_ip Comment author's IP address. 846 * @param string $comment_author_email Comment author's email. 847 * @param string $comment_date_gmt GMT date the comment was posted. 848 * @param bool $wp_error Whether to return a WP_Error object instead of executing 849 * wp_die() or die() if a comment flood is occurring. 850 */ 851 do_action( 852 'check_comment_flood', 853 $commentdata['comment_author_IP'], 854 $commentdata['comment_author_email'], 855 $commentdata['comment_date_gmt'], 856 $wp_error 857 ); 858 859 /** 860 * Filters whether a comment is part of a comment flood. 861 * 862 * The default check is wp_check_comment_flood(). See check_comment_flood_db(). 863 * 864 * @since 4.7.0 865 * @since 5.5.0 The `$avoid_die` parameter was renamed to `$wp_error`. 866 * 867 * @param bool $is_flood Is a comment flooding occurring? Default false. 868 * @param string $comment_author_ip Comment author's IP address. 869 * @param string $comment_author_email Comment author's email. 870 * @param string $comment_date_gmt GMT date the comment was posted. 871 * @param bool $wp_error Whether to return a WP_Error object instead of executing 872 * wp_die() or die() if a comment flood is occurring. 873 */ 874 $is_flood = apply_filters( 875 'wp_is_comment_flood', 876 false, 877 $commentdata['comment_author_IP'], 878 $commentdata['comment_author_email'], 879 $commentdata['comment_date_gmt'], 880 $wp_error 881 ); 882 883 if ( $is_flood ) { 884 /** This filter is documented in wp-includes/comment.php */ 885 $comment_flood_message = apply_filters( 'comment_flood_message', __( 'You are posting comments too quickly. Slow down.' ) ); 886 887 return new WP_Error( 'comment_flood', $comment_flood_message, 429 ); 888 } 889 890 return wp_check_comment_data( $commentdata ); 891 } 892 893 /** 894 * Hooks WP's native database-based comment-flood check. 895 * 896 * This wrapper maintains backward compatibility with plugins that expect to 897 * be able to unhook the legacy check_comment_flood_db() function from 898 * 'check_comment_flood' using remove_action(). 899 * 900 * @since 2.3.0 901 * @since 4.7.0 Converted to be an add_filter() wrapper. 902 */ 903 function check_comment_flood_db() { 904 add_filter( 'wp_is_comment_flood', 'wp_check_comment_flood', 10, 5 ); 905 } 906 907 /** 908 * Checks whether comment flooding is occurring. 909 * 910 * Won't run, if current user can manage options, so to not block 911 * administrators. 912 * 913 * @since 4.7.0 914 * 915 * @global wpdb $wpdb WordPress database abstraction object. 916 * 917 * @param bool $is_flood Is a comment flooding occurring? 918 * @param string $ip Comment author's IP address. 919 * @param string $email Comment author's email address. 920 * @param string $date MySQL time string. 921 * @param bool $avoid_die When true, a disallowed comment will result in the function 922 * returning without executing wp_die() or die(). Default false. 923 * @return bool Whether comment flooding is occurring. 924 */ 925 function wp_check_comment_flood( $is_flood, $ip, $email, $date, $avoid_die = false ) { 926 global $wpdb; 927 928 // Another callback has declared a flood. Trust it. 929 if ( true === $is_flood ) { 930 return $is_flood; 931 } 932 933 // Don't throttle admins or moderators. 934 if ( current_user_can( 'manage_options' ) || current_user_can( 'moderate_comments' ) ) { 935 return false; 936 } 937 938 $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS ); 939 940 if ( is_user_logged_in() ) { 941 $user = get_current_user_id(); 942 $check_column = '`user_id`'; 943 } else { 944 $user = $ip; 945 $check_column = '`comment_author_IP`'; 946 } 947 948 $sql = $wpdb->prepare( 949 "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", 950 $hour_ago, 951 $user, 952 $email 953 ); 954 955 $lasttime = $wpdb->get_var( $sql ); 956 957 if ( $lasttime ) { 958 $time_lastcomment = mysql2date( 'U', $lasttime, false ); 959 $time_newcomment = mysql2date( 'U', $date, false ); 960 961 /** 962 * Filters the comment flood status. 963 * 964 * @since 2.1.0 965 * 966 * @param bool $bool Whether a comment flood is occurring. Default false. 967 * @param int $time_lastcomment Timestamp of when the last comment was posted. 968 * @param int $time_newcomment Timestamp of when the new comment was posted. 969 */ 970 $flood_die = apply_filters( 'comment_flood_filter', false, $time_lastcomment, $time_newcomment ); 971 972 if ( $flood_die ) { 973 /** 974 * Fires before the comment flood message is triggered. 975 * 976 * @since 1.5.0 977 * 978 * @param int $time_lastcomment Timestamp of when the last comment was posted. 979 * @param int $time_newcomment Timestamp of when the new comment was posted. 980 */ 981 do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment ); 982 983 if ( $avoid_die ) { 984 return true; 985 } else { 986 /** 987 * Filters the comment flood error message. 988 * 989 * @since 5.2.0 990 * 991 * @param string $comment_flood_message Comment flood error message. 992 */ 993 $comment_flood_message = apply_filters( 'comment_flood_message', __( 'You are posting comments too quickly. Slow down.' ) ); 994 995 if ( wp_doing_ajax() ) { 996 die( $comment_flood_message ); 997 } 998 999 wp_die( $comment_flood_message, 429 ); 1000 } 1001 } 1002 } 1003 1004 return false; 1005 } 1006 1007 /** 1008 * Separates an array of comments into an array keyed by comment_type. 1009 * 1010 * @since 2.7.0 1011 * 1012 * @param WP_Comment[] $comments Array of comments. 1013 * @return array<string, WP_Comment[]> Array of comments keyed by comment type. 1014 */ 1015 function separate_comments( &$comments ) { 1016 $comments_by_type = array( 1017 'comment' => array(), 1018 'trackback' => array(), 1019 'pingback' => array(), 1020 'pings' => array(), 1021 ); 1022 1023 $count = count( $comments ); 1024 1025 for ( $i = 0; $i < $count; $i++ ) { 1026 $type = $comments[ $i ]->comment_type; 1027 1028 if ( empty( $type ) ) { 1029 $type = 'comment'; 1030 } 1031 1032 $comments_by_type[ $type ][] = &$comments[ $i ]; 1033 1034 if ( 'trackback' === $type || 'pingback' === $type ) { 1035 $comments_by_type['pings'][] = &$comments[ $i ]; 1036 } 1037 } 1038 1039 return $comments_by_type; 1040 } 1041 1042 /** 1043 * Calculates the total number of comment pages. 1044 * 1045 * @since 2.7.0 1046 * 1047 * @uses Walker_Comment 1048 * 1049 * @global WP_Query $wp_query WordPress Query object. 1050 * 1051 * @param WP_Comment[] $comments Optional. Array of WP_Comment objects. Defaults to `$wp_query->comments`. 1052 * @param int $per_page Optional. Comments per page. Defaults to the value of `comments_per_page` 1053 * query var, option of the same name, or 1 (in that order). 1054 * @param bool $threaded Optional. Control over flat or threaded comments. Defaults to the value 1055 * of `thread_comments` option. 1056 * @return int Number of comment pages. 1057 */ 1058 function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) { 1059 global $wp_query; 1060 1061 if ( null === $comments && null === $per_page && null === $threaded && ! empty( $wp_query->max_num_comment_pages ) ) { 1062 return $wp_query->max_num_comment_pages; 1063 } 1064 1065 if ( ( ! $comments || ! is_array( $comments ) ) && ! empty( $wp_query->comments ) ) { 1066 $comments = $wp_query->comments; 1067 } 1068 1069 if ( empty( $comments ) ) { 1070 return 0; 1071 } 1072 1073 if ( ! get_option( 'page_comments' ) ) { 1074 return 1; 1075 } 1076 1077 $per_page ??= (int) get_query_var( 'comments_per_page' ); 1078 1079 if ( 0 === $per_page ) { 1080 $per_page = (int) get_option( 'comments_per_page' ); 1081 } 1082 1083 if ( 0 === $per_page ) { 1084 return 1; 1085 } 1086 1087 $threaded ??= get_option( 'thread_comments' ); 1088 1089 if ( $threaded ) { 1090 $walker = new Walker_Comment(); 1091 $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page ); 1092 } else { 1093 $count = ceil( count( $comments ) / $per_page ); 1094 } 1095 1096 return (int) $count; 1097 } 1098 1099 /** 1100 * Calculates what page number a comment will appear on for comment paging. 1101 * 1102 * @since 2.7.0 1103 * 1104 * @global wpdb $wpdb WordPress database abstraction object. 1105 * 1106 * @param int $comment_id Comment ID. 1107 * @param array $args { 1108 * Array of optional arguments. 1109 * 1110 * @type string $type Limit paginated comments to those matching a given type. 1111 * Accepts 'comment', 'trackback', 'pingback', 'pings' 1112 * (trackbacks and pingbacks), or 'all'. Default 'all'. 1113 * @type int $per_page Per-page count to use when calculating pagination. 1114 * Defaults to the value of the 'comments_per_page' option. 1115 * @type int|string $max_depth If greater than 1, comment page will be determined 1116 * for the top-level parent `$comment_id`. 1117 * Defaults to the value of the 'thread_comments_depth' option. 1118 * } 1119 * @return int|null Comment page number or null on error. 1120 */ 1121 function get_page_of_comment( $comment_id, $args = array() ) { 1122 global $wpdb; 1123 1124 $page = null; 1125 1126 $comment = get_comment( $comment_id ); 1127 if ( ! $comment ) { 1128 return null; 1129 } 1130 1131 $defaults = array( 1132 'type' => 'all', 1133 'page' => '', 1134 'per_page' => '', 1135 'max_depth' => '', 1136 ); 1137 $args = wp_parse_args( $args, $defaults ); 1138 $original_args = $args; 1139 1140 // Order of precedence: 1. `$args['per_page']`, 2. 'comments_per_page' query_var, 3. 'comments_per_page' option. 1141 if ( get_option( 'page_comments' ) ) { 1142 if ( '' === $args['per_page'] ) { 1143 $args['per_page'] = get_query_var( 'comments_per_page' ); 1144 } 1145 1146 if ( '' === $args['per_page'] ) { 1147 $args['per_page'] = get_option( 'comments_per_page' ); 1148 } 1149 } 1150 1151 if ( empty( $args['per_page'] ) ) { 1152 $args['per_page'] = 0; 1153 $args['page'] = 0; 1154 } 1155 1156 if ( $args['per_page'] < 1 ) { 1157 $page = 1; 1158 } 1159 1160 if ( null === $page ) { 1161 if ( '' === $args['max_depth'] ) { 1162 if ( get_option( 'thread_comments' ) ) { 1163 $args['max_depth'] = get_option( 'thread_comments_depth' ); 1164 } else { 1165 $args['max_depth'] = -1; 1166 } 1167 } 1168 1169 // Find this comment's top-level parent if threading is enabled. 1170 if ( $args['max_depth'] > 1 && '0' !== $comment->comment_parent ) { 1171 return get_page_of_comment( $comment->comment_parent, $args ); 1172 } 1173 1174 $comment_args = array( 1175 'type' => $args['type'], 1176 'post_id' => $comment->comment_post_ID, 1177 'fields' => 'ids', 1178 'count' => true, 1179 'status' => 'approve', 1180 'orderby' => 'none', 1181 'parent' => 0, 1182 'date_query' => array( 1183 array( 1184 'column' => "$wpdb->comments.comment_date_gmt", 1185 'before' => $comment->comment_date_gmt, 1186 ), 1187 ), 1188 ); 1189 1190 if ( is_user_logged_in() ) { 1191 $comment_args['include_unapproved'] = array( get_current_user_id() ); 1192 } else { 1193 $unapproved_email = wp_get_unapproved_comment_author_email(); 1194 1195 if ( $unapproved_email ) { 1196 $comment_args['include_unapproved'] = array( $unapproved_email ); 1197 } 1198 } 1199 1200 /** 1201 * Filters the arguments used to query comments in get_page_of_comment(). 1202 * 1203 * @since 5.5.0 1204 * 1205 * @see WP_Comment_Query::__construct() 1206 * 1207 * @param array $comment_args { 1208 * Array of WP_Comment_Query arguments. 1209 * 1210 * @type string $type Limit paginated comments to those matching a given type. 1211 * Accepts 'comment', 'trackback', 'pingback', 'pings' 1212 * (trackbacks and pingbacks), or 'all'. Default 'all'. 1213 * @type int $post_id ID of the post. 1214 * @type string $fields Comment fields to return. 1215 * @type bool $count Whether to return a comment count (true) or array 1216 * of comment objects (false). 1217 * @type string $status Comment status. 1218 * @type int $parent Parent ID of comment to retrieve children of. 1219 * @type array $date_query Date query clauses to limit comments by. See WP_Date_Query. 1220 * @type array $include_unapproved Array of IDs or email addresses whose unapproved comments 1221 * will be included in paginated comments. 1222 * } 1223 */ 1224 $comment_args = apply_filters( 'get_page_of_comment_query_args', $comment_args ); 1225 1226 $comment_query = new WP_Comment_Query(); 1227 $older_comment_count = $comment_query->query( $comment_args ); 1228 1229 // No older comments? Then it's page #1. 1230 if ( 0 === $older_comment_count ) { 1231 $page = 1; 1232 1233 // Divide comments older than this one by comments per page to get this comment's page number. 1234 } else { 1235 $page = (int) ceil( ( $older_comment_count + 1 ) / $args['per_page'] ); 1236 } 1237 } 1238 1239 /** 1240 * Filters the calculated page on which a comment appears. 1241 * 1242 * @since 4.4.0 1243 * @since 4.7.0 Introduced the `$comment_id` parameter. 1244 * 1245 * @param int $page Comment page. 1246 * @param array $args { 1247 * Arguments used to calculate pagination. These include arguments auto-detected by the function, 1248 * based on query vars, system settings, etc. For pristine arguments passed to the function, 1249 * see `$original_args`. 1250 * 1251 * @type string $type Type of comments to count. 1252 * @type int $page Calculated current page. 1253 * @type int $per_page Calculated number of comments per page. 1254 * @type int $max_depth Maximum comment threading depth allowed. 1255 * } 1256 * @param array $original_args { 1257 * Array of arguments passed to the function. Some or all of these may not be set. 1258 * 1259 * @type string $type Type of comments to count. 1260 * @type int $page Current comment page. 1261 * @type int $per_page Number of comments per page. 1262 * @type int $max_depth Maximum comment threading depth allowed. 1263 * } 1264 * @param int $comment_id ID of the comment. 1265 */ 1266 return apply_filters( 'get_page_of_comment', (int) $page, $args, $original_args, $comment_id ); 1267 } 1268 1269 /** 1270 * Retrieves the maximum character lengths for the comment form fields. 1271 * 1272 * @since 4.5.0 1273 * 1274 * @global wpdb $wpdb WordPress database abstraction object. 1275 * 1276 * @return int[] Array of maximum lengths keyed by field name. 1277 */ 1278 function wp_get_comment_fields_max_lengths() { 1279 global $wpdb; 1280 1281 $lengths = array( 1282 'comment_author' => 245, 1283 'comment_author_email' => 100, 1284 'comment_author_url' => 200, 1285 'comment_content' => 65525, 1286 ); 1287 1288 if ( $wpdb->is_mysql ) { 1289 foreach ( $lengths as $column => $length ) { 1290 $col_length = $wpdb->get_col_length( $wpdb->comments, $column ); 1291 $max_length = 0; 1292 1293 // No point if we can't get the DB column lengths. 1294 if ( is_wp_error( $col_length ) ) { 1295 break; 1296 } 1297 1298 if ( ! is_array( $col_length ) && (int) $col_length > 0 ) { 1299 $max_length = (int) $col_length; 1300 } elseif ( is_array( $col_length ) && isset( $col_length['length'] ) && (int) $col_length['length'] > 0 ) { 1301 $max_length = (int) $col_length['length']; 1302 1303 if ( ! empty( $col_length['type'] ) && 'byte' === $col_length['type'] ) { 1304 $max_length = $max_length - 10; 1305 } 1306 } 1307 1308 if ( $max_length > 0 ) { 1309 $lengths[ $column ] = $max_length; 1310 } 1311 } 1312 } 1313 1314 /** 1315 * Filters the lengths for the comment form fields. 1316 * 1317 * @since 4.5.0 1318 * 1319 * @param int[] $lengths Array of maximum lengths keyed by field name. 1320 */ 1321 return apply_filters( 'wp_get_comment_fields_max_lengths', $lengths ); 1322 } 1323 1324 /** 1325 * Compares the lengths of comment data against the maximum character limits. 1326 * 1327 * @since 4.7.0 1328 * 1329 * @param array $comment_data Array of arguments for inserting a comment. 1330 * @return WP_Error|true WP_Error when a comment field exceeds the limit, 1331 * otherwise true. 1332 */ 1333 function wp_check_comment_data_max_lengths( $comment_data ) { 1334 $max_lengths = wp_get_comment_fields_max_lengths(); 1335 1336 if ( isset( $comment_data['comment_author'] ) && mb_strlen( $comment_data['comment_author'], '8bit' ) > $max_lengths['comment_author'] ) { 1337 return new WP_Error( 'comment_author_column_length', __( '<strong>Error:</strong> Your name is too long.' ), 200 ); 1338 } 1339 1340 if ( isset( $comment_data['comment_author_email'] ) && strlen( $comment_data['comment_author_email'] ) > $max_lengths['comment_author_email'] ) { 1341 return new WP_Error( 'comment_author_email_column_length', __( '<strong>Error:</strong> Your email address is too long.' ), 200 ); 1342 } 1343 1344 if ( isset( $comment_data['comment_author_url'] ) && strlen( $comment_data['comment_author_url'] ) > $max_lengths['comment_author_url'] ) { 1345 return new WP_Error( 'comment_author_url_column_length', __( '<strong>Error:</strong> Your URL is too long.' ), 200 ); 1346 } 1347 1348 if ( isset( $comment_data['comment_content'] ) && mb_strlen( $comment_data['comment_content'], '8bit' ) > $max_lengths['comment_content'] ) { 1349 return new WP_Error( 'comment_content_column_length', __( '<strong>Error:</strong> Your comment is too long.' ), 200 ); 1350 } 1351 1352 return true; 1353 } 1354 1355 /** 1356 * Checks whether comment data passes internal checks or has disallowed content. 1357 * 1358 * @since 6.7.0 1359 * 1360 * @global wpdb $wpdb WordPress database abstraction object. 1361 * 1362 * @param array $comment_data Array of arguments for inserting a comment. 1363 * @return int|string|WP_Error The approval status on success (0|1|'spam'|'trash'), 1364 * WP_Error otherwise. 1365 */ 1366 function wp_check_comment_data( $comment_data ) { 1367 global $wpdb; 1368 1369 if ( ! empty( $comment_data['user_id'] ) ) { 1370 $user = get_userdata( $comment_data['user_id'] ); 1371 $post_author = (int) $wpdb->get_var( 1372 $wpdb->prepare( 1373 "SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", 1374 $comment_data['comment_post_ID'] 1375 ) 1376 ); 1377 } 1378 1379 if ( isset( $user ) && ( $comment_data['user_id'] === $post_author || $user->has_cap( 'moderate_comments' ) ) ) { 1380 // The author and the admins get respect. 1381 $approved = 1; 1382 } else { 1383 // Everyone else's comments will be checked. 1384 if ( check_comment( 1385 $comment_data['comment_author'], 1386 $comment_data['comment_author_email'], 1387 $comment_data['comment_author_url'], 1388 $comment_data['comment_content'], 1389 $comment_data['comment_author_IP'], 1390 $comment_data['comment_agent'], 1391 $comment_data['comment_type'] 1392 ) ) { 1393 $approved = 1; 1394 } else { 1395 $approved = 0; 1396 } 1397 1398 if ( wp_check_comment_disallowed_list( 1399 $comment_data['comment_author'], 1400 $comment_data['comment_author_email'], 1401 $comment_data['comment_author_url'], 1402 $comment_data['comment_content'], 1403 $comment_data['comment_author_IP'], 1404 $comment_data['comment_agent'] 1405 ) ) { 1406 $approved = EMPTY_TRASH_DAYS ? 'trash' : 'spam'; 1407 } 1408 } 1409 1410 /** 1411 * Filters a comment's approval status before it is set. 1412 * 1413 * @since 2.1.0 1414 * @since 4.9.0 Returning a WP_Error value from the filter will short-circuit comment insertion 1415 * and allow skipping further processing. 1416 * 1417 * @param int|string|WP_Error $approved The approval status. Accepts 1, 0, 'spam', 'trash', 1418 * or WP_Error. 1419 * @param array $commentdata Comment data. 1420 */ 1421 return apply_filters( 'pre_comment_approved', $approved, $comment_data ); 1422 } 1423 1424 /** 1425 * Checks if a comment contains disallowed characters or words. 1426 * 1427 * @since 5.5.0 1428 * 1429 * @param string $author The author of the comment. 1430 * @param string $email The email of the comment. 1431 * @param string $url The url used in the comment. 1432 * @param string $comment The comment content. 1433 * @param string $user_ip The comment author's IP address. 1434 * @param string $user_agent The author's browser user agent. 1435 * @return bool True if the comment contains disallowed content, false otherwise. 1436 */ 1437 function wp_check_comment_disallowed_list( $author, $email, $url, $comment, $user_ip, $user_agent ) { 1438 /** 1439 * Fires before the comment is tested for disallowed characters or words. 1440 * 1441 * @since 1.5.0 1442 * @deprecated 5.5.0 Use {@see 'wp_check_comment_disallowed_list'} instead. 1443 * 1444 * @param string $author Comment author. 1445 * @param string $email Comment author's email. 1446 * @param string $url Comment author's URL. 1447 * @param string $comment Comment content. 1448 * @param string $user_ip Comment author's IP address. 1449 * @param string $user_agent Comment author's browser user agent. 1450 */ 1451 do_action_deprecated( 1452 'wp_blacklist_check', 1453 array( $author, $email, $url, $comment, $user_ip, $user_agent ), 1454 '5.5.0', 1455 'wp_check_comment_disallowed_list', 1456 __( 'Please consider writing more inclusive code.' ) 1457 ); 1458 1459 /** 1460 * Fires before the comment is tested for disallowed characters or words. 1461 * 1462 * @since 5.5.0 1463 * 1464 * @param string $author Comment author. 1465 * @param string $email Comment author's email. 1466 * @param string $url Comment author's URL. 1467 * @param string $comment Comment content. 1468 * @param string $user_ip Comment author's IP address. 1469 * @param string $user_agent Comment author's browser user agent. 1470 */ 1471 do_action( 'wp_check_comment_disallowed_list', $author, $email, $url, $comment, $user_ip, $user_agent ); 1472 1473 $mod_keys = trim( get_option( 'disallowed_keys' ) ); 1474 if ( '' === $mod_keys ) { 1475 return false; // If moderation keys are empty. 1476 } 1477 1478 // Ensure HTML tags are not being used to bypass the list of disallowed characters and words. 1479 $comment_without_html = wp_strip_all_tags( $comment ); 1480 1481 $words = explode( "\n", $mod_keys ); 1482 1483 foreach ( (array) $words as $word ) { 1484 $word = trim( $word ); 1485 1486 // Skip empty lines. 1487 if ( empty( $word ) ) { 1488 continue; } 1489 1490 // Do some escaping magic so that '#' chars in the spam words don't break things: 1491 $word = preg_quote( $word, '#' ); 1492 1493 $pattern = "#$word#iu"; 1494 if ( preg_match( $pattern, $author ) 1495 || preg_match( $pattern, $email ) 1496 || preg_match( $pattern, $url ) 1497 || preg_match( $pattern, $comment ) 1498 || preg_match( $pattern, $comment_without_html ) 1499 || preg_match( $pattern, $user_ip ) 1500 || preg_match( $pattern, $user_agent ) 1501 ) { 1502 return true; 1503 } 1504 } 1505 return false; 1506 } 1507 1508 /** 1509 * Retrieves the total comment counts for the whole site or a single post. 1510 * 1511 * The comment stats are cached and then retrieved, if they already exist in the 1512 * cache. 1513 * 1514 * @see get_comment_count() Which handles fetching the live comment counts. 1515 * 1516 * @since 2.5.0 1517 * 1518 * @param int $post_id Optional. Restrict the comment counts to the given post. Default 0, which indicates that 1519 * comment counts for the whole site will be retrieved. 1520 * @return stdClass { 1521 * The number of comments keyed by their status. 1522 * 1523 * @type int $approved The number of approved comments. 1524 * @type int $moderated The number of comments awaiting moderation (a.k.a. pending). 1525 * @type int $spam The number of spam comments. 1526 * @type int $trash The number of trashed comments. 1527 * @type int $post-trashed The number of comments for posts that are in the trash. 1528 * @type int $total_comments The total number of non-trashed comments, including spam. 1529 * @type int $all The total number of pending or approved comments. 1530 * } 1531 */ 1532 function wp_count_comments( $post_id = 0 ) { 1533 $post_id = (int) $post_id; 1534 1535 /** 1536 * Filters the comments count for a given post or the whole site. 1537 * 1538 * @since 2.7.0 1539 * 1540 * @param array|stdClass $count An empty array or an object containing comment counts. 1541 * @param int $post_id The post ID. Can be 0 to represent the whole site. 1542 */ 1543 $filtered = apply_filters( 'wp_count_comments', array(), $post_id ); 1544 if ( ! empty( $filtered ) ) { 1545 return $filtered; 1546 } 1547 1548 $count = wp_cache_get( "comments-{$post_id}", 'counts' ); 1549 if ( false !== $count ) { 1550 return $count; 1551 } 1552 1553 $stats = get_comment_count( $post_id ); 1554 $stats['moderated'] = $stats['awaiting_moderation']; 1555 unset( $stats['awaiting_moderation'] ); 1556 1557 $stats_object = (object) $stats; 1558 wp_cache_set( "comments-{$post_id}", $stats_object, 'counts' ); 1559 1560 return $stats_object; 1561 } 1562 1563 /** 1564 * Trashes or deletes a comment. 1565 * 1566 * The comment is moved to Trash instead of permanently deleted unless Trash is 1567 * disabled, item is already in the Trash, or $force_delete is true. 1568 * 1569 * The post comment count will be updated if the comment was approved and has a 1570 * post ID available. 1571 * 1572 * @since 2.0.0 1573 * @since 7.2.0 A note's reactions are deleted along with it, rather than 1574 * being reparented. 1575 * 1576 * @global wpdb $wpdb WordPress database abstraction object. 1577 * 1578 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object. 1579 * @param bool $force_delete Whether to bypass Trash and force deletion. Default false. 1580 * @return bool True on success, false on failure. 1581 */ 1582 function wp_delete_comment( $comment_id, $force_delete = false ) { 1583 global $wpdb; 1584 1585 $comment = get_comment( $comment_id ); 1586 if ( ! $comment ) { 1587 return false; 1588 } 1589 1590 if ( ! $force_delete && EMPTY_TRASH_DAYS && ! in_array( wp_get_comment_status( $comment ), array( 'trash', 'spam' ), true ) ) { 1591 return wp_trash_comment( $comment_id ); 1592 } 1593 1594 /** 1595 * Fires immediately before a comment is deleted from the database. 1596 * 1597 * @since 1.2.0 1598 * @since 4.9.0 Added the `$comment` parameter. 1599 * 1600 * @param string $comment_id The comment ID as a numeric string. 1601 * @param WP_Comment $comment The comment to be deleted. 1602 */ 1603 do_action( 'delete_comment', $comment->comment_ID, $comment ); 1604 1605 /* 1606 * Delete a note's reactions rather than letting them be reparented below. 1607 * A reaction only means anything attached to its note, and an orphaned one 1608 * would keep the reactor's identity on a note that no longer exists. This 1609 * covers every status: a reaction the user removed is trashed, not deleted. 1610 */ 1611 if ( 'note' === $comment->comment_type ) { 1612 $reaction_ids = get_comments( 1613 array( 1614 'parent' => $comment->comment_ID, 1615 'type' => 'reaction', 1616 'status' => 'any', 1617 'fields' => 'ids', 1618 ) 1619 ); 1620 1621 foreach ( $reaction_ids as $reaction_id ) { 1622 wp_delete_comment( $reaction_id, true ); 1623 } 1624 } 1625 1626 // Move children up a level. 1627 $children = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment->comment_ID ) ); 1628 if ( ! empty( $children ) ) { 1629 $wpdb->update( $wpdb->comments, array( 'comment_parent' => $comment->comment_parent ), array( 'comment_parent' => $comment->comment_ID ) ); 1630 clean_comment_cache( $children ); 1631 } 1632 1633 // Delete metadata. 1634 $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment->comment_ID ) ); 1635 foreach ( $meta_ids as $mid ) { 1636 delete_metadata_by_mid( 'comment', $mid ); 1637 } 1638 1639 if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment->comment_ID ) ) ) { 1640 return false; 1641 } 1642 1643 /** 1644 * Fires immediately after a comment is deleted from the database. 1645 * 1646 * @since 2.9.0 1647 * @since 4.9.0 Added the `$comment` parameter. 1648 * 1649 * @param string $comment_id The comment ID as a numeric string. 1650 * @param WP_Comment $comment The deleted comment. 1651 */ 1652 do_action( 'deleted_comment', $comment->comment_ID, $comment ); 1653 1654 $post_id = $comment->comment_post_ID; 1655 if ( $post_id && '1' === $comment->comment_approved ) { 1656 wp_update_comment_count( $post_id ); 1657 } 1658 1659 clean_comment_cache( $comment->comment_ID ); 1660 1661 /** This action is documented in wp-includes/comment.php */ 1662 do_action( 'wp_set_comment_status', $comment->comment_ID, 'delete' ); 1663 1664 wp_transition_comment_status( 'delete', $comment->comment_approved, $comment ); 1665 1666 return true; 1667 } 1668 1669 /** 1670 * Moves a comment to the Trash 1671 * 1672 * If Trash is disabled, comment is permanently deleted. 1673 * 1674 * @since 2.9.0 1675 * @since 6.9.0 Any child notes are deleted when deleting a note. 1676 * @since 7.2.0 A note's reactions are trashed along with it. 1677 * @since 7.2.0 The child notes trashed along with a note are recorded, so that they can be restored with it. 1678 * 1679 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object. 1680 * @return bool True on success, false on failure. 1681 */ 1682 function wp_trash_comment( $comment_id ) { 1683 if ( ! EMPTY_TRASH_DAYS ) { 1684 $comment = get_comment( $comment_id ); 1685 $success = wp_delete_comment( $comment_id, true ); 1686 1687 if ( ! $success ) { 1688 return false; 1689 } 1690 1691 // Also delete children of top level 'note' type comments. 1692 if ( $comment && 'note' === $comment->comment_type && 0 === (int) $comment->comment_parent ) { 1693 $children = $comment->get_children( 1694 array( 1695 'fields' => 'ids', 1696 'status' => 'all', 1697 'type' => 'note', 1698 ) 1699 ); 1700 1701 foreach ( $children as $child_id ) { 1702 if ( ! wp_delete_comment( $child_id, true ) ) { 1703 $success = false; 1704 } 1705 } 1706 } 1707 1708 return $success; 1709 } 1710 1711 $comment = get_comment( $comment_id ); 1712 if ( ! $comment ) { 1713 return false; 1714 } 1715 1716 /** 1717 * Fires immediately before a comment is sent to the Trash. 1718 * 1719 * @since 2.9.0 1720 * @since 4.9.0 Added the `$comment` parameter. 1721 * 1722 * @param string $comment_id The comment ID as a numeric string. 1723 * @param WP_Comment $comment The comment to be trashed. 1724 */ 1725 do_action( 'trash_comment', $comment->comment_ID, $comment ); 1726 1727 if ( wp_set_comment_status( $comment, 'trash' ) ) { 1728 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' ); 1729 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' ); 1730 add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved ); 1731 add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() ); 1732 1733 /** 1734 * Fires immediately after a comment is sent to Trash. 1735 * 1736 * @since 2.9.0 1737 * @since 4.9.0 Added the `$comment` parameter. 1738 * 1739 * @param string $comment_id The comment ID as a numeric string. 1740 * @param WP_Comment $comment The trashed comment. 1741 */ 1742 do_action( 'trashed_comment', $comment->comment_ID, $comment ); 1743 1744 /* 1745 * Trash a note's reactions with it, at any depth. The child-note 1746 * cascade below trashes each reply in turn, which brings the replies' 1747 * own reactions along through this same branch. 1748 * 1749 * Restoring the note does not bring its reactions back: 1750 * wp_untrash_comment() only restores the child notes recorded below. 1751 */ 1752 if ( 'note' === $comment->comment_type ) { 1753 $reaction_ids = get_comments( 1754 array( 1755 'parent' => $comment->comment_ID, 1756 'type' => 'reaction', 1757 'status' => 'approve', 1758 'fields' => 'ids', 1759 ) 1760 ); 1761 1762 foreach ( $reaction_ids as $reaction_id ) { 1763 wp_trash_comment( $reaction_id ); 1764 } 1765 } 1766 1767 // For top level 'note' type comments, also trash children. 1768 if ( 'note' === $comment->comment_type && 0 === (int) $comment->comment_parent ) { 1769 $children = $comment->get_children( 1770 array( 1771 'fields' => 'ids', 1772 'status' => 'all', 1773 'type' => 'note', 1774 ) 1775 ); 1776 1777 // Skip children already in the Trash, so that they are not restored with the parent. 1778 $children = array_values( 1779 array_filter( 1780 array_map( 'intval', $children ), 1781 static function ( $child_id ) { 1782 return 'trash' !== wp_get_comment_status( $child_id ); 1783 } 1784 ) 1785 ); 1786 1787 // Record the children trashed along with the parent, so that they can be restored with it. 1788 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_children' ); 1789 if ( $children ) { 1790 add_comment_meta( $comment->comment_ID, '_wp_trash_meta_children', $children ); 1791 } 1792 1793 $success = true; 1794 foreach ( $children as $child_id ) { 1795 if ( ! wp_trash_comment( $child_id ) ) { 1796 $success = false; 1797 } 1798 } 1799 return $success; 1800 } 1801 1802 return true; 1803 } 1804 1805 return false; 1806 } 1807 1808 /** 1809 * Removes a comment from the Trash 1810 * 1811 * @since 2.9.0 1812 * @since 7.2.0 Any child notes trashed along with a note are restored when restoring the note. 1813 * 1814 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object. 1815 * @return bool True on success, false on failure. 1816 */ 1817 function wp_untrash_comment( $comment_id ) { 1818 $comment = get_comment( $comment_id ); 1819 if ( ! $comment ) { 1820 return false; 1821 } 1822 1823 /** 1824 * Fires immediately before a comment is restored from the Trash. 1825 * 1826 * @since 2.9.0 1827 * @since 4.9.0 Added the `$comment` parameter. 1828 * 1829 * @param string $comment_id The comment ID as a numeric string. 1830 * @param WP_Comment $comment The comment to be untrashed. 1831 */ 1832 do_action( 'untrash_comment', $comment->comment_ID, $comment ); 1833 1834 $status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true ); 1835 if ( empty( $status ) ) { 1836 $status = '0'; 1837 } 1838 1839 if ( wp_set_comment_status( $comment, $status ) ) { 1840 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' ); 1841 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' ); 1842 1843 /** 1844 * Fires immediately after a comment is restored from the Trash. 1845 * 1846 * @since 2.9.0 1847 * @since 4.9.0 Added the `$comment` parameter. 1848 * 1849 * @param string $comment_id The comment ID as a numeric string. 1850 * @param WP_Comment $comment The untrashed comment. 1851 */ 1852 do_action( 'untrashed_comment', $comment->comment_ID, $comment ); 1853 1854 // For top level 'note' type comments, also restore the children trashed along with it. 1855 if ( 'note' === $comment->comment_type && 0 === (int) $comment->comment_parent ) { 1856 $children = get_comment_meta( $comment->comment_ID, '_wp_trash_meta_children', true ); 1857 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_children' ); 1858 1859 if ( ! is_array( $children ) ) { 1860 return true; 1861 } 1862 1863 $success = true; 1864 foreach ( $children as $child_id ) { 1865 $child = get_comment( (int) $child_id ); 1866 1867 // Skip children that have been deleted, moved, or restored in the meantime. 1868 if ( 1869 ! $child || 1870 'note' !== $child->comment_type || 1871 (int) $child->comment_parent !== (int) $comment->comment_ID || 1872 'trash' !== wp_get_comment_status( $child ) 1873 ) { 1874 continue; 1875 } 1876 1877 if ( ! wp_untrash_comment( $child ) ) { 1878 $success = false; 1879 } 1880 } 1881 return $success; 1882 } 1883 1884 return true; 1885 } 1886 1887 return false; 1888 } 1889 1890 /** 1891 * Marks a comment as Spam. 1892 * 1893 * @since 2.9.0 1894 * 1895 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object. 1896 * @return bool True on success, false on failure. 1897 */ 1898 function wp_spam_comment( $comment_id ) { 1899 $comment = get_comment( $comment_id ); 1900 if ( ! $comment ) { 1901 return false; 1902 } 1903 1904 /** 1905 * Fires immediately before a comment is marked as Spam. 1906 * 1907 * @since 2.9.0 1908 * @since 4.9.0 Added the `$comment` parameter. 1909 * 1910 * @param int $comment_id The comment ID. 1911 * @param WP_Comment $comment The comment to be marked as spam. 1912 */ 1913 do_action( 'spam_comment', $comment->comment_ID, $comment ); 1914 1915 if ( wp_set_comment_status( $comment, 'spam' ) ) { 1916 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' ); 1917 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' ); 1918 add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved ); 1919 add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() ); 1920 1921 /** 1922 * Fires immediately after a comment is marked as Spam. 1923 * 1924 * @since 2.9.0 1925 * @since 4.9.0 Added the `$comment` parameter. 1926 * 1927 * @param int $comment_id The comment ID. 1928 * @param WP_Comment $comment The comment marked as spam. 1929 */ 1930 do_action( 'spammed_comment', $comment->comment_ID, $comment ); 1931 1932 return true; 1933 } 1934 1935 return false; 1936 } 1937 1938 /** 1939 * Removes a comment from the Spam. 1940 * 1941 * @since 2.9.0 1942 * 1943 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object. 1944 * @return bool True on success, false on failure. 1945 */ 1946 function wp_unspam_comment( $comment_id ) { 1947 $comment = get_comment( $comment_id ); 1948 if ( ! $comment ) { 1949 return false; 1950 } 1951 1952 /** 1953 * Fires immediately before a comment is unmarked as Spam. 1954 * 1955 * @since 2.9.0 1956 * @since 4.9.0 Added the `$comment` parameter. 1957 * 1958 * @param string $comment_id The comment ID as a numeric string. 1959 * @param WP_Comment $comment The comment to be unmarked as spam. 1960 */ 1961 do_action( 'unspam_comment', $comment->comment_ID, $comment ); 1962 1963 $status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true ); 1964 if ( empty( $status ) ) { 1965 $status = '0'; 1966 } 1967 1968 if ( wp_set_comment_status( $comment, $status ) ) { 1969 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' ); 1970 delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' ); 1971 1972 /** 1973 * Fires immediately after a comment is unmarked as Spam. 1974 * 1975 * @since 2.9.0 1976 * @since 4.9.0 Added the `$comment` parameter. 1977 * 1978 * @param string $comment_id The comment ID as a numeric string. 1979 * @param WP_Comment $comment The comment unmarked as spam. 1980 */ 1981 do_action( 'unspammed_comment', $comment->comment_ID, $comment ); 1982 1983 return true; 1984 } 1985 1986 return false; 1987 } 1988 1989 /** 1990 * Retrieves the status of a comment by comment ID. 1991 * 1992 * @since 1.0.0 1993 * 1994 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object 1995 * @return string|false Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure. 1996 * 1997 * @phpstan-return 'approved'|'spam'|'trash'|'unapproved'|false 1998 */ 1999 function wp_get_comment_status( $comment_id ) { 2000 $comment = get_comment( $comment_id ); 2001 if ( ! $comment ) { 2002 return false; 2003 } 2004 2005 $approved = $comment->comment_approved; 2006 2007 if ( null === $approved ) { 2008 return false; 2009 } elseif ( '1' === $approved ) { 2010 return 'approved'; 2011 } elseif ( '0' === $approved ) { 2012 return 'unapproved'; 2013 } elseif ( 'spam' === $approved ) { 2014 return 'spam'; 2015 } elseif ( 'trash' === $approved ) { 2016 return 'trash'; 2017 } else { 2018 return false; 2019 } 2020 } 2021 2022 /** 2023 * Calls hooks for when a comment status transition occurs. 2024 * 2025 * Calls hooks for comment status transitions. If the new comment status is not the same 2026 * as the previous comment status, then two hooks will be ran, the first is 2027 * {@see 'transition_comment_status'} with new status, old status, and comment data. 2028 * The next action called is {@see 'comment_$old_status_to_$new_status'}. It has 2029 * the comment data. 2030 * 2031 * The final action will run whether or not the comment statuses are the same. 2032 * The action is named {@see 'comment_$new_status_$comment->comment_type'}. 2033 * 2034 * @since 2.7.0 2035 * 2036 * @param string $new_status New comment status. 2037 * @param string $old_status Previous comment status. 2038 * @param WP_Comment $comment Comment object. 2039 */ 2040 function wp_transition_comment_status( $new_status, $old_status, $comment ) { 2041 /* 2042 * Translate raw statuses to human-readable formats for the hooks. 2043 * This is not a complete list of comment status, it's only the ones 2044 * that need to be renamed. 2045 */ 2046 $comment_statuses = array( 2047 0 => 'unapproved', 2048 'hold' => 'unapproved', // wp_set_comment_status() uses "hold". 2049 1 => 'approved', 2050 'approve' => 'approved', // wp_set_comment_status() uses "approve". 2051 ); 2052 if ( isset( $comment_statuses[ $new_status ] ) ) { 2053 $new_status = $comment_statuses[ $new_status ]; 2054 } 2055 if ( isset( $comment_statuses[ $old_status ] ) ) { 2056 $old_status = $comment_statuses[ $old_status ]; 2057 } 2058 2059 // Call the hooks. 2060 if ( $new_status !== $old_status ) { 2061 /** 2062 * Fires when the comment status is in transition. 2063 * 2064 * @since 2.7.0 2065 * 2066 * @param string $new_status The new comment status. 2067 * @param string $old_status The old comment status. 2068 * @param WP_Comment $comment Comment object. 2069 */ 2070 do_action( 'transition_comment_status', $new_status, $old_status, $comment ); 2071 2072 /** 2073 * Fires when the comment status is in transition from one specific status to another. 2074 * 2075 * The dynamic portions of the hook name, `$old_status`, and `$new_status`, 2076 * refer to the old and new comment statuses, respectively. 2077 * 2078 * Possible hook names include: 2079 * 2080 * - `comment_unapproved_to_approved` 2081 * - `comment_spam_to_approved` 2082 * - `comment_approved_to_unapproved` 2083 * - `comment_spam_to_unapproved` 2084 * - `comment_unapproved_to_spam` 2085 * - `comment_approved_to_spam` 2086 * 2087 * @since 2.7.0 2088 * 2089 * @param WP_Comment $comment Comment object. 2090 */ 2091 do_action( "comment_{$old_status}_to_{$new_status}", $comment ); 2092 } 2093 /** 2094 * Fires when the status of a specific comment type is in transition. 2095 * 2096 * The dynamic portions of the hook name, `$new_status`, and `$comment->comment_type`, 2097 * refer to the new comment status, and the type of comment, respectively. 2098 * 2099 * Typical comment types include 'comment', 'pingback', or 'trackback'. 2100 * 2101 * Possible hook names include: 2102 * 2103 * - `comment_approved_comment` 2104 * - `comment_approved_pingback` 2105 * - `comment_approved_trackback` 2106 * - `comment_unapproved_comment` 2107 * - `comment_unapproved_pingback` 2108 * - `comment_unapproved_trackback` 2109 * - `comment_spam_comment` 2110 * - `comment_spam_pingback` 2111 * - `comment_spam_trackback` 2112 * 2113 * @since 2.7.0 2114 * 2115 * @param string $comment_id The comment ID as a numeric string. 2116 * @param WP_Comment $comment Comment object. 2117 */ 2118 do_action( "comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment ); 2119 } 2120 2121 /** 2122 * Clears the lastcommentmodified cached value when a comment status is changed. 2123 * 2124 * Deletes the lastcommentmodified cache key when a comment enters or leaves 2125 * 'approved' status. 2126 * 2127 * @since 4.7.0 2128 * @access private 2129 * 2130 * @param string $new_status The new comment status. 2131 * @param string $old_status The old comment status. 2132 */ 2133 function _clear_modified_cache_on_transition_comment_status( $new_status, $old_status ) { 2134 if ( 'approved' === $new_status || 'approved' === $old_status ) { 2135 $data = array(); 2136 foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) { 2137 $data[] = "lastcommentmodified:$timezone"; 2138 } 2139 wp_cache_delete_multiple( $data, 'timeinfo' ); 2140 } 2141 } 2142 2143 /** 2144 * Gets current commenter's name, email, and URL. 2145 * 2146 * Expects cookies content to already be sanitized. User of this function might 2147 * wish to recheck the returned array for validity. 2148 * 2149 * @see sanitize_comment_cookies() Use to sanitize cookies 2150 * 2151 * @since 2.0.4 2152 * 2153 * @return array { 2154 * An array of current commenter variables. 2155 * 2156 * @type string $comment_author The name of the current commenter, or an empty string. 2157 * @type string $comment_author_email The email address of the current commenter, or an empty string. 2158 * @type string $comment_author_url The URL address of the current commenter, or an empty string. 2159 * } 2160 */ 2161 function wp_get_current_commenter() { 2162 // Cookies should already be sanitized. 2163 2164 $comment_author = ''; 2165 if ( isset( $_COOKIE[ 'comment_author_' . COOKIEHASH ] ) ) { 2166 $comment_author = $_COOKIE[ 'comment_author_' . COOKIEHASH ]; 2167 } 2168 2169 $comment_author_email = ''; 2170 if ( isset( $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] ) ) { 2171 $comment_author_email = $_COOKIE[ 'comment_author_email_' . COOKIEHASH ]; 2172 } 2173 2174 $comment_author_url = ''; 2175 if ( isset( $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] ) ) { 2176 $comment_author_url = $_COOKIE[ 'comment_author_url_' . COOKIEHASH ]; 2177 } 2178 2179 /** 2180 * Filters the current commenter's name, email, and URL. 2181 * 2182 * @since 3.1.0 2183 * 2184 * @param array $comment_author_data { 2185 * An array of current commenter variables. 2186 * 2187 * @type string $comment_author The name of the current commenter, or an empty string. 2188 * @type string $comment_author_email The email address of the current commenter, or an empty string. 2189 * @type string $comment_author_url The URL address of the current commenter, or an empty string. 2190 * } 2191 */ 2192 return apply_filters( 'wp_get_current_commenter', compact( 'comment_author', 'comment_author_email', 'comment_author_url' ) ); 2193 } 2194 2195 /** 2196 * Gets unapproved comment author's email. 2197 * 2198 * Used to allow the commenter to see their pending comment. 2199 * 2200 * @since 5.1.0 2201 * @since 5.7.0 The window within which the author email for an unapproved comment 2202 * can be retrieved was extended to 10 minutes. 2203 * 2204 * @return string The unapproved comment author's email (when supplied). 2205 */ 2206 function wp_get_unapproved_comment_author_email() { 2207 $commenter_email = ''; 2208 2209 if ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) { 2210 $comment_id = (int) $_GET['unapproved']; 2211 $comment = get_comment( $comment_id ); 2212 2213 if ( $comment && hash_equals( $_GET['moderation-hash'], wp_hash( $comment->comment_date_gmt ) ) ) { 2214 // The comment will only be viewable by the comment author for 10 minutes. 2215 $comment_preview_expires = strtotime( $comment->comment_date_gmt . '+10 minutes' ); 2216 2217 if ( time() < $comment_preview_expires ) { 2218 $commenter_email = $comment->comment_author_email; 2219 } 2220 } 2221 } 2222 2223 if ( ! $commenter_email ) { 2224 $commenter = wp_get_current_commenter(); 2225 $commenter_email = $commenter['comment_author_email']; 2226 } 2227 2228 return $commenter_email; 2229 } 2230 2231 /** 2232 * Inserts a comment into the database. 2233 * 2234 * @since 2.0.0 2235 * @since 4.4.0 Introduced the `$comment_meta` argument. 2236 * @since 5.5.0 Default value for `$comment_type` argument changed to `comment`. 2237 * 2238 * @global wpdb $wpdb WordPress database abstraction object. 2239 * 2240 * @param array $commentdata { 2241 * Array of arguments for inserting a new comment. 2242 * 2243 * @type string $comment_agent The HTTP user agent of the `$comment_author` when 2244 * the comment was submitted. Default empty. 2245 * @type int|string $comment_approved Whether the comment has been approved. Default 1. 2246 * @type string $comment_author The name of the author of the comment. Default empty. 2247 * @type string $comment_author_email The email address of the `$comment_author`. Default empty. 2248 * @type string $comment_author_IP The IP address of the `$comment_author`. Default empty. 2249 * @type string $comment_author_url The URL address of the `$comment_author`. Default empty. 2250 * @type string $comment_content The content of the comment. Default empty. 2251 * @type string $comment_date The date the comment was submitted. To set the date 2252 * manually, `$comment_date_gmt` must also be specified. 2253 * Default is the current time. 2254 * @type string $comment_date_gmt The date the comment was submitted in the GMT timezone. 2255 * Default is `$comment_date` in the site's GMT timezone. 2256 * @type int $comment_karma The karma of the comment. Default 0. 2257 * @type int $comment_parent ID of this comment's parent, if any. Default 0. 2258 * @type int $comment_post_ID ID of the post that relates to the comment, if any. 2259 * Default 0. 2260 * @type string $comment_type Comment type. Default 'comment'. 2261 * @type array $comment_meta Optional. Array of key/value pairs to be stored in commentmeta for the 2262 * new comment. 2263 * @type int $user_id ID of the user who submitted the comment. Default 0. 2264 * } 2265 * @return int|false The new comment's ID on success, false on failure. 2266 */ 2267 function wp_insert_comment( $commentdata ) { 2268 global $wpdb; 2269 2270 $data = wp_unslash( $commentdata ); 2271 2272 $comment_author = ! isset( $data['comment_author'] ) ? '' : $data['comment_author']; 2273 $comment_author_email = ! isset( $data['comment_author_email'] ) ? '' : $data['comment_author_email']; 2274 $comment_author_url = ! isset( $data['comment_author_url'] ) ? '' : $data['comment_author_url']; 2275 $comment_author_ip = ! isset( $data['comment_author_IP'] ) ? '' : $data['comment_author_IP']; 2276 2277 $comment_date = ! isset( $data['comment_date'] ) ? current_time( 'mysql' ) : $data['comment_date']; 2278 $comment_date_gmt = ! isset( $data['comment_date_gmt'] ) ? get_gmt_from_date( $comment_date ) : $data['comment_date_gmt']; 2279 2280 $comment_post_id = ! isset( $data['comment_post_ID'] ) ? 0 : $data['comment_post_ID']; 2281 $comment_content = ! isset( $data['comment_content'] ) ? '' : $data['comment_content']; 2282 $comment_karma = ! isset( $data['comment_karma'] ) ? 0 : $data['comment_karma']; 2283 $comment_approved = ! isset( $data['comment_approved'] ) ? 1 : $data['comment_approved']; 2284 $comment_agent = ! isset( $data['comment_agent'] ) ? '' : $data['comment_agent']; 2285 $comment_type = empty( $data['comment_type'] ) ? 'comment' : $data['comment_type']; 2286 $comment_parent = ! isset( $data['comment_parent'] ) ? 0 : $data['comment_parent']; 2287 2288 $user_id = ! isset( $data['user_id'] ) ? 0 : $data['user_id']; 2289 2290 $compacted = array( 2291 'comment_post_ID' => $comment_post_id, 2292 'comment_author_IP' => $comment_author_ip, 2293 ); 2294 2295 $compacted += compact( 2296 'comment_author', 2297 'comment_author_email', 2298 'comment_author_url', 2299 'comment_date', 2300 'comment_date_gmt', 2301 'comment_content', 2302 'comment_karma', 2303 'comment_approved', 2304 'comment_agent', 2305 'comment_type', 2306 'comment_parent', 2307 'user_id' 2308 ); 2309 2310 if ( ! $wpdb->insert( $wpdb->comments, $compacted ) ) { 2311 return false; 2312 } 2313 2314 $id = (int) $wpdb->insert_id; 2315 2316 if ( 1 === (int) $comment_approved ) { 2317 wp_update_comment_count( $comment_post_id ); 2318 2319 $data = array(); 2320 foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) { 2321 $data[] = "lastcommentmodified:$timezone"; 2322 } 2323 wp_cache_delete_multiple( $data, 'timeinfo' ); 2324 } 2325 2326 clean_comment_cache( $id ); 2327 2328 $comment = get_comment( $id ); 2329 2330 // If metadata is provided, store it. 2331 if ( isset( $commentdata['comment_meta'] ) && is_array( $commentdata['comment_meta'] ) ) { 2332 foreach ( $commentdata['comment_meta'] as $meta_key => $meta_value ) { 2333 add_comment_meta( $comment->comment_ID, $meta_key, $meta_value, true ); 2334 } 2335 } 2336 2337 /** 2338 * Fires immediately after a comment is inserted into the database. 2339 * 2340 * @since 2.8.0 2341 * 2342 * @param int $id The comment ID. 2343 * @param WP_Comment $comment Comment object. 2344 */ 2345 do_action( 'wp_insert_comment', $id, $comment ); 2346 2347 return $id; 2348 } 2349 2350 /** 2351 * Filters and sanitizes comment data. 2352 * 2353 * Sets the comment data 'filtered' field to true when finished. This can be 2354 * checked as to whether the comment should be filtered and to keep from 2355 * filtering the same comment more than once. 2356 * 2357 * @since 2.0.0 2358 * 2359 * @param array $commentdata Contains information on the comment. 2360 * @return array Parsed comment information. 2361 */ 2362 function wp_filter_comment( $commentdata ) { 2363 if ( isset( $commentdata['user_ID'] ) ) { 2364 /** 2365 * Filters the comment author's user ID before it is set. 2366 * 2367 * The first time this filter is evaluated, `user_ID` is checked 2368 * (for back-compat), followed by the standard `user_id` value. 2369 * 2370 * @since 1.5.0 2371 * 2372 * @param int $user_id The comment author's user ID. 2373 */ 2374 $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_ID'] ); 2375 } elseif ( isset( $commentdata['user_id'] ) ) { 2376 /** This filter is documented in wp-includes/comment.php */ 2377 $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_id'] ); 2378 } 2379 2380 /** 2381 * Filters the comment author's browser user agent before it is set. 2382 * 2383 * @since 1.5.0 2384 * 2385 * @param string $comment_agent The comment author's browser user agent. 2386 */ 2387 $commentdata['comment_agent'] = apply_filters( 'pre_comment_user_agent', ( $commentdata['comment_agent'] ?? '' ) ); 2388 /** This filter is documented in wp-includes/comment.php */ 2389 $commentdata['comment_author'] = apply_filters( 'pre_comment_author_name', $commentdata['comment_author'] ); 2390 /** 2391 * Filters the comment content before it is set. 2392 * 2393 * @since 1.5.0 2394 * 2395 * @param string $comment_content The comment content. 2396 */ 2397 $commentdata['comment_content'] = apply_filters( 'pre_comment_content', $commentdata['comment_content'] ); 2398 /** 2399 * Filters the comment author's IP address before it is set. 2400 * 2401 * @since 1.5.0 2402 * 2403 * @param string $comment_author_ip The comment author's IP address. 2404 */ 2405 $commentdata['comment_author_IP'] = apply_filters( 'pre_comment_user_ip', $commentdata['comment_author_IP'] ); 2406 /** This filter is documented in wp-includes/comment.php */ 2407 $commentdata['comment_author_url'] = apply_filters( 'pre_comment_author_url', $commentdata['comment_author_url'] ); 2408 /** This filter is documented in wp-includes/comment.php */ 2409 $commentdata['comment_author_email'] = apply_filters( 'pre_comment_author_email', $commentdata['comment_author_email'] ); 2410 2411 $commentdata['filtered'] = true; 2412 2413 return $commentdata; 2414 } 2415 2416 /** 2417 * Determines whether a comment should be blocked because of comment flood. 2418 * 2419 * @since 2.1.0 2420 * 2421 * @param bool $block Whether plugin has already blocked comment. 2422 * @param int $time_lastcomment Timestamp for last comment. 2423 * @param int $time_newcomment Timestamp for new comment. 2424 * @return bool Whether comment should be blocked. 2425 */ 2426 function wp_throttle_comment_flood( $block, $time_lastcomment, $time_newcomment ) { 2427 if ( $block ) { // A plugin has already blocked... we'll let that decision stand. 2428 return $block; 2429 } 2430 if ( ( $time_newcomment - $time_lastcomment ) < 15 ) { 2431 return true; 2432 } 2433 return false; 2434 } 2435 2436 /** 2437 * Adds a new comment to the database. 2438 * 2439 * Filters new comment to ensure that the fields are sanitized and valid before 2440 * inserting comment into database. Calls {@see 'comment_post'} action with comment ID 2441 * and whether comment is approved by WordPress. Also has {@see 'preprocess_comment'} 2442 * filter for processing the comment data before the function handles it. 2443 * 2444 * We use `REMOTE_ADDR` here directly. If you are behind a proxy, you should ensure 2445 * that it is properly set, such as in wp-config.php, for your environment. 2446 * 2447 * See {@link https://core.trac.wordpress.org/ticket/9235} 2448 * 2449 * @since 1.5.0 2450 * @since 4.3.0 Introduced the `comment_agent` and `comment_author_IP` arguments. 2451 * @since 4.7.0 The `$avoid_die` parameter was added, allowing the function 2452 * to return a WP_Error object instead of dying. 2453 * @since 5.5.0 The `$avoid_die` parameter was renamed to `$wp_error`. 2454 * @since 5.5.0 Introduced the `comment_type` argument. 2455 * 2456 * @see wp_insert_comment() 2457 * @global wpdb $wpdb WordPress database abstraction object. 2458 * 2459 * @param array $commentdata { 2460 * Comment data. 2461 * 2462 * @type string $comment_author The name of the comment author. 2463 * @type string $comment_author_email The comment author email address. 2464 * @type string $comment_author_url The comment author URL. 2465 * @type string $comment_content The content of the comment. 2466 * @type string $comment_date The date the comment was submitted. Default is the current time. 2467 * @type string $comment_date_gmt The date the comment was submitted in the GMT timezone. 2468 * Default is `$comment_date` in the GMT timezone. 2469 * @type string $comment_type Comment type. Default 'comment'. 2470 * @type int $comment_parent The ID of this comment's parent, if any. Default 0. 2471 * @type int $comment_post_ID The ID of the post that relates to the comment. 2472 * @type int $user_id The ID of the user who submitted the comment. Default 0. 2473 * @type int $user_ID Kept for backward-compatibility. Use `$user_id` instead. 2474 * @type string $comment_agent Comment author user agent. Default is the value of 'HTTP_USER_AGENT' 2475 * in the `$_SERVER` superglobal sent in the original request. 2476 * @type string $comment_author_IP Comment author IP address in IPv4 format. Default is the value of 2477 * 'REMOTE_ADDR' in the `$_SERVER` superglobal sent in the original request. 2478 * } 2479 * @param bool $wp_error Should errors be returned as WP_Error objects instead of 2480 * executing wp_die()? Default false. 2481 * @return int|false|WP_Error The ID of the comment on success, false or WP_Error on failure. 2482 */ 2483 function wp_new_comment( $commentdata, $wp_error = false ) { 2484 global $wpdb; 2485 2486 /* 2487 * Normalize `user_ID` to `user_id`, but pass the old key 2488 * to the `preprocess_comment` filter for backward compatibility. 2489 */ 2490 if ( isset( $commentdata['user_ID'] ) ) { 2491 $commentdata['user_ID'] = (int) $commentdata['user_ID']; 2492 $commentdata['user_id'] = $commentdata['user_ID']; 2493 } elseif ( isset( $commentdata['user_id'] ) ) { 2494 $commentdata['user_id'] = (int) $commentdata['user_id']; 2495 $commentdata['user_ID'] = $commentdata['user_id']; 2496 } 2497 2498 $prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0; 2499 2500 $commentdata['comment_author_IP'] ??= $_SERVER['REMOTE_ADDR']; 2501 $commentdata['comment_agent'] ??= $_SERVER['HTTP_USER_AGENT'] ?? ''; 2502 2503 /** 2504 * Filters a comment's data before it is sanitized and inserted into the database. 2505 * 2506 * @since 1.5.0 2507 * @since 5.6.0 Comment data includes the `comment_agent` and `comment_author_IP` values. 2508 * 2509 * @param array $commentdata Comment data. 2510 */ 2511 $commentdata = apply_filters( 'preprocess_comment', $commentdata ); 2512 2513 $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID']; 2514 2515 // Normalize `user_ID` to `user_id` again, after the filter. 2516 if ( isset( $commentdata['user_ID'] ) && $prefiltered_user_id !== (int) $commentdata['user_ID'] ) { 2517 $commentdata['user_ID'] = (int) $commentdata['user_ID']; 2518 $commentdata['user_id'] = $commentdata['user_ID']; 2519 } elseif ( isset( $commentdata['user_id'] ) ) { 2520 $commentdata['user_id'] = (int) $commentdata['user_id']; 2521 $commentdata['user_ID'] = $commentdata['user_id']; 2522 } 2523 2524 $commentdata['comment_parent'] = isset( $commentdata['comment_parent'] ) ? absint( $commentdata['comment_parent'] ) : 0; 2525 2526 $parent_status = ( $commentdata['comment_parent'] > 0 ) ? wp_get_comment_status( $commentdata['comment_parent'] ) : ''; 2527 2528 $commentdata['comment_parent'] = ( 'approved' === $parent_status || 'unapproved' === $parent_status ) ? $commentdata['comment_parent'] : 0; 2529 2530 $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '', $commentdata['comment_author_IP'] ); 2531 2532 $commentdata['comment_agent'] = substr( $commentdata['comment_agent'], 0, 254 ); 2533 2534 if ( empty( $commentdata['comment_date'] ) ) { 2535 $commentdata['comment_date'] = current_time( 'mysql' ); 2536 } 2537 2538 if ( empty( $commentdata['comment_date_gmt'] ) ) { 2539 $commentdata['comment_date_gmt'] = current_time( 'mysql', true ); 2540 } 2541 2542 if ( empty( $commentdata['comment_type'] ) ) { 2543 $commentdata['comment_type'] = 'comment'; 2544 } 2545 2546 $commentdata['comment_approved'] = wp_allow_comment( $commentdata, $wp_error ); 2547 2548 if ( is_wp_error( $commentdata['comment_approved'] ) ) { 2549 return $commentdata['comment_approved']; 2550 } 2551 2552 $commentdata = wp_filter_comment( $commentdata ); 2553 2554 if ( ! in_array( $commentdata['comment_approved'], array( 'trash', 'spam' ), true ) ) { 2555 // Validate the comment again after filters are applied to comment data. 2556 $commentdata['comment_approved'] = wp_check_comment_data( $commentdata ); 2557 } 2558 2559 if ( is_wp_error( $commentdata['comment_approved'] ) ) { 2560 return $commentdata['comment_approved']; 2561 } 2562 2563 $comment_id = wp_insert_comment( $commentdata ); 2564 2565 if ( ! $comment_id ) { 2566 $fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' ); 2567 2568 foreach ( $fields as $field ) { 2569 if ( isset( $commentdata[ $field ] ) ) { 2570 $commentdata[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $commentdata[ $field ] ); 2571 } 2572 } 2573 2574 $commentdata = wp_filter_comment( $commentdata ); 2575 2576 $commentdata['comment_approved'] = wp_allow_comment( $commentdata, $wp_error ); 2577 if ( is_wp_error( $commentdata['comment_approved'] ) ) { 2578 return $commentdata['comment_approved']; 2579 } 2580 2581 $comment_id = wp_insert_comment( $commentdata ); 2582 if ( ! $comment_id ) { 2583 return false; 2584 } 2585 } 2586 2587 /** 2588 * Fires immediately after a comment is inserted into the database. 2589 * 2590 * @since 1.2.0 2591 * @since 4.5.0 The `$commentdata` parameter was added. 2592 * 2593 * @param int $comment_id The comment ID. 2594 * @param int|string $comment_approved 1 if the comment is approved, 0 if not, 'spam' if spam. 2595 * @param array $commentdata Comment data. 2596 */ 2597 do_action( 'comment_post', $comment_id, $commentdata['comment_approved'], $commentdata ); 2598 2599 return $comment_id; 2600 } 2601 2602 /** 2603 * Sends a comment moderation notification to the comment moderator. 2604 * 2605 * @since 4.4.0 2606 * 2607 * @param int $comment_id ID of the comment. 2608 * @return bool True on success, false on failure. 2609 */ 2610 function wp_new_comment_notify_moderator( $comment_id ) { 2611 $comment = get_comment( $comment_id ); 2612 2613 // Only send notifications for pending comments. 2614 $maybe_notify = ( '0' === $comment->comment_approved ); 2615 2616 /** This filter is documented in wp-includes/pluggable.php */ 2617 $maybe_notify = apply_filters( 'notify_moderator', $maybe_notify, $comment_id ); 2618 2619 if ( ! $maybe_notify ) { 2620 return false; 2621 } 2622 2623 return wp_notify_moderator( $comment_id ); 2624 } 2625 2626 /** 2627 * Sends a notification of a new comment to the post author. 2628 * 2629 * Uses the {@see 'notify_post_author'} filter to determine whether the post author 2630 * should be notified when a new comment is added, overriding site setting. 2631 * 2632 * @since 4.4.0 2633 * @since 7.1.0 The comment approval status is now checked before the 2634 * {@see 'notify_post_author'} filter, and invalid comment IDs 2635 * return false without firing the filter. 2636 * 2637 * @param int $comment_id Comment ID. 2638 * @return bool True on success, false on failure. 2639 */ 2640 function wp_new_comment_notify_postauthor( $comment_id ) { 2641 $comment = get_comment( $comment_id ); 2642 if ( ! ( $comment instanceof WP_Comment ) ) { 2643 return false; 2644 } 2645 $comment_id = (int) $comment->comment_ID; 2646 $is_note = ( 'note' === $comment->comment_type ); 2647 2648 /* 2649 * Determine the default notification behavior. Notes are eligible regardless 2650 * of approval status, based on the 'wp_notes_notify' option. Other comments 2651 * are only eligible once approved, based on the 'comments_notify' option. 2652 */ 2653 if ( $is_note ) { 2654 $maybe_notify = (bool) get_option( 'wp_notes_notify', 1 ); 2655 } elseif ( '1' !== $comment->comment_approved ) { 2656 $maybe_notify = false; 2657 } else { 2658 $maybe_notify = (bool) get_option( 'comments_notify' ); 2659 } 2660 2661 /** 2662 * Filters whether to send the post author new comment and note notification emails, 2663 * overriding the site settings and defaults. By default, notifications are sent for 2664 * all notes and for approved comments. 2665 * 2666 * @since 4.4.0 2667 * @since 7.1.0 Comment approval status is checked before this filter, 2668 * and the filter no longer fires for invalid comment IDs. 2669 * 2670 * @param bool $maybe_notify Whether to notify the post author about the new comment. 2671 * @param int $comment_id The ID of the comment for the notification. 2672 */ 2673 $maybe_notify = apply_filters( 'notify_post_author', $maybe_notify, $comment_id ); 2674 2675 /* 2676 * wp_notify_postauthor() checks if notifying the author of their own comment. 2677 * By default, it won't, but filters can override this. 2678 */ 2679 if ( ! $maybe_notify ) { 2680 return false; 2681 } 2682 2683 return wp_notify_postauthor( $comment_id ); 2684 } 2685 2686 /** 2687 * Send a notification to the post author when a new note is added via the REST API. 2688 * 2689 * @since 6.9.0 2690 * 2691 * @param WP_Comment $comment The comment object. 2692 */ 2693 function wp_new_comment_via_rest_notify_postauthor( $comment ) { 2694 if ( $comment instanceof WP_Comment && 'note' === $comment->comment_type ) { 2695 wp_new_comment_notify_postauthor( (int) $comment->comment_ID ); 2696 } 2697 } 2698 2699 /** 2700 * Extracts the mentioned user IDs from note content. 2701 * 2702 * Mentions are stored as chips carrying the `wp-note-mention` class plus a 2703 * `user-N` class token holding the mentioned user's ID: 2704 * `<span class="wp-note-mention user-N">@Name</span>`. Only elements that 2705 * carry both classes are treated as mentions. 2706 * 2707 * @since 7.1.0 2708 * 2709 * @param string $content Note (comment) content, as stored. 2710 * @return int[] Unique, positive mentioned user IDs. 2711 * @phpstan-return list<positive-int> 2712 */ 2713 function wp_get_note_mentioned_user_ids( string $content ): array { 2714 if ( ! str_contains( $content, 'wp-note-mention' ) ) { 2715 return array(); 2716 } 2717 2718 $user_ids = array(); 2719 $processor = new WP_HTML_Tag_Processor( $content ); 2720 while ( 2721 $processor->next_tag( 2722 array( 2723 'tag_name' => 'SPAN', 2724 'class_name' => 'wp-note-mention', 2725 ) 2726 ) 2727 ) { 2728 foreach ( $processor->class_list() as $class_name ) { 2729 if ( 1 === preg_match( '/^user-(\d+)$/', $class_name, $matches ) ) { 2730 $user_id = (int) $matches[1]; 2731 if ( $user_id > 0 ) { 2732 $user_ids[] = $user_id; 2733 } 2734 break; 2735 } 2736 } 2737 } 2738 2739 return array_values( array_unique( $user_ids, SORT_NUMERIC ) ); 2740 } 2741 2742 /** 2743 * Notifies mentioned users about a new note. 2744 * 2745 * Runs on {@see 'rest_insert_comment'} alongside the post author notification. 2746 * The recipient set is the users mentioned in this note, minus the note's own 2747 * author (a user is not notified about their own note) and the post author, 2748 * who is already notified about every note by 2749 * {@see wp_new_comment_via_rest_notify_postauthor()}. 2750 * 2751 * Only fires when a note is created, not when an existing one is edited, so 2752 * correcting a note does not re-notify everyone who already received it. 2753 * 2754 * @since 7.1.0 2755 * 2756 * @param WP_Comment|null $comment The note that was just inserted. (May only be null as an edge case.) 2757 * @param mixed $request The REST request. Unused. 2758 * @param bool $creating Whether this is a create (true) or update (false). 2759 */ 2760 function wp_notify_note_mentions( ?WP_Comment $comment, $request = null, bool $creating = true ): void { 2761 if ( ! $creating || ! $comment ) { 2762 return; 2763 } 2764 2765 if ( 'note' !== $comment->comment_type ) { 2766 return; 2767 } 2768 2769 // Share the single user-facing notes notification preference. 2770 if ( ! get_option( 'wp_notes_notify', 1 ) ) { 2771 return; 2772 } 2773 2774 $mentioned = wp_get_note_mentioned_user_ids( $comment->comment_content ); 2775 2776 $author_id = (int) $comment->user_id; 2777 $comment_post_id = (int) $comment->comment_post_ID; 2778 $post = $comment_post_id ? get_post( $comment_post_id ) : null; 2779 $post_author_id = $post ? (int) $post->post_author : 0; 2780 2781 /* 2782 * The recipient set is bounded and small (one note's mentions), so emails 2783 * are sent synchronously here. If notification volume ever warrants it, 2784 * the right fix is to offload delivery to a background queue rather than 2785 * throttle within the request. 2786 */ 2787 foreach ( $mentioned as $user_id ) { 2788 // Never notify the author about their own note. 2789 if ( $user_id === $author_id ) { 2790 continue; 2791 } 2792 2793 // The post author is already notified of every note. 2794 if ( $user_id === $post_author_id ) { 2795 continue; 2796 } 2797 2798 $user = get_userdata( $user_id ); 2799 if ( ! $user || empty( $user->user_email ) ) { 2800 continue; 2801 } 2802 2803 /* 2804 * Only notify users who can actually read the note. Notes are 2805 * internal: WP_REST_Comments_Controller::check_read_permission() 2806 * only exposes a note to its author or to users who can edit it, so 2807 * the email audience is held to the same bar. A plain read_post 2808 * check would leak note content to, for example, subscribers on a 2809 * public post, who cannot see the note in the editor. 2810 */ 2811 if ( ! user_can( $user_id, 'edit_comment', $comment->comment_ID ) ) { 2812 continue; 2813 } 2814 2815 wp_send_note_notification( $user, $comment, $post ); 2816 } 2817 } 2818 2819 /** 2820 * Sends a single note mention notification email. 2821 * 2822 * The email is composed in the recipient's locale, matching how other 2823 * user-directed notifications are composed, and links to the post editor the 2824 * same way the post author's note notification does. 2825 * 2826 * @since 7.1.0 2827 * 2828 * @param WP_User $user The recipient. 2829 * @param WP_Comment $comment The note that triggered the notification. 2830 * @param WP_Post|null $post The post the note belongs to. 2831 * @return bool Whether the email was accepted for delivery by {@see wp_mail()}. 2832 */ 2833 function wp_send_note_notification( WP_User $user, WP_Comment $comment, ?WP_Post $post ): bool { 2834 $switched_locale = switch_to_user_locale( $user->ID ); 2835 2836 /* 2837 * The site title and the post title are escaped on the way into the database, 2838 * and note content is stored as HTML. Both are reversed once here for the 2839 * plain text arena of emails. Decoding a second time would go too far and 2840 * resolve entities the author meant to be read literally. 2841 */ 2842 $blogname = wp_specialchars_decode( get_bloginfo( 'name', 'display' ), ENT_QUOTES ); 2843 $post_title = $post ? wp_specialchars_decode( get_the_title( $post ), ENT_QUOTES ) : ''; 2844 $author_name = $comment->comment_author ? $comment->comment_author : __( 'Someone' ); 2845 $content = wp_specialchars_decode( wp_strip_all_tags( $comment->comment_content ) ); 2846 2847 /* 2848 * The rest of the message is composed for the recipient, and so is the editor 2849 * link: get_edit_post_link() answers for whoever is current, which here is the 2850 * note's author over REST and nobody at all under WP-Cron. 2851 */ 2852 $edit_link = ''; 2853 if ( $post ) { 2854 $previous_user_id = get_current_user_id(); 2855 wp_set_current_user( $user->ID ); 2856 $edit_link = (string) get_edit_post_link( $post->ID, 'url' ); 2857 wp_set_current_user( $previous_user_id ); 2858 } 2859 2860 /* translators: 1: Note author's name, 2: Post title. */ 2861 $message = sprintf( __( '%1$s mentioned you in a note on "%2$s".' ), $author_name, $post_title ); 2862 /* translators: Note mention notification email subject. 1: Site title, 2: Post title. */ 2863 $subject = sprintf( __( '[%1$s] You were mentioned in a note on "%2$s"' ), $blogname, $post_title ); 2864 2865 $lines = array( $message, '' ); 2866 if ( '' !== $content ) { 2867 $lines[] = $content; 2868 } 2869 if ( $edit_link ) { 2870 $lines[] = ''; 2871 $lines[] = __( 'Edit This' ) . ': ' . $edit_link; 2872 } 2873 2874 // Declared explicitly so a filtered default cannot turn the message into HTML. 2875 $headers = 'Content-Type: text/plain; charset="' . get_option( 'blog_charset' ) . '"'; 2876 2877 $sent = wp_mail( $user->user_email, $subject, implode( "\n", $lines ), $headers ); 2878 2879 if ( $switched_locale ) { 2880 restore_previous_locale(); 2881 } 2882 2883 return $sent; 2884 } 2885 2886 /** 2887 * Sets the status of a comment. 2888 * 2889 * The {@see 'wp_set_comment_status'} action is called after the comment is handled. 2890 * If the comment status is not in the list, then false is returned, even when `$wp_error` is true. 2891 * 2892 * @since 1.0.0 2893 * 2894 * @global wpdb $wpdb WordPress database abstraction object. 2895 * 2896 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object. 2897 * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'. 2898 * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default false. 2899 * @return bool|WP_Error True on success, false or WP_Error on failure. False for an invalid 2900 * `$comment_status` regardless of `$wp_error`. 2901 * 2902 * @phpstan-return ( 2903 * $wp_error is false 2904 * ? bool 2905 * : ( $comment_status is 'hold'|'0'|'approve'|'1'|'spam'|'trash' ? true|WP_Error : bool|WP_Error ) 2906 * ) 2907 */ 2908 function wp_set_comment_status( $comment_id, $comment_status, $wp_error = false ) { 2909 global $wpdb; 2910 2911 switch ( $comment_status ) { 2912 case 'hold': 2913 case '0': 2914 $status = '0'; 2915 break; 2916 case 'approve': 2917 case '1': 2918 $status = '1'; 2919 add_action( 'wp_set_comment_status', 'wp_new_comment_notify_postauthor' ); 2920 break; 2921 case 'spam': 2922 $status = 'spam'; 2923 break; 2924 case 'trash': 2925 $status = 'trash'; 2926 break; 2927 default: 2928 return false; 2929 } 2930 2931 $comment_old = clone get_comment( $comment_id ); 2932 2933 if ( ! $wpdb->update( $wpdb->comments, array( 'comment_approved' => $status ), array( 'comment_ID' => $comment_old->comment_ID ) ) ) { 2934 if ( $wp_error ) { 2935 return new WP_Error( 'db_update_error', __( 'Could not update comment status.' ), $wpdb->last_error ); 2936 } else { 2937 return false; 2938 } 2939 } 2940 2941 clean_comment_cache( $comment_old->comment_ID ); 2942 2943 $comment = get_comment( $comment_old->comment_ID ); 2944 2945 /** 2946 * Fires immediately after transitioning a comment's status from one to another in the database 2947 * and removing the comment from the object cache, but prior to all status transition hooks. 2948 * 2949 * @since 1.5.0 2950 * 2951 * @param string $comment_id Comment ID as a numeric string. 2952 * @param string $comment_status Current comment status. Possible values include 2953 * 'hold', '0', 'approve', '1', 'spam', and 'trash'. 2954 */ 2955 do_action( 'wp_set_comment_status', $comment->comment_ID, $comment_status ); 2956 2957 wp_transition_comment_status( $comment_status, $comment_old->comment_approved, $comment ); 2958 2959 wp_update_comment_count( $comment->comment_post_ID ); 2960 2961 return true; 2962 } 2963 2964 /** 2965 * Updates an existing comment in the database. 2966 * 2967 * Filters the comment and makes sure certain fields are valid before updating. 2968 * 2969 * @since 2.0.0 2970 * @since 4.9.0 Add updating comment meta during comment update. 2971 * @since 5.5.0 The `$wp_error` parameter was added. 2972 * @since 5.5.0 The return values for an invalid comment or post ID 2973 * were changed to false instead of 0. 2974 * 2975 * @global wpdb $wpdb WordPress database abstraction object. 2976 * 2977 * @param array $commentarr Contains information on the comment. 2978 * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false. 2979 * @return int|false|WP_Error The value 1 if the comment was updated, 0 if not updated. 2980 * False or a WP_Error object on failure. 2981 * 2982 * @phpstan-return ( $wp_error is false ? int|false : int|WP_Error ) 2983 */ 2984 function wp_update_comment( $commentarr, $wp_error = false ) { 2985 global $wpdb; 2986 2987 // First, get all of the original fields. 2988 $comment = get_comment( $commentarr['comment_ID'], ARRAY_A ); 2989 2990 if ( empty( $comment ) ) { 2991 if ( $wp_error ) { 2992 return new WP_Error( 'invalid_comment_id', __( 'Invalid comment ID.' ) ); 2993 } else { 2994 return false; 2995 } 2996 } 2997 2998 // Make sure that the comment post ID is valid (if specified). 2999 if ( ! empty( $commentarr['comment_post_ID'] ) && ! get_post( $commentarr['comment_post_ID'] ) ) { 3000 if ( $wp_error ) { 3001 return new WP_Error( 'invalid_post_id', __( 'Invalid post ID.' ) ); 3002 } else { 3003 return false; 3004 } 3005 } 3006 3007 $filter_comment = false; 3008 if ( ! has_filter( 'pre_comment_content', 'wp_filter_kses' ) ) { 3009 $filter_comment = ! user_can( $comment['user_id'] ?? 0, 'unfiltered_html' ); 3010 } 3011 3012 if ( $filter_comment ) { 3013 add_filter( 'pre_comment_content', 'wp_filter_kses' ); 3014 } 3015 3016 // Escape data pulled from DB. 3017 $comment = wp_slash( $comment ); 3018 3019 $old_status = $comment['comment_approved']; 3020 3021 // Merge old and new fields with new fields overwriting old ones. 3022 $commentarr = array_merge( $comment, $commentarr ); 3023 3024 $commentarr = wp_filter_comment( $commentarr ); 3025 3026 if ( $filter_comment ) { 3027 remove_filter( 'pre_comment_content', 'wp_filter_kses' ); 3028 } 3029 3030 // Now extract the merged array. 3031 $data = wp_unslash( $commentarr ); 3032 3033 /** 3034 * Filters the comment content before it is updated in the database. 3035 * 3036 * @since 1.5.0 3037 * 3038 * @param string $comment_content The comment data. 3039 */ 3040 $data['comment_content'] = apply_filters( 'comment_save_pre', $data['comment_content'] ); 3041 3042 $data['comment_date_gmt'] = get_gmt_from_date( $data['comment_date'] ); 3043 3044 if ( ! isset( $data['comment_approved'] ) ) { 3045 $data['comment_approved'] = 1; 3046 } elseif ( 'hold' === $data['comment_approved'] ) { 3047 $data['comment_approved'] = 0; 3048 } elseif ( 'approve' === $data['comment_approved'] ) { 3049 $data['comment_approved'] = 1; 3050 } 3051 3052 $comment_id = $data['comment_ID']; 3053 $comment_post_id = $data['comment_post_ID']; 3054 3055 /** 3056 * Filters the comment data immediately before it is updated in the database. 3057 * 3058 * Note: data being passed to the filter is already unslashed. 3059 * 3060 * @since 4.7.0 3061 * @since 5.5.0 Returning a WP_Error value from the filter will short-circuit comment update 3062 * and allow skipping further processing. 3063 * 3064 * @param array|WP_Error $data The new, processed comment data, or WP_Error. 3065 * @param array $comment The old, unslashed comment data. 3066 * @param array $commentarr The new, raw comment data. 3067 */ 3068 $data = apply_filters( 'wp_update_comment_data', $data, $comment, $commentarr ); 3069 3070 // Do not continue on failure. 3071 if ( is_wp_error( $data ) ) { 3072 if ( $wp_error ) { 3073 return $data; 3074 } else { 3075 return false; 3076 } 3077 } 3078 3079 $keys = array( 3080 'comment_post_ID', 3081 'comment_author', 3082 'comment_author_email', 3083 'comment_author_url', 3084 'comment_author_IP', 3085 'comment_date', 3086 'comment_date_gmt', 3087 'comment_content', 3088 'comment_karma', 3089 'comment_approved', 3090 'comment_agent', 3091 'comment_type', 3092 'comment_parent', 3093 'user_id', 3094 ); 3095 3096 $data = wp_array_slice_assoc( $data, $keys ); 3097 3098 $result = $wpdb->update( $wpdb->comments, $data, array( 'comment_ID' => $comment_id ) ); 3099 3100 if ( false === $result ) { 3101 if ( $wp_error ) { 3102 return new WP_Error( 'db_update_error', __( 'Could not update comment in the database.' ), $wpdb->last_error ); 3103 } else { 3104 return false; 3105 } 3106 } 3107 3108 // If metadata is provided, store it. 3109 if ( isset( $commentarr['comment_meta'] ) && is_array( $commentarr['comment_meta'] ) ) { 3110 foreach ( $commentarr['comment_meta'] as $meta_key => $meta_value ) { 3111 update_comment_meta( $comment_id, $meta_key, $meta_value ); 3112 } 3113 } 3114 3115 clean_comment_cache( $comment_id ); 3116 wp_update_comment_count( $comment_post_id ); 3117 3118 /** 3119 * Fires immediately after a comment is updated in the database. 3120 * 3121 * The hook also fires immediately before comment status transition hooks are fired. 3122 * 3123 * @since 1.2.0 3124 * @since 4.6.0 Added the `$data` parameter. 3125 * 3126 * @param int $comment_id The comment ID. 3127 * @param array $data Comment data. 3128 */ 3129 do_action( 'edit_comment', $comment_id, $data ); 3130 3131 $comment = get_comment( $comment_id ); 3132 3133 wp_transition_comment_status( $comment->comment_approved, $old_status, $comment ); 3134 3135 return $result; 3136 } 3137 3138 /** 3139 * Determines whether to defer comment counting. 3140 * 3141 * When setting $defer to true, all post comment counts will not be updated 3142 * until $defer is set to false. When $defer is set to false, then all 3143 * previously deferred updated post comment counts will then be automatically 3144 * updated without having to call wp_update_comment_count() after. 3145 * 3146 * @since 2.5.0 3147 * 3148 * @param bool $defer 3149 * @return bool Whether comment counting is deferred. 3150 */ 3151 function wp_defer_comment_counting( $defer = null ) { 3152 static $_defer = false; 3153 3154 if ( is_bool( $defer ) ) { 3155 $_defer = $defer; 3156 // Flush any deferred counts. 3157 if ( ! $defer ) { 3158 wp_update_comment_count( null, true ); 3159 } 3160 } 3161 3162 return $_defer; 3163 } 3164 3165 /** 3166 * Updates the comment count for post(s). 3167 * 3168 * When $do_deferred is false (is by default) and the comments have been set to 3169 * be deferred, the post_id will be added to a queue, which will be updated at a 3170 * later date and only updated once per post ID. 3171 * 3172 * If the comments have not be set up to be deferred, then the post will be 3173 * updated. When $do_deferred is set to true, then all previous deferred post 3174 * IDs will be updated along with the current $post_id. 3175 * 3176 * @since 2.1.0 3177 * 3178 * @see wp_update_comment_count_now() For what could cause a false return value 3179 * 3180 * @param int|null $post_id Post ID. 3181 * @param bool $do_deferred Optional. Whether to process previously deferred 3182 * post comment counts. Default false. 3183 * @return bool|null True on success, false on failure or if post with ID does 3184 * not exist. 3185 */ 3186 function wp_update_comment_count( $post_id, $do_deferred = false ) { 3187 static $_deferred = array(); 3188 3189 if ( empty( $post_id ) && ! $do_deferred ) { 3190 return false; 3191 } 3192 3193 if ( $do_deferred ) { 3194 $_deferred = array_unique( $_deferred ); 3195 foreach ( $_deferred as $i => $_post_id ) { 3196 wp_update_comment_count_now( $_post_id ); 3197 unset( $_deferred[ $i ] ); 3198 /** @todo Move this outside of the foreach and reset $_deferred to an array instead */ 3199 } 3200 } 3201 3202 if ( wp_defer_comment_counting() ) { 3203 $_deferred[] = $post_id; 3204 return true; 3205 } elseif ( $post_id ) { 3206 return wp_update_comment_count_now( $post_id ); 3207 } 3208 return null; 3209 } 3210 3211 /** 3212 * Updates the comment count for the post. 3213 * 3214 * @since 2.5.0 3215 * 3216 * @global wpdb $wpdb WordPress database abstraction object. 3217 * 3218 * @param int $post_id Post ID 3219 * @return bool True on success, false if the post does not exist. 3220 */ 3221 function wp_update_comment_count_now( $post_id ) { 3222 global $wpdb; 3223 3224 $post_id = (int) $post_id; 3225 3226 if ( ! $post_id ) { 3227 return false; 3228 } 3229 3230 wp_cache_delete( 'comments-0', 'counts' ); 3231 wp_cache_delete( "comments-{$post_id}", 'counts' ); 3232 3233 $post = get_post( $post_id ); 3234 3235 if ( ! $post ) { 3236 return false; 3237 } 3238 3239 $old = (int) $post->comment_count; 3240 3241 /** 3242 * Filters a post's comment count before it is updated in the database. 3243 * 3244 * @since 4.5.0 3245 * 3246 * @param int|null $new The new comment count. Default null. 3247 * @param int $old The old comment count. 3248 * @param int $post_id Post ID. 3249 */ 3250 $new = apply_filters( 'pre_wp_update_comment_count_now', null, $old, $post_id ); 3251 3252 if ( is_null( $new ) ) { 3253 $new = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1' AND comment_type NOT IN ( 'note', 'reaction' )", $post_id ) ); 3254 } else { 3255 $new = (int) $new; 3256 } 3257 3258 $wpdb->update( $wpdb->posts, array( 'comment_count' => $new ), array( 'ID' => $post_id ) ); 3259 3260 clean_post_cache( $post ); 3261 3262 /** 3263 * Fires immediately after a post's comment count is updated in the database. 3264 * 3265 * @since 2.3.0 3266 * 3267 * @param int $post_id Post ID. 3268 * @param int $new The new comment count. 3269 * @param int $old The old comment count. 3270 */ 3271 do_action( 'wp_update_comment_count', $post_id, $new, $old ); 3272 3273 /** This action is documented in wp-includes/post.php */ 3274 do_action( "edit_post_{$post->post_type}", $post_id, $post ); 3275 3276 /** This action is documented in wp-includes/post.php */ 3277 do_action( 'edit_post', $post_id, $post ); 3278 3279 return true; 3280 } 3281 3282 // 3283 // Ping and trackback functions. 3284 // 3285 3286 /** 3287 * Finds a pingback server URI based on the given URL. 3288 * 3289 * Checks the HTML for the rel="pingback" link and X-Pingback headers. It does 3290 * a check for the X-Pingback headers first and returns that, if available. 3291 * The check for the rel="pingback" has more overhead than just the header. 3292 * 3293 * @since 1.5.0 3294 * 3295 * @param string $url URL to ping. 3296 * @param string $deprecated Not Used. 3297 * @return string|false String containing URI on success, false on failure. 3298 * 3299 * @phpstan-param '' $deprecated 3300 */ 3301 function discover_pingback_server_uri( $url, $deprecated = '' ) { 3302 if ( ! empty( $deprecated ) ) { 3303 _deprecated_argument( __FUNCTION__, '2.7.0' ); 3304 } 3305 3306 $pingback_str_dquote = 'rel="pingback"'; 3307 $pingback_str_squote = 'rel=\'pingback\''; 3308 3309 /** @todo Should use Filter Extension or custom preg_match instead. */ 3310 $parsed_url = parse_url( $url ); 3311 3312 if ( ! isset( $parsed_url['host'] ) ) { // Not a URL. This should never happen. 3313 return false; 3314 } 3315 3316 // Do not search for a pingback server on our own uploads. 3317 $uploads_dir = wp_get_upload_dir(); 3318 if ( str_starts_with( $url, $uploads_dir['baseurl'] ) ) { 3319 return false; 3320 } 3321 3322 $response = wp_safe_remote_head( 3323 $url, 3324 array( 3325 'timeout' => 2, 3326 'httpversion' => '1.0', 3327 ) 3328 ); 3329 3330 if ( is_wp_error( $response ) ) { 3331 return false; 3332 } 3333 3334 if ( wp_remote_retrieve_header( $response, 'X-Pingback' ) ) { 3335 return wp_remote_retrieve_header( $response, 'X-Pingback' ); 3336 } 3337 3338 // Not an (x)html, sgml, or xml page, no use going further. 3339 if ( preg_match( '#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'Content-Type' ) ) ) { 3340 return false; 3341 } 3342 3343 // Now do a GET since we're going to look in the HTML headers (and we're sure it's not a binary file). 3344 $response = wp_safe_remote_get( 3345 $url, 3346 array( 3347 'timeout' => 2, 3348 'httpversion' => '1.0', 3349 ) 3350 ); 3351 3352 if ( is_wp_error( $response ) ) { 3353 return false; 3354 } 3355 3356 $contents = wp_remote_retrieve_body( $response ); 3357 3358 $pingback_link_offset_dquote = strpos( $contents, $pingback_str_dquote ); 3359 $pingback_link_offset_squote = strpos( $contents, $pingback_str_squote ); 3360 3361 if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) { 3362 $quote = ( $pingback_link_offset_dquote ) ? '"' : '\''; 3363 $pingback_link_offset = ( '"' === $quote ) ? $pingback_link_offset_dquote : $pingback_link_offset_squote; 3364 $pingback_href_pos = strpos( $contents, 'href=', $pingback_link_offset ); 3365 $pingback_href_start = $pingback_href_pos + 6; 3366 $pingback_href_end = strpos( $contents, $quote, $pingback_href_start ); 3367 $pingback_server_url_len = $pingback_href_end - $pingback_href_start; 3368 $pingback_server_url = substr( $contents, $pingback_href_start, $pingback_server_url_len ); 3369 3370 // We may find rel="pingback" but an incomplete pingback URL. 3371 if ( $pingback_server_url_len > 0 ) { // We got it! 3372 return $pingback_server_url; 3373 } 3374 } 3375 3376 return false; 3377 } 3378 3379 /** 3380 * Performs all pingbacks, enclosures, trackbacks, and sends to pingback services. 3381 * 3382 * @since 2.1.0 3383 * @since 5.6.0 Introduced `do_all_pings` action hook for individual services. 3384 */ 3385 function do_all_pings() { 3386 /** 3387 * Fires immediately after the `do_pings` event to hook services individually. 3388 * 3389 * @since 5.6.0 3390 */ 3391 do_action( 'do_all_pings' ); 3392 } 3393 3394 /** 3395 * Performs all pingbacks. 3396 * 3397 * @since 5.6.0 3398 */ 3399 function do_all_pingbacks() { 3400 $pings = get_posts( 3401 array( 3402 'post_type' => get_post_types(), 3403 'suppress_filters' => false, 3404 'nopaging' => true, 3405 'meta_key' => '_pingme', 3406 'fields' => 'ids', 3407 ) 3408 ); 3409 3410 foreach ( $pings as $ping ) { 3411 delete_post_meta( $ping, '_pingme' ); 3412 pingback( null, $ping ); 3413 } 3414 } 3415 3416 /** 3417 * Performs all enclosures. 3418 * 3419 * @since 5.6.0 3420 */ 3421 function do_all_enclosures() { 3422 $enclosures = get_posts( 3423 array( 3424 'post_type' => get_post_types(), 3425 'suppress_filters' => false, 3426 'nopaging' => true, 3427 'meta_key' => '_encloseme', 3428 'fields' => 'ids', 3429 ) 3430 ); 3431 3432 foreach ( $enclosures as $enclosure ) { 3433 delete_post_meta( $enclosure, '_encloseme' ); 3434 do_enclose( null, $enclosure ); 3435 } 3436 } 3437 3438 /** 3439 * Performs all trackbacks. 3440 * 3441 * @since 5.6.0 3442 */ 3443 function do_all_trackbacks() { 3444 $trackbacks = get_posts( 3445 array( 3446 'post_type' => get_post_types(), 3447 'suppress_filters' => false, 3448 'nopaging' => true, 3449 'meta_key' => '_trackbackme', 3450 'fields' => 'ids', 3451 ) 3452 ); 3453 3454 foreach ( $trackbacks as $trackback ) { 3455 delete_post_meta( $trackback, '_trackbackme' ); 3456 do_trackbacks( $trackback ); 3457 } 3458 } 3459 3460 /** 3461 * Performs trackbacks. 3462 * 3463 * @since 1.5.0 3464 * @since 4.7.0 `$post` can be a WP_Post object. 3465 * 3466 * @global wpdb $wpdb WordPress database abstraction object. 3467 * 3468 * @param int|WP_Post $post Post ID or object to do trackbacks on. 3469 * @return void|false Returns false on failure. 3470 */ 3471 function do_trackbacks( $post ) { 3472 global $wpdb; 3473 3474 $post = get_post( $post ); 3475 3476 if ( ! $post ) { 3477 return false; 3478 } 3479 3480 $to_ping = get_to_ping( $post ); 3481 $pinged = get_pung( $post ); 3482 3483 if ( empty( $to_ping ) ) { 3484 $wpdb->update( $wpdb->posts, array( 'to_ping' => '' ), array( 'ID' => $post->ID ) ); 3485 return; 3486 } 3487 3488 if ( empty( $post->post_excerpt ) ) { 3489 /** This filter is documented in wp-includes/post-template.php */ 3490 $excerpt = apply_filters( 'the_content', $post->post_content ); 3491 } else { 3492 /** This filter is documented in wp-includes/post-template.php */ 3493 $excerpt = apply_filters( 'the_excerpt', $post->post_excerpt ); 3494 } 3495 3496 $excerpt = str_replace( ']]>', ']]>', $excerpt ); 3497 $excerpt = wp_html_excerpt( $excerpt, 252, '…' ); 3498 3499 /** This filter is documented in wp-includes/post-template.php */ 3500 $post_title = apply_filters( 'the_title', $post->post_title, $post->ID ); 3501 $post_title = strip_tags( $post_title ); 3502 3503 foreach ( (array) $to_ping as $tb_ping ) { 3504 $tb_ping = trim( $tb_ping ); 3505 if ( ! in_array( $tb_ping, $pinged, true ) ) { 3506 trackback( $tb_ping, $post_title, $excerpt, $post->ID ); 3507 $pinged[] = $tb_ping; 3508 } else { 3509 $wpdb->query( 3510 $wpdb->prepare( 3511 "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", 3512 $tb_ping, 3513 $post->ID 3514 ) 3515 ); 3516 } 3517 } 3518 } 3519 3520 /** 3521 * Sends pings to all of the ping site services. 3522 * 3523 * @since 1.2.0 3524 * 3525 * @param int $post_id Post ID. 3526 * @return int Same post ID as provided. 3527 */ 3528 function generic_ping( $post_id = 0 ) { 3529 $services = get_option( 'ping_sites' ); 3530 3531 $services = explode( "\n", $services ); 3532 foreach ( (array) $services as $service ) { 3533 $service = trim( $service ); 3534 if ( '' !== $service ) { 3535 weblog_ping( $service ); 3536 } 3537 } 3538 3539 return $post_id; 3540 } 3541 3542 /** 3543 * Determines whether pings should be disabled for the current environment. 3544 * 3545 * By default, all pings (outgoing pingbacks, trackbacks, and ping service 3546 * notifications, as well as incoming pingbacks and trackbacks) are disabled 3547 * for non-production environments ('local', 'development', 'staging'). 3548 * 3549 * @since 7.1.0 3550 * 3551 * @return bool True if pings should be disabled, false otherwise. 3552 */ 3553 function wp_should_disable_pings_for_environment() { 3554 $environment_type = wp_get_environment_type(); 3555 $should_disable = 'production' !== $environment_type; 3556 3557 /** 3558 * Filters whether pings should be disabled for the current environment. 3559 * 3560 * Returning false re-enables pings in non-production environments. 3561 * Returning true disables pings even in production. 3562 * 3563 * @since 7.1.0 3564 * 3565 * @param bool $should_disable Whether pings should be disabled. Default true 3566 * for non-production environments, false for production. 3567 * @param string $environment_type The current environment type as returned by 3568 * wp_get_environment_type(). 3569 */ 3570 return apply_filters( 'wp_should_disable_pings_for_environment', $should_disable, $environment_type ); 3571 } 3572 3573 /** 3574 * Removes outgoing ping callbacks in non-production environments. 3575 * 3576 * Hooked to `do_all_pings` at priority 1 so it runs before the default 3577 * priority 10 callbacks. Does not remove `do_all_enclosures`. 3578 * 3579 * @since 7.1.0 3580 */ 3581 function wp_maybe_disable_outgoing_pings_for_environment() { 3582 if ( wp_should_disable_pings_for_environment() ) { 3583 remove_action( 'do_all_pings', 'do_all_pingbacks' ); 3584 remove_action( 'do_all_pings', 'do_all_trackbacks' ); 3585 remove_action( 'do_all_pings', 'generic_ping' ); 3586 } 3587 } 3588 3589 /** 3590 * Rejects incoming trackbacks in non-production environments. 3591 * 3592 * Hooked to `pre_trackback_post` which fires in `wp-trackback.php` before the 3593 * trackback is processed. Calls `trackback_response()` which sends an XML error 3594 * response and terminates the request. 3595 * 3596 * @since 7.1.0 3597 */ 3598 function wp_maybe_disable_trackback_for_environment() { 3599 if ( wp_should_disable_pings_for_environment() ) { 3600 trackback_response( 1, __( 'Trackbacks are disabled in non-production environments.' ) ); 3601 } 3602 } 3603 3604 /** 3605 * Removes the pingback XML-RPC method in non-production environments. 3606 * 3607 * @since 7.1.0 3608 * 3609 * @param string[] $methods An array of XML-RPC methods, keyed by their methodName. 3610 * @return string[] Modified array of XML-RPC methods. 3611 */ 3612 function wp_maybe_disable_xmlrpc_pingback_for_environment( $methods ) { 3613 if ( wp_should_disable_pings_for_environment() ) { 3614 unset( $methods['pingback.ping'] ); 3615 } 3616 3617 return $methods; 3618 } 3619 3620 /** 3621 * Pings back the links found in a post. 3622 * 3623 * @since 0.71 3624 * @since 4.7.0 `$post` can be a WP_Post object. 3625 * @since 6.8.0 Returns an array of pingback statuses indexed by link. 3626 * 3627 * @param string $content Post content to check for links. If empty will retrieve from post. 3628 * @param int|WP_Post $post Post ID or object. 3629 * @return array<string, bool> An array of pingback statuses indexed by link. 3630 */ 3631 function pingback( $content, $post ) { 3632 require_once ABSPATH . WPINC . '/class-IXR.php'; 3633 require_once ABSPATH . WPINC . '/class-wp-http-ixr-client.php'; 3634 3635 // Original code by Mort (http://mort.mine.nu:8080). 3636 $post_links = array(); 3637 3638 $post = get_post( $post ); 3639 3640 if ( ! $post ) { 3641 return array(); 3642 } 3643 3644 $pung = get_pung( $post ); 3645 3646 if ( empty( $content ) ) { 3647 $content = $post->post_content; 3648 } 3649 3650 /* 3651 * Step 1. 3652 * Parsing the post, external links (if any) are stored in the $post_links array. 3653 */ 3654 $post_links_temp = wp_extract_urls( $content ); 3655 3656 $ping_status = array(); 3657 /* 3658 * Step 2. 3659 * Walking through the links array. 3660 * First we get rid of links pointing to sites, not to specific files. 3661 * Example: 3662 * http://dummy-weblog.org 3663 * http://dummy-weblog.org/ 3664 * http://dummy-weblog.org/post.php 3665 * We don't wanna ping first and second types, even if they have a valid <link/>. 3666 */ 3667 foreach ( (array) $post_links_temp as $link_test ) { 3668 // If we haven't pung it already and it isn't a link to itself. 3669 if ( ! in_array( $link_test, $pung, true ) && ( url_to_postid( $link_test ) !== $post->ID ) 3670 // Also, let's never ping local attachments. 3671 && ! is_local_attachment( $link_test ) 3672 ) { 3673 $test = parse_url( $link_test ); 3674 if ( $test ) { 3675 if ( isset( $test['query'] ) ) { 3676 $post_links[] = $link_test; 3677 } elseif ( isset( $test['path'] ) && ( '/' !== $test['path'] ) && ( '' !== $test['path'] ) ) { 3678 $post_links[] = $link_test; 3679 } 3680 } 3681 } 3682 } 3683 3684 $post_links = array_unique( $post_links ); 3685 3686 /** 3687 * Fires just before pinging back links found in a post. 3688 * 3689 * @since 2.0.0 3690 * 3691 * @param string[] $post_links Array of link URLs to be checked (passed by reference). 3692 * @param string[] $pung Array of link URLs already pinged (passed by reference). 3693 * @param int $post_id The post ID. 3694 */ 3695 do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post->ID ) ); 3696 3697 foreach ( (array) $post_links as $pagelinkedto ) { 3698 $pingback_server_url = discover_pingback_server_uri( $pagelinkedto ); 3699 3700 if ( $pingback_server_url ) { 3701 // Allow an additional 60 seconds for each pingback to complete. 3702 if ( function_exists( 'set_time_limit' ) ) { 3703 set_time_limit( 60 ); 3704 } 3705 3706 // Now, the RPC call. 3707 $pagelinkedfrom = get_permalink( $post ); 3708 3709 // Using a timeout of 3 seconds should be enough to cover slow servers. 3710 $client = new WP_HTTP_IXR_Client( $pingback_server_url ); 3711 $client->timeout = 3; 3712 /** 3713 * Filters the user agent sent when pinging-back a URL. 3714 * 3715 * @since 2.9.0 3716 * 3717 * @param string $concat_useragent The user agent concatenated with ' -- WordPress/' 3718 * and the WordPress version. 3719 * @param string $useragent The useragent. 3720 * @param string $pingback_server_url The server URL being linked to. 3721 * @param string $pagelinkedto URL of page linked to. 3722 * @param string $pagelinkedfrom URL of page linked from. 3723 */ 3724 $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . get_bloginfo( 'version' ), $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom ); 3725 // When set to true, this outputs debug messages by itself. 3726 $client->debug = false; 3727 3728 $status = $client->query( 'pingback.ping', $pagelinkedfrom, $pagelinkedto ); 3729 3730 if ( $status // Ping registered. 3731 || ( $client->error instanceof IXR_Error && 48 === $client->error->code ) // Already registered. 3732 ) { 3733 add_ping( $post, $pagelinkedto ); 3734 } 3735 $ping_status[ $pagelinkedto ] = $status; 3736 } 3737 } 3738 3739 return $ping_status; 3740 } 3741 3742 /** 3743 * Checks whether blog is public before returning sites. 3744 * 3745 * @since 2.1.0 3746 * 3747 * @param mixed $sites Will return if blog is public, will not return if not public. 3748 * @return mixed Empty string if blog is not public, returns $sites, if site is public. 3749 */ 3750 function privacy_ping_filter( $sites ) { 3751 if ( '0' !== get_option( 'blog_public' ) ) { 3752 return $sites; 3753 } else { 3754 return ''; 3755 } 3756 } 3757 3758 /** 3759 * Sends a Trackback. 3760 * 3761 * Updates database when sending trackback to prevent duplicates. 3762 * 3763 * @since 0.71 3764 * 3765 * @global wpdb $wpdb WordPress database abstraction object. 3766 * 3767 * @param string $trackback_url URL to send trackbacks. 3768 * @param string $title Title of post. 3769 * @param string $excerpt Excerpt of post. 3770 * @param int $post_id Post ID. 3771 * @return int|false|null Database query from update. 3772 */ 3773 function trackback( $trackback_url, $title, $excerpt, $post_id ) { 3774 global $wpdb; 3775 3776 if ( empty( $trackback_url ) ) { 3777 return null; 3778 } 3779 3780 $options = array(); 3781 $options['timeout'] = 10; 3782 $options['body'] = array( 3783 'title' => $title, 3784 'url' => get_permalink( $post_id ), 3785 'blog_name' => get_option( 'blogname' ), 3786 'excerpt' => $excerpt, 3787 ); 3788 3789 $response = wp_safe_remote_post( $trackback_url, $options ); 3790 3791 if ( is_wp_error( $response ) ) { 3792 return null; 3793 } 3794 3795 $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $post_id ) ); 3796 return $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $post_id ) ); 3797 } 3798 3799 /** 3800 * Sends a pingback. 3801 * 3802 * @since 1.2.0 3803 * 3804 * @param string $server Host of blog to connect to. 3805 * @param string $path Path to send the ping. 3806 */ 3807 function weblog_ping( $server = '', $path = '' ) { 3808 require_once ABSPATH . WPINC . '/class-IXR.php'; 3809 require_once ABSPATH . WPINC . '/class-wp-http-ixr-client.php'; 3810 3811 // Using a timeout of 3 seconds should be enough to cover slow servers. 3812 $client = new WP_HTTP_IXR_Client( $server, ( ( ! strlen( trim( $path ) ) || ( '/' === $path ) ) ? false : $path ) ); 3813 $client->timeout = 3; 3814 $client->useragent .= ' -- WordPress/' . get_bloginfo( 'version' ); 3815 3816 // When set to true, this outputs debug messages by itself. 3817 $client->debug = false; 3818 $home = trailingslashit( home_url() ); 3819 if ( ! $client->query( 'weblogUpdates.extendedPing', get_option( 'blogname' ), $home, get_bloginfo( 'rss2_url' ) ) ) { // Then try a normal ping. 3820 $client->query( 'weblogUpdates.ping', get_option( 'blogname' ), $home ); 3821 } 3822 } 3823 3824 /** 3825 * Default filter attached to pingback_ping_source_uri to validate the pingback's Source URI. 3826 * 3827 * @since 3.5.1 3828 * 3829 * @see wp_http_validate_url() 3830 * 3831 * @param string $source_uri 3832 * @return string Validated source URI. 3833 */ 3834 function pingback_ping_source_uri( $source_uri ) { 3835 return (string) wp_http_validate_url( $source_uri ); 3836 } 3837 3838 /** 3839 * Default filter attached to xmlrpc_pingback_error. 3840 * 3841 * Returns a generic pingback error code unless the error code is 48, 3842 * which reports that the pingback is already registered. 3843 * 3844 * @since 3.5.1 3845 * 3846 * @link https://www.hixie.ch/specs/pingback/pingback#TOC3 3847 * 3848 * @param IXR_Error $ixr_error 3849 * @return IXR_Error 3850 */ 3851 function xmlrpc_pingback_error( $ixr_error ) { 3852 if ( 48 === $ixr_error->code ) { 3853 return $ixr_error; 3854 } 3855 return new IXR_Error( 0, '' ); 3856 } 3857 3858 // 3859 // Cache. 3860 // 3861 3862 /** 3863 * Removes a comment from the object cache. 3864 * 3865 * @since 2.3.0 3866 * 3867 * @param int|array $ids Comment ID or an array of comment IDs to remove from cache. 3868 */ 3869 function clean_comment_cache( $ids ) { 3870 $comment_ids = (array) $ids; 3871 wp_cache_delete_multiple( $comment_ids, 'comment' ); 3872 foreach ( $comment_ids as $id ) { 3873 /** 3874 * Fires immediately after a comment has been removed from the object cache. 3875 * 3876 * @since 4.5.0 3877 * 3878 * @param int $id Comment ID. 3879 */ 3880 do_action( 'clean_comment_cache', $id ); 3881 } 3882 3883 wp_cache_set_comments_last_changed(); 3884 } 3885 3886 /** 3887 * Updates the comment cache of given comments. 3888 * 3889 * Will add the comments in $comments to the cache. If comment ID already exists 3890 * in the comment cache then it will not be updated. The comment is added to the 3891 * cache using the comment group with the key using the ID of the comments. 3892 * 3893 * @since 2.3.0 3894 * @since 4.4.0 Introduced the `$update_meta_cache` parameter. 3895 * 3896 * @param WP_Comment[] $comments Array of comment objects 3897 * @param bool $update_meta_cache Whether to update commentmeta cache. Default true. 3898 */ 3899 function update_comment_cache( $comments, $update_meta_cache = true ) { 3900 $data = array(); 3901 foreach ( (array) $comments as $comment ) { 3902 $data[ $comment->comment_ID ] = $comment; 3903 } 3904 wp_cache_add_multiple( $data, 'comment' ); 3905 3906 if ( $update_meta_cache ) { 3907 // Avoid `wp_list_pluck()` in case `$comments` is passed by reference. 3908 $comment_ids = array(); 3909 foreach ( $comments as $comment ) { 3910 $comment_ids[] = $comment->comment_ID; 3911 } 3912 update_meta_cache( 'comment', $comment_ids ); 3913 } 3914 } 3915 3916 /** 3917 * Adds any comments from the given IDs to the cache that do not already exist in cache. 3918 * 3919 * @since 4.4.0 3920 * @since 6.1.0 This function is no longer marked as "private". 3921 * @since 6.3.0 Use wp_lazyload_comment_meta() for lazy-loading of comment meta. 3922 * 3923 * @see update_comment_cache() 3924 * @global wpdb $wpdb WordPress database abstraction object. 3925 * 3926 * @param int[] $comment_ids Array of comment IDs. 3927 * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true. 3928 */ 3929 function _prime_comment_caches( $comment_ids, $update_meta_cache = true ) { 3930 global $wpdb; 3931 3932 $non_cached_ids = _get_non_cached_ids( $comment_ids, 'comment' ); 3933 if ( ! empty( $non_cached_ids ) ) { 3934 $fresh_comments = $wpdb->get_results( sprintf( "SELECT $wpdb->comments.* FROM $wpdb->comments WHERE comment_ID IN (%s)", implode( ',', array_map( 'intval', $non_cached_ids ) ) ) ); 3935 3936 update_comment_cache( $fresh_comments, false ); 3937 } 3938 3939 if ( $update_meta_cache ) { 3940 wp_lazyload_comment_meta( $comment_ids ); 3941 } 3942 } 3943 3944 // 3945 // Internal. 3946 // 3947 3948 /** 3949 * Closes comments on old posts on the fly, without any extra DB queries. Hooked to the_posts. 3950 * 3951 * @since 2.7.0 3952 * @access private 3953 * 3954 * @param WP_Post[] $posts Array of post objects. 3955 * @param WP_Query $query Query object. 3956 * @return WP_Post[] 3957 */ 3958 function _close_comments_for_old_posts( $posts, $query ) { 3959 if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) ) { 3960 return $posts; 3961 } 3962 3963 /** 3964 * Filters the list of post types to automatically close comments for. 3965 * 3966 * @since 3.2.0 3967 * 3968 * @param string[] $post_types An array of post type names. 3969 */ 3970 $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) ); 3971 if ( ! in_array( $posts[0]->post_type, $post_types, true ) ) { 3972 return $posts; 3973 } 3974 3975 $days_old = (int) get_option( 'close_comments_days_old' ); 3976 if ( ! $days_old ) { 3977 return $posts; 3978 } 3979 3980 if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) { 3981 $posts[0]->comment_status = 'closed'; 3982 $posts[0]->ping_status = 'closed'; 3983 } 3984 3985 return $posts; 3986 } 3987 3988 /** 3989 * Closes comments on an old post. Hooked to comments_open and pings_open. 3990 * 3991 * @since 2.7.0 3992 * @access private 3993 * 3994 * @param bool $open Comments open or closed. 3995 * @param int $post_id Post ID. 3996 * @return bool True if comments are open, false otherwise. 3997 */ 3998 function _close_comments_for_old_post( $open, $post_id ) { 3999 if ( ! $open ) { 4000 return $open; 4001 } 4002 4003 if ( ! get_option( 'close_comments_for_old_posts' ) ) { 4004 return $open; 4005 } 4006 4007 $days_old = (int) get_option( 'close_comments_days_old' ); 4008 if ( ! $days_old ) { 4009 return $open; 4010 } 4011 4012 $post = get_post( $post_id ); 4013 4014 /** This filter is documented in wp-includes/comment.php */ 4015 $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) ); 4016 if ( ! in_array( $post->post_type, $post_types, true ) ) { 4017 return $open; 4018 } 4019 4020 // Undated drafts should not show up as comments closed. 4021 if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) { 4022 return $open; 4023 } 4024 4025 if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) { 4026 return false; 4027 } 4028 4029 return $open; 4030 } 4031 4032 /** 4033 * Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form. 4034 * 4035 * This function expects unslashed data, as opposed to functions such as `wp_new_comment()` which 4036 * expect slashed data. 4037 * 4038 * @since 4.4.0 4039 * 4040 * @param array $comment_data { 4041 * Comment data. 4042 * 4043 * @type string|int $comment_post_ID The ID of the post that relates to the comment. 4044 * @type string $author The name of the comment author. 4045 * @type string $email The comment author email address. 4046 * @type string $url The comment author URL. 4047 * @type string $comment The content of the comment. 4048 * @type string|int $comment_parent The ID of this comment's parent, if any. Default 0. 4049 * @type string $_wp_unfiltered_html_comment The nonce value for allowing unfiltered HTML. 4050 * } 4051 * @return WP_Comment|WP_Error A WP_Comment object on success, a WP_Error object on failure. 4052 */ 4053 function wp_handle_comment_submission( $comment_data ) { 4054 $comment_post_id = 0; 4055 $comment_author = ''; 4056 $comment_author_email = ''; 4057 $comment_author_url = ''; 4058 $comment_content = ''; 4059 $comment_parent = 0; 4060 $user_id = 0; 4061 4062 if ( isset( $comment_data['comment_post_ID'] ) ) { 4063 $comment_post_id = (int) $comment_data['comment_post_ID']; 4064 } 4065 if ( isset( $comment_data['author'] ) && is_string( $comment_data['author'] ) ) { 4066 $comment_author = trim( strip_tags( $comment_data['author'] ) ); 4067 } 4068 if ( isset( $comment_data['email'] ) && is_string( $comment_data['email'] ) ) { 4069 $comment_author_email = trim( $comment_data['email'] ); 4070 } 4071 if ( isset( $comment_data['url'] ) && is_string( $comment_data['url'] ) ) { 4072 $comment_author_url = trim( $comment_data['url'] ); 4073 } 4074 if ( isset( $comment_data['comment'] ) && is_string( $comment_data['comment'] ) ) { 4075 $comment_content = trim( $comment_data['comment'] ); 4076 } 4077 if ( isset( $comment_data['comment_parent'] ) ) { 4078 $comment_parent = absint( $comment_data['comment_parent'] ); 4079 $comment_parent_object = get_comment( $comment_parent ); 4080 4081 if ( 4082 0 !== $comment_parent && 4083 ( 4084 ! $comment_parent_object instanceof WP_Comment || 4085 0 === (int) $comment_parent_object->comment_approved 4086 ) 4087 ) { 4088 /** 4089 * Fires when a comment reply is attempted to an unapproved comment. 4090 * 4091 * @since 6.2.0 4092 * 4093 * @param int $comment_post_id Post ID. 4094 * @param int $comment_parent Parent comment ID. 4095 */ 4096 do_action( 'comment_reply_to_unapproved_comment', $comment_post_id, $comment_parent ); 4097 4098 return new WP_Error( 'comment_reply_to_unapproved_comment', __( 'Sorry, replies to unapproved comments are not allowed.' ), 403 ); 4099 } 4100 } 4101 4102 $post = get_post( $comment_post_id ); 4103 4104 if ( empty( $post->comment_status ) ) { 4105 4106 /** 4107 * Fires when a comment is attempted on a post that does not exist. 4108 * 4109 * @since 1.5.0 4110 * 4111 * @param int $comment_post_id Post ID. 4112 */ 4113 do_action( 'comment_id_not_found', $comment_post_id ); 4114 4115 return new WP_Error( 'comment_id_not_found' ); 4116 4117 } 4118 4119 // get_post_status() will get the parent status for attachments. 4120 $status = get_post_status( $post ); 4121 4122 if ( ( 'private' === $status ) && ! current_user_can( 'read_post', $comment_post_id ) ) { 4123 return new WP_Error( 'comment_id_not_found' ); 4124 } 4125 4126 $status_obj = get_post_status_object( $status ); 4127 4128 if ( ! comments_open( $comment_post_id ) ) { 4129 4130 /** 4131 * Fires when a comment is attempted on a post that has comments closed. 4132 * 4133 * @since 1.5.0 4134 * 4135 * @param int $comment_post_id Post ID. 4136 */ 4137 do_action( 'comment_closed', $comment_post_id ); 4138 4139 return new WP_Error( 'comment_closed', __( 'Sorry, comments are closed for this item.' ), 403 ); 4140 4141 } elseif ( 'trash' === $status ) { 4142 4143 /** 4144 * Fires when a comment is attempted on a trashed post. 4145 * 4146 * @since 2.9.0 4147 * 4148 * @param int $comment_post_id Post ID. 4149 */ 4150 do_action( 'comment_on_trash', $comment_post_id ); 4151 4152 return new WP_Error( 'comment_on_trash' ); 4153 4154 } elseif ( ! $status_obj->public && ! $status_obj->private ) { 4155 4156 /** 4157 * Fires when a comment is attempted on a post in draft mode. 4158 * 4159 * @since 1.5.1 4160 * 4161 * @param int $comment_post_id Post ID. 4162 */ 4163 do_action( 'comment_on_draft', $comment_post_id ); 4164 4165 if ( current_user_can( 'read_post', $comment_post_id ) ) { 4166 return new WP_Error( 'comment_on_draft', __( 'Sorry, comments are not allowed for this item.' ), 403 ); 4167 } else { 4168 return new WP_Error( 'comment_on_draft' ); 4169 } 4170 } elseif ( post_password_required( $comment_post_id ) ) { 4171 4172 /** 4173 * Fires when a comment is attempted on a password-protected post. 4174 * 4175 * @since 2.9.0 4176 * 4177 * @param int $comment_post_id Post ID. 4178 */ 4179 do_action( 'comment_on_password_protected', $comment_post_id ); 4180 4181 return new WP_Error( 'comment_on_password_protected' ); 4182 4183 } else { 4184 /** 4185 * Fires before a comment is posted. 4186 * 4187 * @since 2.8.0 4188 * 4189 * @param int $comment_post_id Post ID. 4190 */ 4191 do_action( 'pre_comment_on_post', $comment_post_id ); 4192 } 4193 4194 // If the user is logged in. 4195 $user = wp_get_current_user(); 4196 if ( $user->exists() ) { 4197 if ( empty( $user->display_name ) ) { 4198 $user->display_name = $user->user_login; 4199 } 4200 4201 $comment_author = $user->display_name; 4202 $comment_author_email = $user->user_email; 4203 $comment_author_url = $user->user_url; 4204 $user_id = $user->ID; 4205 4206 if ( current_user_can( 'unfiltered_html' ) ) { 4207 if ( ! isset( $comment_data['_wp_unfiltered_html_comment'] ) 4208 || ! wp_verify_nonce( $comment_data['_wp_unfiltered_html_comment'], 'unfiltered-html-comment_' . $comment_post_id ) 4209 ) { 4210 kses_remove_filters(); // Start with a clean slate. 4211 kses_init_filters(); // Set up the filters. 4212 remove_filter( 'pre_comment_content', 'wp_filter_post_kses' ); 4213 add_filter( 'pre_comment_content', 'wp_filter_kses' ); 4214 } 4215 } 4216 } else { 4217 if ( get_option( 'comment_registration' ) ) { 4218 return new WP_Error( 'not_logged_in', __( 'Sorry, you must be logged in to comment.' ), 403 ); 4219 } 4220 } 4221 4222 $comment_type = 'comment'; 4223 4224 if ( get_option( 'require_name_email' ) && ! $user->exists() ) { 4225 if ( '' === $comment_author_email || '' === $comment_author ) { 4226 return new WP_Error( 'require_name_email', __( '<strong>Error:</strong> Please fill the required fields.' ), 200 ); 4227 } elseif ( ! is_email( $comment_author_email ) ) { 4228 return new WP_Error( 'require_valid_email', __( '<strong>Error:</strong> Please enter a valid email address.' ), 200 ); 4229 } 4230 } 4231 4232 $commentdata = array( 4233 'comment_post_ID' => $comment_post_id, 4234 ); 4235 4236 $commentdata += compact( 4237 'comment_author', 4238 'comment_author_email', 4239 'comment_author_url', 4240 'comment_content', 4241 'comment_type', 4242 'comment_parent', 4243 'user_id' 4244 ); 4245 4246 /** 4247 * Filters whether an empty comment should be allowed. 4248 * 4249 * @since 5.1.0 4250 * 4251 * @param bool $allow_empty_comment Whether to allow empty comments. Default false. 4252 * @param array $commentdata Array of comment data to be sent to wp_insert_comment(). 4253 */ 4254 $allow_empty_comment = apply_filters( 'allow_empty_comment', false, $commentdata ); 4255 if ( '' === $comment_content && ! $allow_empty_comment ) { 4256 return new WP_Error( 'require_valid_comment', __( '<strong>Error:</strong> Please type your comment text.' ), 200 ); 4257 } 4258 4259 $check_max_lengths = wp_check_comment_data_max_lengths( $commentdata ); 4260 if ( is_wp_error( $check_max_lengths ) ) { 4261 return $check_max_lengths; 4262 } 4263 4264 $comment_id = wp_new_comment( wp_slash( $commentdata ), true ); 4265 if ( is_wp_error( $comment_id ) ) { 4266 return $comment_id; 4267 } 4268 4269 if ( ! $comment_id ) { 4270 return new WP_Error( 'comment_save_error', __( '<strong>Error:</strong> The comment could not be saved. Please try again later.' ), 500 ); 4271 } 4272 4273 return get_comment( $comment_id ); 4274 } 4275 4276 /** 4277 * Registers the personal data exporter for comments. 4278 * 4279 * @since 4.9.6 4280 * 4281 * @param array[] $exporters An array of personal data exporters. 4282 * @return array[] An array of personal data exporters. 4283 */ 4284 function wp_register_comment_personal_data_exporter( $exporters ) { 4285 $exporters['wordpress-comments'] = array( 4286 'exporter_friendly_name' => __( 'WordPress Comments' ), 4287 'callback' => 'wp_comments_personal_data_exporter', 4288 ); 4289 4290 return $exporters; 4291 } 4292 4293 /** 4294 * Finds and exports personal data associated with an email address from the comments table. 4295 * 4296 * @since 4.9.6 4297 * 4298 * @param string $email_address The comment author email address. 4299 * @param int $page Comment page number. 4300 * @return array { 4301 * An array of personal data. 4302 * 4303 * @type array[] $data An array of personal data arrays. 4304 * @type bool $done Whether the exporter is finished. 4305 * } 4306 */ 4307 function wp_comments_personal_data_exporter( $email_address, $page = 1 ) { 4308 // Limit us to 500 comments at a time to avoid timing out. 4309 $number = 500; 4310 $page = (int) $page; 4311 4312 $data_to_export = array(); 4313 4314 $comments = get_comments( 4315 array( 4316 'author_email' => $email_address, 4317 'number' => $number, 4318 'paged' => $page, 4319 'orderby' => 'comment_ID', 4320 'order' => 'ASC', 4321 'update_comment_meta_cache' => false, 4322 ) 4323 ); 4324 4325 $comment_prop_to_export = array( 4326 'comment_author' => __( 'Comment Author' ), 4327 'comment_author_email' => __( 'Comment Author Email' ), 4328 'comment_author_url' => __( 'Comment Author URL' ), 4329 'comment_author_IP' => __( 'Comment Author IP' ), 4330 'comment_agent' => __( 'Comment Author User Agent' ), 4331 'comment_date' => __( 'Comment Date' ), 4332 'comment_content' => __( 'Comment Content' ), 4333 'comment_link' => __( 'Comment URL' ), 4334 ); 4335 4336 foreach ( (array) $comments as $comment ) { 4337 $comment_data_to_export = array(); 4338 4339 foreach ( $comment_prop_to_export as $key => $name ) { 4340 $value = ''; 4341 4342 switch ( $key ) { 4343 case 'comment_author': 4344 case 'comment_author_email': 4345 case 'comment_author_url': 4346 case 'comment_author_IP': 4347 case 'comment_agent': 4348 case 'comment_date': 4349 $value = $comment->{$key}; 4350 break; 4351 4352 case 'comment_content': 4353 $value = get_comment_text( $comment->comment_ID ); 4354 break; 4355 4356 case 'comment_link': 4357 $value = get_comment_link( $comment->comment_ID ); 4358 $value = sprintf( 4359 '<a href="%s" target="_blank">%s</a>', 4360 esc_url( $value ), 4361 esc_html( $value ) 4362 ); 4363 break; 4364 } 4365 4366 if ( ! empty( $value ) ) { 4367 $comment_data_to_export[] = array( 4368 'name' => $name, 4369 'value' => $value, 4370 ); 4371 } 4372 } 4373 4374 $data_to_export[] = array( 4375 'group_id' => 'comments', 4376 'group_label' => __( 'Comments' ), 4377 'group_description' => __( 'User’s comment data.' ), 4378 'item_id' => "comment-{$comment->comment_ID}", 4379 'data' => $comment_data_to_export, 4380 ); 4381 } 4382 4383 $done = count( $comments ) < $number; 4384 4385 return array( 4386 'data' => $data_to_export, 4387 'done' => $done, 4388 ); 4389 } 4390 4391 /** 4392 * Registers the personal data eraser for comments. 4393 * 4394 * @since 4.9.6 4395 * 4396 * @param array $erasers An array of personal data erasers. 4397 * @return array An array of personal data erasers. 4398 */ 4399 function wp_register_comment_personal_data_eraser( $erasers ) { 4400 $erasers['wordpress-comments'] = array( 4401 'eraser_friendly_name' => __( 'WordPress Comments' ), 4402 'callback' => 'wp_comments_personal_data_eraser', 4403 ); 4404 4405 return $erasers; 4406 } 4407 4408 /** 4409 * Erases personal data associated with an email address from the comments table. 4410 * 4411 * @since 4.9.6 4412 * 4413 * @global wpdb $wpdb WordPress database abstraction object. 4414 * 4415 * @param string $email_address The comment author email address. 4416 * @param int $page Comment page number. 4417 * @return array { 4418 * Data removal results. 4419 * 4420 * @type bool $items_removed Whether items were actually removed. 4421 * @type bool $items_retained Whether items were retained. 4422 * @type string[] $messages An array of messages to add to the personal data export file. 4423 * @type bool $done Whether the eraser is finished. 4424 * } 4425 */ 4426 function wp_comments_personal_data_eraser( $email_address, $page = 1 ) { 4427 global $wpdb; 4428 4429 if ( empty( $email_address ) ) { 4430 return array( 4431 'items_removed' => false, 4432 'items_retained' => false, 4433 'messages' => array(), 4434 'done' => true, 4435 ); 4436 } 4437 4438 // Limit us to 500 comments at a time to avoid timing out. 4439 $number = 500; 4440 $page = (int) $page; 4441 $items_removed = false; 4442 $items_retained = false; 4443 4444 $comments = get_comments( 4445 array( 4446 'author_email' => $email_address, 4447 'number' => $number, 4448 'paged' => $page, 4449 'orderby' => 'comment_ID', 4450 'order' => 'ASC', 4451 'include_unapproved' => true, 4452 ) 4453 ); 4454 4455 /* translators: Name of a comment's author after being anonymized. */ 4456 $anon_author = __( 'Anonymous' ); 4457 $messages = array(); 4458 4459 foreach ( (array) $comments as $comment ) { 4460 $anonymized_comment = array(); 4461 $anonymized_comment['comment_agent'] = ''; 4462 $anonymized_comment['comment_author'] = $anon_author; 4463 $anonymized_comment['comment_author_email'] = ''; 4464 $anonymized_comment['comment_author_IP'] = wp_privacy_anonymize_data( 'ip', $comment->comment_author_IP ); 4465 $anonymized_comment['comment_author_url'] = ''; 4466 $anonymized_comment['user_id'] = 0; 4467 4468 $comment_id = (int) $comment->comment_ID; 4469 4470 /** 4471 * Filters whether to anonymize the comment. 4472 * 4473 * @since 4.9.6 4474 * 4475 * @param bool|string $anon_message Whether to apply the comment anonymization (bool) or a custom 4476 * message (string). Default true. 4477 * @param WP_Comment $comment WP_Comment object. 4478 * @param array $anonymized_comment Anonymized comment data. 4479 */ 4480 $anon_message = apply_filters( 'wp_anonymize_comment', true, $comment, $anonymized_comment ); 4481 4482 if ( true !== $anon_message ) { 4483 if ( $anon_message && is_string( $anon_message ) ) { 4484 $messages[] = esc_html( $anon_message ); 4485 } else { 4486 /* translators: %d: Comment ID. */ 4487 $messages[] = sprintf( __( 'Comment %d contains personal data but could not be anonymized.' ), $comment_id ); 4488 } 4489 4490 $items_retained = true; 4491 4492 continue; 4493 } 4494 4495 $args = array( 4496 'comment_ID' => $comment_id, 4497 ); 4498 4499 $updated = $wpdb->update( $wpdb->comments, $anonymized_comment, $args ); 4500 4501 if ( $updated ) { 4502 $items_removed = true; 4503 clean_comment_cache( $comment_id ); 4504 } else { 4505 $items_retained = true; 4506 } 4507 } 4508 4509 $done = count( $comments ) < $number; 4510 4511 return array( 4512 'items_removed' => $items_removed, 4513 'items_retained' => $items_retained, 4514 'messages' => $messages, 4515 'done' => $done, 4516 ); 4517 } 4518 4519 /** 4520 * Sets the last changed time for the 'comment' cache group. 4521 * 4522 * @since 5.0.0 4523 */ 4524 function wp_cache_set_comments_last_changed() { 4525 wp_cache_set_last_changed( 'comment' ); 4526 } 4527 4528 /** 4529 * Updates the comment type for a batch of comments. 4530 * 4531 * @since 5.5.0 4532 * 4533 * @global wpdb $wpdb WordPress database abstraction object. 4534 */ 4535 function _wp_batch_update_comment_type() { 4536 global $wpdb; 4537 4538 $lock_name = 'update_comment_type.lock'; 4539 4540 // Try to lock. 4541 $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) ); 4542 4543 if ( ! $lock_result ) { 4544 $lock_result = get_option( $lock_name ); 4545 4546 // Bail if we were unable to create a lock, or if the existing lock is still valid. 4547 if ( ! $lock_result || ( $lock_result > ( time() - HOUR_IN_SECONDS ) ) ) { 4548 wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' ); 4549 return; 4550 } 4551 } 4552 4553 // Update the lock, as by this point we've definitely got a lock, just need to fire the actions. 4554 update_option( $lock_name, time() ); 4555 4556 // Check if there's still an empty comment type. 4557 $empty_comment_type = $wpdb->get_var( 4558 "SELECT comment_ID FROM $wpdb->comments 4559 WHERE comment_type = '' 4560 LIMIT 1" 4561 ); 4562 4563 // No empty comment type, we're done here. 4564 if ( ! $empty_comment_type ) { 4565 update_option( 'finished_updating_comment_type', true ); 4566 delete_option( $lock_name ); 4567 return; 4568 } 4569 4570 // Empty comment type found? We'll need to run this script again. 4571 wp_schedule_single_event( time() + ( 2 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' ); 4572 4573 /** 4574 * Filters the comment batch size for updating the comment type. 4575 * 4576 * @since 5.5.0 4577 * 4578 * @param int $comment_batch_size The comment batch size. Default 100. 4579 */ 4580 $comment_batch_size = (int) apply_filters( 'wp_update_comment_type_batch_size', 100 ); 4581 4582 // Get the IDs of the comments to update. 4583 $comment_ids = $wpdb->get_col( 4584 $wpdb->prepare( 4585 "SELECT comment_ID 4586 FROM {$wpdb->comments} 4587 WHERE comment_type = '' 4588 ORDER BY comment_ID DESC 4589 LIMIT %d", 4590 $comment_batch_size 4591 ) 4592 ); 4593 4594 if ( $comment_ids ) { 4595 $comment_id_list = implode( ',', $comment_ids ); 4596 4597 // Update the `comment_type` field value to be `comment` for the next batch of comments. 4598 $wpdb->query( 4599 "UPDATE {$wpdb->comments} 4600 SET comment_type = 'comment' 4601 WHERE comment_type = '' 4602 AND comment_ID IN ({$comment_id_list})" // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared 4603 ); 4604 4605 // Make sure to clean the comment cache. 4606 clean_comment_cache( $comment_ids ); 4607 } 4608 4609 delete_option( $lock_name ); 4610 } 4611 4612 /** 4613 * In order to avoid the _wp_batch_update_comment_type() job being accidentally removed, 4614 * check that it's still scheduled while we haven't finished updating comment types. 4615 * 4616 * @ignore 4617 * @since 5.5.0 4618 */ 4619 function _wp_check_for_scheduled_update_comment_type() { 4620 if ( ! get_option( 'finished_updating_comment_type' ) && ! wp_next_scheduled( 'wp_update_comment_type_batch' ) ) { 4621 wp_schedule_single_event( time() + MINUTE_IN_SECONDS, 'wp_update_comment_type_batch' ); 4622 } 4623 } 4624 4625 /** 4626 * Register initial note status meta. 4627 * 4628 * @since 6.9.0 4629 */ 4630 function wp_create_initial_comment_meta() { 4631 register_meta( 4632 'comment', 4633 '_wp_note_status', 4634 array( 4635 'type' => 'string', 4636 'description' => __( 'Note resolution status' ), 4637 'single' => true, 4638 'show_in_rest' => array( 4639 'schema' => array( 4640 'type' => 'string', 4641 'enum' => array( 'resolved', 'reopen' ), 4642 ), 4643 ), 4644 'auth_callback' => function ( $allowed, $meta_key, $object_id ) { 4645 return current_user_can( 'edit_comment', $object_id ); 4646 }, 4647 ) 4648 ); 4649 } 4650 4651 /** 4652 * Strips inline note markers from rendered block output. 4653 * 4654 * Inline notes - notes anchored to a text selection within a block rather than 4655 * the whole block - are anchored in raw block content with 4656 * `<mark class="wp-note" data-id="N">...</mark>` so the marker survives edits, 4657 * but the public HTML should not expose note metadata. This filter unwraps the 4658 * marker entirely - dropping the `<mark>` open tag and its matching closer while 4659 * keeping the marked text - so nothing leaks to the front end. The raw 4660 * `post_content` (and the REST `raw` view, revisions, exports) keeps the marker 4661 * so the editor can re-attach it on reload. 4662 * 4663 * Only note markers are unwrapped: {@see WP_HTML_Tag_Processor::has_class()} 4664 * matches the `wp-note` class by exact token, so a `<mark>` a user or plugin 4665 * added (e.g. a `core/text-color` highlight, or an unrelated `wp-note-foo` 4666 * class) is never flagged and survives byte-for-byte with all of its attributes 4667 * intact. A naive regex would be wrong here: a `\bwp-note\b` word boundary also 4668 * matches `wp-note-foo`, which is why the class check goes through the HTML API 4669 * instead. 4670 * 4671 * The HTML API has no public token-removal method yet, so an anonymous 4672 * {@see WP_HTML_Tag_Processor} subclass unwraps each note `<mark>` and its 4673 * matching closer directly on the parsed token stream. Walking tokens - rather 4674 * than matching `<mark>` with a regex - means a `</mark>`-looking sequence inside 4675 * a comment or attribute value can never be mistaken for a real tag, and a 4676 * nesting stack keeps each note opener paired with its own closer so overlapping 4677 * notes and any user highlight `<mark>` left intact still resolve correctly. 4678 * 4679 * The low-level {@see WP_HTML_Tag_Processor} is used deliberately, rather than 4680 * the tree-building {@see WP_HTML_Processor}. Note markers live in user-editable 4681 * content, so the markup is not guaranteed to be well formed. On certain 4682 * ill-formed nesting the tree builder aborts, which would leave note markers - 4683 * and their metadata - in the rendered output. Scanning tokens instead removes 4684 * every `wp-note` marker it encounters and degrades gracefully: an unbalanced or 4685 * stray tag is left exactly as it was rather than corrupting surrounding markup. 4686 * 4687 * @since 7.1.0 4688 * 4689 * @param string $block_content Rendered block HTML. 4690 * @return string Block HTML with `wp-note` markers unwrapped. 4691 */ 4692 function wp_strip_inline_note_markers( $block_content ) { 4693 if ( ! str_contains( $block_content, 'wp-note' ) ) { 4694 return $block_content; 4695 } 4696 4697 /* 4698 * Anonymous subclass exposing token removal, which WP_HTML_Tag_Processor 4699 * does not provide publicly yet. Removing the current token via its bookmark 4700 * span unwraps the `<mark>` (opener or closer) while keeping the text it 4701 * wraps. 4702 */ 4703 $processor = new class( $block_content ) extends WP_HTML_Tag_Processor { 4704 /** 4705 * Removes the current token, keeping any text it wraps. 4706 */ 4707 public function remove_token(): void { 4708 // Always called after next_tag() returned true, so the bookmark is set. 4709 $this->set_bookmark( 'here' ); 4710 $span = $this->bookmarks['here']; 4711 4712 $this->lexical_updates[] = new WP_HTML_Text_Replacement( $span->start, $span->length, '' ); 4713 } 4714 }; 4715 4716 /* 4717 * Walk every `<mark>`, tracking note nesting on a stack so each note opener 4718 * pairs with its own closer, and unwrap only the note markers. 4719 */ 4720 $mark_stack = array(); 4721 $query = array( 4722 'tag_name' => 'MARK', 4723 'tag_closers' => 'visit', 4724 ); 4725 while ( $processor->next_tag( $query ) ) { 4726 if ( $processor->is_tag_closer() ) { 4727 $is_note = array_pop( $mark_stack ); 4728 } else { 4729 $is_note = $processor->has_class( 'wp-note' ); 4730 $mark_stack[] = $is_note; 4731 } 4732 4733 if ( true === $is_note ) { 4734 $processor->remove_token(); 4735 } 4736 } 4737 4738 return $processor->get_updated_html(); 4739 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Thu Dec 3 08:20:02 2026 | Cross-referenced by PHPXref |