class.akismet.php 53 KB

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