[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Sat Jun 14 08:20:01 2025 Cross-referenced by PHPXref