[ Index ]

PHP Cross Reference of WordPress

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


Generated: Thu Jul 16 01:00:03 2020 Cross-referenced by PHPXref 0.7.1