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