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


Generated : Sat Nov 23 08:20:01 2024 Cross-referenced by PHPXref