[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-content/plugins/akismet/ -> class.akismet.php (source)

   1  <?php
   2  
   3  class Akismet {
   4      const API_HOST = 'rest.akismet.com';
   5      const API_PORT = 80;
   6      const MAX_DELAY_BEFORE_MODERATION_EMAIL = 86400; // One day in seconds
   7  
   8      private static $last_comment = '';
   9      private static $initiated = false;
  10      private static $prevent_moderation_email_for_these_comments = array();
  11      private static $last_comment_result = null;
  12      private static $comment_as_submitted_allowed_keys = array( 'blog' => '', 'blog_charset' => '', 'blog_lang' => '', 'blog_ua' => '', 'comment_agent' => '', 'comment_author' => '', 'comment_author_IP' => '', 'comment_author_email' => '', 'comment_author_url' => '', 'comment_content' => '', 'comment_date_gmt' => '', 'comment_tags' => '', 'comment_type' => '', 'guid' => '', 'is_test' => '', 'permalink' => '', 'reporter' => '', 'site_domain' => '', 'submit_referer' => '', 'submit_uri' => '', 'user_ID' => '', 'user_agent' => '', 'user_id' => '', 'user_ip' => '' );
  13      private static $is_rest_api_call = false;
  14      
  15  	public static function init() {
  16          if ( ! self::$initiated ) {
  17              self::init_hooks();
  18          }
  19      }
  20  
  21      /**
  22       * Initializes WordPress hooks
  23       */
  24  	private static function init_hooks() {
  25          self::$initiated = true;
  26  
  27          add_action( 'wp_insert_comment', array( 'Akismet', 'auto_check_update_meta' ), 10, 2 );
  28          add_filter( 'preprocess_comment', array( 'Akismet', 'auto_check_comment' ), 1 );
  29          add_filter( 'rest_pre_insert_comment', array( 'Akismet', 'rest_auto_check_comment' ), 1 );
  30  
  31          add_action( 'akismet_scheduled_delete', array( 'Akismet', 'delete_old_comments' ) );
  32          add_action( 'akismet_scheduled_delete', array( 'Akismet', 'delete_old_comments_meta' ) );
  33          add_action( 'akismet_scheduled_delete', array( 'Akismet', 'delete_orphaned_commentmeta' ) );
  34          add_action( 'akismet_schedule_cron_recheck', array( 'Akismet', 'cron_recheck' ) );
  35  
  36          add_action( 'comment_form',  array( 'Akismet',  'add_comment_nonce' ), 1 );
  37  
  38          add_action( 'admin_head-edit-comments.php', array( 'Akismet', 'load_form_js' ) );
  39          add_action( 'comment_form', array( 'Akismet', 'load_form_js' ) );
  40          add_action( 'comment_form', array( 'Akismet', 'inject_ak_js' ) );
  41          add_filter( 'script_loader_tag', array( 'Akismet', 'set_form_js_async' ), 10, 3 );
  42  
  43          add_filter( 'comment_moderation_recipients', array( 'Akismet', 'disable_moderation_emails_if_unreachable' ), 1000, 2 );
  44          add_filter( 'pre_comment_approved', array( 'Akismet', 'last_comment_status' ), 10, 2 );
  45          
  46          add_action( 'transition_comment_status', array( 'Akismet', 'transition_comment_status' ), 10, 3 );
  47  
  48          // Run this early in the pingback call, before doing a remote fetch of the source uri
  49          add_action( 'xmlrpc_call', array( 'Akismet', 'pre_check_pingback' ) );
  50          
  51          // Jetpack compatibility
  52          add_filter( 'jetpack_options_whitelist', array( 'Akismet', 'add_to_jetpack_options_whitelist' ) );
  53          add_action( 'update_option_wordpress_api_key', array( 'Akismet', 'updated_option' ), 10, 2 );
  54          add_action( 'add_option_wordpress_api_key', array( 'Akismet', 'added_option' ), 10, 2 );
  55  
  56          add_action( 'comment_form_after',  array( 'Akismet',  'display_comment_form_privacy_notice' ) );
  57      }
  58  
  59  	public static function get_api_key() {
  60          return apply_filters( 'akismet_get_api_key', defined('WPCOM_API_KEY') ? constant('WPCOM_API_KEY') : get_option('wordpress_api_key') );
  61      }
  62  
  63  	public static function check_key_status( $key, $ip = null ) {
  64          return self::http_post( Akismet::build_query( array( 'key' => $key, 'blog' => get_option( 'home' ) ) ), 'verify-key', $ip );
  65      }
  66  
  67  	public static function verify_key( $key, $ip = null ) {
  68          // Shortcut for obviously invalid keys.
  69          if ( strlen( $key ) != 12 ) {
  70              return 'invalid';
  71          }
  72          
  73          $response = self::check_key_status( $key, $ip );
  74  
  75          if ( $response[1] != 'valid' && $response[1] != 'invalid' )
  76              return 'failed';
  77  
  78          return $response[1];
  79      }
  80  
  81  	public static function deactivate_key( $key ) {
  82          $response = self::http_post( Akismet::build_query( array( 'key' => $key, 'blog' => get_option( 'home' ) ) ), 'deactivate' );
  83  
  84          if ( $response[1] != 'deactivated' )
  85              return 'failed';
  86  
  87          return $response[1];
  88      }
  89  
  90      /**
  91       * Add the akismet option to the Jetpack options management whitelist.
  92       *
  93       * @param array $options The list of whitelisted option names.
  94       * @return array The updated whitelist
  95       */
  96  	public static function add_to_jetpack_options_whitelist( $options ) {
  97          $options[] = 'wordpress_api_key';
  98          return $options;
  99      }
 100  
 101      /**
 102       * When the akismet option is updated, run the registration call.
 103       *
 104       * This should only be run when the option is updated from the Jetpack/WP.com
 105       * API call, and only if the new key is different than the old key.
 106       *
 107       * @param mixed  $old_value   The old option value.
 108       * @param mixed  $value       The new option value.
 109       */
 110  	public static function updated_option( $old_value, $value ) {
 111          // Not an API call
 112          if ( ! class_exists( 'WPCOM_JSON_API_Update_Option_Endpoint' ) ) {
 113              return;
 114          }
 115          // Only run the registration if the old key is different.
 116          if ( $old_value !== $value ) {
 117              self::verify_key( $value );
 118          }
 119      }
 120      
 121      /**
 122       * Treat the creation of an API key the same as updating the API key to a new value.
 123       *
 124       * @param mixed  $option_name   Will always be "wordpress_api_key", until something else hooks in here.
 125       * @param mixed  $value         The option value.
 126       */
 127  	public static function added_option( $option_name, $value ) {
 128          if ( 'wordpress_api_key' === $option_name ) {
 129              return self::updated_option( '', $value );
 130          }
 131      }
 132      
 133  	public static function rest_auto_check_comment( $commentdata ) {
 134          self::$is_rest_api_call = true;
 135          
 136          return self::auto_check_comment( $commentdata );
 137      }
 138  
 139  	public static function auto_check_comment( $commentdata ) {
 140          // If no key is configured, then there's no point in doing any of this.
 141          if ( ! self::get_api_key() ) {
 142              return $commentdata;
 143          }
 144  
 145          self::$last_comment_result = null;
 146  
 147          $comment = $commentdata;
 148  
 149          $comment['user_ip']      = self::get_ip_address();
 150          $comment['user_agent']   = self::get_user_agent();
 151          $comment['referrer']     = self::get_referer();
 152          $comment['blog']         = get_option( 'home' );
 153          $comment['blog_lang']    = get_locale();
 154          $comment['blog_charset'] = get_option('blog_charset');
 155          $comment['permalink']    = get_permalink( $comment['comment_post_ID'] );
 156  
 157          if ( ! empty( $comment['user_ID'] ) ) {
 158              $comment['user_role'] = Akismet::get_user_roles( $comment['user_ID'] );
 159          }
 160  
 161          /** See filter documentation in init_hooks(). */
 162          $akismet_nonce_option = apply_filters( 'akismet_comment_nonce', get_option( 'akismet_comment_nonce' ) );
 163          $comment['akismet_comment_nonce'] = 'inactive';
 164          if ( $akismet_nonce_option == 'true' || $akismet_nonce_option == '' ) {
 165              $comment['akismet_comment_nonce'] = 'failed';
 166              if ( isset( $_POST['akismet_comment_nonce'] ) && wp_verify_nonce( $_POST['akismet_comment_nonce'], 'akismet_comment_nonce_' . $comment['comment_post_ID'] ) )
 167                  $comment['akismet_comment_nonce'] = 'passed';
 168  
 169              // comment reply in wp-admin
 170              if ( isset( $_POST['_ajax_nonce-replyto-comment'] ) && check_ajax_referer( 'replyto-comment', '_ajax_nonce-replyto-comment' ) )
 171                  $comment['akismet_comment_nonce'] = 'passed';
 172  
 173          }
 174  
 175          if ( self::is_test_mode() )
 176              $comment['is_test'] = 'true';
 177  
 178          foreach( $_POST as $key => $value ) {
 179              if ( is_string( $value ) )
 180                  $comment["POST_{$key}"] = $value;
 181          }
 182  
 183          foreach ( $_SERVER as $key => $value ) {
 184              if ( ! is_string( $value ) ) {
 185                  continue;
 186              }
 187  
 188              if ( preg_match( "/^HTTP_COOKIE/", $key ) ) {
 189                  continue;
 190              }
 191  
 192              // Send any potentially useful $_SERVER vars, but avoid sending junk we don't need.
 193              if ( preg_match( "/^(HTTP_|REMOTE_ADDR|REQUEST_URI|DOCUMENT_URI)/", $key ) ) {
 194                  $comment[ "$key" ] = $value;
 195              }
 196          }
 197  
 198          $post = get_post( $comment['comment_post_ID'] );
 199  
 200          if ( ! is_null( $post ) ) {
 201              // $post can technically be null, although in the past, it's always been an indicator of another plugin interfering.
 202              $comment[ 'comment_post_modified_gmt' ] = $post->post_modified_gmt;
 203          }
 204  
 205          $response = self::http_post( Akismet::build_query( $comment ), 'comment-check' );
 206  
 207          do_action( 'akismet_comment_check_response', $response );
 208  
 209          $commentdata['comment_as_submitted'] = array_intersect_key( $comment, self::$comment_as_submitted_allowed_keys );
 210  
 211          // Also include any form fields we inject into the comment form, like ak_js
 212          foreach ( $_POST as $key => $value ) {
 213              if ( is_string( $value ) && strpos( $key, 'ak_' ) === 0 ) {
 214                  $commentdata['comment_as_submitted'][ 'POST_' . $key ] = $value;
 215              }
 216          }
 217  
 218          $commentdata['akismet_result'] = $response[1];
 219  
 220          if ( isset( $response[0]['x-akismet-pro-tip'] ) )
 221              $commentdata['akismet_pro_tip'] = $response[0]['x-akismet-pro-tip'];
 222  
 223          if ( isset( $response[0]['x-akismet-error'] ) ) {
 224              // An error occurred that we anticipated (like a suspended key) and want the user to act on.
 225              // Send to moderation.
 226              self::$last_comment_result = '0';
 227          }
 228          else if ( 'true' == $response[1] ) {
 229              // akismet_spam_count will be incremented later by comment_is_spam()
 230              self::$last_comment_result = 'spam';
 231  
 232              $discard = ( isset( $commentdata['akismet_pro_tip'] ) && $commentdata['akismet_pro_tip'] === 'discard' && self::allow_discard() );
 233  
 234              do_action( 'akismet_spam_caught', $discard );
 235  
 236              if ( $discard ) {
 237                  // The spam is obvious, so we're bailing out early. 
 238                  // akismet_result_spam() won't be called so bump the counter here
 239                  if ( $incr = apply_filters( 'akismet_spam_count_incr', 1 ) ) {
 240                      update_option( 'akismet_spam_count', get_option( 'akismet_spam_count' ) + $incr );
 241                  }
 242  
 243                  if ( self::$is_rest_api_call ) {
 244                      return new WP_Error( 'akismet_rest_comment_discarded', __( 'Comment discarded.', 'akismet' ) );
 245                  }
 246                  else {
 247                      // Redirect back to the previous page, or failing that, the post permalink, or failing that, the homepage of the blog.
 248                      $redirect_to = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : ( $post ? get_permalink( $post ) : home_url() );
 249                      wp_safe_redirect( esc_url_raw( $redirect_to ) );
 250                      die();
 251                  }
 252              }
 253              else if ( self::$is_rest_api_call ) {
 254                  // The way the REST API structures its calls, we can set the comment_approved value right away.
 255                  $commentdata['comment_approved'] = 'spam';
 256              }
 257          }
 258          
 259          // if the response is neither true nor false, hold the comment for moderation and schedule a recheck
 260          if ( 'true' != $response[1] && 'false' != $response[1] ) {
 261              if ( !current_user_can('moderate_comments') ) {
 262                  // Comment status should be moderated
 263                  self::$last_comment_result = '0';
 264              }
 265  
 266              if ( ! wp_next_scheduled( 'akismet_schedule_cron_recheck' ) ) {
 267                  wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
 268                  do_action( 'akismet_scheduled_recheck', 'invalid-response-' . $response[1] );
 269              }
 270  
 271              self::$prevent_moderation_email_for_these_comments[] = $commentdata;
 272          }
 273  
 274          // Delete old comments daily
 275          if ( ! wp_next_scheduled( 'akismet_scheduled_delete' ) ) {
 276              wp_schedule_event( time(), 'daily', 'akismet_scheduled_delete' );
 277          }
 278  
 279          self::set_last_comment( $commentdata );
 280          self::fix_scheduled_recheck();
 281  
 282          return $commentdata;
 283      }
 284      
 285  	public static function get_last_comment() {
 286          return self::$last_comment;
 287      }
 288      
 289  	public static function set_last_comment( $comment ) {
 290          if ( is_null( $comment ) ) {
 291              self::$last_comment = null;
 292          }
 293          else {
 294              // We filter it here so that it matches the filtered comment data that we'll have to compare against later.
 295              // wp_filter_comment expects comment_author_IP
 296              self::$last_comment = wp_filter_comment(
 297                  array_merge(
 298                      array( 'comment_author_IP' => self::get_ip_address() ),
 299                      $comment
 300                  )
 301              );
 302          }
 303      }
 304  
 305      // this fires on wp_insert_comment.  we can't update comment_meta when auto_check_comment() runs
 306      // because we don't know the comment ID at that point.
 307  	public static function auto_check_update_meta( $id, $comment ) {
 308          // wp_insert_comment() might be called in other contexts, so make sure this is the same comment
 309          // as was checked by auto_check_comment
 310          if ( is_object( $comment ) && !empty( self::$last_comment ) && is_array( self::$last_comment ) ) {
 311              if ( self::matches_last_comment( $comment ) ) {
 312                  load_plugin_textdomain( 'akismet' );
 313  
 314                  // normal result: true or false
 315                  if ( self::$last_comment['akismet_result'] == 'true' ) {
 316                      update_comment_meta( $comment->comment_ID, 'akismet_result', 'true' );
 317                      self::update_comment_history( $comment->comment_ID, '', 'check-spam' );
 318                      if ( $comment->comment_approved != 'spam' ) {
 319                          self::update_comment_history(
 320                              $comment->comment_ID,
 321                              '',
 322                              'status-changed-' . $comment->comment_approved
 323                          );
 324                      }
 325                  } elseif ( self::$last_comment['akismet_result'] == 'false' ) {
 326                      update_comment_meta( $comment->comment_ID, 'akismet_result', 'false' );
 327                      self::update_comment_history( $comment->comment_ID, '', 'check-ham' );
 328                      // Status could be spam or trash, depending on the WP version and whether this change applies:
 329                      // https://core.trac.wordpress.org/changeset/34726
 330                      if ( $comment->comment_approved == 'spam' || $comment->comment_approved == 'trash' ) {
 331                          if ( function_exists( 'wp_check_comment_disallowed_list' ) ) {
 332                              if ( wp_check_comment_disallowed_list( $comment->comment_author, $comment->comment_author_email, $comment->comment_author_url, $comment->comment_content, $comment->comment_author_IP, $comment->comment_agent ) ) {
 333                                  self::update_comment_history( $comment->comment_ID, '', 'wp-disallowed' );
 334                              } else {
 335                                  self::update_comment_history( $comment->comment_ID, '', 'status-changed-' . $comment->comment_approved );
 336                              }
 337                          } else if ( function_exists( 'wp_blacklist_check' ) && wp_blacklist_check( $comment->comment_author, $comment->comment_author_email, $comment->comment_author_url, $comment->comment_content, $comment->comment_author_IP, $comment->comment_agent ) ) {
 338                              self::update_comment_history( $comment->comment_ID, '', 'wp-blacklisted' );
 339                          } else {
 340                              self::update_comment_history( $comment->comment_ID, '', 'status-changed-' . $comment->comment_approved );
 341                          }
 342                      }
 343                  } else {
 344                       // abnormal result: error
 345                      update_comment_meta( $comment->comment_ID, 'akismet_error', time() );
 346                      self::update_comment_history(
 347                          $comment->comment_ID,
 348                          '',
 349                          'check-error',
 350                          array( 'response' => substr( self::$last_comment['akismet_result'], 0, 50 ) )
 351                      );
 352                  }
 353  
 354                  // record the complete original data as submitted for checking
 355                  if ( isset( self::$last_comment['comment_as_submitted'] ) ) {
 356                      update_comment_meta( $comment->comment_ID, 'akismet_as_submitted', self::$last_comment['comment_as_submitted'] );
 357                  }
 358  
 359                  if ( isset( self::$last_comment['akismet_pro_tip'] ) ) {
 360                      update_comment_meta( $comment->comment_ID, 'akismet_pro_tip', self::$last_comment['akismet_pro_tip'] );
 361                  }
 362              }
 363          }
 364      }
 365  
 366  	public static function delete_old_comments() {
 367          global $wpdb;
 368  
 369          /**
 370           * Determines how many comments will be deleted in each batch.
 371           *
 372           * @param int The default, as defined by AKISMET_DELETE_LIMIT.
 373           */
 374          $delete_limit = apply_filters( 'akismet_delete_comment_limit', defined( 'AKISMET_DELETE_LIMIT' ) ? AKISMET_DELETE_LIMIT : 10000 );
 375          $delete_limit = max( 1, intval( $delete_limit ) );
 376  
 377          /**
 378           * Determines how many days a comment will be left in the Spam queue before being deleted.
 379           *
 380           * @param int The default number of days.
 381           */
 382          $delete_interval = apply_filters( 'akismet_delete_comment_interval', 15 );
 383          $delete_interval = max( 1, intval( $delete_interval ) );
 384  
 385          while ( $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_id FROM {$wpdb->comments} WHERE DATE_SUB(NOW(), INTERVAL %d DAY) > comment_date_gmt AND comment_approved = 'spam' LIMIT %d", $delete_interval, $delete_limit ) ) ) {
 386              if ( empty( $comment_ids ) )
 387                  return;
 388  
 389              $wpdb->queries = array();
 390  
 391              foreach ( $comment_ids as $comment_id ) {
 392                  do_action( 'delete_comment', $comment_id );
 393                  do_action( 'akismet_batch_delete_count', __FUNCTION__ );
 394              }
 395  
 396              // Prepared as strings since comment_id is an unsigned BIGINT, and using %d will constrain the value to the maximum signed BIGINT.
 397              $format_string = implode( ", ", array_fill( 0, count( $comment_ids ), '%s' ) );
 398  
 399              $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->comments} WHERE comment_id IN ( " . $format_string . " )", $comment_ids ) );
 400              $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->commentmeta} WHERE comment_id IN ( " . $format_string . " )", $comment_ids ) );
 401  
 402              clean_comment_cache( $comment_ids );
 403              do_action( 'akismet_delete_comment_batch', count( $comment_ids ) );
 404          }
 405  
 406          if ( apply_filters( 'akismet_optimize_table', ( mt_rand(1, 5000) == 11), $wpdb->comments ) ) // lucky number
 407              $wpdb->query("OPTIMIZE TABLE {$wpdb->comments}");
 408      }
 409  
 410  	public static function delete_old_comments_meta() {
 411          global $wpdb;
 412  
 413          $interval = apply_filters( 'akismet_delete_commentmeta_interval', 15 );
 414  
 415          # enforce a minimum of 1 day
 416          $interval = absint( $interval );
 417          if ( $interval < 1 )
 418              $interval = 1;
 419  
 420          // akismet_as_submitted meta values are large, so expire them
 421          // after $interval days regardless of the comment status
 422          while ( $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT m.comment_id FROM {$wpdb->commentmeta} as m INNER JOIN {$wpdb->comments} as c USING(comment_id) WHERE m.meta_key = 'akismet_as_submitted' AND DATE_SUB(NOW(), INTERVAL %d DAY) > c.comment_date_gmt LIMIT 10000", $interval ) ) ) {
 423              if ( empty( $comment_ids ) )
 424                  return;
 425  
 426              $wpdb->queries = array();
 427  
 428              foreach ( $comment_ids as $comment_id ) {
 429                  delete_comment_meta( $comment_id, 'akismet_as_submitted' );
 430                  do_action( 'akismet_batch_delete_count', __FUNCTION__ );
 431              }
 432  
 433              do_action( 'akismet_delete_commentmeta_batch', count( $comment_ids ) );
 434          }
 435  
 436          if ( apply_filters( 'akismet_optimize_table', ( mt_rand(1, 5000) == 11), $wpdb->commentmeta ) ) // lucky number
 437              $wpdb->query("OPTIMIZE TABLE {$wpdb->commentmeta}");
 438      }
 439  
 440      // Clear out comments meta that no longer have corresponding comments in the database
 441  	public static function delete_orphaned_commentmeta() {
 442          global $wpdb;
 443  
 444          $last_meta_id = 0;
 445          $start_time = isset( $_SERVER['REQUEST_TIME_FLOAT'] ) ? $_SERVER['REQUEST_TIME_FLOAT'] : microtime( true );
 446          $max_exec_time = max( ini_get('max_execution_time') - 5, 3 );
 447  
 448          while ( $commentmeta_results = $wpdb->get_results( $wpdb->prepare( "SELECT m.meta_id, m.comment_id, m.meta_key FROM {$wpdb->commentmeta} as m LEFT JOIN {$wpdb->comments} as c USING(comment_id) WHERE c.comment_id IS NULL AND m.meta_id > %d ORDER BY m.meta_id LIMIT 1000", $last_meta_id ) ) ) {
 449              if ( empty( $commentmeta_results ) )
 450                  return;
 451  
 452              $wpdb->queries = array();
 453  
 454              $commentmeta_deleted = 0;
 455  
 456              foreach ( $commentmeta_results as $commentmeta ) {
 457                  if ( 'akismet_' == substr( $commentmeta->meta_key, 0, 8 ) ) {
 458                      delete_comment_meta( $commentmeta->comment_id, $commentmeta->meta_key );
 459                      do_action( 'akismet_batch_delete_count', __FUNCTION__ );
 460                      $commentmeta_deleted++;
 461                  }
 462  
 463                  $last_meta_id = $commentmeta->meta_id;
 464              }
 465  
 466              do_action( 'akismet_delete_commentmeta_batch', $commentmeta_deleted );
 467  
 468              // If we're getting close to max_execution_time, quit for this round.
 469              if ( microtime(true) - $start_time > $max_exec_time )
 470                  return;
 471          }
 472  
 473          if ( apply_filters( 'akismet_optimize_table', ( mt_rand(1, 5000) == 11), $wpdb->commentmeta ) ) // lucky number
 474              $wpdb->query("OPTIMIZE TABLE {$wpdb->commentmeta}");
 475      }
 476  
 477      // how many approved comments does this author have?
 478  	public static function get_user_comments_approved( $user_id, $comment_author_email, $comment_author, $comment_author_url ) {
 479          global $wpdb;
 480  
 481          if ( !empty( $user_id ) )
 482              return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->comments} WHERE user_id = %d AND comment_approved = 1", $user_id ) );
 483  
 484          if ( !empty( $comment_author_email ) )
 485              return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_author_email = %s AND comment_author = %s AND comment_author_url = %s AND comment_approved = 1", $comment_author_email, $comment_author, $comment_author_url ) );
 486  
 487          return 0;
 488      }
 489  
 490      // get the full comment history for a given comment, as an array in reverse chronological order
 491  	public static function get_comment_history( $comment_id ) {
 492          $history = get_comment_meta( $comment_id, 'akismet_history', false );
 493          if ( empty( $history ) || empty( $history[ 0 ] ) ) {
 494              return false;
 495          }
 496          
 497          /*
 498          // To see all variants when testing.
 499          $history[] = array( 'time' => 445856401, 'message' => 'Old versions of Akismet stored the message as a literal string in the commentmeta.', 'event' => null );
 500          $history[] = array( 'time' => 445856402, 'event' => 'recheck-spam' );
 501          $history[] = array( 'time' => 445856403, 'event' => 'check-spam' );
 502          $history[] = array( 'time' => 445856404, 'event' => 'recheck-ham' );
 503          $history[] = array( 'time' => 445856405, 'event' => 'check-ham' );
 504          $history[] = array( 'time' => 445856406, 'event' => 'wp-blacklisted' );
 505          $history[] = array( 'time' => 445856406, 'event' => 'wp-disallowed' );
 506          $history[] = array( 'time' => 445856407, 'event' => 'report-spam' );
 507          $history[] = array( 'time' => 445856408, 'event' => 'report-spam', 'user' => 'sam' );
 508          $history[] = array( 'message' => 'sam reported this comment as spam (hardcoded message).', 'time' => 445856400, 'event' => 'report-spam', 'user' => 'sam' );
 509          $history[] = array( 'time' => 445856409, 'event' => 'report-ham', 'user' => 'sam' );
 510          $history[] = array( 'message' => 'sam reported this comment as ham (hardcoded message).', 'time' => 445856400, 'event' => 'report-ham', 'user' => 'sam' ); //
 511          $history[] = array( 'time' => 445856410, 'event' => 'cron-retry-spam' );
 512          $history[] = array( 'time' => 445856411, 'event' => 'cron-retry-ham' );
 513          $history[] = array( 'time' => 445856412, 'event' => 'check-error' ); //
 514          $history[] = array( 'time' => 445856413, 'event' => 'check-error', 'meta' => array( 'response' => 'The server was taking a nap.' ) );
 515          $history[] = array( 'time' => 445856414, 'event' => 'recheck-error' ); // Should not generate a message.
 516          $history[] = array( 'time' => 445856415, 'event' => 'recheck-error', 'meta' => array( 'response' => 'The server was taking a nap.' ) );
 517          $history[] = array( 'time' => 445856416, 'event' => 'status-changedtrash' );
 518          $history[] = array( 'time' => 445856417, 'event' => 'status-changedspam' );
 519          $history[] = array( 'time' => 445856418, 'event' => 'status-changedhold' );
 520          $history[] = array( 'time' => 445856419, 'event' => 'status-changedapprove' );
 521          $history[] = array( 'time' => 445856420, 'event' => 'status-changed-trash' );
 522          $history[] = array( 'time' => 445856421, 'event' => 'status-changed-spam' );
 523          $history[] = array( 'time' => 445856422, 'event' => 'status-changed-hold' );
 524          $history[] = array( 'time' => 445856423, 'event' => 'status-changed-approve' );
 525          $history[] = array( 'time' => 445856424, 'event' => 'status-trash', 'user' => 'sam' );
 526          $history[] = array( 'time' => 445856425, 'event' => 'status-spam', 'user' => 'sam' );
 527          $history[] = array( 'time' => 445856426, 'event' => 'status-hold', 'user' => 'sam' );
 528          $history[] = array( 'time' => 445856427, 'event' => 'status-approve', 'user' => 'sam' );
 529          */
 530          
 531          usort( $history, array( 'Akismet', '_cmp_time' ) );
 532          return $history;
 533      }
 534  
 535      /**
 536       * Log an event for a given comment, storing it in comment_meta.
 537       *
 538       * @param int $comment_id The ID of the relevant comment.
 539       * @param string $message The string description of the event. No longer used.
 540       * @param string $event The event code.
 541       * @param array $meta Metadata about the history entry. e.g., the user that reported or changed the status of a given comment.
 542       */
 543  	public static function update_comment_history( $comment_id, $message, $event=null, $meta=null ) {
 544          global $current_user;
 545  
 546          $user = '';
 547  
 548          $event = array(
 549              'time'    => self::_get_microtime(),
 550              'event'   => $event,
 551          );
 552          
 553          if ( is_object( $current_user ) && isset( $current_user->user_login ) ) {
 554              $event['user'] = $current_user->user_login;
 555          }
 556          
 557          if ( ! empty( $meta ) ) {
 558              $event['meta'] = $meta;
 559          }
 560  
 561          // $unique = false so as to allow multiple values per comment
 562          $r = add_comment_meta( $comment_id, 'akismet_history', $event, false );
 563      }
 564  
 565  	public static function check_db_comment( $id, $recheck_reason = 'recheck_queue' ) {
 566          global $wpdb;
 567  
 568          if ( ! self::get_api_key() ) {
 569              return new WP_Error( 'akismet-not-configured', __( 'Akismet is not configured. Please enter an API key.', 'akismet' ) );
 570          }
 571  
 572          $c = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $id ), ARRAY_A );
 573          
 574          if ( ! $c ) {
 575              return new WP_Error( 'invalid-comment-id', __( 'Comment not found.', 'akismet' ) );
 576          }
 577  
 578          $c['user_ip']        = $c['comment_author_IP'];
 579          $c['user_agent']     = $c['comment_agent'];
 580          $c['referrer']       = '';
 581          $c['blog']           = get_option( 'home' );
 582          $c['blog_lang']      = get_locale();
 583          $c['blog_charset']   = get_option('blog_charset');
 584          $c['permalink']      = get_permalink($c['comment_post_ID']);
 585          $c['recheck_reason'] = $recheck_reason;
 586  
 587          $c['user_role'] = '';
 588          if ( ! empty( $c['user_ID'] ) ) {
 589              $c['user_role'] = Akismet::get_user_roles( $c['user_ID'] );
 590          }
 591  
 592          if ( self::is_test_mode() )
 593              $c['is_test'] = 'true';
 594  
 595          $response = self::http_post( Akismet::build_query( $c ), 'comment-check' );
 596  
 597          if ( ! empty( $response[1] ) ) {
 598              return $response[1];
 599          }
 600  
 601          return false;
 602      }
 603      
 604  	public static function recheck_comment( $id, $recheck_reason = 'recheck_queue' ) {
 605          add_comment_meta( $id, 'akismet_rechecking', true );
 606          
 607          $api_response = self::check_db_comment( $id, $recheck_reason );
 608  
 609          delete_comment_meta( $id, 'akismet_rechecking' );
 610  
 611          if ( is_wp_error( $api_response ) ) {
 612              // Invalid comment ID.
 613          }
 614          else if ( 'true' === $api_response ) {
 615              wp_set_comment_status( $id, 'spam' );
 616              update_comment_meta( $id, 'akismet_result', 'true' );
 617              delete_comment_meta( $id, 'akismet_error' );
 618              delete_comment_meta( $id, 'akismet_delayed_moderation_email' );
 619              Akismet::update_comment_history( $id, '', 'recheck-spam' );
 620          }
 621          elseif ( 'false' === $api_response ) {
 622              update_comment_meta( $id, 'akismet_result', 'false' );
 623              delete_comment_meta( $id, 'akismet_error' );
 624              delete_comment_meta( $id, 'akismet_delayed_moderation_email' );
 625              Akismet::update_comment_history( $id, '', 'recheck-ham' );
 626          }
 627          else {
 628              // abnormal result: error
 629              update_comment_meta( $id, 'akismet_result', 'error' );
 630              Akismet::update_comment_history(
 631                  $id,
 632                  '',
 633                  'recheck-error',
 634                  array( 'response' => substr( $api_response, 0, 50 ) )
 635              );
 636          }
 637  
 638          return $api_response;
 639      }
 640  
 641  	public static function transition_comment_status( $new_status, $old_status, $comment ) {
 642          
 643          if ( $new_status == $old_status )
 644              return;
 645  
 646          if ( 'spam' === $new_status || 'spam' === $old_status ) {
 647              // Clear the cache of the "X comments in your spam queue" count on the dashboard.
 648              wp_cache_delete( 'akismet_spam_count', 'widget' );
 649          }
 650  
 651          # we don't need to record a history item for deleted comments
 652          if ( $new_status == 'delete' )
 653              return;
 654          
 655          if ( !current_user_can( 'edit_post', $comment->comment_post_ID ) && !current_user_can( 'moderate_comments' ) )
 656              return;
 657  
 658          if ( defined('WP_IMPORTING') && WP_IMPORTING == true )
 659              return;
 660              
 661          // if this is present, it means the status has been changed by a re-check, not an explicit user action
 662          if ( get_comment_meta( $comment->comment_ID, 'akismet_rechecking' ) )
 663              return;
 664          
 665          // Assumption alert:
 666          // We want to submit comments to Akismet only when a moderator explicitly spams or approves it - not if the status
 667          // is changed automatically by another plugin.  Unfortunately WordPress doesn't provide an unambiguous way to
 668          // determine why the transition_comment_status action was triggered.  And there are several different ways by which
 669          // to spam and unspam comments: bulk actions, ajax, links in moderation emails, the dashboard, and perhaps others.
 670          // We'll assume that this is an explicit user action if certain POST/GET variables exist.
 671          if (
 672               // status=spam: Marking as spam via the REST API or...
 673               // status=unspam: I'm not sure. Maybe this used to be used instead of status=approved? Or the UI for removing from spam but not approving has been since removed?...
 674               // status=approved: Unspamming via the REST API (Calypso) or...
 675               ( isset( $_POST['status'] ) && in_array( $_POST['status'], array( 'spam', 'unspam', 'approved', ) ) )
 676               // spam=1: Clicking "Spam" underneath a comment in wp-admin and allowing the AJAX request to happen.
 677               || ( isset( $_POST['spam'] ) && (int) $_POST['spam'] == 1 )
 678               // unspam=1: Clicking "Not Spam" underneath a comment in wp-admin and allowing the AJAX request to happen. Or, clicking "Undo" after marking something as spam.
 679               || ( isset( $_POST['unspam'] ) && (int) $_POST['unspam'] == 1 )
 680               // comment_status=spam/unspam: It's unclear where this is happening.
 681               || ( isset( $_POST['comment_status'] )  && in_array( $_POST['comment_status'], array( 'spam', 'unspam' ) ) )
 682               // action=spam: Choosing "Mark as Spam" from the Bulk Actions dropdown in wp-admin (or the "Spam it" link in notification emails).
 683               // action=unspam: Choosing "Not Spam" from the Bulk Actions dropdown in wp-admin.
 684               // action=spamcomment: Following the "Spam" link below a comment in wp-admin (not allowing AJAX request to happen).
 685               // action=unspamcomment: Following the "Not Spam" link below a comment in wp-admin (not allowing AJAX request to happen).
 686               || ( isset( $_GET['action'] ) && in_array( $_GET['action'], array( 'spam', 'unspam', 'spamcomment', 'unspamcomment', ) ) )
 687               // action=editedcomment: Editing a comment via wp-admin (and possibly changing its status).
 688               || ( isset( $_POST['action'] ) && in_array( $_POST['action'], array( 'editedcomment' ) ) )
 689               // for=jetpack: Moderation via the WordPress app, Calypso, anything powered by the Jetpack connection.
 690               || ( isset( $_GET['for'] ) && ( 'jetpack' == $_GET['for'] ) && ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) ) 
 691               // Certain WordPress.com API requests
 692               || ( defined( 'REST_API_REQUEST' ) && REST_API_REQUEST )
 693               // WordPress.org REST API requests
 694               || ( defined( 'REST_REQUEST' ) && REST_REQUEST )
 695           ) {
 696              if ( $new_status == 'spam' && ( $old_status == 'approved' || $old_status == 'unapproved' || !$old_status ) ) {
 697                  return self::submit_spam_comment( $comment->comment_ID );
 698              } elseif ( $old_status == 'spam' && ( $new_status == 'approved' || $new_status == 'unapproved' ) ) {
 699                  return self::submit_nonspam_comment( $comment->comment_ID );
 700              }
 701          }
 702  
 703          self::update_comment_history( $comment->comment_ID, '', 'status-' . $new_status );
 704      }
 705      
 706  	public static function submit_spam_comment( $comment_id ) {
 707          global $wpdb, $current_user, $current_site;
 708  
 709          $comment_id = (int) $comment_id;
 710  
 711          $comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $comment_id ) );
 712  
 713          if ( !$comment ) // it was deleted
 714              return;
 715  
 716          if ( 'spam' != $comment->comment_approved )
 717              return;
 718  
 719          self::update_comment_history( $comment_id, '', 'report-spam' );
 720  
 721          // If the user hasn't configured Akismet, there's nothing else to do at this point.
 722          if ( ! self::get_api_key() ) {
 723              return;
 724          }
 725  
 726          // use the original version stored in comment_meta if available
 727          $as_submitted = self::sanitize_comment_as_submitted( get_comment_meta( $comment_id, 'akismet_as_submitted', true ) );
 728  
 729          if ( $as_submitted && is_array( $as_submitted ) && isset( $as_submitted['comment_content'] ) )
 730              $comment = (object) array_merge( (array)$comment, $as_submitted );
 731  
 732          $comment->blog         = get_option( 'home' );
 733          $comment->blog_lang    = get_locale();
 734          $comment->blog_charset = get_option('blog_charset');
 735          $comment->permalink    = get_permalink($comment->comment_post_ID);
 736  
 737          if ( is_object($current_user) )
 738              $comment->reporter = $current_user->user_login;
 739  
 740          if ( is_object($current_site) )
 741              $comment->site_domain = $current_site->domain;
 742  
 743          $comment->user_role = '';
 744          if ( ! empty( $comment->user_ID ) ) {
 745              $comment->user_role = Akismet::get_user_roles( $comment->user_ID );
 746          }
 747  
 748          if ( self::is_test_mode() )
 749              $comment->is_test = 'true';
 750  
 751          $post = get_post( $comment->comment_post_ID );
 752  
 753          if ( ! is_null( $post ) ) {
 754              $comment->comment_post_modified_gmt = $post->post_modified_gmt;
 755          }
 756  
 757          $response = Akismet::http_post( Akismet::build_query( $comment ), 'submit-spam' );
 758  
 759          update_comment_meta( $comment_id, 'akismet_user_result', 'true' );
 760  
 761          if ( $comment->reporter ) {
 762              update_comment_meta( $comment_id, 'akismet_user', $comment->reporter );
 763          }
 764  
 765          do_action('akismet_submit_spam_comment', $comment_id, $response[1]);
 766      }
 767  
 768  	public static function submit_nonspam_comment( $comment_id ) {
 769          global $wpdb, $current_user, $current_site;
 770  
 771          $comment_id = (int) $comment_id;
 772  
 773          $comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $comment_id ) );
 774          if ( !$comment ) // it was deleted
 775              return;
 776  
 777          self::update_comment_history( $comment_id, '', 'report-ham' );
 778  
 779          // If the user hasn't configured Akismet, there's nothing else to do at this point.
 780          if ( ! self::get_api_key() ) {
 781              return;
 782          }
 783  
 784          // use the original version stored in comment_meta if available
 785          $as_submitted = self::sanitize_comment_as_submitted( get_comment_meta( $comment_id, 'akismet_as_submitted', true ) );
 786  
 787          if ( $as_submitted && is_array($as_submitted) && isset($as_submitted['comment_content']) )
 788              $comment = (object) array_merge( (array)$comment, $as_submitted );
 789  
 790          $comment->blog         = get_option( 'home' );
 791          $comment->blog_lang    = get_locale();
 792          $comment->blog_charset = get_option('blog_charset');
 793          $comment->permalink    = get_permalink( $comment->comment_post_ID );
 794          $comment->user_role    = '';
 795  
 796          if ( is_object($current_user) )
 797              $comment->reporter = $current_user->user_login;
 798  
 799          if ( is_object($current_site) )
 800              $comment->site_domain = $current_site->domain;
 801  
 802          if ( ! empty( $comment->user_ID ) ) {
 803              $comment->user_role = Akismet::get_user_roles( $comment->user_ID );
 804          }
 805  
 806          if ( Akismet::is_test_mode() )
 807              $comment->is_test = 'true';
 808  
 809          $post = get_post( $comment->comment_post_ID );
 810  
 811          if ( ! is_null( $post ) ) {
 812              $comment->comment_post_modified_gmt = $post->post_modified_gmt;
 813          }
 814  
 815          $response = self::http_post( Akismet::build_query( $comment ), 'submit-ham' );
 816  
 817          update_comment_meta( $comment_id, 'akismet_user_result', 'false' );
 818  
 819          if ( $comment->reporter ) {
 820              update_comment_meta( $comment_id, 'akismet_user', $comment->reporter );
 821          }
 822  
 823          do_action('akismet_submit_nonspam_comment', $comment_id, $response[1]);
 824      }
 825  
 826  	public static function cron_recheck() {
 827          global $wpdb;
 828  
 829          $api_key = self::get_api_key();
 830  
 831          $status = self::verify_key( $api_key );
 832          if ( get_option( 'akismet_alert_code' ) || $status == 'invalid' ) {
 833              // since there is currently a problem with the key, reschedule a check for 6 hours hence
 834              wp_schedule_single_event( time() + 21600, 'akismet_schedule_cron_recheck' );
 835              do_action( 'akismet_scheduled_recheck', 'key-problem-' . get_option( 'akismet_alert_code' ) . '-' . $status );
 836              return false;
 837          }
 838  
 839          delete_option('akismet_available_servers');
 840  
 841          $comment_errors = $wpdb->get_col( "SELECT comment_id FROM {$wpdb->commentmeta} WHERE meta_key = 'akismet_error'    LIMIT 100" );
 842          
 843          load_plugin_textdomain( 'akismet' );
 844  
 845          foreach ( (array) $comment_errors as $comment_id ) {
 846              // if the comment no longer exists, or is too old, remove the meta entry from the queue to avoid getting stuck
 847              $comment = get_comment( $comment_id );
 848  
 849              if (
 850                  ! $comment // Comment has been deleted
 851                  || strtotime( $comment->comment_date_gmt ) < strtotime( "-15 days" ) // Comment is too old.
 852                  || $comment->comment_approved !== "0" // Comment is no longer in the Pending queue
 853                  ) {
 854                  delete_comment_meta( $comment_id, 'akismet_error' );
 855                  delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
 856                  continue;
 857              }
 858  
 859              add_comment_meta( $comment_id, 'akismet_rechecking', true );
 860              $status = self::check_db_comment( $comment_id, 'retry' );
 861  
 862              $event = '';
 863              if ( $status == 'true' ) {
 864                  $event = 'cron-retry-spam';
 865              } elseif ( $status == 'false' ) {
 866                  $event = 'cron-retry-ham';
 867              }
 868  
 869              // If we got back a legit response then update the comment history
 870              // other wise just bail now and try again later.  No point in
 871              // re-trying all the comments once we hit one failure.
 872              if ( !empty( $event ) ) {
 873                  delete_comment_meta( $comment_id, 'akismet_error' );
 874                  self::update_comment_history( $comment_id, '', $event );
 875                  update_comment_meta( $comment_id, 'akismet_result', $status );
 876                  // make sure the comment status is still pending.  if it isn't, that means the user has already moved it elsewhere.
 877                  $comment = get_comment( $comment_id );
 878                  if ( $comment && 'unapproved' == wp_get_comment_status( $comment_id ) ) {
 879                      if ( $status == 'true' ) {
 880                          wp_spam_comment( $comment_id );
 881                      } elseif ( $status == 'false' ) {
 882                          // comment is good, but it's still in the pending queue.  depending on the moderation settings
 883                          // we may need to change it to approved.
 884                          if ( check_comment($comment->comment_author, $comment->comment_author_email, $comment->comment_author_url, $comment->comment_content, $comment->comment_author_IP, $comment->comment_agent, $comment->comment_type) )
 885                              wp_set_comment_status( $comment_id, 1 );
 886                          else if ( get_comment_meta( $comment_id, 'akismet_delayed_moderation_email', true ) )
 887                              wp_notify_moderator( $comment_id );
 888                      }
 889                  }
 890                  
 891                  delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
 892              } else {
 893                  // If this comment has been pending moderation for longer than MAX_DELAY_BEFORE_MODERATION_EMAIL,
 894                  // send a moderation email now.
 895                  if ( ( intval( gmdate( 'U' ) ) - strtotime( $comment->comment_date_gmt ) ) < self::MAX_DELAY_BEFORE_MODERATION_EMAIL ) {
 896                      delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
 897                      wp_notify_moderator( $comment_id );
 898                  }
 899  
 900                  delete_comment_meta( $comment_id, 'akismet_rechecking' );
 901                  wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
 902                  do_action( 'akismet_scheduled_recheck', 'check-db-comment-' . $status );
 903                  return;
 904              }
 905              delete_comment_meta( $comment_id, 'akismet_rechecking' );
 906          }
 907  
 908          $remaining = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->commentmeta} WHERE meta_key = 'akismet_error'" );
 909          if ( $remaining && !wp_next_scheduled('akismet_schedule_cron_recheck') ) {
 910              wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
 911              do_action( 'akismet_scheduled_recheck', 'remaining' );
 912          }
 913      }
 914  
 915  	public static function fix_scheduled_recheck() {
 916          $future_check = wp_next_scheduled( 'akismet_schedule_cron_recheck' );
 917          if ( !$future_check ) {
 918              return;
 919          }
 920  
 921          if ( get_option( 'akismet_alert_code' ) > 0 ) {
 922              return;
 923          }
 924  
 925          $check_range = time() + 1200;
 926          if ( $future_check > $check_range ) {
 927              wp_clear_scheduled_hook( 'akismet_schedule_cron_recheck' );
 928              wp_schedule_single_event( time() + 300, 'akismet_schedule_cron_recheck' );
 929              do_action( 'akismet_scheduled_recheck', 'fix-scheduled-recheck' );
 930          }
 931      }
 932  
 933  	public static function add_comment_nonce( $post_id ) {
 934          /**
 935           * To disable the Akismet comment nonce, add a filter for the 'akismet_comment_nonce' tag
 936           * and return any string value that is not 'true' or '' (empty string).
 937           *
 938           * Don't return boolean false, because that implies that the 'akismet_comment_nonce' option
 939           * has not been set and that Akismet should just choose the default behavior for that
 940           * situation.
 941           */
 942          
 943          if ( ! self::get_api_key() ) {
 944              return;
 945          }
 946          
 947          $akismet_comment_nonce_option = apply_filters( 'akismet_comment_nonce', get_option( 'akismet_comment_nonce' ) );
 948  
 949          if ( $akismet_comment_nonce_option == 'true' || $akismet_comment_nonce_option == '' ) {
 950              echo '<p style="display: none;">';
 951              wp_nonce_field( 'akismet_comment_nonce_' . $post_id, 'akismet_comment_nonce', FALSE );
 952              echo '</p>';
 953          }
 954      }
 955  
 956  	public static function is_test_mode() {
 957          return defined('AKISMET_TEST_MODE') && AKISMET_TEST_MODE;
 958      }
 959      
 960  	public static function allow_discard() {
 961          if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
 962              return false;
 963          if ( is_user_logged_in() )
 964              return false;
 965      
 966          return ( get_option( 'akismet_strictness' ) === '1'  );
 967      }
 968  
 969  	public static function get_ip_address() {
 970          return isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : null;
 971      }
 972      
 973      /**
 974       * Do these two comments, without checking the comment_ID, "match"?
 975       *
 976       * @param mixed $comment1 A comment object or array.
 977       * @param mixed $comment2 A comment object or array.
 978       * @return bool Whether the two comments should be treated as the same comment.
 979       */
 980  	private static function comments_match( $comment1, $comment2 ) {
 981          $comment1 = (array) $comment1;
 982          $comment2 = (array) $comment2;
 983  
 984          // Set default values for these strings that we check in order to simplify
 985          // the checks and avoid PHP warnings.
 986          if ( ! isset( $comment1['comment_author'] ) ) {
 987              $comment1['comment_author'] = '';
 988          }
 989  
 990          if ( ! isset( $comment2['comment_author'] ) ) {
 991              $comment2['comment_author'] = '';
 992          }
 993  
 994          if ( ! isset( $comment1['comment_author_email'] ) ) {
 995              $comment1['comment_author_email'] = '';
 996          }
 997  
 998          if ( ! isset( $comment2['comment_author_email'] ) ) {
 999              $comment2['comment_author_email'] = '';
1000          }
1001  
1002          $comments_match = (
1003                 isset( $comment1['comment_post_ID'], $comment2['comment_post_ID'] )
1004              && intval( $comment1['comment_post_ID'] ) == intval( $comment2['comment_post_ID'] )
1005              && (
1006                  // The comment author length max is 255 characters, limited by the TINYTEXT column type.
1007                  // If the comment author includes multibyte characters right around the 255-byte mark, they
1008                  // may be stripped when the author is saved in the DB, so a 300+ char author may turn into
1009                  // a 253-char author when it's saved, not 255 exactly.  The longest possible character is
1010                  // theoretically 6 bytes, so we'll only look at the first 248 bytes to be safe.
1011                  substr( $comment1['comment_author'], 0, 248 ) == substr( $comment2['comment_author'], 0, 248 )
1012                  || substr( stripslashes( $comment1['comment_author'] ), 0, 248 ) == substr( $comment2['comment_author'], 0, 248 )
1013                  || substr( $comment1['comment_author'], 0, 248 ) == substr( stripslashes( $comment2['comment_author'] ), 0, 248 )
1014                  // Certain long comment author names will be truncated to nothing, depending on their encoding.
1015                  || ( ! $comment1['comment_author'] && strlen( $comment2['comment_author'] ) > 248 )
1016                  || ( ! $comment2['comment_author'] && strlen( $comment1['comment_author'] ) > 248 )
1017                  )
1018              && (
1019                  // The email max length is 100 characters, limited by the VARCHAR(100) column type.
1020                  // Same argument as above for only looking at the first 93 characters.
1021                  substr( $comment1['comment_author_email'], 0, 93 ) == substr( $comment2['comment_author_email'], 0, 93 )
1022                  || substr( stripslashes( $comment1['comment_author_email'] ), 0, 93 ) == substr( $comment2['comment_author_email'], 0, 93 )
1023                  || substr( $comment1['comment_author_email'], 0, 93 ) == substr( stripslashes( $comment2['comment_author_email'] ), 0, 93 )
1024                  // Very long emails can be truncated and then stripped if the [0:100] substring isn't a valid address.
1025                  || ( ! $comment1['comment_author_email'] && strlen( $comment2['comment_author_email'] ) > 100 )
1026                  || ( ! $comment2['comment_author_email'] && strlen( $comment1['comment_author_email'] ) > 100 )
1027              )
1028          );
1029  
1030          return $comments_match;
1031      }
1032      
1033      // Does the supplied comment match the details of the one most recently stored in self::$last_comment?
1034  	public static function matches_last_comment( $comment ) {
1035          return self::comments_match( self::$last_comment, $comment );
1036      }
1037  
1038  	private static function get_user_agent() {
1039          return isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : null;
1040      }
1041  
1042  	private static function get_referer() {
1043          return isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : null;
1044      }
1045  
1046      // return a comma-separated list of role names for the given user
1047  	public static function get_user_roles( $user_id ) {
1048          $roles = false;
1049  
1050          if ( !class_exists('WP_User') )
1051              return false;
1052  
1053          if ( $user_id > 0 ) {
1054              $comment_user = new WP_User( $user_id );
1055              if ( isset( $comment_user->roles ) )
1056                  $roles = join( ',', $comment_user->roles );
1057          }
1058  
1059          if ( is_multisite() && is_super_admin( $user_id ) ) {
1060              if ( empty( $roles ) ) {
1061                  $roles = 'super_admin';
1062              } else {
1063                  $comment_user->roles[] = 'super_admin';
1064                  $roles = join( ',', $comment_user->roles );
1065              }
1066          }
1067  
1068          return $roles;
1069      }
1070  
1071      // filter handler used to return a spam result to pre_comment_approved
1072  	public static function last_comment_status( $approved, $comment ) {
1073          if ( is_null( self::$last_comment_result ) ) {
1074              // We didn't have reason to store the result of the last check.
1075              return $approved;
1076          }
1077  
1078          // Only do this if it's the correct comment
1079          if ( ! self::matches_last_comment( $comment ) ) {
1080              self::log( "comment_is_spam mismatched comment, returning unaltered $approved" );
1081              return $approved;
1082          }
1083  
1084          if ( 'trash' === $approved ) {
1085              // If the last comment we checked has had its approval set to 'trash',
1086              // then it failed the comment blacklist check. Let that blacklist override
1087              // the spam check, since users have the (valid) expectation that when
1088              // they fill out their blacklists, comments that match it will always
1089              // end up in the trash.
1090              return $approved;
1091          }
1092  
1093          // bump the counter here instead of when the filter is added to reduce the possibility of overcounting
1094          if ( $incr = apply_filters('akismet_spam_count_incr', 1) )
1095              update_option( 'akismet_spam_count', get_option('akismet_spam_count') + $incr );
1096  
1097          return self::$last_comment_result;
1098      }
1099      
1100      /**
1101       * If Akismet is temporarily unreachable, we don't want to "spam" the blogger with
1102       * moderation emails for comments that will be automatically cleared or spammed on
1103       * the next retry.
1104       *
1105       * For comments that will be rechecked later, empty the list of email addresses that
1106       * the moderation email would be sent to.
1107       *
1108       * @param array $emails An array of email addresses that the moderation email will be sent to.
1109       * @param int $comment_id The ID of the relevant comment.
1110       * @return array An array of email addresses that the moderation email will be sent to.
1111       */
1112  	public static function disable_moderation_emails_if_unreachable( $emails, $comment_id ) {
1113          if ( ! empty( self::$prevent_moderation_email_for_these_comments ) && ! empty( $emails ) ) {
1114              $comment = get_comment( $comment_id );
1115  
1116              foreach ( self::$prevent_moderation_email_for_these_comments as $possible_match ) {
1117                  if ( self::comments_match( $possible_match, $comment ) ) {
1118                      update_comment_meta( $comment_id, 'akismet_delayed_moderation_email', true );
1119                      return array();
1120                  }
1121              }
1122          }
1123  
1124          return $emails;
1125      }
1126  
1127  	public static function _cmp_time( $a, $b ) {
1128          return $a['time'] > $b['time'] ? -1 : 1;
1129      }
1130  
1131  	public static function _get_microtime() {
1132          $mtime = explode( ' ', microtime() );
1133          return $mtime[1] + $mtime[0];
1134      }
1135  
1136      /**
1137       * Make a POST request to the Akismet API.
1138       *
1139       * @param string $request The body of the request.
1140       * @param string $path The path for the request.
1141       * @param string $ip The specific IP address to hit.
1142       * @return array A two-member array consisting of the headers and the response body, both empty in the case of a failure.
1143       */
1144  	public static function http_post( $request, $path, $ip=null ) {
1145  
1146          $akismet_ua = sprintf( 'WordPress/%s | Akismet/%s', $GLOBALS['wp_version'], constant( 'AKISMET_VERSION' ) );
1147          $akismet_ua = apply_filters( 'akismet_ua', $akismet_ua );
1148  
1149          $content_length = strlen( $request );
1150  
1151          $api_key   = self::get_api_key();
1152          $host      = self::API_HOST;
1153  
1154          if ( !empty( $api_key ) )
1155              $host = $api_key.'.'.$host;
1156  
1157          $http_host = $host;
1158          // use a specific IP if provided
1159          // needed by Akismet_Admin::check_server_connectivity()
1160          if ( $ip && long2ip( ip2long( $ip ) ) ) {
1161              $http_host = $ip;
1162          }
1163  
1164          $http_args = array(
1165              'body' => $request,
1166              'headers' => array(
1167                  'Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' ),
1168                  'Host' => $host,
1169                  'User-Agent' => $akismet_ua,
1170              ),
1171              'httpversion' => '1.0',
1172              'timeout' => 15
1173          );
1174  
1175          $akismet_url = $http_akismet_url = "http://{$http_host}/1.1/{$path}";
1176  
1177          /**
1178           * Try SSL first; if that fails, try without it and don't try it again for a while.
1179           */
1180  
1181          $ssl = $ssl_failed = false;
1182  
1183          // Check if SSL requests were disabled fewer than X hours ago.
1184          $ssl_disabled = get_option( 'akismet_ssl_disabled' );
1185  
1186          if ( $ssl_disabled && $ssl_disabled < ( time() - 60 * 60 * 24 ) ) { // 24 hours
1187              $ssl_disabled = false;
1188              delete_option( 'akismet_ssl_disabled' );
1189          }
1190          else if ( $ssl_disabled ) {
1191              do_action( 'akismet_ssl_disabled' );
1192          }
1193  
1194          if ( ! $ssl_disabled && ( $ssl = wp_http_supports( array( 'ssl' ) ) ) ) {
1195              $akismet_url = set_url_scheme( $akismet_url, 'https' );
1196  
1197              do_action( 'akismet_https_request_pre' );
1198          }
1199  
1200          $response = wp_remote_post( $akismet_url, $http_args );
1201  
1202          Akismet::log( compact( 'akismet_url', 'http_args', 'response' ) );
1203  
1204          if ( $ssl && is_wp_error( $response ) ) {
1205              do_action( 'akismet_https_request_failure', $response );
1206  
1207              // Intermittent connection problems may cause the first HTTPS
1208              // request to fail and subsequent HTTP requests to succeed randomly.
1209              // Retry the HTTPS request once before disabling SSL for a time.
1210              $response = wp_remote_post( $akismet_url, $http_args );
1211              
1212              Akismet::log( compact( 'akismet_url', 'http_args', 'response' ) );
1213  
1214              if ( is_wp_error( $response ) ) {
1215                  $ssl_failed = true;
1216  
1217                  do_action( 'akismet_https_request_failure', $response );
1218  
1219                  do_action( 'akismet_http_request_pre' );
1220  
1221                  // Try the request again without SSL.
1222                  $response = wp_remote_post( $http_akismet_url, $http_args );
1223  
1224                  Akismet::log( compact( 'http_akismet_url', 'http_args', 'response' ) );
1225              }
1226          }
1227  
1228          if ( is_wp_error( $response ) ) {
1229              do_action( 'akismet_request_failure', $response );
1230  
1231              return array( '', '' );
1232          }
1233  
1234          if ( $ssl_failed ) {
1235              // The request failed when using SSL but succeeded without it. Disable SSL for future requests.
1236              update_option( 'akismet_ssl_disabled', time() );
1237              
1238              do_action( 'akismet_https_disabled' );
1239          }
1240          
1241          $simplified_response = array( $response['headers'], $response['body'] );
1242          
1243          self::update_alert( $simplified_response );
1244  
1245          return $simplified_response;
1246      }
1247  
1248      // given a response from an API call like check_key_status(), update the alert code options if an alert is present.
1249  	public static function update_alert( $response ) {
1250          $code = $msg = null;
1251          if ( isset( $response[0]['x-akismet-alert-code'] ) ) {
1252              $code = $response[0]['x-akismet-alert-code'];
1253              $msg  = $response[0]['x-akismet-alert-msg'];
1254          }
1255  
1256          // only call update_option() if the value has changed
1257          if ( $code != get_option( 'akismet_alert_code' ) ) {
1258              if ( ! $code ) {
1259                  delete_option( 'akismet_alert_code' );
1260                  delete_option( 'akismet_alert_msg' );
1261              }
1262              else {
1263                  update_option( 'akismet_alert_code', $code );
1264                  update_option( 'akismet_alert_msg', $msg );
1265              }
1266          }
1267      }
1268  
1269  	public static function load_form_js() {
1270          if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
1271              return;
1272          }
1273  
1274          if ( ! self::get_api_key() ) {
1275              return;
1276          }
1277  
1278          wp_register_script( 'akismet-form', plugin_dir_url( __FILE__ ) . '_inc/form.js', array(), AKISMET_VERSION, true );
1279          wp_enqueue_script( 'akismet-form' );
1280      }
1281      
1282      /**
1283       * Mark form.js as async. Because nothing depends on it, it can run at any time
1284       * after it's loaded, and the browser won't have to wait for it to load to continue
1285       * parsing the rest of the page.
1286       */
1287  	public static function set_form_js_async( $tag, $handle, $src ) {
1288          if ( 'akismet-form' !== $handle ) {
1289              return $tag;
1290          }
1291          
1292          return preg_replace( '/^<script /i', '<script async="async" ', $tag );
1293      }
1294      
1295  	public static function inject_ak_js( $post_id ) {
1296          echo '<input type="hidden" id="ak_js" name="ak_js" value="' . mt_rand( 0, 250 ) . '"/>';
1297          echo '<textarea name="ak_hp_textarea" cols="45" rows="8" maxlength="100" style="display: none !important;"></textarea>';
1298      }
1299  
1300  	private static function bail_on_activation( $message, $deactivate = true ) {
1301  ?>
1302  <!doctype html>
1303  <html>
1304  <head>
1305  <meta charset="<?php bloginfo( 'charset' ); ?>" />
1306  <style>
1307  * {
1308      text-align: center;
1309      margin: 0;
1310      padding: 0;
1311      font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
1312  }
1313  p {
1314      margin-top: 1em;
1315      font-size: 18px;
1316  }
1317  </style>
1318  </head>
1319  <body>
1320  <p><?php echo esc_html( $message ); ?></p>
1321  </body>
1322  </html>
1323  <?php
1324          if ( $deactivate ) {
1325              $plugins = get_option( 'active_plugins' );
1326              $akismet = plugin_basename( AKISMET__PLUGIN_DIR . 'akismet.php' );
1327              $update  = false;
1328              foreach ( $plugins as $i => $plugin ) {
1329                  if ( $plugin === $akismet ) {
1330                      $plugins[$i] = false;
1331                      $update = true;
1332                  }
1333              }
1334  
1335              if ( $update ) {
1336                  update_option( 'active_plugins', array_filter( $plugins ) );
1337              }
1338          }
1339          exit;
1340      }
1341  
1342  	public static function view( $name, array $args = array() ) {
1343          $args = apply_filters( 'akismet_view_arguments', $args, $name );
1344          
1345          foreach ( $args AS $key => $val ) {
1346              $$key = $val;
1347          }
1348          
1349          load_plugin_textdomain( 'akismet' );
1350  
1351          $file = AKISMET__PLUGIN_DIR . 'views/'. $name . '.php';
1352  
1353          include( $file );
1354      }
1355  
1356      /**
1357       * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
1358       * @static
1359       */
1360  	public static function plugin_activation() {
1361          if ( version_compare( $GLOBALS['wp_version'], AKISMET__MINIMUM_WP_VERSION, '<' ) ) {
1362              load_plugin_textdomain( 'akismet' );
1363              
1364              $message = '<strong>'.sprintf(esc_html__( 'Akismet %s requires WordPress %s or higher.' , 'akismet'), AKISMET_VERSION, AKISMET__MINIMUM_WP_VERSION ).'</strong> '.sprintf(__('Please <a href="%1$s">upgrade WordPress</a> to a current version, or <a href="%2$s">downgrade to version 2.4 of the Akismet plugin</a>.', 'akismet'), 'https://codex.wordpress.org/Upgrading_WordPress', 'https://wordpress.org/extend/plugins/akismet/download/');
1365  
1366              Akismet::bail_on_activation( $message );
1367          } elseif ( ! empty( $_SERVER['SCRIPT_NAME'] ) && false !== strpos( $_SERVER['SCRIPT_NAME'], '/wp-admin/plugins.php' ) ) {
1368              add_option( 'Activated_Akismet', true );
1369          }
1370      }
1371  
1372      /**
1373       * Removes all connection options
1374       * @static
1375       */
1376  	public static function plugin_deactivation( ) {
1377          self::deactivate_key( self::get_api_key() );
1378          
1379          // Remove any scheduled cron jobs.
1380          $akismet_cron_events = array(
1381              'akismet_schedule_cron_recheck',
1382              'akismet_scheduled_delete',
1383          );
1384          
1385          foreach ( $akismet_cron_events as $akismet_cron_event ) {
1386              $timestamp = wp_next_scheduled( $akismet_cron_event );
1387              
1388              if ( $timestamp ) {
1389                  wp_unschedule_event( $timestamp, $akismet_cron_event );
1390              }
1391          }
1392      }
1393      
1394      /**
1395       * Essentially a copy of WP's build_query but one that doesn't expect pre-urlencoded values.
1396       *
1397       * @param array $args An array of key => value pairs
1398       * @return string A string ready for use as a URL query string.
1399       */
1400  	public static function build_query( $args ) {
1401          return _http_build_query( $args, '', '&' );
1402      }
1403  
1404      /**
1405       * Log debugging info to the error log.
1406       *
1407       * Enabled when WP_DEBUG_LOG is enabled (and WP_DEBUG, since according to
1408       * core, "WP_DEBUG_DISPLAY and WP_DEBUG_LOG perform no function unless
1409       * WP_DEBUG is true), but can be disabled via the akismet_debug_log filter.
1410       *
1411       * @param mixed $akismet_debug The data to log.
1412       */
1413  	public static function log( $akismet_debug ) {
1414          if ( apply_filters( 'akismet_debug_log', defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG && defined( 'AKISMET_DEBUG' ) && AKISMET_DEBUG ) ) {
1415              error_log( print_r( compact( 'akismet_debug' ), true ) );
1416          }
1417      }
1418  
1419  	public static function pre_check_pingback( $method ) {
1420          if ( $method !== 'pingback.ping' )
1421              return;
1422  
1423          global $wp_xmlrpc_server;
1424      
1425          if ( !is_object( $wp_xmlrpc_server ) )
1426              return false;
1427      
1428          // Lame: tightly coupled with the IXR class.
1429          $args = $wp_xmlrpc_server->message->params;
1430      
1431          if ( !empty( $args[1] ) ) {
1432              $post_id = url_to_postid( $args[1] );
1433  
1434              // If pingbacks aren't open on this post, we'll still check whether this request is part of a potential DDOS,
1435              // but indicate to the server that pingbacks are indeed closed so we don't include this request in the user's stats,
1436              // since the user has already done their part by disabling pingbacks.
1437              $pingbacks_closed = false;
1438              
1439              $post = get_post( $post_id );
1440              
1441              if ( ! $post || ! pings_open( $post ) ) {
1442                  $pingbacks_closed = true;
1443              }
1444  
1445              $comment = array(
1446                  'comment_author_url' => $args[0],
1447                  'comment_post_ID' => $post_id,
1448                  'comment_author' => '',
1449                  'comment_author_email' => '',
1450                  'comment_content' => '',
1451                  'comment_type' => 'pingback',
1452                  'akismet_pre_check' => '1',
1453                  'comment_pingback_target' => $args[1],
1454                  'pingbacks_closed' => $pingbacks_closed ? '1' : '0',
1455              );
1456  
1457              $comment = Akismet::auto_check_comment( $comment );
1458  
1459              if ( isset( $comment['akismet_result'] ) && 'true' == $comment['akismet_result'] ) {
1460                  // Lame: tightly coupled with the IXR classes. Unfortunately the action provides no context and no way to return anything.
1461                  $wp_xmlrpc_server->error( new IXR_Error( 0, 'Invalid discovery target' ) );
1462              }
1463          }
1464      }
1465  
1466      /**
1467       * Ensure that we are loading expected scalar values from akismet_as_submitted commentmeta.
1468       *
1469       * @param mixed $meta_value
1470       * @return mixed
1471       */
1472  	private static function sanitize_comment_as_submitted( $meta_value ) {
1473          if ( empty( $meta_value ) ) {
1474              return $meta_value;
1475          }
1476  
1477          $meta_value = (array) $meta_value;
1478  
1479          foreach ( $meta_value as $key => $value ) {
1480              if ( ! is_scalar( $value ) ) {
1481                  unset( $meta_value[ $key ] );
1482              } else {
1483                  // These can change, so they're not explicitly listed in comment_as_submitted_allowed_keys.
1484                  if ( strpos( $key, 'POST_ak_' ) === 0 ) {
1485                      continue;
1486                  }
1487  
1488                  if ( ! isset( self::$comment_as_submitted_allowed_keys[ $key ] ) ) {
1489                      unset( $meta_value[ $key ] );
1490                  }
1491              }
1492          }
1493  
1494          return $meta_value;
1495      }
1496      
1497  	public static function predefined_api_key() {
1498          if ( defined( 'WPCOM_API_KEY' ) ) {
1499              return true;
1500          }
1501          
1502          return apply_filters( 'akismet_predefined_api_key', false );
1503      }
1504  
1505      /**
1506       * Controls the display of a privacy related notice underneath the comment form using the `akismet_comment_form_privacy_notice` option and filter respectively.
1507       * Default is top not display the notice, leaving the choice to site admins, or integrators.
1508       */
1509  	public static function display_comment_form_privacy_notice() {
1510          if ( 'display' !== apply_filters( 'akismet_comment_form_privacy_notice', get_option( 'akismet_comment_form_privacy_notice', 'hide' ) ) ) {
1511              return;
1512          }
1513          echo apply_filters(
1514              'akismet_comment_form_privacy_notice_markup',
1515              '<p class="akismet_comment_form_privacy_notice">' . sprintf(
1516                  __( 'This site uses Akismet to reduce spam. <a href="%s" target="_blank" rel="nofollow noopener">Learn how your comment data is processed</a>.', 'akismet' ),
1517                  'https://akismet.com/privacy/'
1518              ) . '</p>'
1519          );
1520      }
1521  }


Generated : Mon Jan 25 08:20:01 2021 Cross-referenced by PHPXref