[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> comment.php (source)

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


Generated : Sun Mar 9 08:20:01 2025 Cross-referenced by PHPXref