[ 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|bool 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   *
1926   * @return string The unapproved comment author's email (when supplied).
1927   */
1928  function wp_get_unapproved_comment_author_email() {
1929      $commenter_email = '';
1930  
1931      if ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) {
1932          $comment_id = (int) $_GET['unapproved'];
1933          $comment    = get_comment( $comment_id );
1934  
1935          if ( $comment && hash_equals( $_GET['moderation-hash'], wp_hash( $comment->comment_date_gmt ) ) ) {
1936              // The comment will only be viewable by the comment author for 1 minute.
1937              $comment_preview_expires = strtotime( $comment->comment_date_gmt . '+1 minute' );
1938  
1939              if ( time() < $comment_preview_expires ) {
1940                  $commenter_email = $comment->comment_author_email;
1941              }
1942          }
1943      }
1944  
1945      if ( ! $commenter_email ) {
1946          $commenter       = wp_get_current_commenter();
1947          $commenter_email = $commenter['comment_author_email'];
1948      }
1949  
1950      return $commenter_email;
1951  }
1952  
1953  /**
1954   * Inserts a comment into the database.
1955   *
1956   * @since 2.0.0
1957   * @since 4.4.0 Introduced the `$comment_meta` argument.
1958   * @since 5.5.0 Default value for `$comment_type` argument changed to `comment`.
1959   *
1960   * @global wpdb $wpdb WordPress database abstraction object.
1961   *
1962   * @param array $commentdata {
1963   *     Array of arguments for inserting a new comment.
1964   *
1965   *     @type string     $comment_agent        The HTTP user agent of the `$comment_author` when
1966   *                                            the comment was submitted. Default empty.
1967   *     @type int|string $comment_approved     Whether the comment has been approved. Default 1.
1968   *     @type string     $comment_author       The name of the author of the comment. Default empty.
1969   *     @type string     $comment_author_email The email address of the `$comment_author`. Default empty.
1970   *     @type string     $comment_author_IP    The IP address of the `$comment_author`. Default empty.
1971   *     @type string     $comment_author_url   The URL address of the `$comment_author`. Default empty.
1972   *     @type string     $comment_content      The content of the comment. Default empty.
1973   *     @type string     $comment_date         The date the comment was submitted. To set the date
1974   *                                            manually, `$comment_date_gmt` must also be specified.
1975   *                                            Default is the current time.
1976   *     @type string     $comment_date_gmt     The date the comment was submitted in the GMT timezone.
1977   *                                            Default is `$comment_date` in the site's GMT timezone.
1978   *     @type int        $comment_karma        The karma of the comment. Default 0.
1979   *     @type int        $comment_parent       ID of this comment's parent, if any. Default 0.
1980   *     @type int        $comment_post_ID      ID of the post that relates to the comment, if any.
1981   *                                            Default 0.
1982   *     @type string     $comment_type         Comment type. Default 'comment'.
1983   *     @type array      $comment_meta         Optional. Array of key/value pairs to be stored in commentmeta for the
1984   *                                            new comment.
1985   *     @type int        $user_id              ID of the user who submitted the comment. Default 0.
1986   * }
1987   * @return int|false The new comment's ID on success, false on failure.
1988   */
1989  function wp_insert_comment( $commentdata ) {
1990      global $wpdb;
1991      $data = wp_unslash( $commentdata );
1992  
1993      $comment_author       = ! isset( $data['comment_author'] ) ? '' : $data['comment_author'];
1994      $comment_author_email = ! isset( $data['comment_author_email'] ) ? '' : $data['comment_author_email'];
1995      $comment_author_url   = ! isset( $data['comment_author_url'] ) ? '' : $data['comment_author_url'];
1996      $comment_author_IP    = ! isset( $data['comment_author_IP'] ) ? '' : $data['comment_author_IP'];
1997  
1998      $comment_date     = ! isset( $data['comment_date'] ) ? current_time( 'mysql' ) : $data['comment_date'];
1999      $comment_date_gmt = ! isset( $data['comment_date_gmt'] ) ? get_gmt_from_date( $comment_date ) : $data['comment_date_gmt'];
2000  
2001      $comment_post_ID  = ! isset( $data['comment_post_ID'] ) ? 0 : $data['comment_post_ID'];
2002      $comment_content  = ! isset( $data['comment_content'] ) ? '' : $data['comment_content'];
2003      $comment_karma    = ! isset( $data['comment_karma'] ) ? 0 : $data['comment_karma'];
2004      $comment_approved = ! isset( $data['comment_approved'] ) ? 1 : $data['comment_approved'];
2005      $comment_agent    = ! isset( $data['comment_agent'] ) ? '' : $data['comment_agent'];
2006      $comment_type     = empty( $data['comment_type'] ) ? 'comment' : $data['comment_type'];
2007      $comment_parent   = ! isset( $data['comment_parent'] ) ? 0 : $data['comment_parent'];
2008  
2009      $user_id = ! isset( $data['user_id'] ) ? 0 : $data['user_id'];
2010  
2011      $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' );
2012      if ( ! $wpdb->insert( $wpdb->comments, $compacted ) ) {
2013          return false;
2014      }
2015  
2016      $id = (int) $wpdb->insert_id;
2017  
2018      if ( 1 == $comment_approved ) {
2019          wp_update_comment_count( $comment_post_ID );
2020  
2021          foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
2022              wp_cache_delete( "lastcommentmodified:$timezone", 'timeinfo' );
2023          }
2024      }
2025  
2026      clean_comment_cache( $id );
2027  
2028      $comment = get_comment( $id );
2029  
2030      // If metadata is provided, store it.
2031      if ( isset( $commentdata['comment_meta'] ) && is_array( $commentdata['comment_meta'] ) ) {
2032          foreach ( $commentdata['comment_meta'] as $meta_key => $meta_value ) {
2033              add_comment_meta( $comment->comment_ID, $meta_key, $meta_value, true );
2034          }
2035      }
2036  
2037      /**
2038       * Fires immediately after a comment is inserted into the database.
2039       *
2040       * @since 2.8.0
2041       *
2042       * @param int        $id      The comment ID.
2043       * @param WP_Comment $comment Comment object.
2044       */
2045      do_action( 'wp_insert_comment', $id, $comment );
2046  
2047      return $id;
2048  }
2049  
2050  /**
2051   * Filters and sanitizes comment data.
2052   *
2053   * Sets the comment data 'filtered' field to true when finished. This can be
2054   * checked as to whether the comment should be filtered and to keep from
2055   * filtering the same comment more than once.
2056   *
2057   * @since 2.0.0
2058   *
2059   * @param array $commentdata Contains information on the comment.
2060   * @return array Parsed comment information.
2061   */
2062  function wp_filter_comment( $commentdata ) {
2063      if ( isset( $commentdata['user_ID'] ) ) {
2064          /**
2065           * Filters the comment author's user ID before it is set.
2066           *
2067           * The first time this filter is evaluated, 'user_ID' is checked
2068           * (for back-compat), followed by the standard 'user_id' value.
2069           *
2070           * @since 1.5.0
2071           *
2072           * @param int $user_ID The comment author's user ID.
2073           */
2074          $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_ID'] );
2075      } elseif ( isset( $commentdata['user_id'] ) ) {
2076          /** This filter is documented in wp-includes/comment.php */
2077          $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_id'] );
2078      }
2079  
2080      /**
2081       * Filters the comment author's browser user agent before it is set.
2082       *
2083       * @since 1.5.0
2084       *
2085       * @param string $comment_agent The comment author's browser user agent.
2086       */
2087      $commentdata['comment_agent'] = apply_filters( 'pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
2088      /** This filter is documented in wp-includes/comment.php */
2089      $commentdata['comment_author'] = apply_filters( 'pre_comment_author_name', $commentdata['comment_author'] );
2090      /**
2091       * Filters the comment content before it is set.
2092       *
2093       * @since 1.5.0
2094       *
2095       * @param string $comment_content The comment content.
2096       */
2097      $commentdata['comment_content'] = apply_filters( 'pre_comment_content', $commentdata['comment_content'] );
2098      /**
2099       * Filters the comment author's IP address before it is set.
2100       *
2101       * @since 1.5.0
2102       *
2103       * @param string $comment_author_ip The comment author's IP address.
2104       */
2105      $commentdata['comment_author_IP'] = apply_filters( 'pre_comment_user_ip', $commentdata['comment_author_IP'] );
2106      /** This filter is documented in wp-includes/comment.php */
2107      $commentdata['comment_author_url'] = apply_filters( 'pre_comment_author_url', $commentdata['comment_author_url'] );
2108      /** This filter is documented in wp-includes/comment.php */
2109      $commentdata['comment_author_email'] = apply_filters( 'pre_comment_author_email', $commentdata['comment_author_email'] );
2110      $commentdata['filtered']             = true;
2111      return $commentdata;
2112  }
2113  
2114  /**
2115   * Whether a comment should be blocked because of comment flood.
2116   *
2117   * @since 2.1.0
2118   *
2119   * @param bool $block            Whether plugin has already blocked comment.
2120   * @param int  $time_lastcomment Timestamp for last comment.
2121   * @param int  $time_newcomment  Timestamp for new comment.
2122   * @return bool Whether comment should be blocked.
2123   */
2124  function wp_throttle_comment_flood( $block, $time_lastcomment, $time_newcomment ) {
2125      if ( $block ) { // A plugin has already blocked... we'll let that decision stand.
2126          return $block;
2127      }
2128      if ( ( $time_newcomment - $time_lastcomment ) < 15 ) {
2129          return true;
2130      }
2131      return false;
2132  }
2133  
2134  /**
2135   * Adds a new comment to the database.
2136   *
2137   * Filters new comment to ensure that the fields are sanitized and valid before
2138   * inserting comment into database. Calls {@see 'comment_post'} action with comment ID
2139   * and whether comment is approved by WordPress. Also has {@see 'preprocess_comment'}
2140   * filter for processing the comment data before the function handles it.
2141   *
2142   * We use `REMOTE_ADDR` here directly. If you are behind a proxy, you should ensure
2143   * that it is properly set, such as in wp-config.php, for your environment.
2144   *
2145   * See {@link https://core.trac.wordpress.org/ticket/9235}
2146   *
2147   * @since 1.5.0
2148   * @since 4.3.0 Introduced the `comment_agent` and `comment_author_IP` arguments.
2149   * @since 4.7.0 The `$avoid_die` parameter was added, allowing the function
2150   *              to return a WP_Error object instead of dying.
2151   * @since 5.5.0 The `$avoid_die` parameter was renamed to `$wp_error`.
2152   * @since 5.5.0 Introduced the `comment_type` argument.
2153   *
2154   * @see wp_insert_comment()
2155   * @global wpdb $wpdb WordPress database abstraction object.
2156   *
2157   * @param array $commentdata {
2158   *     Comment data.
2159   *
2160   *     @type string $comment_author       The name of the comment author.
2161   *     @type string $comment_author_email The comment author email address.
2162   *     @type string $comment_author_url   The comment author URL.
2163   *     @type string $comment_content      The content of the comment.
2164   *     @type string $comment_date         The date the comment was submitted. Default is the current time.
2165   *     @type string $comment_date_gmt     The date the comment was submitted in the GMT timezone.
2166   *                                        Default is `$comment_date` in the GMT timezone.
2167   *     @type string $comment_type         Comment type. Default 'comment'.
2168   *     @type int    $comment_parent       The ID of this comment's parent, if any. Default 0.
2169   *     @type int    $comment_post_ID      The ID of the post that relates to the comment.
2170   *     @type int    $user_id              The ID of the user who submitted the comment. Default 0.
2171   *     @type int    $user_ID              Kept for backward-compatibility. Use `$user_id` instead.
2172   *     @type string $comment_agent        Comment author user agent. Default is the value of 'HTTP_USER_AGENT'
2173   *                                        in the `$_SERVER` superglobal sent in the original request.
2174   *     @type string $comment_author_IP    Comment author IP address in IPv4 format. Default is the value of
2175   *                                        'REMOTE_ADDR' in the `$_SERVER` superglobal sent in the original request.
2176   * }
2177   * @param bool  $wp_error Should errors be returned as WP_Error objects instead of
2178   *                        executing wp_die()? Default false.
2179   * @return int|false|WP_Error The ID of the comment on success, false or WP_Error on failure.
2180   */
2181  function wp_new_comment( $commentdata, $wp_error = false ) {
2182      global $wpdb;
2183  
2184      if ( isset( $commentdata['user_ID'] ) ) {
2185          $commentdata['user_ID'] = (int) $commentdata['user_ID'];
2186          $commentdata['user_id'] = $commentdata['user_ID'];
2187      }
2188  
2189      $prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0;
2190  
2191      if ( ! isset( $commentdata['comment_author_IP'] ) ) {
2192          $commentdata['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
2193      }
2194  
2195      if ( ! isset( $commentdata['comment_agent'] ) ) {
2196          $commentdata['comment_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '';
2197      }
2198  
2199      /**
2200       * Filters a comment's data before it is sanitized and inserted into the database.
2201       *
2202       * @since 1.5.0
2203       * @since 5.6.0 Comment data includes the `comment_agent` and `comment_author_IP` values.
2204       *
2205       * @param array $commentdata Comment data.
2206       */
2207      $commentdata = apply_filters( 'preprocess_comment', $commentdata );
2208  
2209      $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
2210      if ( isset( $commentdata['user_ID'] ) && $prefiltered_user_id !== (int) $commentdata['user_ID'] ) {
2211          $commentdata['user_ID'] = (int) $commentdata['user_ID'];
2212          $commentdata['user_id'] = $commentdata['user_ID'];
2213      } elseif ( isset( $commentdata['user_id'] ) ) {
2214          $commentdata['user_id'] = (int) $commentdata['user_id'];
2215      }
2216  
2217      $commentdata['comment_parent'] = isset( $commentdata['comment_parent'] ) ? absint( $commentdata['comment_parent'] ) : 0;
2218  
2219      $parent_status = ( $commentdata['comment_parent'] > 0 ) ? wp_get_comment_status( $commentdata['comment_parent'] ) : '';
2220  
2221      $commentdata['comment_parent'] = ( 'approved' === $parent_status || 'unapproved' === $parent_status ) ? $commentdata['comment_parent'] : 0;
2222  
2223      $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '', $commentdata['comment_author_IP'] );
2224  
2225      $commentdata['comment_agent'] = substr( $commentdata['comment_agent'], 0, 254 );
2226  
2227      if ( empty( $commentdata['comment_date'] ) ) {
2228          $commentdata['comment_date'] = current_time( 'mysql' );
2229      }
2230  
2231      if ( empty( $commentdata['comment_date_gmt'] ) ) {
2232          $commentdata['comment_date_gmt'] = current_time( 'mysql', 1 );
2233      }
2234  
2235      if ( empty( $commentdata['comment_type'] ) ) {
2236          $commentdata['comment_type'] = 'comment';
2237      }
2238  
2239      $commentdata = wp_filter_comment( $commentdata );
2240  
2241      $commentdata['comment_approved'] = wp_allow_comment( $commentdata, $wp_error );
2242      if ( is_wp_error( $commentdata['comment_approved'] ) ) {
2243          return $commentdata['comment_approved'];
2244      }
2245  
2246      $comment_ID = wp_insert_comment( $commentdata );
2247      if ( ! $comment_ID ) {
2248          $fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' );
2249  
2250          foreach ( $fields as $field ) {
2251              if ( isset( $commentdata[ $field ] ) ) {
2252                  $commentdata[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $commentdata[ $field ] );
2253              }
2254          }
2255  
2256          $commentdata = wp_filter_comment( $commentdata );
2257  
2258          $commentdata['comment_approved'] = wp_allow_comment( $commentdata, $wp_error );
2259          if ( is_wp_error( $commentdata['comment_approved'] ) ) {
2260              return $commentdata['comment_approved'];
2261          }
2262  
2263          $comment_ID = wp_insert_comment( $commentdata );
2264          if ( ! $comment_ID ) {
2265              return false;
2266          }
2267      }
2268  
2269      /**
2270       * Fires immediately after a comment is inserted into the database.
2271       *
2272       * @since 1.2.0
2273       * @since 4.5.0 The `$commentdata` parameter was added.
2274       *
2275       * @param int        $comment_ID       The comment ID.
2276       * @param int|string $comment_approved 1 if the comment is approved, 0 if not, 'spam' if spam.
2277       * @param array      $commentdata      Comment data.
2278       */
2279      do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'], $commentdata );
2280  
2281      return $comment_ID;
2282  }
2283  
2284  /**
2285   * Send a comment moderation notification to the comment moderator.
2286   *
2287   * @since 4.4.0
2288   *
2289   * @param int $comment_ID ID of the comment.
2290   * @return bool True on success, false on failure.
2291   */
2292  function wp_new_comment_notify_moderator( $comment_ID ) {
2293      $comment = get_comment( $comment_ID );
2294  
2295      // Only send notifications for pending comments.
2296      $maybe_notify = ( '0' == $comment->comment_approved );
2297  
2298      /** This filter is documented in wp-includes/comment.php */
2299      $maybe_notify = apply_filters( 'notify_moderator', $maybe_notify, $comment_ID );
2300  
2301      if ( ! $maybe_notify ) {
2302          return false;
2303      }
2304  
2305      return wp_notify_moderator( $comment_ID );
2306  }
2307  
2308  /**
2309   * Send a notification of a new comment to the post author.
2310   *
2311   * @since 4.4.0
2312   *
2313   * Uses the {@see 'notify_post_author'} filter to determine whether the post author
2314   * should be notified when a new comment is added, overriding site setting.
2315   *
2316   * @param int $comment_ID Comment ID.
2317   * @return bool True on success, false on failure.
2318   */
2319  function wp_new_comment_notify_postauthor( $comment_ID ) {
2320      $comment = get_comment( $comment_ID );
2321  
2322      $maybe_notify = get_option( 'comments_notify' );
2323  
2324      /**
2325       * Filters whether to send the post author new comment notification emails,
2326       * overriding the site setting.
2327       *
2328       * @since 4.4.0
2329       *
2330       * @param bool $maybe_notify Whether to notify the post author about the new comment.
2331       * @param int  $comment_ID   The ID of the comment for the notification.
2332       */
2333      $maybe_notify = apply_filters( 'notify_post_author', $maybe_notify, $comment_ID );
2334  
2335      /*
2336       * wp_notify_postauthor() checks if notifying the author of their own comment.
2337       * By default, it won't, but filters can override this.
2338       */
2339      if ( ! $maybe_notify ) {
2340          return false;
2341      }
2342  
2343      // Only send notifications for approved comments.
2344      if ( ! isset( $comment->comment_approved ) || '1' != $comment->comment_approved ) {
2345          return false;
2346      }
2347  
2348      return wp_notify_postauthor( $comment_ID );
2349  }
2350  
2351  /**
2352   * Sets the status of a comment.
2353   *
2354   * The {@see 'wp_set_comment_status'} action is called after the comment is handled.
2355   * If the comment status is not in the list, then false is returned.
2356   *
2357   * @since 1.0.0
2358   *
2359   * @global wpdb $wpdb WordPress database abstraction object.
2360   *
2361   * @param int|WP_Comment $comment_id     Comment ID or WP_Comment object.
2362   * @param string         $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
2363   * @param bool           $wp_error       Whether to return a WP_Error object if there is a failure. Default false.
2364   * @return bool|WP_Error True on success, false or WP_Error on failure.
2365   */
2366  function wp_set_comment_status( $comment_id, $comment_status, $wp_error = false ) {
2367      global $wpdb;
2368  
2369      switch ( $comment_status ) {
2370          case 'hold':
2371          case '0':
2372              $status = '0';
2373              break;
2374          case 'approve':
2375          case '1':
2376              $status = '1';
2377              add_action( 'wp_set_comment_status', 'wp_new_comment_notify_postauthor' );
2378              break;
2379          case 'spam':
2380              $status = 'spam';
2381              break;
2382          case 'trash':
2383              $status = 'trash';
2384              break;
2385          default:
2386              return false;
2387      }
2388  
2389      $comment_old = clone get_comment( $comment_id );
2390  
2391      if ( ! $wpdb->update( $wpdb->comments, array( 'comment_approved' => $status ), array( 'comment_ID' => $comment_old->comment_ID ) ) ) {
2392          if ( $wp_error ) {
2393              return new WP_Error( 'db_update_error', __( 'Could not update comment status.' ), $wpdb->last_error );
2394          } else {
2395              return false;
2396          }
2397      }
2398  
2399      clean_comment_cache( $comment_old->comment_ID );
2400  
2401      $comment = get_comment( $comment_old->comment_ID );
2402  
2403      /**
2404       * Fires immediately after transitioning a comment's status from one to another in the database
2405       * and removing the comment from the object cache, but prior to all status transition hooks.
2406       *
2407       * @since 1.5.0
2408       *
2409       * @param int         $comment_id     Comment ID.
2410       * @param string|bool $comment_status Current comment status. Possible values include
2411       *                                    'hold', 'approve', 'spam', 'trash', or false.
2412       */
2413      do_action( 'wp_set_comment_status', $comment->comment_ID, $comment_status );
2414  
2415      wp_transition_comment_status( $comment_status, $comment_old->comment_approved, $comment );
2416  
2417      wp_update_comment_count( $comment->comment_post_ID );
2418  
2419      return true;
2420  }
2421  
2422  /**
2423   * Updates an existing comment in the database.
2424   *
2425   * Filters the comment and makes sure certain fields are valid before updating.
2426   *
2427   * @since 2.0.0
2428   * @since 4.9.0 Add updating comment meta during comment update.
2429   * @since 5.5.0 The `$wp_error` parameter was added.
2430   * @since 5.5.0 The return values for an invalid comment or post ID
2431   *              were changed to false instead of 0.
2432   *
2433   * @global wpdb $wpdb WordPress database abstraction object.
2434   *
2435   * @param array $commentarr Contains information on the comment.
2436   * @param bool  $wp_error   Optional. Whether to return a WP_Error on failure. Default false.
2437   * @return int|false|WP_Error The value 1 if the comment was updated, 0 if not updated.
2438   *                            False or a WP_Error object on failure.
2439   */
2440  function wp_update_comment( $commentarr, $wp_error = false ) {
2441      global $wpdb;
2442  
2443      // First, get all of the original fields.
2444      $comment = get_comment( $commentarr['comment_ID'], ARRAY_A );
2445      if ( empty( $comment ) ) {
2446          if ( $wp_error ) {
2447              return new WP_Error( 'invalid_comment_id', __( 'Invalid comment ID.' ) );
2448          } else {
2449              return false;
2450          }
2451      }
2452  
2453      // Make sure that the comment post ID is valid (if specified).
2454      if ( ! empty( $commentarr['comment_post_ID'] ) && ! get_post( $commentarr['comment_post_ID'] ) ) {
2455          if ( $wp_error ) {
2456              return new WP_Error( 'invalid_post_id', __( 'Invalid post ID.' ) );
2457          } else {
2458              return false;
2459          }
2460      }
2461  
2462      // Escape data pulled from DB.
2463      $comment = wp_slash( $comment );
2464  
2465      $old_status = $comment['comment_approved'];
2466  
2467      // Merge old and new fields with new fields overwriting old ones.
2468      $commentarr = array_merge( $comment, $commentarr );
2469  
2470      $commentarr = wp_filter_comment( $commentarr );
2471  
2472      // Now extract the merged array.
2473      $data = wp_unslash( $commentarr );
2474  
2475      /**
2476       * Filters the comment content before it is updated in the database.
2477       *
2478       * @since 1.5.0
2479       *
2480       * @param string $comment_content The comment data.
2481       */
2482      $data['comment_content'] = apply_filters( 'comment_save_pre', $data['comment_content'] );
2483  
2484      $data['comment_date_gmt'] = get_gmt_from_date( $data['comment_date'] );
2485  
2486      if ( ! isset( $data['comment_approved'] ) ) {
2487          $data['comment_approved'] = 1;
2488      } elseif ( 'hold' === $data['comment_approved'] ) {
2489          $data['comment_approved'] = 0;
2490      } elseif ( 'approve' === $data['comment_approved'] ) {
2491          $data['comment_approved'] = 1;
2492      }
2493  
2494      $comment_ID      = $data['comment_ID'];
2495      $comment_post_ID = $data['comment_post_ID'];
2496  
2497      /**
2498       * Filters the comment data immediately before it is updated in the database.
2499       *
2500       * Note: data being passed to the filter is already unslashed.
2501       *
2502       * @since 4.7.0
2503       * @since 5.5.0 Returning a WP_Error value from the filter will short-circuit comment update
2504       *              and allow skipping further processing.
2505       *
2506       * @param array|WP_Error $data       The new, processed comment data, or WP_Error.
2507       * @param array          $comment    The old, unslashed comment data.
2508       * @param array          $commentarr The new, raw comment data.
2509       */
2510      $data = apply_filters( 'wp_update_comment_data', $data, $comment, $commentarr );
2511  
2512      // Do not carry on on failure.
2513      if ( is_wp_error( $data ) ) {
2514          if ( $wp_error ) {
2515              return $data;
2516          } else {
2517              return false;
2518          }
2519      }
2520  
2521      $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' );
2522      $data = wp_array_slice_assoc( $data, $keys );
2523  
2524      $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
2525  
2526      if ( false === $rval ) {
2527          if ( $wp_error ) {
2528              return new WP_Error( 'db_update_error', __( 'Could not update comment in the database.' ), $wpdb->last_error );
2529          } else {
2530              return false;
2531          }
2532      }
2533  
2534      // If metadata is provided, store it.
2535      if ( isset( $commentarr['comment_meta'] ) && is_array( $commentarr['comment_meta'] ) ) {
2536          foreach ( $commentarr['comment_meta'] as $meta_key => $meta_value ) {
2537              update_comment_meta( $comment_ID, $meta_key, $meta_value );
2538          }
2539      }
2540  
2541      clean_comment_cache( $comment_ID );
2542      wp_update_comment_count( $comment_post_ID );
2543  
2544      /**
2545       * Fires immediately after a comment is updated in the database.
2546       *
2547       * The hook also fires immediately before comment status transition hooks are fired.
2548       *
2549       * @since 1.2.0
2550       * @since 4.6.0 Added the `$data` parameter.
2551       *
2552       * @param int   $comment_ID The comment ID.
2553       * @param array $data       Comment data.
2554       */
2555      do_action( 'edit_comment', $comment_ID, $data );
2556  
2557      $comment = get_comment( $comment_ID );
2558  
2559      wp_transition_comment_status( $comment->comment_approved, $old_status, $comment );
2560  
2561      return $rval;
2562  }
2563  
2564  /**
2565   * Whether to defer comment counting.
2566   *
2567   * When setting $defer to true, all post comment counts will not be updated
2568   * until $defer is set to false. When $defer is set to false, then all
2569   * previously deferred updated post comment counts will then be automatically
2570   * updated without having to call wp_update_comment_count() after.
2571   *
2572   * @since 2.5.0
2573   *
2574   * @param bool $defer
2575   * @return bool
2576   */
2577  function wp_defer_comment_counting( $defer = null ) {
2578      static $_defer = false;
2579  
2580      if ( is_bool( $defer ) ) {
2581          $_defer = $defer;
2582          // Flush any deferred counts.
2583          if ( ! $defer ) {
2584              wp_update_comment_count( null, true );
2585          }
2586      }
2587  
2588      return $_defer;
2589  }
2590  
2591  /**
2592   * Updates the comment count for post(s).
2593   *
2594   * When $do_deferred is false (is by default) and the comments have been set to
2595   * be deferred, the post_id will be added to a queue, which will be updated at a
2596   * later date and only updated once per post ID.
2597   *
2598   * If the comments have not be set up to be deferred, then the post will be
2599   * updated. When $do_deferred is set to true, then all previous deferred post
2600   * IDs will be updated along with the current $post_id.
2601   *
2602   * @since 2.1.0
2603   *
2604   * @see wp_update_comment_count_now() For what could cause a false return value
2605   *
2606   * @param int|null $post_id     Post ID.
2607   * @param bool     $do_deferred Optional. Whether to process previously deferred
2608   *                              post comment counts. Default false.
2609   * @return bool|void True on success, false on failure or if post with ID does
2610   *                   not exist.
2611   */
2612  function wp_update_comment_count( $post_id, $do_deferred = false ) {
2613      static $_deferred = array();
2614  
2615      if ( empty( $post_id ) && ! $do_deferred ) {
2616          return false;
2617      }
2618  
2619      if ( $do_deferred ) {
2620          $_deferred = array_unique( $_deferred );
2621          foreach ( $_deferred as $i => $_post_id ) {
2622              wp_update_comment_count_now( $_post_id );
2623              unset( $_deferred[ $i ] );
2624              /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
2625          }
2626      }
2627  
2628      if ( wp_defer_comment_counting() ) {
2629          $_deferred[] = $post_id;
2630          return true;
2631      } elseif ( $post_id ) {
2632          return wp_update_comment_count_now( $post_id );
2633      }
2634  
2635  }
2636  
2637  /**
2638   * Updates the comment count for the post.
2639   *
2640   * @since 2.5.0
2641   *
2642   * @global wpdb $wpdb WordPress database abstraction object.
2643   *
2644   * @param int $post_id Post ID
2645   * @return bool True on success, false if the post does not exist.
2646   */
2647  function wp_update_comment_count_now( $post_id ) {
2648      global $wpdb;
2649      $post_id = (int) $post_id;
2650      if ( ! $post_id ) {
2651          return false;
2652      }
2653  
2654      wp_cache_delete( 'comments-0', 'counts' );
2655      wp_cache_delete( "comments-{$post_id}", 'counts' );
2656  
2657      $post = get_post( $post_id );
2658      if ( ! $post ) {
2659          return false;
2660      }
2661  
2662      $old = (int) $post->comment_count;
2663  
2664      /**
2665       * Filters a post's comment count before it is updated in the database.
2666       *
2667       * @since 4.5.0
2668       *
2669       * @param int|null $new     The new comment count. Default null.
2670       * @param int      $old     The old comment count.
2671       * @param int      $post_id Post ID.
2672       */
2673      $new = apply_filters( 'pre_wp_update_comment_count_now', null, $old, $post_id );
2674  
2675      if ( is_null( $new ) ) {
2676          $new = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id ) );
2677      } else {
2678          $new = (int) $new;
2679      }
2680  
2681      $wpdb->update( $wpdb->posts, array( 'comment_count' => $new ), array( 'ID' => $post_id ) );
2682  
2683      clean_post_cache( $post );
2684  
2685      /**
2686       * Fires immediately after a post's comment count is updated in the database.
2687       *
2688       * @since 2.3.0
2689       *
2690       * @param int $post_id Post ID.
2691       * @param int $new     The new comment count.
2692       * @param int $old     The old comment count.
2693       */
2694      do_action( 'wp_update_comment_count', $post_id, $new, $old );
2695  
2696      /** This action is documented in wp-includes/post.php */
2697      do_action( "edit_post_{$post->post_type}", $post_id, $post );
2698  
2699      /** This action is documented in wp-includes/post.php */
2700      do_action( 'edit_post', $post_id, $post );
2701  
2702      return true;
2703  }
2704  
2705  //
2706  // Ping and trackback functions.
2707  //
2708  
2709  /**
2710   * Finds a pingback server URI based on the given URL.
2711   *
2712   * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
2713   * a check for the x-pingback headers first and returns that, if available. The
2714   * check for the rel="pingback" has more overhead than just the header.
2715   *
2716   * @since 1.5.0
2717   *
2718   * @param string $url        URL to ping.
2719   * @param int    $deprecated Not Used.
2720   * @return string|false String containing URI on success, false on failure.
2721   */
2722  function discover_pingback_server_uri( $url, $deprecated = '' ) {
2723      if ( ! empty( $deprecated ) ) {
2724          _deprecated_argument( __FUNCTION__, '2.7.0' );
2725      }
2726  
2727      $pingback_str_dquote = 'rel="pingback"';
2728      $pingback_str_squote = 'rel=\'pingback\'';
2729  
2730      /** @todo Should use Filter Extension or custom preg_match instead. */
2731      $parsed_url = parse_url( $url );
2732  
2733      if ( ! isset( $parsed_url['host'] ) ) { // Not a URL. This should never happen.
2734          return false;
2735      }
2736  
2737      // Do not search for a pingback server on our own uploads.
2738      $uploads_dir = wp_get_upload_dir();
2739      if ( 0 === strpos( $url, $uploads_dir['baseurl'] ) ) {
2740          return false;
2741      }
2742  
2743      $response = wp_safe_remote_head(
2744          $url,
2745          array(
2746              'timeout'     => 2,
2747              'httpversion' => '1.0',
2748          )
2749      );
2750  
2751      if ( is_wp_error( $response ) ) {
2752          return false;
2753      }
2754  
2755      if ( wp_remote_retrieve_header( $response, 'x-pingback' ) ) {
2756          return wp_remote_retrieve_header( $response, 'x-pingback' );
2757      }
2758  
2759      // Not an (x)html, sgml, or xml page, no use going further.
2760      if ( preg_match( '#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'content-type' ) ) ) {
2761          return false;
2762      }
2763  
2764      // Now do a GET since we're going to look in the HTML headers (and we're sure it's not a binary file).
2765      $response = wp_safe_remote_get(
2766          $url,
2767          array(
2768              'timeout'     => 2,
2769              'httpversion' => '1.0',
2770          )
2771      );
2772  
2773      if ( is_wp_error( $response ) ) {
2774          return false;
2775      }
2776  
2777      $contents = wp_remote_retrieve_body( $response );
2778  
2779      $pingback_link_offset_dquote = strpos( $contents, $pingback_str_dquote );
2780      $pingback_link_offset_squote = strpos( $contents, $pingback_str_squote );
2781      if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
2782          $quote                   = ( $pingback_link_offset_dquote ) ? '"' : '\'';
2783          $pingback_link_offset    = ( '"' === $quote ) ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
2784          $pingback_href_pos       = strpos( $contents, 'href=', $pingback_link_offset );
2785          $pingback_href_start     = $pingback_href_pos + 6;
2786          $pingback_href_end       = strpos( $contents, $quote, $pingback_href_start );
2787          $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
2788          $pingback_server_url     = substr( $contents, $pingback_href_start, $pingback_server_url_len );
2789  
2790          // We may find rel="pingback" but an incomplete pingback URL.
2791          if ( $pingback_server_url_len > 0 ) { // We got it!
2792              return $pingback_server_url;
2793          }
2794      }
2795  
2796      return false;
2797  }
2798  
2799  /**
2800   * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
2801   *
2802   * @since 2.1.0
2803   * @since 5.6.0 Introduced `do_all_pings` action hook for individual services.
2804   */
2805  function do_all_pings() {
2806      /**
2807       * Fires immediately after the `do_pings` event to hook services individually.
2808       *
2809       * @since 5.6.0
2810       */
2811      do_action( 'do_all_pings' );
2812  }
2813  
2814  /**
2815   * Perform all pingbacks.
2816   *
2817   * @since 5.6.0
2818   */
2819  function do_all_pingbacks() {
2820      $pings = get_posts(
2821          array(
2822              'post_type'        => get_post_types(),
2823              'suppress_filters' => false,
2824              'nopaging'         => true,
2825              'meta_key'         => '_pingme',
2826              'fields'           => 'ids',
2827          )
2828      );
2829  
2830      foreach ( $pings as $ping ) {
2831          delete_post_meta( $ping, '_pingme' );
2832          pingback( null, $ping );
2833      }
2834  }
2835  
2836  /**
2837   * Perform all enclosures.
2838   *
2839   * @since 5.6.0
2840   */
2841  function do_all_enclosures() {
2842      $enclosures = get_posts(
2843          array(
2844              'post_type'        => get_post_types(),
2845              'suppress_filters' => false,
2846              'nopaging'         => true,
2847              'meta_key'         => '_encloseme',
2848              'fields'           => 'ids',
2849          )
2850      );
2851  
2852      foreach ( $enclosures as $enclosure ) {
2853          delete_post_meta( $enclosure, '_encloseme' );
2854          do_enclose( null, $enclosure );
2855      }
2856  }
2857  
2858  /**
2859   * Perform all trackbacks.
2860   *
2861   * @since 5.6.0
2862   */
2863  function do_all_trackbacks() {
2864      $trackbacks = get_posts(
2865          array(
2866              'post_type'        => get_post_types(),
2867              'suppress_filters' => false,
2868              'nopaging'         => true,
2869              'meta_key'         => '_trackbackme',
2870              'fields'           => 'ids',
2871          )
2872      );
2873  
2874      foreach ( $trackbacks as $trackback ) {
2875          delete_post_meta( $trackback, '_trackbackme' );
2876          do_trackbacks( $trackback );
2877      }
2878  }
2879  
2880  /**
2881   * Perform trackbacks.
2882   *
2883   * @since 1.5.0
2884   * @since 4.7.0 `$post_id` can be a WP_Post object.
2885   *
2886   * @global wpdb $wpdb WordPress database abstraction object.
2887   *
2888   * @param int|WP_Post $post_id Post object or ID to do trackbacks on.
2889   */
2890  function do_trackbacks( $post_id ) {
2891      global $wpdb;
2892      $post = get_post( $post_id );
2893      if ( ! $post ) {
2894          return false;
2895      }
2896  
2897      $to_ping = get_to_ping( $post );
2898      $pinged  = get_pung( $post );
2899      if ( empty( $to_ping ) ) {
2900          $wpdb->update( $wpdb->posts, array( 'to_ping' => '' ), array( 'ID' => $post->ID ) );
2901          return;
2902      }
2903  
2904      if ( empty( $post->post_excerpt ) ) {
2905          /** This filter is documented in wp-includes/post-template.php */
2906          $excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
2907      } else {
2908          /** This filter is documented in wp-includes/post-template.php */
2909          $excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );
2910      }
2911  
2912      $excerpt = str_replace( ']]>', ']]&gt;', $excerpt );
2913      $excerpt = wp_html_excerpt( $excerpt, 252, '&#8230;' );
2914  
2915      /** This filter is documented in wp-includes/post-template.php */
2916      $post_title = apply_filters( 'the_title', $post->post_title, $post->ID );
2917      $post_title = strip_tags( $post_title );
2918  
2919      if ( $to_ping ) {
2920          foreach ( (array) $to_ping as $tb_ping ) {
2921              $tb_ping = trim( $tb_ping );
2922              if ( ! in_array( $tb_ping, $pinged, true ) ) {
2923                  trackback( $tb_ping, $post_title, $excerpt, $post->ID );
2924                  $pinged[] = $tb_ping;
2925              } else {
2926                  $wpdb->query(
2927                      $wpdb->prepare(
2928                          "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s,
2929                      '')) WHERE ID = %d",
2930                          $tb_ping,
2931                          $post->ID
2932                      )
2933                  );
2934              }
2935          }
2936      }
2937  }
2938  
2939  /**
2940   * Sends pings to all of the ping site services.
2941   *
2942   * @since 1.2.0
2943   *
2944   * @param int $post_id Post ID.
2945   * @return int Same as Post ID from parameter
2946   */
2947  function generic_ping( $post_id = 0 ) {
2948      $services = get_option( 'ping_sites' );
2949  
2950      $services = explode( "\n", $services );
2951      foreach ( (array) $services as $service ) {
2952          $service = trim( $service );
2953          if ( '' !== $service ) {
2954              weblog_ping( $service );
2955          }
2956      }
2957  
2958      return $post_id;
2959  }
2960  
2961  /**
2962   * Pings back the links found in a post.
2963   *
2964   * @since 0.71
2965   * @since 4.7.0 `$post_id` can be a WP_Post object.
2966   *
2967   * @param string      $content Post content to check for links. If empty will retrieve from post.
2968   * @param int|WP_Post $post_id Post Object or ID.
2969   */
2970  function pingback( $content, $post_id ) {
2971      include_once  ABSPATH . WPINC . '/class-IXR.php';
2972      include_once  ABSPATH . WPINC . '/class-wp-http-ixr-client.php';
2973  
2974      // Original code by Mort (http://mort.mine.nu:8080).
2975      $post_links = array();
2976  
2977      $post = get_post( $post_id );
2978      if ( ! $post ) {
2979          return;
2980      }
2981  
2982      $pung = get_pung( $post );
2983  
2984      if ( empty( $content ) ) {
2985          $content = $post->post_content;
2986      }
2987  
2988      /*
2989       * Step 1.
2990       * Parsing the post, external links (if any) are stored in the $post_links array.
2991       */
2992      $post_links_temp = wp_extract_urls( $content );
2993  
2994      /*
2995       * Step 2.
2996       * Walking through the links array.
2997       * First we get rid of links pointing to sites, not to specific files.
2998       * Example:
2999       * http://dummy-weblog.org
3000       * http://dummy-weblog.org/
3001       * http://dummy-weblog.org/post.php
3002       * We don't wanna ping first and second types, even if they have a valid <link/>.
3003       */
3004      foreach ( (array) $post_links_temp as $link_test ) {
3005          // If we haven't pung it already and it isn't a link to itself.
3006          if ( ! in_array( $link_test, $pung, true ) && ( url_to_postid( $link_test ) != $post->ID )
3007              // Also, let's never ping local attachments.
3008              && ! is_local_attachment( $link_test )
3009          ) {
3010              $test = parse_url( $link_test );
3011              if ( $test ) {
3012                  if ( isset( $test['query'] ) ) {
3013                      $post_links[] = $link_test;
3014                  } elseif ( isset( $test['path'] ) && ( '/' !== $test['path'] ) && ( '' !== $test['path'] ) ) {
3015                      $post_links[] = $link_test;
3016                  }
3017              }
3018          }
3019      }
3020  
3021      $post_links = array_unique( $post_links );
3022  
3023      /**
3024       * Fires just before pinging back links found in a post.
3025       *
3026       * @since 2.0.0
3027       *
3028       * @param string[] $post_links Array of link URLs to be checked (passed by reference).
3029       * @param string[] $pung       Array of link URLs already pinged (passed by reference).
3030       * @param int      $post_ID    The post ID.
3031       */
3032      do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post->ID ) );
3033  
3034      foreach ( (array) $post_links as $pagelinkedto ) {
3035          $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
3036  
3037          if ( $pingback_server_url ) {
3038              set_time_limit( 60 );
3039              // Now, the RPC call.
3040              $pagelinkedfrom = get_permalink( $post );
3041  
3042              // Using a timeout of 3 seconds should be enough to cover slow servers.
3043              $client          = new WP_HTTP_IXR_Client( $pingback_server_url );
3044              $client->timeout = 3;
3045              /**
3046               * Filters the user agent sent when pinging-back a URL.
3047               *
3048               * @since 2.9.0
3049               *
3050               * @param string $concat_useragent    The user agent concatenated with ' -- WordPress/'
3051               *                                    and the WordPress version.
3052               * @param string $useragent           The useragent.
3053               * @param string $pingback_server_url The server URL being linked to.
3054               * @param string $pagelinkedto        URL of page linked to.
3055               * @param string $pagelinkedfrom      URL of page linked from.
3056               */
3057              $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . get_bloginfo( 'version' ), $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom );
3058              // When set to true, this outputs debug messages by itself.
3059              $client->debug = false;
3060  
3061              if ( $client->query( 'pingback.ping', $pagelinkedfrom, $pagelinkedto ) || ( isset( $client->error->code ) && 48 == $client->error->code ) ) { // Already registered.
3062                  add_ping( $post, $pagelinkedto );
3063              }
3064          }
3065      }
3066  }
3067  
3068  /**
3069   * Check whether blog is public before returning sites.
3070   *
3071   * @since 2.1.0
3072   *
3073   * @param mixed $sites Will return if blog is public, will not return if not public.
3074   * @return mixed Empty string if blog is not public, returns $sites, if site is public.
3075   */
3076  function privacy_ping_filter( $sites ) {
3077      if ( '0' != get_option( 'blog_public' ) ) {
3078          return $sites;
3079      } else {
3080          return '';
3081      }
3082  }
3083  
3084  /**
3085   * Send a Trackback.
3086   *
3087   * Updates database when sending trackback to prevent duplicates.
3088   *
3089   * @since 0.71
3090   *
3091   * @global wpdb $wpdb WordPress database abstraction object.
3092   *
3093   * @param string $trackback_url URL to send trackbacks.
3094   * @param string $title         Title of post.
3095   * @param string $excerpt       Excerpt of post.
3096   * @param int    $ID            Post ID.
3097   * @return int|false|void Database query from update.
3098   */
3099  function trackback( $trackback_url, $title, $excerpt, $ID ) {
3100      global $wpdb;
3101  
3102      if ( empty( $trackback_url ) ) {
3103          return;
3104      }
3105  
3106      $options            = array();
3107      $options['timeout'] = 10;
3108      $options['body']    = array(
3109          'title'     => $title,
3110          'url'       => get_permalink( $ID ),
3111          'blog_name' => get_option( 'blogname' ),
3112          'excerpt'   => $excerpt,
3113      );
3114  
3115      $response = wp_safe_remote_post( $trackback_url, $options );
3116  
3117      if ( is_wp_error( $response ) ) {
3118          return;
3119      }
3120  
3121      $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID ) );
3122      return $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID ) );
3123  }
3124  
3125  /**
3126   * Send a pingback.
3127   *
3128   * @since 1.2.0
3129   *
3130   * @param string $server Host of blog to connect to.
3131   * @param string $path Path to send the ping.
3132   */
3133  function weblog_ping( $server = '', $path = '' ) {
3134      include_once  ABSPATH . WPINC . '/class-IXR.php';
3135      include_once  ABSPATH . WPINC . '/class-wp-http-ixr-client.php';
3136  
3137      // Using a timeout of 3 seconds should be enough to cover slow servers.
3138      $client             = new WP_HTTP_IXR_Client( $server, ( ( ! strlen( trim( $path ) ) || ( '/' === $path ) ) ? false : $path ) );
3139      $client->timeout    = 3;
3140      $client->useragent .= ' -- WordPress/' . get_bloginfo( 'version' );
3141  
3142      // When set to true, this outputs debug messages by itself.
3143      $client->debug = false;
3144      $home          = trailingslashit( home_url() );
3145      if ( ! $client->query( 'weblogUpdates.extendedPing', get_option( 'blogname' ), $home, get_bloginfo( 'rss2_url' ) ) ) { // Then try a normal ping.
3146          $client->query( 'weblogUpdates.ping', get_option( 'blogname' ), $home );
3147      }
3148  }
3149  
3150  /**
3151   * Default filter attached to pingback_ping_source_uri to validate the pingback's Source URI
3152   *
3153   * @since 3.5.1
3154   *
3155   * @see wp_http_validate_url()
3156   *
3157   * @param string $source_uri
3158   * @return string
3159   */
3160  function pingback_ping_source_uri( $source_uri ) {
3161      return (string) wp_http_validate_url( $source_uri );
3162  }
3163  
3164  /**
3165   * Default filter attached to xmlrpc_pingback_error.
3166   *
3167   * Returns a generic pingback error code unless the error code is 48,
3168   * which reports that the pingback is already registered.
3169   *
3170   * @since 3.5.1
3171   *
3172   * @link https://www.hixie.ch/specs/pingback/pingback#TOC3
3173   *
3174   * @param IXR_Error $ixr_error
3175   * @return IXR_Error
3176   */
3177  function xmlrpc_pingback_error( $ixr_error ) {
3178      if ( 48 === $ixr_error->code ) {
3179          return $ixr_error;
3180      }
3181      return new IXR_Error( 0, '' );
3182  }
3183  
3184  //
3185  // Cache.
3186  //
3187  
3188  /**
3189   * Removes a comment from the object cache.
3190   *
3191   * @since 2.3.0
3192   *
3193   * @param int|array $ids Comment ID or an array of comment IDs to remove from cache.
3194   */
3195  function clean_comment_cache( $ids ) {
3196      foreach ( (array) $ids as $id ) {
3197          wp_cache_delete( $id, 'comment' );
3198  
3199          /**
3200           * Fires immediately after a comment has been removed from the object cache.
3201           *
3202           * @since 4.5.0
3203           *
3204           * @param int $id Comment ID.
3205           */
3206          do_action( 'clean_comment_cache', $id );
3207      }
3208  
3209      wp_cache_set( 'last_changed', microtime(), 'comment' );
3210  }
3211  
3212  /**
3213   * Updates the comment cache of given comments.
3214   *
3215   * Will add the comments in $comments to the cache. If comment ID already exists
3216   * in the comment cache then it will not be updated. The comment is added to the
3217   * cache using the comment group with the key using the ID of the comments.
3218   *
3219   * @since 2.3.0
3220   * @since 4.4.0 Introduced the `$update_meta_cache` parameter.
3221   *
3222   * @param WP_Comment[] $comments          Array of comment objects
3223   * @param bool         $update_meta_cache Whether to update commentmeta cache. Default true.
3224   */
3225  function update_comment_cache( $comments, $update_meta_cache = true ) {
3226      foreach ( (array) $comments as $comment ) {
3227          wp_cache_add( $comment->comment_ID, $comment, 'comment' );
3228      }
3229  
3230      if ( $update_meta_cache ) {
3231          // Avoid `wp_list_pluck()` in case `$comments` is passed by reference.
3232          $comment_ids = array();
3233          foreach ( $comments as $comment ) {
3234              $comment_ids[] = $comment->comment_ID;
3235          }
3236          update_meta_cache( 'comment', $comment_ids );
3237      }
3238  }
3239  
3240  /**
3241   * Adds any comments from the given IDs to the cache that do not already exist in cache.
3242   *
3243   * @since 4.4.0
3244   * @access private
3245   *
3246   * @see update_comment_cache()
3247   * @global wpdb $wpdb WordPress database abstraction object.
3248   *
3249   * @param int[] $comment_ids       Array of comment IDs.
3250   * @param bool  $update_meta_cache Optional. Whether to update the meta cache. Default true.
3251   */
3252  function _prime_comment_caches( $comment_ids, $update_meta_cache = true ) {
3253      global $wpdb;
3254  
3255      $non_cached_ids = _get_non_cached_ids( $comment_ids, 'comment' );
3256      if ( ! empty( $non_cached_ids ) ) {
3257          $fresh_comments = $wpdb->get_results( sprintf( "SELECT $wpdb->comments.* FROM $wpdb->comments WHERE comment_ID IN (%s)", implode( ',', array_map( 'intval', $non_cached_ids ) ) ) );
3258  
3259          update_comment_cache( $fresh_comments, $update_meta_cache );
3260      }
3261  }
3262  
3263  //
3264  // Internal.
3265  //
3266  
3267  /**
3268   * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
3269   *
3270   * @since 2.7.0
3271   * @access private
3272   *
3273   * @param WP_Post  $posts Post data object.
3274   * @param WP_Query $query Query object.
3275   * @return array
3276   */
3277  function _close_comments_for_old_posts( $posts, $query ) {
3278      if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) ) {
3279          return $posts;
3280      }
3281  
3282      /**
3283       * Filters the list of post types to automatically close comments for.
3284       *
3285       * @since 3.2.0
3286       *
3287       * @param string[] $post_types An array of post type names.
3288       */
3289      $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
3290      if ( ! in_array( $posts[0]->post_type, $post_types, true ) ) {
3291          return $posts;
3292      }
3293  
3294      $days_old = (int) get_option( 'close_comments_days_old' );
3295      if ( ! $days_old ) {
3296          return $posts;
3297      }
3298  
3299      if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
3300          $posts[0]->comment_status = 'closed';
3301          $posts[0]->ping_status    = 'closed';
3302      }
3303  
3304      return $posts;
3305  }
3306  
3307  /**
3308   * Close comments on an old post. Hooked to comments_open and pings_open.
3309   *
3310   * @since 2.7.0
3311   * @access private
3312   *
3313   * @param bool $open    Comments open or closed.
3314   * @param int  $post_id Post ID.
3315   * @return bool $open
3316   */
3317  function _close_comments_for_old_post( $open, $post_id ) {
3318      if ( ! $open ) {
3319          return $open;
3320      }
3321  
3322      if ( ! get_option( 'close_comments_for_old_posts' ) ) {
3323          return $open;
3324      }
3325  
3326      $days_old = (int) get_option( 'close_comments_days_old' );
3327      if ( ! $days_old ) {
3328          return $open;
3329      }
3330  
3331      $post = get_post( $post_id );
3332  
3333      /** This filter is documented in wp-includes/comment.php */
3334      $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
3335      if ( ! in_array( $post->post_type, $post_types, true ) ) {
3336          return $open;
3337      }
3338  
3339      // Undated drafts should not show up as comments closed.
3340      if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
3341          return $open;
3342      }
3343  
3344      if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
3345          return false;
3346      }
3347  
3348      return $open;
3349  }
3350  
3351  /**
3352   * Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form.
3353   *
3354   * This function expects unslashed data, as opposed to functions such as `wp_new_comment()` which
3355   * expect slashed data.
3356   *
3357   * @since 4.4.0
3358   *
3359   * @param array $comment_data {
3360   *     Comment data.
3361   *
3362   *     @type string|int $comment_post_ID             The ID of the post that relates to the comment.
3363   *     @type string     $author                      The name of the comment author.
3364   *     @type string     $email                       The comment author email address.
3365   *     @type string     $url                         The comment author URL.
3366   *     @type string     $comment                     The content of the comment.
3367   *     @type string|int $comment_parent              The ID of this comment's parent, if any. Default 0.
3368   *     @type string     $_wp_unfiltered_html_comment The nonce value for allowing unfiltered HTML.
3369   * }
3370   * @return WP_Comment|WP_Error A WP_Comment object on success, a WP_Error object on failure.
3371   */
3372  function wp_handle_comment_submission( $comment_data ) {
3373  
3374      $comment_post_ID      = 0;
3375      $comment_parent       = 0;
3376      $user_ID              = 0;
3377      $comment_author       = null;
3378      $comment_author_email = null;
3379      $comment_author_url   = null;
3380      $comment_content      = null;
3381  
3382      if ( isset( $comment_data['comment_post_ID'] ) ) {
3383          $comment_post_ID = (int) $comment_data['comment_post_ID'];
3384      }
3385      if ( isset( $comment_data['author'] ) && is_string( $comment_data['author'] ) ) {
3386          $comment_author = trim( strip_tags( $comment_data['author'] ) );
3387      }
3388      if ( isset( $comment_data['email'] ) && is_string( $comment_data['email'] ) ) {
3389          $comment_author_email = trim( $comment_data['email'] );
3390      }
3391      if ( isset( $comment_data['url'] ) && is_string( $comment_data['url'] ) ) {
3392          $comment_author_url = trim( $comment_data['url'] );
3393      }
3394      if ( isset( $comment_data['comment'] ) && is_string( $comment_data['comment'] ) ) {
3395          $comment_content = trim( $comment_data['comment'] );
3396      }
3397      if ( isset( $comment_data['comment_parent'] ) ) {
3398          $comment_parent = absint( $comment_data['comment_parent'] );
3399      }
3400  
3401      $post = get_post( $comment_post_ID );
3402  
3403      if ( empty( $post->comment_status ) ) {
3404  
3405          /**
3406           * Fires when a comment is attempted on a post that does not exist.
3407           *
3408           * @since 1.5.0
3409           *
3410           * @param int $comment_post_ID Post ID.
3411           */
3412          do_action( 'comment_id_not_found', $comment_post_ID );
3413  
3414          return new WP_Error( 'comment_id_not_found' );
3415  
3416      }
3417  
3418      // get_post_status() will get the parent status for attachments.
3419      $status = get_post_status( $post );
3420  
3421      if ( ( 'private' === $status ) && ! current_user_can( 'read_post', $comment_post_ID ) ) {
3422          return new WP_Error( 'comment_id_not_found' );
3423      }
3424  
3425      $status_obj = get_post_status_object( $status );
3426  
3427      if ( ! comments_open( $comment_post_ID ) ) {
3428  
3429          /**
3430           * Fires when a comment is attempted on a post that has comments closed.
3431           *
3432           * @since 1.5.0
3433           *
3434           * @param int $comment_post_ID Post ID.
3435           */
3436          do_action( 'comment_closed', $comment_post_ID );
3437  
3438          return new WP_Error( 'comment_closed', __( 'Sorry, comments are closed for this item.' ), 403 );
3439  
3440      } elseif ( 'trash' === $status ) {
3441  
3442          /**
3443           * Fires when a comment is attempted on a trashed post.
3444           *
3445           * @since 2.9.0
3446           *
3447           * @param int $comment_post_ID Post ID.
3448           */
3449          do_action( 'comment_on_trash', $comment_post_ID );
3450  
3451          return new WP_Error( 'comment_on_trash' );
3452  
3453      } elseif ( ! $status_obj->public && ! $status_obj->private ) {
3454  
3455          /**
3456           * Fires when a comment is attempted on a post in draft mode.
3457           *
3458           * @since 1.5.1
3459           *
3460           * @param int $comment_post_ID Post ID.
3461           */
3462          do_action( 'comment_on_draft', $comment_post_ID );
3463  
3464          if ( current_user_can( 'read_post', $comment_post_ID ) ) {
3465              return new WP_Error( 'comment_on_draft', __( 'Sorry, comments are not allowed for this item.' ), 403 );
3466          } else {
3467              return new WP_Error( 'comment_on_draft' );
3468          }
3469      } elseif ( post_password_required( $comment_post_ID ) ) {
3470  
3471          /**
3472           * Fires when a comment is attempted on a password-protected post.
3473           *
3474           * @since 2.9.0
3475           *
3476           * @param int $comment_post_ID Post ID.
3477           */
3478          do_action( 'comment_on_password_protected', $comment_post_ID );
3479  
3480          return new WP_Error( 'comment_on_password_protected' );
3481  
3482      } else {
3483  
3484          /**
3485           * Fires before a comment is posted.
3486           *
3487           * @since 2.8.0
3488           *
3489           * @param int $comment_post_ID Post ID.
3490           */
3491          do_action( 'pre_comment_on_post', $comment_post_ID );
3492  
3493      }
3494  
3495      // If the user is logged in.
3496      $user = wp_get_current_user();
3497      if ( $user->exists() ) {
3498          if ( empty( $user->display_name ) ) {
3499              $user->display_name = $user->user_login;
3500          }
3501          $comment_author       = $user->display_name;
3502          $comment_author_email = $user->user_email;
3503          $comment_author_url   = $user->user_url;
3504          $user_ID              = $user->ID;
3505          if ( current_user_can( 'unfiltered_html' ) ) {
3506              if ( ! isset( $comment_data['_wp_unfiltered_html_comment'] )
3507                  || ! wp_verify_nonce( $comment_data['_wp_unfiltered_html_comment'], 'unfiltered-html-comment_' . $comment_post_ID )
3508              ) {
3509                  kses_remove_filters(); // Start with a clean slate.
3510                  kses_init_filters();   // Set up the filters.
3511                  remove_filter( 'pre_comment_content', 'wp_filter_post_kses' );
3512                  add_filter( 'pre_comment_content', 'wp_filter_kses' );
3513              }
3514          }
3515      } else {
3516          if ( get_option( 'comment_registration' ) ) {
3517              return new WP_Error( 'not_logged_in', __( 'Sorry, you must be logged in to comment.' ), 403 );
3518          }
3519      }
3520  
3521      $comment_type = 'comment';
3522  
3523      if ( get_option( 'require_name_email' ) && ! $user->exists() ) {
3524          if ( '' == $comment_author_email || '' == $comment_author ) {
3525              return new WP_Error( 'require_name_email', __( '<strong>Error</strong>: Please fill the required fields (name, email).' ), 200 );
3526          } elseif ( ! is_email( $comment_author_email ) ) {
3527              return new WP_Error( 'require_valid_email', __( '<strong>Error</strong>: Please enter a valid email address.' ), 200 );
3528          }
3529      }
3530  
3531      $commentdata = compact(
3532          'comment_post_ID',
3533          'comment_author',
3534          'comment_author_email',
3535          'comment_author_url',
3536          'comment_content',
3537          'comment_type',
3538          'comment_parent',
3539          'user_ID'
3540      );
3541  
3542      /**
3543       * Filters whether an empty comment should be allowed.
3544       *
3545       * @since 5.1.0
3546       *
3547       * @param bool  $allow_empty_comment Whether to allow empty comments. Default false.
3548       * @param array $commentdata         Array of comment data to be sent to wp_insert_comment().
3549       */
3550      $allow_empty_comment = apply_filters( 'allow_empty_comment', false, $commentdata );
3551      if ( '' === $comment_content && ! $allow_empty_comment ) {
3552          return new WP_Error( 'require_valid_comment', __( '<strong>Error</strong>: Please type your comment text.' ), 200 );
3553      }
3554  
3555      $check_max_lengths = wp_check_comment_data_max_lengths( $commentdata );
3556      if ( is_wp_error( $check_max_lengths ) ) {
3557          return $check_max_lengths;
3558      }
3559  
3560      $comment_id = wp_new_comment( wp_slash( $commentdata ), true );
3561      if ( is_wp_error( $comment_id ) ) {
3562          return $comment_id;
3563      }
3564  
3565      if ( ! $comment_id ) {
3566          return new WP_Error( 'comment_save_error', __( '<strong>Error</strong>: The comment could not be saved. Please try again later.' ), 500 );
3567      }
3568  
3569      return get_comment( $comment_id );
3570  }
3571  
3572  /**
3573   * Registers the personal data exporter for comments.
3574   *
3575   * @since 4.9.6
3576   *
3577   * @param array $exporters An array of personal data exporters.
3578   * @return array An array of personal data exporters.
3579   */
3580  function wp_register_comment_personal_data_exporter( $exporters ) {
3581      $exporters['wordpress-comments'] = array(
3582          'exporter_friendly_name' => __( 'WordPress Comments' ),
3583          'callback'               => 'wp_comments_personal_data_exporter',
3584      );
3585  
3586      return $exporters;
3587  }
3588  
3589  /**
3590   * Finds and exports personal data associated with an email address from the comments table.
3591   *
3592   * @since 4.9.6
3593   *
3594   * @param string $email_address The comment author email address.
3595   * @param int    $page          Comment page.
3596   * @return array An array of personal data.
3597   */
3598  function wp_comments_personal_data_exporter( $email_address, $page = 1 ) {
3599      // Limit us to 500 comments at a time to avoid timing out.
3600      $number = 500;
3601      $page   = (int) $page;
3602  
3603      $data_to_export = array();
3604  
3605      $comments = get_comments(
3606          array(
3607              'author_email'              => $email_address,
3608              'number'                    => $number,
3609              'paged'                     => $page,
3610              'order_by'                  => 'comment_ID',
3611              'order'                     => 'ASC',
3612              'update_comment_meta_cache' => false,
3613          )
3614      );
3615  
3616      $comment_prop_to_export = array(
3617          'comment_author'       => __( 'Comment Author' ),
3618          'comment_author_email' => __( 'Comment Author Email' ),
3619          'comment_author_url'   => __( 'Comment Author URL' ),
3620          'comment_author_IP'    => __( 'Comment Author IP' ),
3621          'comment_agent'        => __( 'Comment Author User Agent' ),
3622          'comment_date'         => __( 'Comment Date' ),
3623          'comment_content'      => __( 'Comment Content' ),
3624          'comment_link'         => __( 'Comment URL' ),
3625      );
3626  
3627      foreach ( (array) $comments as $comment ) {
3628          $comment_data_to_export = array();
3629  
3630          foreach ( $comment_prop_to_export as $key => $name ) {
3631              $value = '';
3632  
3633              switch ( $key ) {
3634                  case 'comment_author':
3635                  case 'comment_author_email':
3636                  case 'comment_author_url':
3637                  case 'comment_author_IP':
3638                  case 'comment_agent':
3639                  case 'comment_date':
3640                      $value = $comment->{$key};
3641                      break;
3642  
3643                  case 'comment_content':
3644                      $value = get_comment_text( $comment->comment_ID );
3645                      break;
3646  
3647                  case 'comment_link':
3648                      $value = get_comment_link( $comment->comment_ID );
3649                      $value = sprintf(
3650                          '<a href="%s" target="_blank" rel="noopener">%s</a>',
3651                          esc_url( $value ),
3652                          esc_html( $value )
3653                      );
3654                      break;
3655              }
3656  
3657              if ( ! empty( $value ) ) {
3658                  $comment_data_to_export[] = array(
3659                      'name'  => $name,
3660                      'value' => $value,
3661                  );
3662              }
3663          }
3664  
3665          $data_to_export[] = array(
3666              'group_id'          => 'comments',
3667              'group_label'       => __( 'Comments' ),
3668              'group_description' => __( 'User&#8217;s comment data.' ),
3669              'item_id'           => "comment-{$comment->comment_ID}",
3670              'data'              => $comment_data_to_export,
3671          );
3672      }
3673  
3674      $done = count( $comments ) < $number;
3675  
3676      return array(
3677          'data' => $data_to_export,
3678          'done' => $done,
3679      );
3680  }
3681  
3682  /**
3683   * Registers the personal data eraser for comments.
3684   *
3685   * @since 4.9.6
3686   *
3687   * @param array $erasers An array of personal data erasers.
3688   * @return array An array of personal data erasers.
3689   */
3690  function wp_register_comment_personal_data_eraser( $erasers ) {
3691      $erasers['wordpress-comments'] = array(
3692          'eraser_friendly_name' => __( 'WordPress Comments' ),
3693          'callback'             => 'wp_comments_personal_data_eraser',
3694      );
3695  
3696      return $erasers;
3697  }
3698  
3699  /**
3700   * Erases personal data associated with an email address from the comments table.
3701   *
3702   * @since 4.9.6
3703   *
3704   * @param string $email_address The comment author email address.
3705   * @param int    $page          Comment page.
3706   * @return array
3707   */
3708  function wp_comments_personal_data_eraser( $email_address, $page = 1 ) {
3709      global $wpdb;
3710  
3711      if ( empty( $email_address ) ) {
3712          return array(
3713              'items_removed'  => false,
3714              'items_retained' => false,
3715              'messages'       => array(),
3716              'done'           => true,
3717          );
3718      }
3719  
3720      // Limit us to 500 comments at a time to avoid timing out.
3721      $number         = 500;
3722      $page           = (int) $page;
3723      $items_removed  = false;
3724      $items_retained = false;
3725  
3726      $comments = get_comments(
3727          array(
3728              'author_email'       => $email_address,
3729              'number'             => $number,
3730              'paged'              => $page,
3731              'order_by'           => 'comment_ID',
3732              'order'              => 'ASC',
3733              'include_unapproved' => true,
3734          )
3735      );
3736  
3737      /* translators: Name of a comment's author after being anonymized. */
3738      $anon_author = __( 'Anonymous' );
3739      $messages    = array();
3740  
3741      foreach ( (array) $comments as $comment ) {
3742          $anonymized_comment                         = array();
3743          $anonymized_comment['comment_agent']        = '';
3744          $anonymized_comment['comment_author']       = $anon_author;
3745          $anonymized_comment['comment_author_email'] = '';
3746          $anonymized_comment['comment_author_IP']    = wp_privacy_anonymize_data( 'ip', $comment->comment_author_IP );
3747          $anonymized_comment['comment_author_url']   = '';
3748          $anonymized_comment['user_id']              = 0;
3749  
3750          $comment_id = (int) $comment->comment_ID;
3751  
3752          /**
3753           * Filters whether to anonymize the comment.
3754           *
3755           * @since 4.9.6
3756           *
3757           * @param bool|string $anon_message       Whether to apply the comment anonymization (bool) or a custom
3758           *                                        message (string). Default true.
3759           * @param WP_Comment  $comment            WP_Comment object.
3760           * @param array       $anonymized_comment Anonymized comment data.
3761           */
3762          $anon_message = apply_filters( 'wp_anonymize_comment', true, $comment, $anonymized_comment );
3763  
3764          if ( true !== $anon_message ) {
3765              if ( $anon_message && is_string( $anon_message ) ) {
3766                  $messages[] = esc_html( $anon_message );
3767              } else {
3768                  /* translators: %d: Comment ID. */
3769                  $messages[] = sprintf( __( 'Comment %d contains personal data but could not be anonymized.' ), $comment_id );
3770              }
3771  
3772              $items_retained = true;
3773  
3774              continue;
3775          }
3776  
3777          $args = array(
3778              'comment_ID' => $comment_id,
3779          );
3780  
3781          $updated = $wpdb->update( $wpdb->comments, $anonymized_comment, $args );
3782  
3783          if ( $updated ) {
3784              $items_removed = true;
3785              clean_comment_cache( $comment_id );
3786          } else {
3787              $items_retained = true;
3788          }
3789      }
3790  
3791      $done = count( $comments ) < $number;
3792  
3793      return array(
3794          'items_removed'  => $items_removed,
3795          'items_retained' => $items_retained,
3796          'messages'       => $messages,
3797          'done'           => $done,
3798      );
3799  }
3800  
3801  /**
3802   * Sets the last changed time for the 'comment' cache group.
3803   *
3804   * @since 5.0.0
3805   */
3806  function wp_cache_set_comments_last_changed() {
3807      wp_cache_set( 'last_changed', microtime(), 'comment' );
3808  }
3809  
3810  /**
3811   * Updates the comment type for a batch of comments.
3812   *
3813   * @since 5.5.0
3814   *
3815   * @global wpdb $wpdb WordPress database abstraction object.
3816   */
3817  function _wp_batch_update_comment_type() {
3818      global $wpdb;
3819  
3820      $lock_name = 'update_comment_type.lock';
3821  
3822      // Try to lock.
3823      $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) );
3824  
3825      if ( ! $lock_result ) {
3826          $lock_result = get_option( $lock_name );
3827  
3828          // Bail if we were unable to create a lock, or if the existing lock is still valid.
3829          if ( ! $lock_result || ( $lock_result > ( time() - HOUR_IN_SECONDS ) ) ) {
3830              wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' );
3831              return;
3832          }
3833      }
3834  
3835      // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
3836      update_option( $lock_name, time() );
3837  
3838      // Check if there's still an empty comment type.
3839      $empty_comment_type = $wpdb->get_var(
3840          "SELECT comment_ID FROM $wpdb->comments
3841          WHERE comment_type = ''
3842          LIMIT 1"
3843      );
3844  
3845      // No empty comment type, we're done here.
3846      if ( ! $empty_comment_type ) {
3847          update_option( 'finished_updating_comment_type', true );
3848          delete_option( $lock_name );
3849          return;
3850      }
3851  
3852      // Empty comment type found? We'll need to run this script again.
3853      wp_schedule_single_event( time() + ( 2 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' );
3854  
3855      /**
3856       * Filters the comment batch size for updating the comment type.
3857       *
3858       * @since 5.5.0
3859       *
3860       * @param int $comment_batch_size The comment batch size. Default 100.
3861       */
3862      $comment_batch_size = (int) apply_filters( 'wp_update_comment_type_batch_size', 100 );
3863  
3864      // Get the IDs of the comments to update.
3865      $comment_ids = $wpdb->get_col(
3866          $wpdb->prepare(
3867              "SELECT comment_ID
3868              FROM {$wpdb->comments}
3869              WHERE comment_type = ''
3870              ORDER BY comment_ID DESC
3871              LIMIT %d",
3872              $comment_batch_size
3873          )
3874      );
3875  
3876      if ( $comment_ids ) {
3877          $comment_id_list = implode( ',', $comment_ids );
3878  
3879          // Update the `comment_type` field value to be `comment` for the next batch of comments.
3880          $wpdb->query(
3881              "UPDATE {$wpdb->comments}
3882              SET comment_type = 'comment'
3883              WHERE comment_type = ''
3884              AND comment_ID IN ({$comment_id_list})" // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
3885          );
3886  
3887          // Make sure to clean the comment cache.
3888          clean_comment_cache( $comment_ids );
3889      }
3890  
3891      delete_option( $lock_name );
3892  }
3893  
3894  /**
3895   * In order to avoid the _wp_batch_update_comment_type() job being accidentally removed,
3896   * check that it's still scheduled while we haven't finished updating comment types.
3897   *
3898   * @ignore
3899   * @since 5.5.0
3900   */
3901  function _wp_check_for_scheduled_update_comment_type() {
3902      if ( ! get_option( 'finished_updating_comment_type' ) && ! wp_next_scheduled( 'wp_update_comment_type_batch' ) ) {
3903          wp_schedule_single_event( time() + MINUTE_IN_SECONDS, 'wp_update_comment_type_batch' );
3904      }
3905  }


Generated: Tue Dec 1 01:00:04 2020 Cross-referenced by PHPXref 0.7.1