]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-content/plugins/akismet/class.akismet.php
WordPress 4.1-scripts
[autoinstalls/wordpress.git] / wp-content / plugins / akismet / class.akismet.php
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         
13         public static function init() {
14                 if ( ! self::$initiated ) {
15                         self::init_hooks();
16                 }
17         }
18
19         /**
20          * Initializes WordPress hooks
21          */
22         private static function init_hooks() {
23                 self::$initiated = true;
24
25                 add_action( 'wp_insert_comment', array( 'Akismet', 'auto_check_update_meta' ), 10, 2 );
26                 add_action( 'preprocess_comment', array( 'Akismet', 'auto_check_comment' ), 1 );
27                 add_action( 'akismet_scheduled_delete', array( 'Akismet', 'delete_old_comments' ) );
28                 add_action( 'akismet_scheduled_delete', array( 'Akismet', 'delete_old_comments_meta' ) );
29                 add_action( 'akismet_schedule_cron_recheck', array( 'Akismet', 'cron_recheck' ) );
30
31                 $akismet_comment_nonce_option = apply_filters( 'akismet_comment_nonce', get_option( 'akismet_comment_nonce' ) );
32
33                 if ( $akismet_comment_nonce_option == 'true' || $akismet_comment_nonce_option == '' )
34                         add_action( 'comment_form',  array( 'Akismet',  'add_comment_nonce' ), 1 );
35
36                 add_action( 'admin_head-edit-comments.php', array( 'Akismet', 'load_form_js' ) );
37                 add_action( 'comment_form', array( 'Akismet', 'load_form_js' ) );
38                 add_action( 'comment_form', array( 'Akismet', 'inject_ak_js' ) );
39
40                 add_filter( 'comment_moderation_recipients', array( 'Akismet', 'disable_moderation_emails_if_unreachable' ), 1000, 2 );
41                 add_filter( 'pre_comment_approved', array( 'Akismet', 'last_comment_status' ), 10, 2 );
42                 
43                 add_action( 'transition_comment_status', array( 'Akismet', 'transition_comment_status' ), 10, 3 );
44
45                 if ( '3.0.5' == $GLOBALS['wp_version'] ) {
46                         remove_filter( 'comment_text', 'wp_kses_data' );
47                         if ( is_admin() )
48                                 add_filter( 'comment_text', 'wp_kses_post' );
49                 }
50         }
51
52         public static function get_api_key() {
53                 return apply_filters( 'akismet_get_api_key', defined('WPCOM_API_KEY') ? constant('WPCOM_API_KEY') : get_option('wordpress_api_key') );
54         }
55
56         public static function check_key_status( $key, $ip = null ) {
57                 return self::http_post( Akismet::build_query( array( 'key' => $key, 'blog' => get_option('home') ) ), 'verify-key', $ip );
58         }
59
60         public static function verify_key( $key, $ip = null ) {
61                 $response = self::check_key_status( $key, $ip );
62
63                 if ( $response[1] != 'valid' && $response[1] != 'invalid' )
64                         return 'failed';
65
66                 self::update_alert( $response );
67
68                 return $response[1];
69         }
70
71         public static function auto_check_comment( $commentdata ) {
72                 self::$last_comment_result = null;
73
74                 $comment = $commentdata;
75
76                 $comment['user_ip']      = self::get_ip_address();
77                 $comment['user_agent']   = self::get_user_agent();
78                 $comment['referrer']     = self::get_referer();
79                 $comment['blog']         = get_option('home');
80                 $comment['blog_lang']    = get_locale();
81                 $comment['blog_charset'] = get_option('blog_charset');
82                 $comment['permalink']    = get_permalink( $comment['comment_post_ID'] );
83
84                 if ( !empty( $comment['user_ID'] ) )
85                         $comment['user_role'] = Akismet::get_user_roles( $comment['user_ID'] );
86
87                 $akismet_nonce_option = apply_filters( 'akismet_comment_nonce', get_option( 'akismet_comment_nonce' ) );
88                 $comment['akismet_comment_nonce'] = 'inactive';
89                 if ( $akismet_nonce_option == 'true' || $akismet_nonce_option == '' ) {
90                         $comment['akismet_comment_nonce'] = 'failed';
91                         if ( isset( $_POST['akismet_comment_nonce'] ) && wp_verify_nonce( $_POST['akismet_comment_nonce'], 'akismet_comment_nonce_' . $comment['comment_post_ID'] ) )
92                                 $comment['akismet_comment_nonce'] = 'passed';
93
94                         // comment reply in wp-admin
95                         if ( isset( $_POST['_ajax_nonce-replyto-comment'] ) && check_ajax_referer( 'replyto-comment', '_ajax_nonce-replyto-comment' ) )
96                                 $comment['akismet_comment_nonce'] = 'passed';
97
98                 }
99
100                 if ( self::is_test_mode() )
101                         $comment['is_test'] = 'true';
102
103                 foreach( $_POST as $key => $value ) {
104                         if ( is_string( $value ) )
105                                 $comment["POST_{$key}"] = $value;
106                 }
107
108                 $ignore = array( 'HTTP_COOKIE', 'HTTP_COOKIE2', 'PHP_AUTH_PW' );
109
110                 foreach ( $_SERVER as $key => $value ) {
111                         if ( !in_array( $key, $ignore ) && is_string($value) )
112                                 $comment["$key"] = $value;
113                         else
114                                 $comment["$key"] = '';
115                 }
116
117                 $post = get_post( $comment['comment_post_ID'] );
118                 $comment[ 'comment_post_modified_gmt' ] = $post->post_modified_gmt;
119
120                 $response = self::http_post( Akismet::build_query( $comment ), 'comment-check' );
121
122                 do_action( 'akismet_comment_check_response', $response );
123
124                 self::update_alert( $response );
125
126                 $commentdata['comment_as_submitted'] = array_intersect_key( $comment, 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' => '' ) );
127                 $commentdata['akismet_result']       = $response[1];
128
129                 if ( isset( $response[0]['x-akismet-pro-tip'] ) )
130                 $commentdata['akismet_pro_tip'] = $response[0]['x-akismet-pro-tip'];
131
132                 if ( isset( $response[0]['x-akismet-error'] ) ) {
133                         // An error occurred that we anticipated (like a suspended key) and want the user to act on.
134                         // Send to moderation.
135                         self::$last_comment_result = '0';
136                 }
137                 else if ( 'true' == $response[1] ) {
138                         // akismet_spam_count will be incremented later by comment_is_spam()
139                         self::$last_comment_result = 'spam';
140
141                         $discard = ( isset( $commentdata['akismet_pro_tip'] ) && $commentdata['akismet_pro_tip'] === 'discard' && self::allow_discard() );
142
143                         do_action( 'akismet_spam_caught', $discard );
144
145                         if ( $discard ) {
146                                 // akismet_result_spam() won't be called so bump the counter here
147                                 if ( $incr = apply_filters('akismet_spam_count_incr', 1) )
148                                         update_option( 'akismet_spam_count', get_option('akismet_spam_count') + $incr );
149                                 $redirect_to = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : get_permalink( $post );
150                                 wp_safe_redirect( esc_url_raw( $redirect_to ) );
151                                 die();
152                         }
153                 }
154                 
155                 // if the response is neither true nor false, hold the comment for moderation and schedule a recheck
156                 if ( 'true' != $response[1] && 'false' != $response[1] ) {
157                         if ( !current_user_can('moderate_comments') ) {
158                                 // Comment status should be moderated
159                                 self::$last_comment_result = '0';
160                         }
161                         if ( function_exists('wp_next_scheduled') && function_exists('wp_schedule_single_event') ) {
162                                 if ( !wp_next_scheduled( 'akismet_schedule_cron_recheck' ) ) {
163                                         wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
164                                 }
165                         }
166
167                         self::$prevent_moderation_email_for_these_comments[] = $commentdata;
168                 }
169
170                 if ( function_exists('wp_next_scheduled') && function_exists('wp_schedule_event') ) {
171                         // WP 2.1+: delete old comments daily
172                         if ( !wp_next_scheduled( 'akismet_scheduled_delete' ) )
173                                 wp_schedule_event( time(), 'daily', 'akismet_scheduled_delete' );
174                 }
175                 elseif ( (mt_rand(1, 10) == 3) ) {
176                         // WP 2.0: run this one time in ten
177                         self::delete_old_comments();
178                 }
179                 
180                 self::set_last_comment( $commentdata );
181                 self::fix_scheduled_recheck();
182
183                 return self::$last_comment;
184         }
185         
186         public static function get_last_comment() {
187                 return self::$last_comment;
188         }
189         
190         public static function set_last_comment( $comment ) {
191                 if ( is_null( $comment ) ) {
192                         self::$last_comment = null;
193                 }
194                 else {
195                         // We filter it here so that it matches the filtered comment data that we'll have to compare against later.
196                         // wp_filter_comment expects comment_author_IP
197                         self::$last_comment = wp_filter_comment(
198                                 array_merge(
199                                         array( 'comment_author_IP' => self::get_ip_address() ),
200                                         $comment
201                                 )
202                         );
203                 }
204         }
205
206         // this fires on wp_insert_comment.  we can't update comment_meta when auto_check_comment() runs
207         // because we don't know the comment ID at that point.
208         public static function auto_check_update_meta( $id, $comment ) {
209
210                 // failsafe for old WP versions
211                 if ( !function_exists('add_comment_meta') )
212                         return false;
213
214                 if ( !isset( self::$last_comment['comment_author_email'] ) )
215                         self::$last_comment['comment_author_email'] = '';
216
217                 // wp_insert_comment() might be called in other contexts, so make sure this is the same comment
218                 // as was checked by auto_check_comment
219                 if ( is_object( $comment ) && !empty( self::$last_comment ) && is_array( self::$last_comment ) ) {
220                         if ( self::matches_last_comment( $comment ) ) {
221                                         
222                                         load_plugin_textdomain( 'akismet' );
223                                         
224                                         // normal result: true or false
225                                         if ( self::$last_comment['akismet_result'] == 'true' ) {
226                                                 update_comment_meta( $comment->comment_ID, 'akismet_result', 'true' );
227                                                 self::update_comment_history( $comment->comment_ID, __('Akismet caught this comment as spam', 'akismet'), 'check-spam' );
228                                                 if ( $comment->comment_approved != 'spam' )
229                                                         self::update_comment_history( $comment->comment_ID, sprintf( __('Comment status was changed to %s', 'akismet'), $comment->comment_approved), 'status-changed'.$comment->comment_approved );
230                                         }
231                                         elseif ( self::$last_comment['akismet_result'] == 'false' ) {
232                                                 update_comment_meta( $comment->comment_ID, 'akismet_result', 'false' );
233                                                 self::update_comment_history( $comment->comment_ID, __('Akismet cleared this comment', 'akismet'), 'check-ham' );
234                                                 if ( $comment->comment_approved == 'spam' ) {
235                                                         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) )
236                                                                 self::update_comment_history( $comment->comment_ID, __('Comment was caught by wp_blacklist_check', 'akismet'), 'wp-blacklisted' );
237                                                         else
238                                                                 self::update_comment_history( $comment->comment_ID, sprintf( __('Comment status was changed to %s', 'akismet'), $comment->comment_approved), 'status-changed-'.$comment->comment_approved );
239                                                 }
240                                         } // abnormal result: error
241                                         else {
242                                                 update_comment_meta( $comment->comment_ID, 'akismet_error', time() );
243                                                 self::update_comment_history( $comment->comment_ID, sprintf( __('Akismet was unable to check this comment (response: %s), will automatically retry again later.', 'akismet'), substr(self::$last_comment['akismet_result'], 0, 50)), 'check-error' );
244                                         }
245
246                                         // record the complete original data as submitted for checking
247                                         if ( isset( self::$last_comment['comment_as_submitted'] ) )
248                                                 update_comment_meta( $comment->comment_ID, 'akismet_as_submitted', self::$last_comment['comment_as_submitted'] );
249
250                                         if ( isset( self::$last_comment['akismet_pro_tip'] ) )
251                                                 update_comment_meta( $comment->comment_ID, 'akismet_pro_tip', self::$last_comment['akismet_pro_tip'] );
252                         }
253                 }
254         }
255
256         public static function delete_old_comments() {
257                 global $wpdb;
258
259                 /**
260                  * Determines how many comments will be deleted in each batch.
261                  *
262                  * @param int The default, as defined by AKISMET_DELETE_LIMIT.
263                  */
264                 $delete_limit = apply_filters( 'akismet_delete_comment_limit', defined( 'AKISMET_DELETE_LIMIT' ) ? AKISMET_DELETE_LIMIT : 10000 );
265                 $delete_limit = max( 1, intval( $delete_limit ) );
266
267                 /**
268                  * Determines how many days a comment will be left in the Spam queue before being deleted.
269                  *
270                  * @param int The default number of days.
271                  */
272                 $delete_interval = apply_filters( 'akismet_delete_comment_interval', 15 );
273                 $delete_interval = max( 1, intval( $delete_interval ) );
274
275                 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 ) ) ) {
276                         if ( empty( $comment_ids ) )
277                                 return;
278
279                         $wpdb->queries = array();
280
281                         foreach ( $comment_ids as $comment_id ) {
282                                 do_action( 'delete_comment', $comment_id );
283                         }
284
285                         $comma_comment_ids = implode( ', ', array_map('intval', $comment_ids) );
286
287                         $wpdb->query("DELETE FROM {$wpdb->comments} WHERE comment_id IN ( $comma_comment_ids )");
288                         $wpdb->query("DELETE FROM {$wpdb->commentmeta} WHERE comment_id IN ( $comma_comment_ids )");
289
290                         clean_comment_cache( $comment_ids );
291                 }
292
293                 if ( apply_filters( 'akismet_optimize_table', ( mt_rand(1, 5000) == 11), $wpdb->comments ) ) // lucky number
294                         $wpdb->query("OPTIMIZE TABLE {$wpdb->comments}");
295         }
296
297         public static function delete_old_comments_meta() {
298                 global $wpdb;
299
300                 $interval = apply_filters( 'akismet_delete_commentmeta_interval', 15 );
301
302                 # enfore a minimum of 1 day
303                 $interval = absint( $interval );
304                 if ( $interval < 1 )
305                         $interval = 1;
306
307                 // akismet_as_submitted meta values are large, so expire them
308                 // after $interval days regardless of the comment status
309                 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 ) ) ) {
310                         if ( empty( $comment_ids ) )
311                                 return;
312
313                         $wpdb->queries = array();
314
315                         foreach ( $comment_ids as $comment_id ) {
316                                 delete_comment_meta( $comment_id, 'akismet_as_submitted' );
317                         }
318                 }
319
320                 if ( apply_filters( 'akismet_optimize_table', ( mt_rand(1, 5000) == 11), $wpdb->commentmeta ) ) // lucky number
321                         $wpdb->query("OPTIMIZE TABLE {$wpdb->commentmeta}");
322         }
323
324         // how many approved comments does this author have?
325         public static function get_user_comments_approved( $user_id, $comment_author_email, $comment_author, $comment_author_url ) {
326                 global $wpdb;
327
328                 if ( !empty( $user_id ) )
329                         return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->comments} WHERE user_id = %d AND comment_approved = 1", $user_id ) );
330
331                 if ( !empty( $comment_author_email ) )
332                         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 ) );
333
334                 return 0;
335         }
336
337         // get the full comment history for a given comment, as an array in reverse chronological order
338         public static function get_comment_history( $comment_id ) {
339
340                 // failsafe for old WP versions
341                 if ( !function_exists('add_comment_meta') )
342                         return false;
343
344                 $history = get_comment_meta( $comment_id, 'akismet_history', false );
345                 usort( $history, array( 'Akismet', '_cmp_time' ) );
346                 return $history;
347         }
348
349         // log an event for a given comment, storing it in comment_meta
350         public static function update_comment_history( $comment_id, $message, $event=null ) {
351                 global $current_user;
352
353                 // failsafe for old WP versions
354                 if ( !function_exists('add_comment_meta') )
355                         return false;
356
357                 $user = '';
358                 if ( is_object( $current_user ) && isset( $current_user->user_login ) )
359                         $user = $current_user->user_login;
360
361                 $event = array(
362                         'time'    => self::_get_microtime(),
363                         'message' => $message,
364                         'event'   => $event,
365                         'user'    => $user,
366                 );
367
368                 // $unique = false so as to allow multiple values per comment
369                 $r = add_comment_meta( $comment_id, 'akismet_history', $event, false );
370         }
371
372         public static function check_db_comment( $id, $recheck_reason = 'recheck_queue' ) {
373                 global $wpdb;
374
375                 $c = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $id ), ARRAY_A );
376                 if ( !$c )
377                         return;
378
379                 $c['user_ip']        = $c['comment_author_IP'];
380                 $c['user_agent']     = $c['comment_agent'];
381                 $c['referrer']       = '';
382                 $c['blog']           = get_option('home');
383                 $c['blog_lang']      = get_locale();
384                 $c['blog_charset']   = get_option('blog_charset');
385                 $c['permalink']      = get_permalink($c['comment_post_ID']);
386                 $c['recheck_reason'] = $recheck_reason;
387
388                 if ( self::is_test_mode() )
389                         $c['is_test'] = 'true';
390
391                 $response = self::http_post( Akismet::build_query( $c ), 'comment-check' );
392
393                 return ( is_array( $response ) && ! empty( $response[1] ) ) ? $response[1] : false;
394         }
395         
396         
397
398         public static function transition_comment_status( $new_status, $old_status, $comment ) {
399                 
400                 if ( $new_status == $old_status )
401                         return;
402
403                 # we don't need to record a history item for deleted comments
404                 if ( $new_status == 'delete' )
405                         return;
406                 
407                 if ( !current_user_can( 'edit_post', $comment->comment_post_ID ) && !current_user_can( 'moderate_comments' ) )
408                         return;
409
410                 if ( defined('WP_IMPORTING') && WP_IMPORTING == true )
411                         return;
412                         
413                 // if this is present, it means the status has been changed by a re-check, not an explicit user action
414                 if ( get_comment_meta( $comment->comment_ID, 'akismet_rechecking' ) )
415                         return;
416                 
417                 global $current_user;
418                 $reporter = '';
419                 if ( is_object( $current_user ) )
420                         $reporter = $current_user->user_login;
421
422                 // Assumption alert:
423                 // We want to submit comments to Akismet only when a moderator explicitly spams or approves it - not if the status
424                 // is changed automatically by another plugin.  Unfortunately WordPress doesn't provide an unambiguous way to
425                 // determine why the transition_comment_status action was triggered.  And there are several different ways by which
426                 // to spam and unspam comments: bulk actions, ajax, links in moderation emails, the dashboard, and perhaps others.
427                 // We'll assume that this is an explicit user action if certain POST/GET variables exist.
428                 if ( ( isset( $_POST['status'] ) && in_array( $_POST['status'], array( 'spam', 'unspam' ) ) ) ||
429                          ( isset( $_POST['spam'] )   && (int) $_POST['spam'] == 1 ) ||
430                          ( isset( $_POST['unspam'] ) && (int) $_POST['unspam'] == 1 ) ||
431                          ( isset( $_POST['comment_status'] )  && in_array( $_POST['comment_status'], array( 'spam', 'unspam' ) ) ) ||
432                          ( isset( $_GET['action'] )  && in_array( $_GET['action'], array( 'spam', 'unspam' ) ) ) ||
433                          ( isset( $_POST['action'] ) && in_array( $_POST['action'], array( 'editedcomment' ) ) )
434                  ) {
435                         if ( $new_status == 'spam' && ( $old_status == 'approved' || $old_status == 'unapproved' || !$old_status ) ) {
436                                 return self::submit_spam_comment( $comment->comment_ID );
437                         } elseif ( $old_status == 'spam' && ( $new_status == 'approved' || $new_status == 'unapproved' ) ) {
438                                 return self::submit_nonspam_comment( $comment->comment_ID );
439                         }
440                 }
441
442                 self::update_comment_history( $comment->comment_ID, sprintf( __('%1$s changed the comment status to %2$s', 'akismet'), $reporter, $new_status ), 'status-' . $new_status );
443         }
444         
445         public static function submit_spam_comment( $comment_id ) {
446                 global $wpdb, $current_user, $current_site;
447
448                 $comment_id = (int) $comment_id;
449
450                 $comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $comment_id ) );
451
452                 if ( !$comment ) // it was deleted
453                         return;
454
455                 if ( 'spam' != $comment->comment_approved )
456                         return;
457
458                 // use the original version stored in comment_meta if available
459                 $as_submitted = get_comment_meta( $comment_id, 'akismet_as_submitted', true);
460
461                 if ( $as_submitted && is_array( $as_submitted ) && isset( $as_submitted['comment_content'] ) )
462                         $comment = (object) array_merge( (array)$comment, $as_submitted );
463
464                 $comment->blog         = get_bloginfo('url');
465                 $comment->blog_lang    = get_locale();
466                 $comment->blog_charset = get_option('blog_charset');
467                 $comment->permalink    = get_permalink($comment->comment_post_ID);
468
469                 if ( is_object($current_user) )
470                         $comment->reporter = $current_user->user_login;
471
472                 if ( is_object($current_site) )
473                         $comment->site_domain = $current_site->domain;
474
475                 $comment->user_role = '';
476                 if ( isset( $comment->user_ID ) )
477                         $comment->user_role = Akismet::get_user_roles( $comment->user_ID );
478
479                 if ( self::is_test_mode() )
480                         $comment->is_test = 'true';
481
482                 $post = get_post( $comment->comment_post_ID );
483                 $comment->comment_post_modified_gmt = $post->post_modified_gmt;
484
485                 $response = Akismet::http_post( Akismet::build_query( $comment ), 'submit-spam' );
486                 if ( $comment->reporter ) {
487                         self::update_comment_history( $comment_id, sprintf( __('%s reported this comment as spam', 'akismet'), $comment->reporter ), 'report-spam' );
488                         update_comment_meta( $comment_id, 'akismet_user_result', 'true' );
489                         update_comment_meta( $comment_id, 'akismet_user', $comment->reporter );
490                 }
491
492                 do_action('akismet_submit_spam_comment', $comment_id, $response[1]);
493         }
494
495         public static function submit_nonspam_comment( $comment_id ) {
496                 global $wpdb, $current_user, $current_site;
497
498                 $comment_id = (int) $comment_id;
499
500                 $comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $comment_id ) );
501                 if ( !$comment ) // it was deleted
502                         return;
503
504                 // use the original version stored in comment_meta if available
505                 $as_submitted = get_comment_meta( $comment_id, 'akismet_as_submitted', true);
506
507                 if ( $as_submitted && is_array($as_submitted) && isset($as_submitted['comment_content']) )
508                         $comment = (object) array_merge( (array)$comment, $as_submitted );
509
510                 $comment->blog         = get_bloginfo('url');
511                 $comment->blog_lang    = get_locale();
512                 $comment->blog_charset = get_option('blog_charset');
513                 $comment->permalink    = get_permalink( $comment->comment_post_ID );
514                 $comment->user_role    = '';
515
516                 if ( is_object($current_user) )
517                         $comment->reporter = $current_user->user_login;
518
519                 if ( is_object($current_site) )
520                         $comment->site_domain = $current_site->domain;
521
522                 if ( isset( $comment->user_ID ) )
523                         $comment->user_role = Akismet::get_user_roles($comment->user_ID);
524
525                 if ( Akismet::is_test_mode() )
526                         $comment->is_test = 'true';
527
528                 $post = get_post( $comment->comment_post_ID );
529                 $comment->comment_post_modified_gmt = $post->post_modified_gmt;
530
531                 $response = self::http_post( Akismet::build_query( $comment ), 'submit-ham' );
532                 if ( $comment->reporter ) {
533                         self::update_comment_history( $comment_id, sprintf( __('%s reported this comment as not spam', 'akismet'), $comment->reporter ), 'report-ham' );
534                         update_comment_meta( $comment_id, 'akismet_user_result', 'false' );
535                         update_comment_meta( $comment_id, 'akismet_user', $comment->reporter );
536                 }
537
538                 do_action('akismet_submit_nonspam_comment', $comment_id, $response[1]);
539         }
540
541         public static function cron_recheck() {
542                 global $wpdb;
543
544                 $api_key = self::get_api_key();
545
546                 $status = self::verify_key( $api_key );
547                 if ( get_option( 'akismet_alert_code' ) || $status == 'invalid' ) {
548                         // since there is currently a problem with the key, reschedule a check for 6 hours hence
549                         wp_schedule_single_event( time() + 21600, 'akismet_schedule_cron_recheck' );
550                         return false;
551                 }
552
553                 delete_option('akismet_available_servers');
554
555                 $comment_errors = $wpdb->get_col( "SELECT comment_id FROM {$wpdb->commentmeta} WHERE meta_key = 'akismet_error' LIMIT 100" );
556                 
557                 load_plugin_textdomain( 'akismet' );
558
559                 foreach ( (array) $comment_errors as $comment_id ) {
560                         // if the comment no longer exists, or is too old, remove the meta entry from the queue to avoid getting stuck
561                         $comment = get_comment( $comment_id );
562                         if ( !$comment || strtotime( $comment->comment_date_gmt ) < strtotime( "-15 days" ) ) {
563                                 delete_comment_meta( $comment_id, 'akismet_error' );
564                                 delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
565                                 continue;
566                         }
567
568                         add_comment_meta( $comment_id, 'akismet_rechecking', true );
569                         $status = self::check_db_comment( $comment_id, 'retry' );
570
571                         $msg = '';
572                         if ( $status == 'true' ) {
573                                 $msg = __( 'Akismet caught this comment as spam during an automatic retry.' , 'akismet');
574                         } elseif ( $status == 'false' ) {
575                                 $msg = __( 'Akismet cleared this comment during an automatic retry.' , 'akismet');
576                         }
577
578                         // If we got back a legit response then update the comment history
579                         // other wise just bail now and try again later.  No point in
580                         // re-trying all the comments once we hit one failure.
581                         if ( !empty( $msg ) ) {
582                                 delete_comment_meta( $comment_id, 'akismet_error' );
583                                 self::update_comment_history( $comment_id, $msg, 'cron-retry' );
584                                 update_comment_meta( $comment_id, 'akismet_result', $status );
585                                 // make sure the comment status is still pending.  if it isn't, that means the user has already moved it elsewhere.
586                                 $comment = get_comment( $comment_id );
587                                 if ( $comment && 'unapproved' == wp_get_comment_status( $comment_id ) ) {
588                                         if ( $status == 'true' ) {
589                                                 wp_spam_comment( $comment_id );
590                                         } elseif ( $status == 'false' ) {
591                                                 // comment is good, but it's still in the pending queue.  depending on the moderation settings
592                                                 // we may need to change it to approved.
593                                                 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) )
594                                                         wp_set_comment_status( $comment_id, 1 );
595                                                 else if ( get_comment_meta( $comment_id, 'akismet_delayed_moderation_email', true ) )
596                                                         wp_notify_moderator( $comment_id );
597                                         }
598                                 }
599                                 
600                                 delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
601                         } else {
602                                 // If this comment has been pending moderation for longer than MAX_DELAY_BEFORE_MODERATION_EMAIL,
603                                 // send a moderation email now.
604                                 if ( ( intval( gmdate( 'U' ) ) - strtotime( $comment->comment_date_gmt ) ) < self::MAX_DELAY_BEFORE_MODERATION_EMAIL ) {
605                                         delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
606                                         wp_notify_moderator( $comment_id );
607                                 }
608
609                                 delete_comment_meta( $comment_id, 'akismet_rechecking' );
610                                 wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
611                                 return;
612                         }
613                         delete_comment_meta( $comment_id, 'akismet_rechecking' );
614                 }
615
616                 $remaining = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->commentmeta} WHERE meta_key = 'akismet_error'" );
617                 if ( $remaining && !wp_next_scheduled('akismet_schedule_cron_recheck') ) {
618                         wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
619                 }
620         }
621
622         public static function fix_scheduled_recheck() {
623                 $future_check = wp_next_scheduled( 'akismet_schedule_cron_recheck' );
624                 if ( !$future_check ) {
625                         return;
626                 }
627
628                 if ( get_option( 'akismet_alert_code' ) > 0 ) {
629                         return;
630                 }
631
632                 $check_range = time() + 1200;
633                 if ( $future_check > $check_range ) {
634                         wp_clear_scheduled_hook( 'akismet_schedule_cron_recheck' );
635                         wp_schedule_single_event( time() + 300, 'akismet_schedule_cron_recheck' );
636                 }
637         }
638
639         public static function add_comment_nonce( $post_id ) {
640                 echo '<p style="display: none;">';
641                 wp_nonce_field( 'akismet_comment_nonce_' . $post_id, 'akismet_comment_nonce', FALSE );
642                 echo '</p>';
643         }
644
645         public static function is_test_mode() {
646                 return defined('AKISMET_TEST_MODE') && AKISMET_TEST_MODE;
647         }
648         
649         public static function allow_discard() {
650                 if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
651                         return false;
652                 if ( is_user_logged_in() )
653                         return false;
654         
655                 return ( get_option( 'akismet_strictness' ) === '1'  );
656         }
657
658         public static function get_ip_address() {
659                 return isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : null;
660         }
661         
662         /**
663          * Do these two comments, without checking the comment_ID, "match"?
664          *
665          * @param mixed $comment1 A comment object or array.
666          * @param mixed $comment2 A comment object or array.
667          * @return bool Whether the two comments should be treated as the same comment.
668          */
669         private static function comments_match( $comment1, $comment2 ) {
670                 $comment1 = (array) $comment1;
671                 $comment2 = (array) $comment2;
672                 
673                 return (
674                            isset( $comment1['comment_post_ID'], $comment2['comment_post_ID'] )
675                         && intval( $comment1['comment_post_ID'] ) == intval( $comment2['comment_post_ID'] )
676                         && $comment1['comment_author'] == $comment2['comment_author']
677                         && $comment1['comment_author_email'] == $comment2['comment_author_email']
678                 );
679         }
680         
681         // Does the supplied comment match the details of the one most recently stored in self::$last_comment?
682         public static function matches_last_comment( $comment ) {
683                 if ( is_object( $comment ) )
684                         $comment = (array) $comment;
685
686                 return self::comments_match( self::$last_comment, $comment );
687         }
688
689         private static function get_user_agent() {
690                 return isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : null;
691         }
692
693         private static function get_referer() {
694                 return isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : null;
695         }
696
697         // return a comma-separated list of role names for the given user
698         public static function get_user_roles( $user_id ) {
699                 $roles = false;
700
701                 if ( !class_exists('WP_User') )
702                         return false;
703
704                 if ( $user_id > 0 ) {
705                         $comment_user = new WP_User( $user_id );
706                         if ( isset( $comment_user->roles ) )
707                                 $roles = join( ',', $comment_user->roles );
708                 }
709
710                 if ( is_multisite() && is_super_admin( $user_id ) ) {
711                         if ( empty( $roles ) ) {
712                                 $roles = 'super_admin';
713                         } else {
714                                 $comment_user->roles[] = 'super_admin';
715                                 $roles = join( ',', $comment_user->roles );
716                         }
717                 }
718
719                 return $roles;
720         }
721
722         // filter handler used to return a spam result to pre_comment_approved
723         public static function last_comment_status( $approved, $comment ) {
724                 // Only do this if it's the correct comment
725                 if ( is_null(self::$last_comment_result) || ! self::matches_last_comment( $comment ) ) {
726                         self::log( "comment_is_spam mismatched comment, returning unaltered $approved" );
727                         return $approved;
728                 }
729
730                 // bump the counter here instead of when the filter is added to reduce the possibility of overcounting
731                 if ( $incr = apply_filters('akismet_spam_count_incr', 1) )
732                         update_option( 'akismet_spam_count', get_option('akismet_spam_count') + $incr );
733
734                 return self::$last_comment_result;
735         }
736         
737         /**
738          * If Akismet is temporarily unreachable, we don't want to "spam" the blogger with
739          * moderation emails for comments that will be automatically cleared or spammed on
740          * the next retry.
741          *
742          * For comments that will be rechecked later, empty the list of email addresses that
743          * the moderation email would be sent to.
744          *
745          * @param array $emails An array of email addresses that the moderation email will be sent to.
746          * @param int $comment_id The ID of the relevant comment.
747          * @return array An array of email addresses that the moderation email will be sent to.
748          */
749         public static function disable_moderation_emails_if_unreachable( $emails, $comment_id ) {
750                 if ( ! empty( self::$prevent_moderation_email_for_these_comments ) && ! empty( $emails ) ) {
751                         $comment = get_comment( $comment_id );
752
753                         foreach ( self::$prevent_moderation_email_for_these_comments as $possible_match ) {
754                                 if ( self::comments_match( $possible_match, $comment ) ) {
755                                         update_comment_meta( $comment_id, 'akismet_delayed_moderation_email', true );
756                                         return array();
757                                 }
758                         }
759                 }
760
761                 return $emails;
762         }
763
764         public static function _cmp_time( $a, $b ) {
765                 return $a['time'] > $b['time'] ? -1 : 1;
766         }
767
768         public static function _get_microtime() {
769                 $mtime = explode( ' ', microtime() );
770                 return $mtime[1] + $mtime[0];
771         }
772
773         /**
774          * Make a POST request to the Akismet API.
775          *
776          * @param string $request The body of the request.
777          * @param string $path The path for the request.
778          * @param string $ip The specific IP address to hit.
779          * @return array A two-member array consisting of the headers and the response body, both empty in the case of a failure.
780          */
781         public static function http_post( $request, $path, $ip=null ) {
782
783                 $akismet_ua = sprintf( 'WordPress/%s | Akismet/%s', $GLOBALS['wp_version'], constant( 'AKISMET_VERSION' ) );
784                 $akismet_ua = apply_filters( 'akismet_ua', $akismet_ua );
785
786                 $content_length = strlen( $request );
787
788                 $api_key   = self::get_api_key();
789                 $host      = self::API_HOST;
790
791                 if ( !empty( $api_key ) )
792                         $host = $api_key.'.'.$host;
793
794                 $http_host = $host;
795                 // use a specific IP if provided
796                 // needed by Akismet_Admin::check_server_connectivity()
797                 if ( $ip && long2ip( ip2long( $ip ) ) ) {
798                         $http_host = $ip;
799                 }
800
801                 $http_args = array(
802                         'body' => $request,
803                         'headers' => array(
804                                 'Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' ),
805                                 'Host' => $host,
806                                 'User-Agent' => $akismet_ua,
807                         ),
808                         'httpversion' => '1.0',
809                         'timeout' => 15
810                 );
811
812                 $akismet_url = "http://{$http_host}/1.1/{$path}";
813                 $response = wp_remote_post( $akismet_url, $http_args );
814                 Akismet::log( compact( 'akismet_url', 'http_args', 'response' ) );
815                 if ( is_wp_error( $response ) )
816                         return array( '', '' );
817
818                 return array( $response['headers'], $response['body'] );
819         }
820
821         // given a response from an API call like check_key_status(), update the alert code options if an alert is present.
822         private static function update_alert( $response ) {
823                 $code = $msg = null;
824                 if ( isset( $response[0]['x-akismet-alert-code'] ) ) {
825                         $code = $response[0]['x-akismet-alert-code'];
826                         $msg  = $response[0]['x-akismet-alert-msg'];
827                 }
828
829                 // only call update_option() if the value has changed
830                 if ( $code != get_option( 'akismet_alert_code' ) ) {
831                         if ( ! $code ) {
832                                 delete_option( 'akismet_alert_code' );
833                                 delete_option( 'akismet_alert_msg' );
834                         }
835                         else {
836                                 update_option( 'akismet_alert_code', $code );
837                                 update_option( 'akismet_alert_msg', $msg );
838                         }
839                 }
840         }
841
842         public static function load_form_js() {
843                 // WP < 3.3 can't enqueue a script this late in the game and still have it appear in the footer.
844                 // Once we drop support for everything pre-3.3, this can change back to a single enqueue call.
845                 wp_register_script( 'akismet-form', AKISMET__PLUGIN_URL . '_inc/form.js', array(), AKISMET_VERSION, true );
846                 add_action( 'wp_footer', array( 'Akismet', 'print_form_js' ) );
847                 add_action( 'admin_footer', array( 'Akismet', 'print_form_js' ) );
848         }
849         
850         public static function print_form_js() {
851                 wp_print_scripts( 'akismet-form' );
852         }
853
854         public static function inject_ak_js( $fields ) {
855                 echo '<p style="display: none;">';
856                 echo '<input type="hidden" id="ak_js" name="ak_js" value="' . mt_rand( 0, 250 ) . '"/>';
857                 echo '</p>';
858         }
859
860         private static function bail_on_activation( $message, $deactivate = true ) {
861 ?>
862 <!doctype html>
863 <html>
864 <head>
865 <meta charset="<?php bloginfo( 'charset' ); ?>">
866 <style>
867 * {
868         text-align: center;
869         margin: 0;
870         padding: 0;
871         font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
872 }
873 p {
874         margin-top: 1em;
875         font-size: 18px;
876 }
877 </style>
878 <body>
879 <p><?php echo esc_html( $message ); ?></p>
880 </body>
881 </html>
882 <?php
883                 if ( $deactivate ) {
884                         $plugins = get_option( 'active_plugins' );
885                         $akismet = plugin_basename( AKISMET__PLUGIN_DIR . 'akismet.php' );
886                         $update  = false;
887                         foreach ( $plugins as $i => $plugin ) {
888                                 if ( $plugin === $akismet ) {
889                                         $plugins[$i] = false;
890                                         $update = true;
891                                 }
892                         }
893
894                         if ( $update ) {
895                                 update_option( 'active_plugins', array_filter( $plugins ) );
896                         }
897                 }
898                 exit;
899         }
900
901         public static function view( $name, array $args = array() ) {
902                 $args = apply_filters( 'akismet_view_arguments', $args, $name );
903                 
904                 foreach ( $args AS $key => $val ) {
905                         $$key = $val;
906                 }
907                 
908                 load_plugin_textdomain( 'akismet' );
909
910                 $file = AKISMET__PLUGIN_DIR . 'views/'. $name . '.php';
911
912                 include( $file );
913         }
914
915         /**
916          * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
917          * @static
918          */
919         public static function plugin_activation() {
920                 if ( version_compare( $GLOBALS['wp_version'], AKISMET__MINIMUM_WP_VERSION, '<' ) ) {
921                         load_plugin_textdomain( 'akismet' );
922                         
923                         $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', 'http://wordpress.org/extend/plugins/akismet/download/');
924
925                         Akismet::bail_on_activation( $message );
926                 }
927         }
928
929         /**
930          * Removes all connection options
931          * @static
932          */
933         public static function plugin_deactivation( ) {
934                 //tidy up
935         }
936         
937         /**
938          * Essentially a copy of WP's build_query but one that doesn't expect pre-urlencoded values.
939          *
940          * @param array $args An array of key => value pairs
941          * @return string A string ready for use as a URL query string.
942          */
943         public static function build_query( $args ) {
944                 return _http_build_query( $args, '', '&' );
945         }
946
947         /**
948          * Log debugging info to the error log.
949          *
950          * Enabled when WP_DEBUG_LOG is enabled, but can be disabled via the akismet_debug_log filter.
951          *
952          * @param mixed $akismet_debug The data to log.
953          */
954         public static function log( $akismet_debug ) {
955                 if ( apply_filters( 'akismet_debug_log', defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) ) {
956                         error_log( print_r( compact( 'akismet_debug' ), true ) );
957                 }
958         }
959 }