WordPress 4.6.1
[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         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
14         public static function init() {
15                 if ( ! self::$initiated ) {
16                         self::init_hooks();
17                 }
18         }
19
20         /**
21          * Initializes WordPress hooks
22          */
23         private static function init_hooks() {
24                 self::$initiated = true;
25
26                 add_action( 'wp_insert_comment', array( 'Akismet', 'auto_check_update_meta' ), 10, 2 );
27                 add_filter( 'preprocess_comment', array( 'Akismet', 'auto_check_comment' ), 1 );
28                 add_action( 'akismet_scheduled_delete', array( 'Akismet', 'delete_old_comments' ) );
29                 add_action( 'akismet_scheduled_delete', array( 'Akismet', 'delete_old_comments_meta' ) );
30                 add_action( 'akismet_schedule_cron_recheck', array( 'Akismet', 'cron_recheck' ) );
31
32                 /**
33                  * To disable the Akismet comment nonce, add a filter for the 'akismet_comment_nonce' tag
34                  * and return any string value that is not 'true' or '' (empty string).
35                  *
36                  * Don't return boolean false, because that implies that the 'akismet_comment_nonce' option
37                  * has not been set and that Akismet should just choose the default behavior for that
38                  * situation.
39                  */
40                 $akismet_comment_nonce_option = apply_filters( 'akismet_comment_nonce', get_option( 'akismet_comment_nonce' ) );
41
42                 if ( $akismet_comment_nonce_option == 'true' || $akismet_comment_nonce_option == '' )
43                         add_action( 'comment_form',  array( 'Akismet',  'add_comment_nonce' ), 1 );
44
45                 add_action( 'admin_head-edit-comments.php', array( 'Akismet', 'load_form_js' ) );
46                 add_action( 'comment_form', array( 'Akismet', 'load_form_js' ) );
47                 add_action( 'comment_form', array( 'Akismet', 'inject_ak_js' ) );
48
49                 add_filter( 'comment_moderation_recipients', array( 'Akismet', 'disable_moderation_emails_if_unreachable' ), 1000, 2 );
50                 add_filter( 'pre_comment_approved', array( 'Akismet', 'last_comment_status' ), 10, 2 );
51                 
52                 add_action( 'transition_comment_status', array( 'Akismet', 'transition_comment_status' ), 10, 3 );
53
54                 // Run this early in the pingback call, before doing a remote fetch of the source uri
55                 add_action( 'xmlrpc_call', array( 'Akismet', 'pre_check_pingback' ) );
56                 
57                 // Jetpack compatibility
58                 add_filter( 'jetpack_options_whitelist', array( 'Akismet', 'add_to_jetpack_options_whitelist' ) );
59                 add_action( 'update_option_wordpress_api_key', array( 'Akismet', 'updated_option' ), 10, 2 );
60         }
61
62         public static function get_api_key() {
63                 return apply_filters( 'akismet_get_api_key', defined('WPCOM_API_KEY') ? constant('WPCOM_API_KEY') : get_option('wordpress_api_key') );
64         }
65
66         public static function check_key_status( $key, $ip = null ) {
67                 return self::http_post( Akismet::build_query( array( 'key' => $key, 'blog' => get_option( 'home' ) ) ), 'verify-key', $ip );
68         }
69
70         public static function verify_key( $key, $ip = null ) {
71                 $response = self::check_key_status( $key, $ip );
72
73                 if ( $response[1] != 'valid' && $response[1] != 'invalid' )
74                         return 'failed';
75
76                 return $response[1];
77         }
78
79         public static function deactivate_key( $key ) {
80                 $response = self::http_post( Akismet::build_query( array( 'key' => $key, 'blog' => get_option( 'home' ) ) ), 'deactivate' );
81
82                 if ( $response[1] != 'deactivated' )
83                         return 'failed';
84
85                 return $response[1];
86         }
87
88         /**
89          * Add the akismet option to the Jetpack options management whitelist.
90          *
91          * @param array $options The list of whitelisted option names.
92          * @return array The updated whitelist
93          */
94         public static function add_to_jetpack_options_whitelist( $options ) {
95                 $options[] = 'wordpress_api_key';
96                 return $options;
97         }
98
99         /**
100          * When the akismet option is updated, run the registration call.
101          *
102          * This should only be run when the option is updated from the Jetpack/WP.com
103          * API call, and only if the new key is different than the old key.
104          *
105          * @param mixed  $old_value   The old option value.
106          * @param mixed  $value       The new option value.
107          */
108         public static function updated_option( $old_value, $value ) {
109                 // Not an API call
110                 if ( ! class_exists( 'WPCOM_JSON_API_Update_Option_Endpoint' ) ) {
111                         return;
112                 }
113                 // Only run the registration if the old key is different.
114                 if ( $old_value !== $value ) {
115                         self::verify_key( $value );
116                 }
117         }
118
119         public static function auto_check_comment( $commentdata ) {
120                 self::$last_comment_result = null;
121
122                 $comment = $commentdata;
123
124                 $comment['user_ip']      = self::get_ip_address();
125                 $comment['user_agent']   = self::get_user_agent();
126                 $comment['referrer']     = self::get_referer();
127                 $comment['blog']         = get_option( 'home' );
128                 $comment['blog_lang']    = get_locale();
129                 $comment['blog_charset'] = get_option('blog_charset');
130                 $comment['permalink']    = get_permalink( $comment['comment_post_ID'] );
131
132                 if ( !empty( $comment['user_ID'] ) )
133                         $comment['user_role'] = Akismet::get_user_roles( $comment['user_ID'] );
134
135                 /** See filter documentation in init_hooks(). */
136                 $akismet_nonce_option = apply_filters( 'akismet_comment_nonce', get_option( 'akismet_comment_nonce' ) );
137                 $comment['akismet_comment_nonce'] = 'inactive';
138                 if ( $akismet_nonce_option == 'true' || $akismet_nonce_option == '' ) {
139                         $comment['akismet_comment_nonce'] = 'failed';
140                         if ( isset( $_POST['akismet_comment_nonce'] ) && wp_verify_nonce( $_POST['akismet_comment_nonce'], 'akismet_comment_nonce_' . $comment['comment_post_ID'] ) )
141                                 $comment['akismet_comment_nonce'] = 'passed';
142
143                         // comment reply in wp-admin
144                         if ( isset( $_POST['_ajax_nonce-replyto-comment'] ) && check_ajax_referer( 'replyto-comment', '_ajax_nonce-replyto-comment' ) )
145                                 $comment['akismet_comment_nonce'] = 'passed';
146
147                 }
148
149                 if ( self::is_test_mode() )
150                         $comment['is_test'] = 'true';
151
152                 foreach( $_POST as $key => $value ) {
153                         if ( is_string( $value ) )
154                                 $comment["POST_{$key}"] = $value;
155                 }
156
157                 foreach ( $_SERVER as $key => $value ) {
158                         if ( ! is_string( $value ) ) {
159                                 continue;
160                         }
161
162                         if ( preg_match( "/^HTTP_COOKIE/", $key ) ) {
163                                 continue;
164                         }
165
166                         // Send any potentially useful $_SERVER vars, but avoid sending junk we don't need.
167                         if ( preg_match( "/^(HTTP_|REMOTE_ADDR|REQUEST_URI|DOCUMENT_URI)/", $key ) ) {
168                                 $comment[ "$key" ] = $value;
169                         }
170                 }
171
172                 $post = get_post( $comment['comment_post_ID'] );
173                 $comment[ 'comment_post_modified_gmt' ] = $post->post_modified_gmt;
174
175                 $response = self::http_post( Akismet::build_query( $comment ), 'comment-check' );
176
177                 do_action( 'akismet_comment_check_response', $response );
178
179                 $commentdata['comment_as_submitted'] = array_intersect_key( $comment, self::$comment_as_submitted_allowed_keys );
180                 $commentdata['akismet_result']       = $response[1];
181
182                 if ( isset( $response[0]['x-akismet-pro-tip'] ) )
183                 $commentdata['akismet_pro_tip'] = $response[0]['x-akismet-pro-tip'];
184
185                 if ( isset( $response[0]['x-akismet-error'] ) ) {
186                         // An error occurred that we anticipated (like a suspended key) and want the user to act on.
187                         // Send to moderation.
188                         self::$last_comment_result = '0';
189                 }
190                 else if ( 'true' == $response[1] ) {
191                         // akismet_spam_count will be incremented later by comment_is_spam()
192                         self::$last_comment_result = 'spam';
193
194                         $discard = ( isset( $commentdata['akismet_pro_tip'] ) && $commentdata['akismet_pro_tip'] === 'discard' && self::allow_discard() );
195
196                         do_action( 'akismet_spam_caught', $discard );
197
198                         if ( $discard ) {
199                                 // akismet_result_spam() won't be called so bump the counter here
200                                 if ( $incr = apply_filters('akismet_spam_count_incr', 1) )
201                                         update_option( 'akismet_spam_count', get_option('akismet_spam_count') + $incr );
202                                 $redirect_to = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : get_permalink( $post );
203                                 wp_safe_redirect( esc_url_raw( $redirect_to ) );
204                                 die();
205                         }
206                 }
207                 
208                 // if the response is neither true nor false, hold the comment for moderation and schedule a recheck
209                 if ( 'true' != $response[1] && 'false' != $response[1] ) {
210                         if ( !current_user_can('moderate_comments') ) {
211                                 // Comment status should be moderated
212                                 self::$last_comment_result = '0';
213                         }
214                         if ( function_exists('wp_next_scheduled') && function_exists('wp_schedule_single_event') ) {
215                                 if ( !wp_next_scheduled( 'akismet_schedule_cron_recheck' ) ) {
216                                         wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
217                                         do_action( 'akismet_scheduled_recheck', 'invalid-response-' . $response[1] );
218                                 }
219                         }
220
221                         self::$prevent_moderation_email_for_these_comments[] = $commentdata;
222                 }
223
224                 if ( function_exists('wp_next_scheduled') && function_exists('wp_schedule_event') ) {
225                         // WP 2.1+: delete old comments daily
226                         if ( !wp_next_scheduled( 'akismet_scheduled_delete' ) )
227                                 wp_schedule_event( time(), 'daily', 'akismet_scheduled_delete' );
228                 }
229                 elseif ( (mt_rand(1, 10) == 3) ) {
230                         // WP 2.0: run this one time in ten
231                         self::delete_old_comments();
232                 }
233                 
234                 self::set_last_comment( $commentdata );
235                 self::fix_scheduled_recheck();
236
237                 return $commentdata;
238         }
239         
240         public static function get_last_comment() {
241                 return self::$last_comment;
242         }
243         
244         public static function set_last_comment( $comment ) {
245                 if ( is_null( $comment ) ) {
246                         self::$last_comment = null;
247                 }
248                 else {
249                         // We filter it here so that it matches the filtered comment data that we'll have to compare against later.
250                         // wp_filter_comment expects comment_author_IP
251                         self::$last_comment = wp_filter_comment(
252                                 array_merge(
253                                         array( 'comment_author_IP' => self::get_ip_address() ),
254                                         $comment
255                                 )
256                         );
257                 }
258         }
259
260         // this fires on wp_insert_comment.  we can't update comment_meta when auto_check_comment() runs
261         // because we don't know the comment ID at that point.
262         public static function auto_check_update_meta( $id, $comment ) {
263
264                 // failsafe for old WP versions
265                 if ( !function_exists('add_comment_meta') )
266                         return false;
267
268                 if ( !isset( self::$last_comment['comment_author_email'] ) )
269                         self::$last_comment['comment_author_email'] = '';
270
271                 // wp_insert_comment() might be called in other contexts, so make sure this is the same comment
272                 // as was checked by auto_check_comment
273                 if ( is_object( $comment ) && !empty( self::$last_comment ) && is_array( self::$last_comment ) ) {
274                         if ( self::matches_last_comment( $comment ) ) {
275                                         
276                                         load_plugin_textdomain( 'akismet' );
277                                         
278                                         // normal result: true or false
279                                         if ( self::$last_comment['akismet_result'] == 'true' ) {
280                                                 update_comment_meta( $comment->comment_ID, 'akismet_result', 'true' );
281                                                 self::update_comment_history( $comment->comment_ID, '', 'check-spam' );
282                                                 if ( $comment->comment_approved != 'spam' )
283                                                         self::update_comment_history(
284                                                                 $comment->comment_ID,
285                                                                 '',
286                                                                 'status-changed-'.$comment->comment_approved
287                                                         );
288                                         }
289                                         elseif ( self::$last_comment['akismet_result'] == 'false' ) {
290                                                 update_comment_meta( $comment->comment_ID, 'akismet_result', 'false' );
291                                                 self::update_comment_history( $comment->comment_ID, '', 'check-ham' );
292                                                 // Status could be spam or trash, depending on the WP version and whether this change applies:
293                                                 // https://core.trac.wordpress.org/changeset/34726
294                                                 if ( $comment->comment_approved == 'spam' || $comment->comment_approved == 'trash' ) {
295                                                         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) )
296                                                                 self::update_comment_history( $comment->comment_ID, '', 'wp-blacklisted' );
297                                                         else
298                                                                 self::update_comment_history( $comment->comment_ID, '', 'status-changed-'.$comment->comment_approved );
299                                                 }
300                                         } // abnormal result: error
301                                         else {
302                                                 update_comment_meta( $comment->comment_ID, 'akismet_error', time() );
303                                                 self::update_comment_history(
304                                                         $comment->comment_ID,
305                                                         '',
306                                                         'check-error',
307                                                         array( 'response' => substr( self::$last_comment['akismet_result'], 0, 50 ) )
308                                                 );
309                                         }
310
311                                         // record the complete original data as submitted for checking
312                                         if ( isset( self::$last_comment['comment_as_submitted'] ) )
313                                                 update_comment_meta( $comment->comment_ID, 'akismet_as_submitted', self::$last_comment['comment_as_submitted'] );
314
315                                         if ( isset( self::$last_comment['akismet_pro_tip'] ) )
316                                                 update_comment_meta( $comment->comment_ID, 'akismet_pro_tip', self::$last_comment['akismet_pro_tip'] );
317                         }
318                 }
319         }
320
321         public static function delete_old_comments() {
322                 global $wpdb;
323
324                 /**
325                  * Determines how many comments will be deleted in each batch.
326                  *
327                  * @param int The default, as defined by AKISMET_DELETE_LIMIT.
328                  */
329                 $delete_limit = apply_filters( 'akismet_delete_comment_limit', defined( 'AKISMET_DELETE_LIMIT' ) ? AKISMET_DELETE_LIMIT : 10000 );
330                 $delete_limit = max( 1, intval( $delete_limit ) );
331
332                 /**
333                  * Determines how many days a comment will be left in the Spam queue before being deleted.
334                  *
335                  * @param int The default number of days.
336                  */
337                 $delete_interval = apply_filters( 'akismet_delete_comment_interval', 15 );
338                 $delete_interval = max( 1, intval( $delete_interval ) );
339
340                 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 ) ) ) {
341                         if ( empty( $comment_ids ) )
342                                 return;
343
344                         $wpdb->queries = array();
345
346                         foreach ( $comment_ids as $comment_id ) {
347                                 do_action( 'delete_comment', $comment_id );
348                         }
349
350                         // Prepared as strings since comment_id is an unsigned BIGINT, and using %d will constrain the value to the maximum signed BIGINT.
351                         $format_string = implode( ", ", array_fill( 0, count( $comment_ids ), '%s' ) );
352
353                         $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->comments} WHERE comment_id IN ( " . $format_string . " )", $comment_ids ) );
354                         $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->commentmeta} WHERE comment_id IN ( " . $format_string . " )", $comment_ids ) );
355
356                         clean_comment_cache( $comment_ids );
357                 }
358
359                 if ( apply_filters( 'akismet_optimize_table', ( mt_rand(1, 5000) == 11), $wpdb->comments ) ) // lucky number
360                         $wpdb->query("OPTIMIZE TABLE {$wpdb->comments}");
361         }
362
363         public static function delete_old_comments_meta() {
364                 global $wpdb;
365
366                 $interval = apply_filters( 'akismet_delete_commentmeta_interval', 15 );
367
368                 # enfore a minimum of 1 day
369                 $interval = absint( $interval );
370                 if ( $interval < 1 )
371                         $interval = 1;
372
373                 // akismet_as_submitted meta values are large, so expire them
374                 // after $interval days regardless of the comment status
375                 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 ) ) ) {
376                         if ( empty( $comment_ids ) )
377                                 return;
378
379                         $wpdb->queries = array();
380
381                         foreach ( $comment_ids as $comment_id ) {
382                                 delete_comment_meta( $comment_id, 'akismet_as_submitted' );
383                         }
384                 }
385
386                 if ( apply_filters( 'akismet_optimize_table', ( mt_rand(1, 5000) == 11), $wpdb->commentmeta ) ) // lucky number
387                         $wpdb->query("OPTIMIZE TABLE {$wpdb->commentmeta}");
388         }
389
390         // how many approved comments does this author have?
391         public static function get_user_comments_approved( $user_id, $comment_author_email, $comment_author, $comment_author_url ) {
392                 global $wpdb;
393
394                 if ( !empty( $user_id ) )
395                         return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->comments} WHERE user_id = %d AND comment_approved = 1", $user_id ) );
396
397                 if ( !empty( $comment_author_email ) )
398                         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 ) );
399
400                 return 0;
401         }
402
403         // get the full comment history for a given comment, as an array in reverse chronological order
404         public static function get_comment_history( $comment_id ) {
405
406                 // failsafe for old WP versions
407                 if ( !function_exists('add_comment_meta') )
408                         return false;
409
410                 $history = get_comment_meta( $comment_id, 'akismet_history', false );
411                 usort( $history, array( 'Akismet', '_cmp_time' ) );
412                 return $history;
413         }
414
415         /**
416          * Log an event for a given comment, storing it in comment_meta.
417          *
418          * @param int $comment_id The ID of the relevant comment.
419          * @param string $message The string description of the event. No longer used.
420          * @param string $event The event code.
421          * @param array $meta Metadata about the history entry. e.g., the user that reported or changed the status of a given comment.
422          */
423         public static function update_comment_history( $comment_id, $message, $event=null, $meta=null ) {
424                 global $current_user;
425
426                 // failsafe for old WP versions
427                 if ( !function_exists('add_comment_meta') )
428                         return false;
429
430                 $user = '';
431
432                 $event = array(
433                         'time'    => self::_get_microtime(),
434                         'event'   => $event,
435                 );
436                 
437                 if ( is_object( $current_user ) && isset( $current_user->user_login ) ) {
438                         $event['user'] = $current_user->user_login;
439                 }
440                 
441                 if ( ! empty( $meta ) ) {
442                         $event['meta'] = $meta;
443                 }
444
445                 // $unique = false so as to allow multiple values per comment
446                 $r = add_comment_meta( $comment_id, 'akismet_history', $event, false );
447         }
448
449         public static function check_db_comment( $id, $recheck_reason = 'recheck_queue' ) {
450                 global $wpdb;
451
452                 $c = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $id ), ARRAY_A );
453                 
454                 if ( ! $c ) {
455                         return new WP_Error( 'invalid-comment-id', __( 'Comment not found.', 'akismet' ) );
456                 }
457
458                 $c['user_ip']        = $c['comment_author_IP'];
459                 $c['user_agent']     = $c['comment_agent'];
460                 $c['referrer']       = '';
461                 $c['blog']           = get_option( 'home' );
462                 $c['blog_lang']      = get_locale();
463                 $c['blog_charset']   = get_option('blog_charset');
464                 $c['permalink']      = get_permalink($c['comment_post_ID']);
465                 $c['recheck_reason'] = $recheck_reason;
466
467                 $c['user_role'] = '';
468                 if ( isset( $c['user_ID'] ) )
469                         $c['user_role'] = Akismet::get_user_roles($c['user_ID']);
470
471                 if ( self::is_test_mode() )
472                         $c['is_test'] = 'true';
473
474                 $response = self::http_post( Akismet::build_query( $c ), 'comment-check' );
475
476                 if ( ! empty( $response[1] ) ) {
477                         return $response[1];
478                 }
479
480                 return false;
481         }
482         
483         public static function recheck_comment( $id, $recheck_reason = 'recheck_queue' ) {
484                 add_comment_meta( $id, 'akismet_rechecking', true );
485                 
486                 $api_response = self::check_db_comment( $id, $recheck_reason );
487
488                 delete_comment_meta( $id, 'akismet_rechecking' );
489
490                 if ( is_wp_error( $api_response ) ) {
491                         // Invalid comment ID.
492                 }
493                 else if ( 'true' === $api_response ) {
494                         wp_set_comment_status( $id, 'spam' );
495                         update_comment_meta( $id, 'akismet_result', 'true' );
496                         delete_comment_meta( $id, 'akismet_error' );
497                         delete_comment_meta( $id, 'akismet_delayed_moderation_email' );
498                         Akismet::update_comment_history( $id, '', 'recheck-spam' );
499                 }
500                 elseif ( 'false' === $api_response ) {
501                         update_comment_meta( $id, 'akismet_result', 'false' );
502                         delete_comment_meta( $id, 'akismet_error' );
503                         delete_comment_meta( $id, 'akismet_delayed_moderation_email' );
504                         Akismet::update_comment_history( $id, '', 'recheck-ham' );
505                 }
506                 else {
507                         // abnormal result: error
508                         update_comment_meta( $id, 'akismet_result', 'error' );
509                         Akismet::update_comment_history(
510                                 $id,
511                                 '',
512                                 'recheck-error',
513                                 array( 'response' => substr( $api_response, 0, 50 ) )
514                         );
515                 }
516
517                 return $api_response;
518         }
519
520         public static function transition_comment_status( $new_status, $old_status, $comment ) {
521                 
522                 if ( $new_status == $old_status )
523                         return;
524
525                 # we don't need to record a history item for deleted comments
526                 if ( $new_status == 'delete' )
527                         return;
528                 
529                 if ( !current_user_can( 'edit_post', $comment->comment_post_ID ) && !current_user_can( 'moderate_comments' ) )
530                         return;
531
532                 if ( defined('WP_IMPORTING') && WP_IMPORTING == true )
533                         return;
534                         
535                 // if this is present, it means the status has been changed by a re-check, not an explicit user action
536                 if ( get_comment_meta( $comment->comment_ID, 'akismet_rechecking' ) )
537                         return;
538                 
539                 global $current_user;
540                 $reporter = '';
541                 if ( is_object( $current_user ) )
542                         $reporter = $current_user->user_login;
543
544                 // Assumption alert:
545                 // We want to submit comments to Akismet only when a moderator explicitly spams or approves it - not if the status
546                 // is changed automatically by another plugin.  Unfortunately WordPress doesn't provide an unambiguous way to
547                 // determine why the transition_comment_status action was triggered.  And there are several different ways by which
548                 // to spam and unspam comments: bulk actions, ajax, links in moderation emails, the dashboard, and perhaps others.
549                 // We'll assume that this is an explicit user action if certain POST/GET variables exist.
550                 if ( ( isset( $_POST['status'] ) && in_array( $_POST['status'], array( 'spam', 'unspam' ) ) ) ||
551                          ( isset( $_POST['spam'] )   && (int) $_POST['spam'] == 1 ) ||
552                          ( isset( $_POST['unspam'] ) && (int) $_POST['unspam'] == 1 ) ||
553                          ( isset( $_POST['comment_status'] )  && in_array( $_POST['comment_status'], array( 'spam', 'unspam' ) ) ) ||
554                          ( isset( $_GET['action'] )  && in_array( $_GET['action'], array( 'spam', 'unspam', 'spamcomment', 'unspamcomment', ) ) ) ||
555                          ( isset( $_POST['action'] ) && in_array( $_POST['action'], array( 'editedcomment' ) ) ) ||
556                          ( isset( $_GET['for'] ) && ( 'jetpack' == $_GET['for'] ) ) // Moderation via WP.com notifications/WP app/etc.
557                  ) {
558                         if ( $new_status == 'spam' && ( $old_status == 'approved' || $old_status == 'unapproved' || !$old_status ) ) {
559                                 return self::submit_spam_comment( $comment->comment_ID );
560                         } elseif ( $old_status == 'spam' && ( $new_status == 'approved' || $new_status == 'unapproved' ) ) {
561                                 return self::submit_nonspam_comment( $comment->comment_ID );
562                         }
563                 }
564
565                 self::update_comment_history( $comment->comment_ID, '', 'status-' . $new_status );
566         }
567         
568         public static function submit_spam_comment( $comment_id ) {
569                 global $wpdb, $current_user, $current_site;
570
571                 $comment_id = (int) $comment_id;
572
573                 $comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $comment_id ) );
574
575                 if ( !$comment ) // it was deleted
576                         return;
577
578                 if ( 'spam' != $comment->comment_approved )
579                         return;
580
581                 // use the original version stored in comment_meta if available
582                 $as_submitted = self::sanitize_comment_as_submitted( get_comment_meta( $comment_id, 'akismet_as_submitted', true ) );
583
584                 if ( $as_submitted && is_array( $as_submitted ) && isset( $as_submitted['comment_content'] ) )
585                         $comment = (object) array_merge( (array)$comment, $as_submitted );
586
587                 $comment->blog         = get_option( 'home' );
588                 $comment->blog_lang    = get_locale();
589                 $comment->blog_charset = get_option('blog_charset');
590                 $comment->permalink    = get_permalink($comment->comment_post_ID);
591
592                 if ( is_object($current_user) )
593                         $comment->reporter = $current_user->user_login;
594
595                 if ( is_object($current_site) )
596                         $comment->site_domain = $current_site->domain;
597
598                 $comment->user_role = '';
599                 if ( isset( $comment->user_ID ) )
600                         $comment->user_role = Akismet::get_user_roles( $comment->user_ID );
601
602                 if ( self::is_test_mode() )
603                         $comment->is_test = 'true';
604
605                 $post = get_post( $comment->comment_post_ID );
606                 $comment->comment_post_modified_gmt = $post->post_modified_gmt;
607
608                 $response = Akismet::http_post( Akismet::build_query( $comment ), 'submit-spam' );
609                 if ( $comment->reporter ) {
610                         self::update_comment_history( $comment_id, '', 'report-spam' );
611                         update_comment_meta( $comment_id, 'akismet_user_result', 'true' );
612                         update_comment_meta( $comment_id, 'akismet_user', $comment->reporter );
613                 }
614
615                 do_action('akismet_submit_spam_comment', $comment_id, $response[1]);
616         }
617
618         public static function submit_nonspam_comment( $comment_id ) {
619                 global $wpdb, $current_user, $current_site;
620
621                 $comment_id = (int) $comment_id;
622
623                 $comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $comment_id ) );
624                 if ( !$comment ) // it was deleted
625                         return;
626
627                 // use the original version stored in comment_meta if available
628                 $as_submitted = self::sanitize_comment_as_submitted( get_comment_meta( $comment_id, 'akismet_as_submitted', true ) );
629
630                 if ( $as_submitted && is_array($as_submitted) && isset($as_submitted['comment_content']) )
631                         $comment = (object) array_merge( (array)$comment, $as_submitted );
632
633                 $comment->blog         = get_option( 'home' );
634                 $comment->blog_lang    = get_locale();
635                 $comment->blog_charset = get_option('blog_charset');
636                 $comment->permalink    = get_permalink( $comment->comment_post_ID );
637                 $comment->user_role    = '';
638
639                 if ( is_object($current_user) )
640                         $comment->reporter = $current_user->user_login;
641
642                 if ( is_object($current_site) )
643                         $comment->site_domain = $current_site->domain;
644
645                 if ( isset( $comment->user_ID ) )
646                         $comment->user_role = Akismet::get_user_roles($comment->user_ID);
647
648                 if ( Akismet::is_test_mode() )
649                         $comment->is_test = 'true';
650
651                 $post = get_post( $comment->comment_post_ID );
652                 $comment->comment_post_modified_gmt = $post->post_modified_gmt;
653
654                 $response = self::http_post( Akismet::build_query( $comment ), 'submit-ham' );
655                 if ( $comment->reporter ) {
656                         self::update_comment_history( $comment_id, '', 'report-ham' );
657                         update_comment_meta( $comment_id, 'akismet_user_result', 'false' );
658                         update_comment_meta( $comment_id, 'akismet_user', $comment->reporter );
659                 }
660
661                 do_action('akismet_submit_nonspam_comment', $comment_id, $response[1]);
662         }
663
664         public static function cron_recheck() {
665                 global $wpdb;
666
667                 $api_key = self::get_api_key();
668
669                 $status = self::verify_key( $api_key );
670                 if ( get_option( 'akismet_alert_code' ) || $status == 'invalid' ) {
671                         // since there is currently a problem with the key, reschedule a check for 6 hours hence
672                         wp_schedule_single_event( time() + 21600, 'akismet_schedule_cron_recheck' );
673                         do_action( 'akismet_scheduled_recheck', 'key-problem-' . get_option( 'akismet_alert_code' ) . '-' . $status );
674                         return false;
675                 }
676
677                 delete_option('akismet_available_servers');
678
679                 $comment_errors = $wpdb->get_col( "SELECT comment_id FROM {$wpdb->commentmeta} WHERE meta_key = 'akismet_error' LIMIT 100" );
680                 
681                 load_plugin_textdomain( 'akismet' );
682
683                 foreach ( (array) $comment_errors as $comment_id ) {
684                         // if the comment no longer exists, or is too old, remove the meta entry from the queue to avoid getting stuck
685                         $comment = get_comment( $comment_id );
686                         if ( !$comment || strtotime( $comment->comment_date_gmt ) < strtotime( "-15 days" ) ) {
687                                 delete_comment_meta( $comment_id, 'akismet_error' );
688                                 delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
689                                 continue;
690                         }
691
692                         add_comment_meta( $comment_id, 'akismet_rechecking', true );
693                         $status = self::check_db_comment( $comment_id, 'retry' );
694
695                         $event = '';
696                         if ( $status == 'true' ) {
697                                 $event = 'cron-retry-spam';
698                         } elseif ( $status == 'false' ) {
699                                 $event = 'cron-retry-ham';
700                         }
701
702                         // If we got back a legit response then update the comment history
703                         // other wise just bail now and try again later.  No point in
704                         // re-trying all the comments once we hit one failure.
705                         if ( !empty( $event ) ) {
706                                 delete_comment_meta( $comment_id, 'akismet_error' );
707                                 self::update_comment_history( $comment_id, '', $event );
708                                 update_comment_meta( $comment_id, 'akismet_result', $status );
709                                 // make sure the comment status is still pending.  if it isn't, that means the user has already moved it elsewhere.
710                                 $comment = get_comment( $comment_id );
711                                 if ( $comment && 'unapproved' == wp_get_comment_status( $comment_id ) ) {
712                                         if ( $status == 'true' ) {
713                                                 wp_spam_comment( $comment_id );
714                                         } elseif ( $status == 'false' ) {
715                                                 // comment is good, but it's still in the pending queue.  depending on the moderation settings
716                                                 // we may need to change it to approved.
717                                                 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) )
718                                                         wp_set_comment_status( $comment_id, 1 );
719                                                 else if ( get_comment_meta( $comment_id, 'akismet_delayed_moderation_email', true ) )
720                                                         wp_notify_moderator( $comment_id );
721                                         }
722                                 }
723                                 
724                                 delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
725                         } else {
726                                 // If this comment has been pending moderation for longer than MAX_DELAY_BEFORE_MODERATION_EMAIL,
727                                 // send a moderation email now.
728                                 if ( ( intval( gmdate( 'U' ) ) - strtotime( $comment->comment_date_gmt ) ) < self::MAX_DELAY_BEFORE_MODERATION_EMAIL ) {
729                                         delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
730                                         wp_notify_moderator( $comment_id );
731                                 }
732
733                                 delete_comment_meta( $comment_id, 'akismet_rechecking' );
734                                 wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
735                                 do_action( 'akismet_scheduled_recheck', 'check-db-comment-' . $status );
736                                 return;
737                         }
738                         delete_comment_meta( $comment_id, 'akismet_rechecking' );
739                 }
740
741                 $remaining = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->commentmeta} WHERE meta_key = 'akismet_error'" );
742                 if ( $remaining && !wp_next_scheduled('akismet_schedule_cron_recheck') ) {
743                         wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
744                         do_action( 'akismet_scheduled_recheck', 'remaining' );
745                 }
746         }
747
748         public static function fix_scheduled_recheck() {
749                 $future_check = wp_next_scheduled( 'akismet_schedule_cron_recheck' );
750                 if ( !$future_check ) {
751                         return;
752                 }
753
754                 if ( get_option( 'akismet_alert_code' ) > 0 ) {
755                         return;
756                 }
757
758                 $check_range = time() + 1200;
759                 if ( $future_check > $check_range ) {
760                         wp_clear_scheduled_hook( 'akismet_schedule_cron_recheck' );
761                         wp_schedule_single_event( time() + 300, 'akismet_schedule_cron_recheck' );
762                         do_action( 'akismet_scheduled_recheck', 'fix-scheduled-recheck' );
763                 }
764         }
765
766         public static function add_comment_nonce( $post_id ) {
767                 echo '<p style="display: none;">';
768                 wp_nonce_field( 'akismet_comment_nonce_' . $post_id, 'akismet_comment_nonce', FALSE );
769                 echo '</p>';
770         }
771
772         public static function is_test_mode() {
773                 return defined('AKISMET_TEST_MODE') && AKISMET_TEST_MODE;
774         }
775         
776         public static function allow_discard() {
777                 if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
778                         return false;
779                 if ( is_user_logged_in() )
780                         return false;
781         
782                 return ( get_option( 'akismet_strictness' ) === '1'  );
783         }
784
785         public static function get_ip_address() {
786                 return isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : null;
787         }
788         
789         /**
790          * Do these two comments, without checking the comment_ID, "match"?
791          *
792          * @param mixed $comment1 A comment object or array.
793          * @param mixed $comment2 A comment object or array.
794          * @return bool Whether the two comments should be treated as the same comment.
795          */
796         private static function comments_match( $comment1, $comment2 ) {
797                 $comment1 = (array) $comment1;
798                 $comment2 = (array) $comment2;
799                 
800                 $comments_match = (
801                            isset( $comment1['comment_post_ID'], $comment2['comment_post_ID'] )
802                         && intval( $comment1['comment_post_ID'] ) == intval( $comment2['comment_post_ID'] )
803                         && (
804                                 // The comment author length max is 255 characters, limited by the TINYTEXT column type.
805                                 // If the comment author includes multibyte characters right around the 255-byte mark, they
806                                 // may be stripped when the author is saved in the DB, so a 300+ char author may turn into
807                                 // a 253-char author when it's saved, not 255 exactly.  The longest possible character is
808                                 // theoretically 6 bytes, so we'll only look at the first 248 bytes to be safe.
809                                 substr( $comment1['comment_author'], 0, 248 ) == substr( $comment2['comment_author'], 0, 248 )
810                                 || substr( stripslashes( $comment1['comment_author'] ), 0, 248 ) == substr( $comment2['comment_author'], 0, 248 )
811                                 || substr( $comment1['comment_author'], 0, 248 ) == substr( stripslashes( $comment2['comment_author'] ), 0, 248 )
812                                 // Certain long comment author names will be truncated to nothing, depending on their encoding.
813                                 || ( ! $comment1['comment_author'] && strlen( $comment2['comment_author'] ) > 248 )
814                                 || ( ! $comment2['comment_author'] && strlen( $comment1['comment_author'] ) > 248 )
815                                 )
816                         && (
817                                 // The email max length is 100 characters, limited by the VARCHAR(100) column type.
818                                 // Same argument as above for only looking at the first 93 characters.
819                                 substr( $comment1['comment_author_email'], 0, 93 ) == substr( $comment2['comment_author_email'], 0, 93 )
820                                 || substr( stripslashes( $comment1['comment_author_email'] ), 0, 93 ) == substr( $comment2['comment_author_email'], 0, 93 )
821                                 || substr( $comment1['comment_author_email'], 0, 93 ) == substr( stripslashes( $comment2['comment_author_email'] ), 0, 93 )
822                                 // Very long emails can be truncated and then stripped if the [0:100] substring isn't a valid address.
823                                 || ( ! $comment1['comment_author_email'] && strlen( $comment2['comment_author_email'] ) > 100 )
824                                 || ( ! $comment2['comment_author_email'] && strlen( $comment1['comment_author_email'] ) > 100 )
825                         )
826                 );
827
828                 return $comments_match;
829         }
830         
831         // Does the supplied comment match the details of the one most recently stored in self::$last_comment?
832         public static function matches_last_comment( $comment ) {
833                 if ( is_object( $comment ) )
834                         $comment = (array) $comment;
835
836                 return self::comments_match( self::$last_comment, $comment );
837         }
838
839         private static function get_user_agent() {
840                 return isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : null;
841         }
842
843         private static function get_referer() {
844                 return isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : null;
845         }
846
847         // return a comma-separated list of role names for the given user
848         public static function get_user_roles( $user_id ) {
849                 $roles = false;
850
851                 if ( !class_exists('WP_User') )
852                         return false;
853
854                 if ( $user_id > 0 ) {
855                         $comment_user = new WP_User( $user_id );
856                         if ( isset( $comment_user->roles ) )
857                                 $roles = join( ',', $comment_user->roles );
858                 }
859
860                 if ( is_multisite() && is_super_admin( $user_id ) ) {
861                         if ( empty( $roles ) ) {
862                                 $roles = 'super_admin';
863                         } else {
864                                 $comment_user->roles[] = 'super_admin';
865                                 $roles = join( ',', $comment_user->roles );
866                         }
867                 }
868
869                 return $roles;
870         }
871
872         // filter handler used to return a spam result to pre_comment_approved
873         public static function last_comment_status( $approved, $comment ) {
874                 if ( is_null( self::$last_comment_result ) ) {
875                         // We didn't have reason to store the result of the last check.
876                         return $approved;
877                 }
878
879                 // Only do this if it's the correct comment
880                 if ( ! self::matches_last_comment( $comment ) ) {
881                         self::log( "comment_is_spam mismatched comment, returning unaltered $approved" );
882                         return $approved;
883                 }
884
885                 // bump the counter here instead of when the filter is added to reduce the possibility of overcounting
886                 if ( $incr = apply_filters('akismet_spam_count_incr', 1) )
887                         update_option( 'akismet_spam_count', get_option('akismet_spam_count') + $incr );
888
889                 return self::$last_comment_result;
890         }
891         
892         /**
893          * If Akismet is temporarily unreachable, we don't want to "spam" the blogger with
894          * moderation emails for comments that will be automatically cleared or spammed on
895          * the next retry.
896          *
897          * For comments that will be rechecked later, empty the list of email addresses that
898          * the moderation email would be sent to.
899          *
900          * @param array $emails An array of email addresses that the moderation email will be sent to.
901          * @param int $comment_id The ID of the relevant comment.
902          * @return array An array of email addresses that the moderation email will be sent to.
903          */
904         public static function disable_moderation_emails_if_unreachable( $emails, $comment_id ) {
905                 if ( ! empty( self::$prevent_moderation_email_for_these_comments ) && ! empty( $emails ) ) {
906                         $comment = get_comment( $comment_id );
907
908                         foreach ( self::$prevent_moderation_email_for_these_comments as $possible_match ) {
909                                 if ( self::comments_match( $possible_match, $comment ) ) {
910                                         update_comment_meta( $comment_id, 'akismet_delayed_moderation_email', true );
911                                         return array();
912                                 }
913                         }
914                 }
915
916                 return $emails;
917         }
918
919         public static function _cmp_time( $a, $b ) {
920                 return $a['time'] > $b['time'] ? -1 : 1;
921         }
922
923         public static function _get_microtime() {
924                 $mtime = explode( ' ', microtime() );
925                 return $mtime[1] + $mtime[0];
926         }
927
928         /**
929          * Make a POST request to the Akismet API.
930          *
931          * @param string $request The body of the request.
932          * @param string $path The path for the request.
933          * @param string $ip The specific IP address to hit.
934          * @return array A two-member array consisting of the headers and the response body, both empty in the case of a failure.
935          */
936         public static function http_post( $request, $path, $ip=null ) {
937
938                 $akismet_ua = sprintf( 'WordPress/%s | Akismet/%s', $GLOBALS['wp_version'], constant( 'AKISMET_VERSION' ) );
939                 $akismet_ua = apply_filters( 'akismet_ua', $akismet_ua );
940
941                 $content_length = strlen( $request );
942
943                 $api_key   = self::get_api_key();
944                 $host      = self::API_HOST;
945
946                 if ( !empty( $api_key ) )
947                         $host = $api_key.'.'.$host;
948
949                 $http_host = $host;
950                 // use a specific IP if provided
951                 // needed by Akismet_Admin::check_server_connectivity()
952                 if ( $ip && long2ip( ip2long( $ip ) ) ) {
953                         $http_host = $ip;
954                 }
955
956                 $http_args = array(
957                         'body' => $request,
958                         'headers' => array(
959                                 'Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' ),
960                                 'Host' => $host,
961                                 'User-Agent' => $akismet_ua,
962                         ),
963                         'httpversion' => '1.0',
964                         'timeout' => 15
965                 );
966
967                 $akismet_url = $http_akismet_url = "http://{$http_host}/1.1/{$path}";
968
969                 /**
970                  * Try SSL first; if that fails, try without it and don't try it again for a while.
971                  */
972
973                 $ssl = $ssl_failed = false;
974
975                 // Check if SSL requests were disabled fewer than X hours ago.
976                 $ssl_disabled = get_option( 'akismet_ssl_disabled' );
977
978                 if ( $ssl_disabled && $ssl_disabled < ( time() - 60 * 60 * 24 ) ) { // 24 hours
979                         $ssl_disabled = false;
980                         delete_option( 'akismet_ssl_disabled' );
981                 }
982                 else if ( $ssl_disabled ) {
983                         do_action( 'akismet_ssl_disabled' );
984                 }
985
986                 if ( ! $ssl_disabled && function_exists( 'wp_http_supports') && ( $ssl = wp_http_supports( array( 'ssl' ) ) ) ) {
987                         $akismet_url = set_url_scheme( $akismet_url, 'https' );
988
989                         do_action( 'akismet_https_request_pre' );
990                 }
991
992                 $response = wp_remote_post( $akismet_url, $http_args );
993
994                 Akismet::log( compact( 'akismet_url', 'http_args', 'response' ) );
995
996                 if ( $ssl && is_wp_error( $response ) ) {
997                         do_action( 'akismet_https_request_failure', $response );
998
999                         // Intermittent connection problems may cause the first HTTPS
1000                         // request to fail and subsequent HTTP requests to succeed randomly.
1001                         // Retry the HTTPS request once before disabling SSL for a time.
1002                         $response = wp_remote_post( $akismet_url, $http_args );
1003                         
1004                         Akismet::log( compact( 'akismet_url', 'http_args', 'response' ) );
1005
1006                         if ( is_wp_error( $response ) ) {
1007                                 $ssl_failed = true;
1008
1009                                 do_action( 'akismet_https_request_failure', $response );
1010
1011                                 do_action( 'akismet_http_request_pre' );
1012
1013                                 // Try the request again without SSL.
1014                                 $response = wp_remote_post( $http_akismet_url, $http_args );
1015
1016                                 Akismet::log( compact( 'http_akismet_url', 'http_args', 'response' ) );
1017                         }
1018                 }
1019
1020                 if ( is_wp_error( $response ) ) {
1021                         do_action( 'akismet_request_failure', $response );
1022
1023                         return array( '', '' );
1024                 }
1025
1026                 if ( $ssl_failed ) {
1027                         // The request failed when using SSL but succeeded without it. Disable SSL for future requests.
1028                         update_option( 'akismet_ssl_disabled', time() );
1029                         
1030                         do_action( 'akismet_https_disabled' );
1031                 }
1032                 
1033                 $simplified_response = array( $response['headers'], $response['body'] );
1034                 
1035                 self::update_alert( $simplified_response );
1036
1037                 return $simplified_response;
1038         }
1039
1040         // given a response from an API call like check_key_status(), update the alert code options if an alert is present.
1041         private static function update_alert( $response ) {
1042                 $code = $msg = null;
1043                 if ( isset( $response[0]['x-akismet-alert-code'] ) ) {
1044                         $code = $response[0]['x-akismet-alert-code'];
1045                         $msg  = $response[0]['x-akismet-alert-msg'];
1046                 }
1047
1048                 // only call update_option() if the value has changed
1049                 if ( $code != get_option( 'akismet_alert_code' ) ) {
1050                         if ( ! $code ) {
1051                                 delete_option( 'akismet_alert_code' );
1052                                 delete_option( 'akismet_alert_msg' );
1053                         }
1054                         else {
1055                                 update_option( 'akismet_alert_code', $code );
1056                                 update_option( 'akismet_alert_msg', $msg );
1057                         }
1058                 }
1059         }
1060
1061         public static function load_form_js() {
1062                 // WP < 3.3 can't enqueue a script this late in the game and still have it appear in the footer.
1063                 // Once we drop support for everything pre-3.3, this can change back to a single enqueue call.
1064                 wp_register_script( 'akismet-form', plugin_dir_url( __FILE__ ) . '_inc/form.js', array(), AKISMET_VERSION, true );
1065                 add_action( 'wp_footer', array( 'Akismet', 'print_form_js' ) );
1066                 add_action( 'admin_footer', array( 'Akismet', 'print_form_js' ) );
1067         }
1068         
1069         public static function print_form_js() {
1070                 wp_print_scripts( 'akismet-form' );
1071         }
1072
1073         public static function inject_ak_js( $fields ) {
1074                 echo '<p style="display: none;">';
1075                 echo '<input type="hidden" id="ak_js" name="ak_js" value="' . mt_rand( 0, 250 ) . '"/>';
1076                 echo '</p>';
1077         }
1078
1079         private static function bail_on_activation( $message, $deactivate = true ) {
1080 ?>
1081 <!doctype html>
1082 <html>
1083 <head>
1084 <meta charset="<?php bloginfo( 'charset' ); ?>">
1085 <style>
1086 * {
1087         text-align: center;
1088         margin: 0;
1089         padding: 0;
1090         font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
1091 }
1092 p {
1093         margin-top: 1em;
1094         font-size: 18px;
1095 }
1096 </style>
1097 <body>
1098 <p><?php echo esc_html( $message ); ?></p>
1099 </body>
1100 </html>
1101 <?php
1102                 if ( $deactivate ) {
1103                         $plugins = get_option( 'active_plugins' );
1104                         $akismet = plugin_basename( AKISMET__PLUGIN_DIR . 'akismet.php' );
1105                         $update  = false;
1106                         foreach ( $plugins as $i => $plugin ) {
1107                                 if ( $plugin === $akismet ) {
1108                                         $plugins[$i] = false;
1109                                         $update = true;
1110                                 }
1111                         }
1112
1113                         if ( $update ) {
1114                                 update_option( 'active_plugins', array_filter( $plugins ) );
1115                         }
1116                 }
1117                 exit;
1118         }
1119
1120         public static function view( $name, array $args = array() ) {
1121                 $args = apply_filters( 'akismet_view_arguments', $args, $name );
1122                 
1123                 foreach ( $args AS $key => $val ) {
1124                         $$key = $val;
1125                 }
1126                 
1127                 load_plugin_textdomain( 'akismet' );
1128
1129                 $file = AKISMET__PLUGIN_DIR . 'views/'. $name . '.php';
1130
1131                 include( $file );
1132         }
1133
1134         /**
1135          * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
1136          * @static
1137          */
1138         public static function plugin_activation() {
1139                 if ( version_compare( $GLOBALS['wp_version'], AKISMET__MINIMUM_WP_VERSION, '<' ) ) {
1140                         load_plugin_textdomain( 'akismet' );
1141                         
1142                         $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/');
1143
1144                         Akismet::bail_on_activation( $message );
1145                 }
1146         }
1147
1148         /**
1149          * Removes all connection options
1150          * @static
1151          */
1152         public static function plugin_deactivation( ) {
1153                 return self::deactivate_key( self::get_api_key() );
1154         }
1155         
1156         /**
1157          * Essentially a copy of WP's build_query but one that doesn't expect pre-urlencoded values.
1158          *
1159          * @param array $args An array of key => value pairs
1160          * @return string A string ready for use as a URL query string.
1161          */
1162         public static function build_query( $args ) {
1163                 return _http_build_query( $args, '', '&' );
1164         }
1165
1166         /**
1167          * Log debugging info to the error log.
1168          *
1169          * Enabled when WP_DEBUG_LOG is enabled (and WP_DEBUG, since according to
1170          * core, "WP_DEBUG_DISPLAY and WP_DEBUG_LOG perform no function unless
1171          * WP_DEBUG is true), but can be disabled via the akismet_debug_log filter.
1172          *
1173          * @param mixed $akismet_debug The data to log.
1174          */
1175         public static function log( $akismet_debug ) {
1176                 if ( apply_filters( 'akismet_debug_log', defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) ) {
1177                         error_log( print_r( compact( 'akismet_debug' ), true ) );
1178                 }
1179         }
1180
1181         public static function pre_check_pingback( $method ) {
1182                 if ( $method !== 'pingback.ping' )
1183                         return;
1184
1185                 global $wp_xmlrpc_server;
1186         
1187                 if ( !is_object( $wp_xmlrpc_server ) )
1188                         return false;
1189         
1190                 // Lame: tightly coupled with the IXR class.
1191                 $args = $wp_xmlrpc_server->message->params;
1192         
1193                 if ( !empty( $args[1] ) ) {
1194                         $post_id = url_to_postid( $args[1] );
1195
1196                         // If this gets through the pre-check, make sure we properly identify the outbound request as a pingback verification
1197                         Akismet::pingback_forwarded_for( null, $args[0] );
1198                         add_filter( 'http_request_args', array( 'Akismet', 'pingback_forwarded_for' ), 10, 2 );
1199
1200                         $comment = array(
1201                                 'comment_author_url' => $args[0],
1202                                 'comment_post_ID' => $post_id,
1203                                 'comment_author' => '',
1204                                 'comment_author_email' => '',
1205                                 'comment_content' => '',
1206                                 'comment_type' => 'pingback',
1207                                 'akismet_pre_check' => '1',
1208                                 'comment_pingback_target' => $args[1],
1209                         );
1210
1211                         $comment = Akismet::auto_check_comment( $comment );
1212
1213                         if ( isset( $comment['akismet_result'] ) && 'true' == $comment['akismet_result'] ) {
1214                                 // Lame: tightly coupled with the IXR classes. Unfortunately the action provides no context and no way to return anything.
1215                                 $wp_xmlrpc_server->error( new IXR_Error( 0, 'Invalid discovery target' ) );
1216                         }
1217                 }
1218         }
1219         
1220         public static function pingback_forwarded_for( $r, $url ) {
1221                 static $urls = array();
1222         
1223                 // Call this with $r == null to prime the callback to add headers on a specific URL
1224                 if ( is_null( $r ) && !in_array( $url, $urls ) ) {
1225                         $urls[] = $url;
1226                 }
1227
1228                 // Add X-Pingback-Forwarded-For header, but only for requests to a specific URL (the apparent pingback source)
1229                 if ( is_array( $r ) && is_array( $r['headers'] ) && !isset( $r['headers']['X-Pingback-Forwarded-For'] ) && in_array( $url, $urls ) ) {
1230                         $remote_ip = preg_replace( '/[^a-fx0-9:.,]/i', '', $_SERVER['REMOTE_ADDR'] );
1231                 
1232                         // Note: this assumes REMOTE_ADDR is correct, and it may not be if a reverse proxy or CDN is in use
1233                         $r['headers']['X-Pingback-Forwarded-For'] = $remote_ip;
1234
1235                         // Also identify the request as a pingback verification in the UA string so it appears in logs
1236                         $r['user-agent'] .= '; verifying pingback from ' . $remote_ip;
1237                 }
1238
1239                 return $r;
1240         }
1241         
1242         /**
1243          * Ensure that we are loading expected scalar values from akismet_as_submitted commentmeta.
1244          *
1245          * @param mixed $meta_value
1246          * @return mixed
1247          */
1248         private static function sanitize_comment_as_submitted( $meta_value ) {
1249                 if ( empty( $meta_value ) ) {
1250                         return $meta_value;
1251                 }
1252
1253                 $meta_value = (array) $meta_value;
1254
1255                 foreach ( $meta_value as $key => $value ) {
1256                         if ( ! isset( self::$comment_as_submitted_allowed_keys[$key] ) || ! is_scalar( $value ) ) {
1257                                 unset( $meta_value[$key] );
1258                         }
1259                 }
1260
1261                 return $meta_value;
1262         }
1263 }