]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-content/plugins/akismet/class.akismet-admin.php
WordPress 4.4
[autoinstalls/wordpress.git] / wp-content / plugins / akismet / class.akismet-admin.php
1 <?php
2
3 class Akismet_Admin {
4         const NONCE = 'akismet-update-key';
5
6         private static $initiated = false;
7         private static $notices = array();
8
9         public static function init() {
10                 if ( ! self::$initiated ) {
11                         self::init_hooks();
12                 }
13
14                 if ( isset( $_POST['action'] ) && $_POST['action'] == 'enter-key' ) {
15                         self::enter_api_key();
16                 }
17         }
18
19         public static function init_hooks() {
20                 // The standalone stats page was removed in 3.0 for an all-in-one config and stats page.
21                 // Redirect any links that might have been bookmarked or in browser history.
22                 if ( isset( $_GET['page'] ) && 'akismet-stats-display' == $_GET['page'] ) {
23                         wp_safe_redirect( esc_url_raw( self::get_page_url( 'stats' ) ), 301 );
24                         die;
25                 }
26
27                 self::$initiated = true;
28
29                 add_action( 'admin_init', array( 'Akismet_Admin', 'admin_init' ) );
30                 add_action( 'admin_menu', array( 'Akismet_Admin', 'admin_menu' ), 5 ); # Priority 5, so it's called before Jetpack's admin_menu.
31                 add_action( 'admin_notices', array( 'Akismet_Admin', 'display_notice' ) );
32                 add_action( 'admin_enqueue_scripts', array( 'Akismet_Admin', 'load_resources' ) );
33                 add_action( 'activity_box_end', array( 'Akismet_Admin', 'dashboard_stats' ) );
34                 add_action( 'rightnow_end', array( 'Akismet_Admin', 'rightnow_stats' ) );
35                 add_action( 'manage_comments_nav', array( 'Akismet_Admin', 'check_for_spam_button' ) );
36                 add_action( 'admin_action_akismet_recheck_queue', array( 'Akismet_Admin', 'recheck_queue' ) );
37                 add_action( 'wp_ajax_akismet_recheck_queue', array( 'Akismet_Admin', 'recheck_queue' ) );
38                 add_action( 'wp_ajax_comment_author_deurl', array( 'Akismet_Admin', 'remove_comment_author_url' ) );
39                 add_action( 'wp_ajax_comment_author_reurl', array( 'Akismet_Admin', 'add_comment_author_url' ) );
40                 add_action( 'jetpack_auto_activate_akismet', array( 'Akismet_Admin', 'connect_jetpack_user' ) );
41
42                 add_filter( 'plugin_action_links', array( 'Akismet_Admin', 'plugin_action_links' ), 10, 2 );
43                 add_filter( 'comment_row_actions', array( 'Akismet_Admin', 'comment_row_action' ), 10, 2 );
44                 
45                 add_filter( 'plugin_action_links_'.plugin_basename( plugin_dir_path( __FILE__ ) . 'akismet.php'), array( 'Akismet_Admin', 'admin_plugin_settings_link' ) );
46                 
47                 add_filter( 'wxr_export_skip_commentmeta', array( 'Akismet_Admin', 'exclude_commentmeta_from_export' ), 10, 3 );
48         }
49
50         public static function admin_init() {
51                 load_plugin_textdomain( 'akismet' );
52                 add_meta_box( 'akismet-status', __('Comment History', 'akismet'), array( 'Akismet_Admin', 'comment_status_meta_box' ), 'comment', 'normal' );
53         }
54
55         public static function admin_menu() {
56                 if ( class_exists( 'Jetpack' ) )
57                         add_action( 'jetpack_admin_menu', array( 'Akismet_Admin', 'load_menu' ) );
58                 else
59                         self::load_menu();
60         }
61
62         public static function admin_head() {
63                 if ( !current_user_can( 'manage_options' ) )
64                         return;
65         }
66         
67         public static function admin_plugin_settings_link( $links ) { 
68                 $settings_link = '<a href="'.esc_url( self::get_page_url() ).'">'.__('Settings', 'akismet').'</a>';
69                 array_unshift( $links, $settings_link ); 
70                 return $links; 
71         }
72
73         public static function load_menu() {
74                 if ( class_exists( 'Jetpack' ) )
75                         $hook = add_submenu_page( 'jetpack', __( 'Akismet' , 'akismet'), __( 'Akismet' , 'akismet'), 'manage_options', 'akismet-key-config', array( 'Akismet_Admin', 'display_page' ) );
76                 else
77                         $hook = add_options_page( __('Akismet', 'akismet'), __('Akismet', 'akismet'), 'manage_options', 'akismet-key-config', array( 'Akismet_Admin', 'display_page' ) );
78
79                 if ( version_compare( $GLOBALS['wp_version'], '3.3', '>=' ) ) {
80                         add_action( "load-$hook", array( 'Akismet_Admin', 'admin_help' ) );
81                 }
82         }
83
84         public static function load_resources() {
85                 global $hook_suffix;
86
87                 if ( in_array( $hook_suffix, array(
88                         'index.php', # dashboard
89                         'edit-comments.php',
90                         'comment.php',
91                         'post.php',
92                         'settings_page_akismet-key-config',
93                         'jetpack_page_akismet-key-config',
94                 ) ) ) {
95                         wp_register_style( 'akismet.css', AKISMET__PLUGIN_URL . '_inc/akismet.css', array(), AKISMET_VERSION );
96                         wp_enqueue_style( 'akismet.css');
97
98                         wp_register_script( 'akismet.js', AKISMET__PLUGIN_URL . '_inc/akismet.js', array('jquery','postbox'), AKISMET_VERSION );
99                         wp_enqueue_script( 'akismet.js' );
100                         wp_localize_script( 'akismet.js', 'WPAkismet', array(
101                                 'comment_author_url_nonce' => wp_create_nonce( 'comment_author_url_nonce' ),
102                                 'strings' => array(
103                                         'Remove this URL' => __( 'Remove this URL' , 'akismet'),
104                                         'Removing...'     => __( 'Removing...' , 'akismet'),
105                                         'URL removed'     => __( 'URL removed' , 'akismet'),
106                                         '(undo)'          => __( '(undo)' , 'akismet'),
107                                         'Re-adding...'    => __( 'Re-adding...' , 'akismet'),
108                                 )
109                         ) );
110                 }
111         }
112
113         /**
114          * Add help to the Akismet page
115          *
116          * @return false if not the Akismet page
117          */
118         public static function admin_help() {
119                 $current_screen = get_current_screen();
120
121                 // Screen Content
122                 if ( current_user_can( 'manage_options' ) ) {
123                         if ( !Akismet::get_api_key() || ( isset( $_GET['view'] ) && $_GET['view'] == 'start' ) ) {
124                                 //setup page
125                                 $current_screen->add_help_tab(
126                                         array(
127                                                 'id'            => 'overview',
128                                                 'title'         => __( 'Overview' , 'akismet'),
129                                                 'content'       =>
130                                                         '<p><strong>' . esc_html__( 'Akismet Setup' , 'akismet') . '</strong></p>' .
131                                                         '<p>' . esc_html__( 'Akismet filters out spam, so you can focus on more important things.' , 'akismet') . '</p>' .
132                                                         '<p>' . esc_html__( 'On this page, you are able to set up the Akismet plugin.' , 'akismet') . '</p>',
133                                         )
134                                 );
135
136                                 $current_screen->add_help_tab(
137                                         array(
138                                                 'id'            => 'setup-signup',
139                                                 'title'         => __( 'New to Akismet' , 'akismet'),
140                                                 'content'       =>
141                                                         '<p><strong>' . esc_html__( 'Akismet Setup' , 'akismet') . '</strong></p>' .
142                                                         '<p>' . esc_html__( 'You need to enter an API key to activate the Akismet service on your site.' , 'akismet') . '</p>' .
143                                                         '<p>' . sprintf( __( 'Sign up for an account on %s to get an API Key.' , 'akismet'), '<a href="https://akismet.com/plugin-signup/" target="_blank">Akismet.com</a>' ) . '</p>',
144                                         )
145                                 );
146
147                                 $current_screen->add_help_tab(
148                                         array(
149                                                 'id'            => 'setup-manual',
150                                                 'title'         => __( 'Enter an API Key' , 'akismet'),
151                                                 'content'       =>
152                                                         '<p><strong>' . esc_html__( 'Akismet Setup' , 'akismet') . '</strong></p>' .
153                                                         '<p>' . esc_html__( 'If you already have an API key' , 'akismet') . '</p>' .
154                                                         '<ol>' .
155                                                                 '<li>' . esc_html__( 'Copy and paste the API key into the text field.' , 'akismet') . '</li>' .
156                                                                 '<li>' . esc_html__( 'Click the Use this Key button.' , 'akismet') . '</li>' .
157                                                         '</ol>',
158                                         )
159                                 );
160                         }
161                         elseif ( isset( $_GET['view'] ) && $_GET['view'] == 'stats' ) {
162                                 //stats page
163                                 $current_screen->add_help_tab(
164                                         array(
165                                                 'id'            => 'overview',
166                                                 'title'         => __( 'Overview' , 'akismet'),
167                                                 'content'       =>
168                                                         '<p><strong>' . esc_html__( 'Akismet Stats' , 'akismet') . '</strong></p>' .
169                                                         '<p>' . esc_html__( 'Akismet filters out spam, so you can focus on more important things.' , 'akismet') . '</p>' .
170                                                         '<p>' . esc_html__( 'On this page, you are able to view stats on spam filtered on your site.' , 'akismet') . '</p>',
171                                         )
172                                 );
173                         }
174                         else {
175                                 //configuration page
176                                 $current_screen->add_help_tab(
177                                         array(
178                                                 'id'            => 'overview',
179                                                 'title'         => __( 'Overview' , 'akismet'),
180                                                 'content'       =>
181                                                         '<p><strong>' . esc_html__( 'Akismet Configuration' , 'akismet') . '</strong></p>' .
182                                                         '<p>' . esc_html__( 'Akismet filters out spam, so you can focus on more important things.' , 'akismet') . '</p>' .
183                                                         '<p>' . esc_html__( 'On this page, you are able to enter/remove an API key, view account information and view spam stats.' , 'akismet') . '</p>',
184                                         )
185                                 );
186
187                                 $current_screen->add_help_tab(
188                                         array(
189                                                 'id'            => 'settings',
190                                                 'title'         => __( 'Settings' , 'akismet'),
191                                                 'content'       =>
192                                                         '<p><strong>' . esc_html__( 'Akismet Configuration' , 'akismet') . '</strong></p>' .
193                                                         '<p><strong>' . esc_html__( 'API Key' , 'akismet') . '</strong> - ' . esc_html__( 'Enter/remove an API key.' , 'akismet') . '</p>' .
194                                                         '<p><strong>' . esc_html__( 'Comments' , 'akismet') . '</strong> - ' . esc_html__( 'Show the number of approved comments beside each comment author in the comments list page.' , 'akismet') . '</p>' .
195                                                         '<p><strong>' . esc_html__( 'Strictness' , 'akismet') . '</strong> - ' . esc_html__( 'Choose to either discard the worst spam automatically or to always put all spam in spam folder.' , 'akismet') . '</p>',
196                                         )
197                                 );
198
199                                 $current_screen->add_help_tab(
200                                         array(
201                                                 'id'            => 'account',
202                                                 'title'         => __( 'Account' , 'akismet'),
203                                                 'content'       =>
204                                                         '<p><strong>' . esc_html__( 'Akismet Configuration' , 'akismet') . '</strong></p>' .
205                                                         '<p><strong>' . esc_html__( 'Subscription Type' , 'akismet') . '</strong> - ' . esc_html__( 'The Akismet subscription plan' , 'akismet') . '</p>' .
206                                                         '<p><strong>' . esc_html__( 'Status' , 'akismet') . '</strong> - ' . esc_html__( 'The subscription status - active, cancelled or suspended' , 'akismet') . '</p>',
207                                         )
208                                 );
209                         }
210                 }
211
212                 // Help Sidebar
213                 $current_screen->set_help_sidebar(
214                         '<p><strong>' . esc_html__( 'For more information:' , 'akismet') . '</strong></p>' .
215                         '<p><a href="https://akismet.com/faq/" target="_blank">'     . esc_html__( 'Akismet FAQ' , 'akismet') . '</a></p>' .
216                         '<p><a href="https://akismet.com/support/" target="_blank">' . esc_html__( 'Akismet Support' , 'akismet') . '</a></p>'
217                 );
218         }
219
220         public static function enter_api_key() {
221                 if ( function_exists('current_user_can') && !current_user_can('manage_options') )
222                         die(__('Cheatin&#8217; uh?', 'akismet'));
223
224                 if ( !wp_verify_nonce( $_POST['_wpnonce'], self::NONCE ) )
225                         return false;
226
227                 foreach( array( 'akismet_strictness', 'akismet_show_user_comments_approved' ) as $option ) {
228                         update_option( $option, isset( $_POST[$option] ) && (int) $_POST[$option] == 1 ? '1' : '0' );
229                 }
230
231                 if ( defined( 'WPCOM_API_KEY' ) )
232                         return false; //shouldn't have option to save key if already defined
233
234                 $new_key = preg_replace( '/[^a-f0-9]/i', '', $_POST['key'] );
235                 $old_key = Akismet::get_api_key();
236
237                 if ( empty( $new_key ) ) {
238                         if ( !empty( $old_key ) ) {
239                                 delete_option( 'wordpress_api_key' );
240                                 self::$notices[] = 'new-key-empty';
241                         }
242                 }
243                 elseif ( $new_key != $old_key ) {
244                         self::save_key( $new_key );
245                 }
246
247                 return true;
248         }
249
250         public static function save_key( $api_key ) {
251                 $key_status = Akismet::verify_key( $api_key );
252
253                 if ( $key_status == 'valid' ) {
254                         $akismet_user = self::get_akismet_user( $api_key );
255                         
256                         if ( $akismet_user ) {                          
257                                 if ( in_array( $akismet_user->status, array( 'active', 'active-dunning', 'no-sub' ) ) )
258                                         update_option( 'wordpress_api_key', $api_key );
259                                 
260                                 if (  $akismet_user->status == 'active' )
261                                         self::$notices['status'] = 'new-key-valid';
262                                 else
263                                         self::$notices['status'] = $akismet_user->status;
264                         }
265                         else
266                                 self::$notices['status'] = 'new-key-invalid';
267                 }
268                 elseif ( in_array( $key_status, array( 'invalid', 'failed' ) ) )
269                         self::$notices['status'] = 'new-key-'.$key_status;
270         }
271
272         public static function dashboard_stats() {
273                 if ( !function_exists('did_action') || did_action( 'rightnow_end' ) )
274                         return; // We already displayed this info in the "Right Now" section
275
276                 if ( !$count = get_option('akismet_spam_count') )
277                         return;
278
279                 global $submenu;
280
281                 echo '<h3>' . esc_html( _x( 'Spam', 'comments' , 'akismet') ) . '</h3>';
282
283                 echo '<p>'.sprintf( _n(
284                                 '<a href="%1$s">Akismet</a> has protected your site from <a href="%2$s">%3$s spam comment</a>.',
285                                 '<a href="%1$s">Akismet</a> has protected your site from <a href="%2$s">%3$s spam comments</a>.',
286                                 $count
287                         , 'akismet'), 'https://akismet.com/wordpress/', esc_url( add_query_arg( array( 'page' => 'akismet-admin' ), admin_url( isset( $submenu['edit-comments.php'] ) ? 'edit-comments.php' : 'edit.php' ) ) ), number_format_i18n($count) ).'</p>';
288         }
289
290         // WP 2.5+
291         public static function rightnow_stats() {
292                 if ( $count = get_option('akismet_spam_count') ) {
293                         $intro = sprintf( _n(
294                                 '<a href="%1$s">Akismet</a> has protected your site from %2$s spam comment already. ',
295                                 '<a href="%1$s">Akismet</a> has protected your site from %2$s spam comments already. ',
296                                 $count
297                         , 'akismet'), 'https://akismet.com/wordpress/', number_format_i18n( $count ) );
298                 } else {
299                         $intro = sprintf( __('<a href="%s">Akismet</a> blocks spam from getting to your blog. ', 'akismet'), 'https://akismet.com/wordpress/' );
300                 }
301
302                 $link = add_query_arg( array( 'comment_status' => 'spam' ), admin_url( 'edit-comments.php' ) );
303
304                 if ( $queue_count = self::get_spam_count() ) {
305                         $queue_text = sprintf( _n(
306                                 'There&#8217;s <a href="%2$s">%1$s comment</a> in your spam queue right now.',
307                                 'There are <a href="%2$s">%1$s comments</a> in your spam queue right now.',
308                                 $queue_count
309                         , 'akismet'), number_format_i18n( $queue_count ), esc_url( $link ) );
310                 } else {
311                         $queue_text = sprintf( __( "There&#8217;s nothing in your <a href='%s'>spam queue</a> at the moment." , 'akismet'), esc_url( $link ) );
312                 }
313
314                 $text = $intro . '<br />' . $queue_text;
315                 echo "<p class='akismet-right-now'>$text</p>\n";
316         }
317
318         public static function check_for_spam_button( $comment_status ) {
319                 // The "Check for Spam" button should only appear when the page might be showing
320                 // a comment with comment_approved=0, which means an un-trashed, un-spammed,
321                 // not-yet-moderated comment.
322                 if ( 'all' != $comment_status && 'moderated' != $comment_status ) {
323                         return;
324                 }
325
326                 if ( function_exists('plugins_url') )
327                         $link = add_query_arg( array( 'action' => 'akismet_recheck_queue' ), admin_url( 'admin.php' ) );
328                 else
329                         $link = add_query_arg( array( 'page' => 'akismet-admin', 'recheckqueue' => 'true', 'noheader' => 'true' ), admin_url( 'edit-comments.php' ) );
330
331                 echo '</div><div class="alignleft"><a class="button-secondary checkforspam" href="' . esc_url( $link ) . '">' . esc_html__('Check for Spam', 'akismet') . '</a><span class="checkforspam-spinner"></span>';
332         }
333
334         public static function recheck_queue() {
335                 global $wpdb;
336
337                 Akismet::fix_scheduled_recheck();
338
339                 if ( ! ( isset( $_GET['recheckqueue'] ) || ( isset( $_REQUEST['action'] ) && 'akismet_recheck_queue' == $_REQUEST['action'] ) ) )
340                         return;
341
342                 $paginate = '';
343                 if ( isset( $_POST['limit'] ) && isset( $_POST['offset'] ) ) {
344                         $paginate = $wpdb->prepare( " LIMIT %d OFFSET %d", array( $_POST['limit'], $_POST['offset'] ) );
345                 }
346                 $moderation = $wpdb->get_results( "SELECT * FROM {$wpdb->comments} WHERE comment_approved = '0'{$paginate}", ARRAY_A );
347
348                 foreach ( (array) $moderation as $c ) {
349                         $c['user_ip']      = $c['comment_author_IP'];
350                         $c['user_agent']   = $c['comment_agent'];
351                         $c['referrer']     = '';
352                         $c['blog']         = get_bloginfo('url');
353                         $c['blog_lang']    = get_locale();
354                         $c['blog_charset'] = get_option('blog_charset');
355                         $c['permalink']    = get_permalink($c['comment_post_ID']);
356
357                         $c['user_role'] = '';
358                         if ( isset( $c['user_ID'] ) )
359                                 $c['user_role'] = Akismet::get_user_roles($c['user_ID']);
360
361                         if ( Akismet::is_test_mode() )
362                                 $c['is_test'] = 'true';
363
364                         add_comment_meta( $c['comment_ID'], 'akismet_rechecking', true );
365
366                         $response = Akismet::http_post( Akismet::build_query( $c ), 'comment-check' );
367                         
368                         if ( 'true' == $response[1] ) {
369                                 wp_set_comment_status( $c['comment_ID'], 'spam' );
370                                 update_comment_meta( $c['comment_ID'], 'akismet_result', 'true' );
371                                 delete_comment_meta( $c['comment_ID'], 'akismet_error' );
372                                 delete_comment_meta( $c['comment_ID'], 'akismet_delayed_moderation_email' );
373                                 Akismet::update_comment_history( $c['comment_ID'], '', 'recheck-spam' );
374
375                         } elseif ( 'false' == $response[1] ) {
376                                 update_comment_meta( $c['comment_ID'], 'akismet_result', 'false' );
377                                 delete_comment_meta( $c['comment_ID'], 'akismet_error' );
378                                 delete_comment_meta( $c['comment_ID'], 'akismet_delayed_moderation_email' );
379                                 Akismet::update_comment_history( $c['comment_ID'], '', 'recheck-ham' );
380                         // abnormal result: error
381                         } else {
382                                 update_comment_meta( $c['comment_ID'], 'akismet_result', 'error' );
383                                 Akismet::update_comment_history(
384                                         $c['comment_ID'],
385                                         '',
386                                         'recheck-error',
387                                         array( 'response' => substr( $response[1], 0, 50 ) )
388                                 );
389                         }
390
391                         delete_comment_meta( $c['comment_ID'], 'akismet_rechecking' );
392                 }
393                 if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
394                         wp_send_json( array(
395                                 'processed' => count((array) $moderation),
396                         ));
397                 }
398                 else {
399                         $redirect_to = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : admin_url( 'edit-comments.php' );
400                         wp_safe_redirect( $redirect_to );
401                         exit;
402                 }
403         }
404
405         // Adds an 'x' link next to author URLs, clicking will remove the author URL and show an undo link
406         public static function remove_comment_author_url() {
407                 if ( !empty( $_POST['id'] ) && check_admin_referer( 'comment_author_url_nonce' ) ) {
408                         $comment = get_comment( intval( $_POST['id'] ), ARRAY_A );
409                         if ( $comment && current_user_can( 'edit_comment', $comment['comment_ID'] ) ) {
410                                 $comment['comment_author_url'] = '';
411                                 do_action( 'comment_remove_author_url' );
412                                 print( wp_update_comment( $comment ) );
413                                 die();
414                         }
415                 }
416         }
417
418         public static function add_comment_author_url() {
419                 if ( !empty( $_POST['id'] ) && !empty( $_POST['url'] ) && check_admin_referer( 'comment_author_url_nonce' ) ) {
420                         $comment = get_comment( intval( $_POST['id'] ), ARRAY_A );
421                         if ( $comment && current_user_can( 'edit_comment', $comment['comment_ID'] ) ) {
422                                 $comment['comment_author_url'] = esc_url( $_POST['url'] );
423                                 do_action( 'comment_add_author_url' );
424                                 print( wp_update_comment( $comment ) );
425                                 die();
426                         }
427                 }
428         }
429
430         public static function comment_row_action( $a, $comment ) {
431
432                 // failsafe for old WP versions
433                 if ( !function_exists('add_comment_meta') )
434                         return $a;
435
436                 $akismet_result = get_comment_meta( $comment->comment_ID, 'akismet_result', true );
437                 $akismet_error  = get_comment_meta( $comment->comment_ID, 'akismet_error', true );
438                 $user_result    = get_comment_meta( $comment->comment_ID, 'akismet_user_result', true);
439                 $comment_status = wp_get_comment_status( $comment->comment_ID );
440                 $desc = null;
441                 if ( $akismet_error ) {
442                         $desc = __( 'Awaiting spam check' , 'akismet');
443                 } elseif ( !$user_result || $user_result == $akismet_result ) {
444                         // Show the original Akismet result if the user hasn't overridden it, or if their decision was the same
445                         if ( $akismet_result == 'true' && $comment_status != 'spam' && $comment_status != 'trash' )
446                                 $desc = __( 'Flagged as spam by Akismet' , 'akismet');
447                         elseif ( $akismet_result == 'false' && $comment_status == 'spam' )
448                                 $desc = __( 'Cleared by Akismet' , 'akismet');
449                 } else {
450                         $who = get_comment_meta( $comment->comment_ID, 'akismet_user', true );
451                         if ( $user_result == 'true' )
452                                 $desc = sprintf( __('Flagged as spam by %s', 'akismet'), $who );
453                         else
454                                 $desc = sprintf( __('Un-spammed by %s', 'akismet'), $who );
455                 }
456
457                 // add a History item to the hover links, just after Edit
458                 if ( $akismet_result ) {
459                         $b = array();
460                         foreach ( $a as $k => $item ) {
461                                 $b[ $k ] = $item;
462                                 if (
463                                         $k == 'edit'
464                                         || ( $k == 'unspam' && $GLOBALS['wp_version'] >= 3.4 )
465                                 ) {
466                                         $b['history'] = '<a href="comment.php?action=editcomment&amp;c='.$comment->comment_ID.'#akismet-status" title="'. esc_attr__( 'View comment history' , 'akismet') . '"> '. esc_html__('History', 'akismet') . '</a>';
467                                 }
468                         }
469
470                         $a = $b;
471                 }
472
473                 if ( $desc )
474                         echo '<span class="akismet-status" commentid="'.$comment->comment_ID.'"><a href="comment.php?action=editcomment&amp;c='.$comment->comment_ID.'#akismet-status" title="' . esc_attr__( 'View comment history' , 'akismet') . '">'.esc_html( $desc ).'</a></span>';
475
476                 $show_user_comments = apply_filters( 'akismet_show_user_comments_approved', get_option('akismet_show_user_comments_approved') );
477                 $show_user_comments = $show_user_comments === 'false' ? false : $show_user_comments; //option used to be saved as 'false' / 'true'
478                 
479                 if ( $show_user_comments ) {
480                         $comment_count = Akismet::get_user_comments_approved( $comment->user_id, $comment->comment_author_email, $comment->comment_author, $comment->comment_author_url );
481                         $comment_count = intval( $comment_count );
482                         echo '<span class="akismet-user-comment-count" commentid="'.$comment->comment_ID.'" style="display:none;"><br><span class="akismet-user-comment-counts">'. sprintf( esc_html( _n( '%s approved', '%s approved', $comment_count , 'akismet') ), number_format_i18n( $comment_count ) ) . '</span></span>';
483                 }
484
485                 return $a;
486         }
487
488         public static function comment_status_meta_box( $comment ) {
489                 $history = Akismet::get_comment_history( $comment->comment_ID );
490
491                 if ( $history ) {
492                         echo '<div class="akismet-history" style="margin: 13px;">';
493
494                         foreach ( $history as $row ) {
495                                 $time = date( 'D d M Y @ h:i:m a', $row['time'] ) . ' GMT';
496                                 
497                                 $message = '';
498                                 
499                                 if ( ! empty( $row['message'] ) ) {
500                                         // Old versions of Akismet stored the message as a literal string in the commentmeta.
501                                         // New versions don't do that for two reasons:
502                                         // 1) Save space.
503                                         // 2) The message can be translated into the current language of the blog, not stuck 
504                                         //    in the language of the blog when the comment was made.
505                                         $message = $row['message'];
506                                 }
507                                 
508                                 // If possible, use a current translation.
509                                 switch ( $row['event'] ) {
510                                         case 'recheck-spam';
511                                                 $message = __( 'Akismet re-checked and caught this comment as spam.', 'akismet' );
512                                         break;
513                                         case 'check-spam':
514                                                 $message = __( 'Akismet caught this comment as spam.', 'akismet' );
515                                         break;
516                                         case 'recheck-ham':
517                                                 $message = __( 'Akismet re-checked and cleared this comment.', 'akismet' );
518                                         break;
519                                         case 'check-ham':
520                                                 $message = __( 'Akismet cleared this comment.', 'akismet' );
521                                         break;
522                                         case 'wp-blacklisted':
523                                                 $message = __( 'Comment was caught by wp_blacklist_check.', 'akismet' );
524                                         break;
525                                         case 'report-spam':
526                                                 if ( isset( $row['user'] ) ) {
527                                                         $message = sprintf( __( '%s reported this comment as spam.', 'akismet' ), $row['user'] );
528                                                 }
529                                                 else if ( ! $message ) {
530                                                         $message = __( 'This comment was reported as spam.', 'akismet' );
531                                                 }
532                                         break;
533                                         case 'report-ham':
534                                                 if ( isset( $row['user'] ) ) {
535                                                         $message = sprintf( __( '%s reported this comment as not spam.', 'akismet' ), $row['user'] );
536                                                 }
537                                                 else if ( ! $message ) {
538                                                         $message = __( 'This comment was reported as not spam.', 'akismet' );
539                                                 }
540                                         break;
541                                         case 'cron-retry-spam':
542                                                 $message = __( 'Akismet caught this comment as spam during an automatic retry.' , 'akismet');
543                                         break;
544                                         case 'cron-retry-ham':
545                                                 $message = __( 'Akismet cleared this comment during an automatic retry.', 'akismet');
546                                         break;
547                                         case 'check-error':
548                                                 if ( isset( $row['meta'], $row['meta']['response'] ) ) {
549                                                         $message = sprintf( __( 'Akismet was unable to check this comment (response: %s) but will automatically retry later.', 'akismet'), $row['meta']['response'] );
550                                                 }
551                                         break;
552                                         case 'recheck-error':
553                                                 if ( isset( $row['meta'], $row['meta']['response'] ) ) {
554                                                         $message = sprintf( __( 'Akismet was unable to recheck this comment (response: %s).', 'akismet'), $row['meta']['response'] );
555                                                 }
556                                         break;
557                                         default:
558                                                 if ( preg_match( '/^status-changed/', $row['event'] ) ) {
559                                                         // Half of these used to be saved without the dash after 'status-changed'.
560                                                         // See https://plugins.trac.wordpress.org/changeset/1150658/akismet/trunk
561                                                         $new_status = preg_replace( '/^status-changed-?/', '', $row['event'] );
562                                                         $message = sprintf( __( 'Comment status was changed to %s', 'akismet' ), $new_status );
563                                                 }
564                                                 else if ( preg_match( '/^status-/', $row['event'] ) ) {
565                                                         $new_status = preg_replace( '/^status-/', '', $row['event'] );
566
567                                                         if ( isset( $row['user'] ) ) {
568                                                                 $message = sprintf( __( '%1$s changed the comment status to %2$s.', 'akismet' ), $row['user'], $new_status );
569                                                         }
570                                                 }
571                                         break;
572                                         
573                                 }
574
575                                 echo '<div style="margin-bottom: 13px;">';
576                                         echo '<span style="color: #999;" alt="' . $time . '" title="' . $time . '">' . sprintf( esc_html__('%s ago', 'akismet'), human_time_diff( $row['time'] ) ) . '</span>';
577                                         echo ' - ';
578                                         echo esc_html( $message );
579                                 echo '</div>';
580                         }
581
582                         echo '</div>';
583                 }
584         }
585
586         public static function plugin_action_links( $links, $file ) {
587                 if ( $file == plugin_basename( AKISMET__PLUGIN_URL . '/akismet.php' ) ) {
588                         $links[] = '<a href="' . esc_url( self::get_page_url() ) . '">'.esc_html__( 'Settings' , 'akismet').'</a>';
589                 }
590
591                 return $links;
592         }
593
594         // Total spam in queue
595         // get_option( 'akismet_spam_count' ) is the total caught ever
596         public static function get_spam_count( $type = false ) {
597                 global $wpdb;
598
599                 if ( !$type ) { // total
600                         $count = wp_cache_get( 'akismet_spam_count', 'widget' );
601                         if ( false === $count ) {
602                                 if ( function_exists('wp_count_comments') ) {
603                                         $count = wp_count_comments();
604                                         $count = $count->spam;
605                                 } else {
606                                         $count = (int) $wpdb->get_var("SELECT COUNT(comment_ID) FROM {$wpdb->comments} WHERE comment_approved = 'spam'");
607                                 }
608                                 wp_cache_set( 'akismet_spam_count', $count, 'widget', 3600 );
609                         }
610                         return $count;
611                 } elseif ( 'comments' == $type || 'comment' == $type ) { // comments
612                         $type = '';
613                 }
614
615                 return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(comment_ID) FROM {$wpdb->comments} WHERE comment_approved = 'spam' AND comment_type = %s", $type ) );
616         }
617
618         // Check connectivity between the WordPress blog and Akismet's servers.
619         // Returns an associative array of server IP addresses, where the key is the IP address, and value is true (available) or false (unable to connect).
620         public static function check_server_ip_connectivity() {
621                 
622                 $servers = $ips = array();
623
624                 // Some web hosts may disable this function
625                 if ( function_exists('gethostbynamel') ) {      
626                         
627                         $ips = gethostbynamel( 'rest.akismet.com' );
628                         if ( $ips && is_array($ips) && count($ips) ) {
629                                 $api_key = Akismet::get_api_key();
630                                 
631                                 foreach ( $ips as $ip ) {
632                                         $response = Akismet::verify_key( $api_key, $ip );
633                                         // even if the key is invalid, at least we know we have connectivity
634                                         if ( $response == 'valid' || $response == 'invalid' )
635                                                 $servers[$ip] = 'connected';
636                                         else
637                                                 $servers[$ip] = $response ? $response : 'unable to connect';
638                                 }
639                         }
640                 }
641                 
642                 return $servers;
643         }
644         
645         // Simpler connectivity check
646         public static function check_server_connectivity($cache_timeout = 86400) {
647                 
648                 $debug = array();
649                 $debug[ 'PHP_VERSION' ]         = PHP_VERSION;
650                 $debug[ 'WORDPRESS_VERSION' ]   = $GLOBALS['wp_version'];
651                 $debug[ 'AKISMET_VERSION' ]     = AKISMET_VERSION;
652                 $debug[ 'AKISMET__PLUGIN_DIR' ] = AKISMET__PLUGIN_DIR;
653                 $debug[ 'SITE_URL' ]            = site_url();
654                 $debug[ 'HOME_URL' ]            = home_url();
655                 
656                 $servers = get_option('akismet_available_servers');
657                 if ( (time() - get_option('akismet_connectivity_time') < $cache_timeout) && $servers !== false ) {
658                         $servers = self::check_server_ip_connectivity();
659                         update_option('akismet_available_servers', $servers);
660                         update_option('akismet_connectivity_time', time());
661                 }
662                         
663                 $response = wp_remote_get( 'http://rest.akismet.com/1.1/test' );
664                 
665                 $debug[ 'gethostbynamel' ]  = function_exists('gethostbynamel') ? 'exists' : 'not here';
666                 $debug[ 'Servers' ]         = $servers;
667                 $debug[ 'Test Connection' ] = $response;
668                 
669                 Akismet::log( $debug );
670                 
671                 if ( $response && 'connected' == wp_remote_retrieve_body( $response ) )
672                         return true;
673                 
674                 return false;
675         }
676
677         // Check the server connectivity and store the available servers in an option. 
678         public static function get_server_connectivity($cache_timeout = 86400) {
679                 return self::check_server_connectivity( $cache_timeout );
680         }
681
682         public static function get_number_spam_waiting() {
683                 global $wpdb;
684                 return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->commentmeta} WHERE meta_key = 'akismet_error'" );
685         }
686
687         public static function get_page_url( $page = 'config' ) {
688
689                 $args = array( 'page' => 'akismet-key-config' );
690
691                 if ( $page == 'stats' )
692                         $args = array( 'page' => 'akismet-key-config', 'view' => 'stats' );
693                 elseif ( $page == 'delete_key' )
694                         $args = array( 'page' => 'akismet-key-config', 'view' => 'start', 'action' => 'delete-key', '_wpnonce' => wp_create_nonce( self::NONCE ) );
695
696                 $url = add_query_arg( $args, class_exists( 'Jetpack' ) ? admin_url( 'admin.php' ) : admin_url( 'options-general.php' ) );
697
698                 return $url;
699         }
700         
701         public static function get_akismet_user( $api_key ) {
702                 $akismet_user = false;
703
704                 $subscription_verification = Akismet::http_post( Akismet::build_query( array( 'key' => $api_key, 'blog' => get_bloginfo( 'url' ) ) ), 'get-subscription' );
705
706                 if ( ! empty( $subscription_verification[1] ) ) {
707                         if ( 'invalid' !== $subscription_verification[1] ) {
708                                 $akismet_user = json_decode( $subscription_verification[1] );
709                         }
710                 }
711
712                 return $akismet_user;
713         }
714         
715         public static function get_stats( $api_key ) {
716                 $stat_totals = array();
717
718                 foreach( array( '6-months', 'all' ) as $interval ) {
719                         $response = Akismet::http_post( Akismet::build_query( array( 'blog' => get_bloginfo( 'url' ), 'key' => $api_key, 'from' => $interval ) ), 'get-stats' );
720
721                         if ( ! empty( $response[1] ) ) {
722                                 $stat_totals[$interval] = json_decode( $response[1] );
723                         }
724                 }
725
726                 return $stat_totals;
727         }
728         
729         public static function verify_wpcom_key( $api_key, $user_id, $extra = array() ) {
730                 $akismet_account = Akismet::http_post( Akismet::build_query( array_merge( array(
731                         'user_id'          => $user_id,
732                         'api_key'          => $api_key,
733                         'get_account_type' => 'true'
734                 ), $extra ) ), 'verify-wpcom-key' );
735
736                 if ( ! empty( $akismet_account[1] ) )
737                         $akismet_account = json_decode( $akismet_account[1] );
738
739                 Akismet::log( compact( 'akismet_account' ) );
740                 
741                 return $akismet_account;
742         }
743         
744         public static function connect_jetpack_user() {
745         
746                 if ( $jetpack_user = self::get_jetpack_user() ) {
747                         if ( isset( $jetpack_user['user_id'] ) && isset(  $jetpack_user['api_key'] ) ) {
748                                 $akismet_user = self::verify_wpcom_key( $jetpack_user['api_key'], $jetpack_user['user_id'], array( 'action' => 'connect_jetpack_user' ) );
749                                                         
750                                 if ( is_object( $akismet_user ) ) {
751                                         self::save_key( $akismet_user->api_key );
752                                         return in_array( $akismet_user->status, array( 'active', 'active-dunning', 'no-sub' ) );
753                                 }
754                         }
755                 }
756                 
757                 return false;
758         }
759
760         public static function display_alert() {
761                 Akismet::view( 'notice', array(
762                         'type' => 'alert',
763                         'code' => (int) get_option( 'akismet_alert_code' ),
764                         'msg'  => get_option( 'akismet_alert_msg' )
765                 ) );
766         }
767
768         public static function display_spam_check_warning() {
769                 Akismet::fix_scheduled_recheck();
770
771                 if ( wp_next_scheduled('akismet_schedule_cron_recheck') > time() && self::get_number_spam_waiting() > 0 ) {
772                         $link_text = apply_filters( 'akismet_spam_check_warning_link_text', sprintf( __( 'Please check your <a href="%s">Akismet configuration</a> and contact your web host if problems persist.', 'akismet'), esc_url( self::get_page_url() ) ) );
773                         Akismet::view( 'notice', array( 'type' => 'spam-check', 'link_text' => $link_text ) );
774                 }
775         }
776
777         public static function display_invalid_version() {
778                 Akismet::view( 'notice', array( 'type' => 'version' ) );
779         }
780
781         public static function display_api_key_warning() {
782                 Akismet::view( 'notice', array( 'type' => 'plugin' ) );
783         }
784
785         public static function display_page() {
786                 if ( !Akismet::get_api_key() || ( isset( $_GET['view'] ) && $_GET['view'] == 'start' ) )
787                         self::display_start_page();
788                 elseif ( isset( $_GET['view'] ) && $_GET['view'] == 'stats' )
789                         self::display_stats_page();
790                 else
791                         self::display_configuration_page();
792         }
793
794         public static function display_start_page() {
795                 if ( isset( $_GET['action'] ) ) {
796                         if ( $_GET['action'] == 'delete-key' ) {
797                                 if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], self::NONCE ) )
798                                         delete_option( 'wordpress_api_key' );
799                         }
800                 }
801
802                 if ( $api_key = Akismet::get_api_key() && ( empty( self::$notices['status'] ) || 'existing-key-invalid' != self::$notices['status'] ) ) {
803                         self::display_configuration_page();
804                         return;
805                 }
806                 
807                 //the user can choose to auto connect their API key by clicking a button on the akismet done page
808                 //if jetpack, get verified api key by using connected wpcom user id
809                 //if no jetpack, get verified api key by using an akismet token 
810                 
811                 $akismet_user = false;
812                 
813                 if ( isset( $_GET['token'] ) && preg_match('/^(\d+)-[0-9a-f]{20}$/', $_GET['token'] ) )
814                         $akismet_user = self::verify_wpcom_key( '', '', array( 'token' => $_GET['token'] ) );
815                 elseif ( $jetpack_user = self::get_jetpack_user() )
816                         $akismet_user = self::verify_wpcom_key( $jetpack_user['api_key'], $jetpack_user['user_id'] );
817                         
818                 if ( isset( $_GET['action'] ) ) {
819                         if ( $_GET['action'] == 'save-key' ) {
820                                 if ( is_object( $akismet_user ) ) {
821                                         self::save_key( $akismet_user->api_key );
822                                         self::display_notice();
823                                         self::display_configuration_page();
824                                         return;                         
825                                 }
826                         }
827                 }
828
829                 echo '<h2 class="ak-header">'.esc_html__('Akismet', 'akismet').'</h2>';
830
831                 self::display_status();
832
833                 Akismet::view( 'start', compact( 'akismet_user' ) );
834         }
835
836         public static function display_stats_page() {
837                 Akismet::view( 'stats' );
838         }
839
840         public static function display_configuration_page() {
841                 $api_key      = Akismet::get_api_key();
842                 $akismet_user = self::get_akismet_user( $api_key );
843                 
844                 if ( ! $akismet_user ) {
845                         // This could happen if the user's key became invalid after it was previously valid and successfully set up.
846                         self::$notices['status'] = 'existing-key-invalid';
847                         self::display_start_page();
848                         return;
849                 }
850
851                 $stat_totals  = self::get_stats( $api_key );
852
853                 // If unset, create the new strictness option using the old discard option to determine its default
854         if ( get_option( 'akismet_strictness' ) === false )
855                 add_option( 'akismet_strictness', (get_option('akismet_discard_month') === 'true' ? '1' : '0') );
856
857                 if ( empty( self::$notices ) ) {
858                         //show status
859                         if ( ! empty( $stat_totals['all'] ) && isset( $stat_totals['all']->time_saved ) && $akismet_user->status == 'active' && $akismet_user->account_type == 'free-api-key' ) {
860
861                                 $time_saved = false;
862
863                                 if ( $stat_totals['all']->time_saved > 1800 ) {
864                                         $total_in_minutes = round( $stat_totals['all']->time_saved / 60 );
865                                         $total_in_hours   = round( $total_in_minutes / 60 );
866                                         $total_in_days    = round( $total_in_hours / 8 );
867                                         $cleaning_up      = __( 'Cleaning up spam takes time.' , 'akismet');
868
869                                         if ( $total_in_days > 1 )
870                                                 $time_saved = $cleaning_up . ' ' . sprintf( __( 'Akismet has saved you %s days!' , 'akismet'), number_format_i18n( $total_in_days ) );
871                                         elseif ( $total_in_hours > 1 )
872                                                 $time_saved = $cleaning_up . ' ' . sprintf( __( 'Akismet has saved you %d hours!' , 'akismet'), $total_in_hours );
873                                         elseif ( $total_in_minutes >= 30 )
874                                                 $time_saved = $cleaning_up . ' ' . sprintf( __( 'Akismet has saved you %d minutes!' , 'akismet'), $total_in_minutes );
875                                 }
876
877                                 Akismet::view( 'notice', array( 'type' => 'active-notice', 'time_saved' => $time_saved ) );
878                         }
879                         
880                         if ( !empty( $akismet_user->limit_reached ) && in_array( $akismet_user->limit_reached, array( 'yellow', 'red' ) ) ) {
881                                 Akismet::view( 'notice', array( 'type' => 'limit-reached', 'level' => $akismet_user->limit_reached ) );
882                         }
883                 }
884                 
885                 if ( !isset( self::$notices['status'] ) && in_array( $akismet_user->status, array( 'cancelled', 'suspended', 'missing', 'no-sub' ) ) )  
886                         Akismet::view( 'notice', array( 'type' => $akismet_user->status ) );
887
888                 Akismet::log( compact( 'stat_totals', 'akismet_user' ) );
889                 Akismet::view( 'config', compact( 'api_key', 'akismet_user', 'stat_totals' ) );
890         }
891
892         public static function display_notice() {
893                 global $hook_suffix;
894
895                 if ( in_array( $hook_suffix, array( 'jetpack_page_akismet-key-config', 'settings_page_akismet-key-config', 'edit-comments.php' ) ) && (int) get_option( 'akismet_alert_code' ) > 0 ) {
896                         Akismet::verify_key( Akismet::get_api_key() ); //verify that the key is still in alert state
897                         
898                         if ( get_option( 'akismet_alert_code' ) > 0 )
899                                 self::display_alert();
900                 }
901                 elseif ( $hook_suffix == 'plugins.php' && !Akismet::get_api_key() ) {
902                         self::display_api_key_warning();
903                 }
904                 elseif ( $hook_suffix == 'edit-comments.php' && wp_next_scheduled( 'akismet_schedule_cron_recheck' ) ) {
905                         self::display_spam_check_warning();
906                 }
907                 elseif ( in_array( $hook_suffix, array( 'jetpack_page_akismet-key-config', 'settings_page_akismet-key-config' ) ) && Akismet::get_api_key() ) {
908                         self::display_status();
909                 }
910         }
911
912         public static function display_status() {
913                 $type = '';
914
915                 if ( !self::get_server_connectivity() )
916                         $type = 'servers-be-down';
917
918                 if ( !empty( $type ) )
919                         Akismet::view( 'notice', compact( 'type' ) );
920                 elseif ( !empty( self::$notices ) ) {
921                         foreach ( self::$notices as $type )
922                                 Akismet::view( 'notice', compact( 'type' ) );
923                 }
924         }
925
926         private static function get_jetpack_user() {
927                 if ( !class_exists('Jetpack') )
928                         return false;
929
930                 Jetpack::load_xml_rpc_client();
931                 $xml = new Jetpack_IXR_ClientMulticall( array( 'user_id' => get_current_user_id() ) );
932
933                 $xml->addCall( 'wpcom.getUserID' );
934                 $xml->addCall( 'akismet.getAPIKey' );
935                 $xml->query();
936
937                 Akismet::log( compact( 'xml' ) );
938
939                 if ( !$xml->isError() ) {
940                         $responses = $xml->getResponse();
941                         if ( count( $responses ) > 1 ) {
942                                 $api_key = array_shift( $responses[0] );
943                                 $user_id = (int) array_shift( $responses[1] );
944                                 return compact( 'api_key', 'user_id' );
945                         }
946                 }
947                 return false;
948         }
949         
950         /**
951          * Some commentmeta isn't useful in an export file. Suppress it (when supported).
952          *
953          * @param bool $exclude
954          * @param string $key The meta key
955          * @param object $meta The meta object
956          * @return bool Whether to exclude this meta entry from the export.
957          */
958         public static function exclude_commentmeta_from_export( $exclude, $key, $meta ) {
959                 if ( in_array( $key, array( 'akismet_as_submitted', 'akismet_rechecking', 'akismet_delayed_moderation_email' ) ) ) {
960                         return true;
961                 }
962                 
963                 return $exclude;
964         }
965 }