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


Generated: Mon Nov 18 01:00:04 2019 Cross-referenced by PHPXref 0.7.1