[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Thu Sep 19 08:20:01 2024 Cross-referenced by PHPXref