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


Generated : Tue Mar 19 08:20:01 2024 Cross-referenced by PHPXref