[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


Generated: Mon Jun 17 08:20:02 2019 Cross-referenced by PHPXref 0.7