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


Generated: Sat Mar 6 01:00:04 2021 Cross-referenced by PHPXref 0.7.1