class.akismet.php 53 KB

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