[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Tue Jan 18 01:00:03 2022 Cross-referenced by PHPXref 0.7.1