[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


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