class.akismet.php 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  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. public static $limit_notices = array(
  7. 10501 => 'FIRST_MONTH_OVER_LIMIT',
  8. 10502 => 'SECOND_MONTH_OVER_LIMIT',
  9. 10504 => 'THIRD_MONTH_APPROACHING_LIMIT',
  10. 10508 => 'THIRD_MONTH_OVER_LIMIT',
  11. 10516 => 'FOUR_PLUS_MONTHS_OVER_LIMIT',
  12. );
  13. private static $last_comment = '';
  14. private static $initiated = false;
  15. private static $prevent_moderation_email_for_these_comments = array();
  16. private static $last_comment_result = null;
  17. 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' => '' );
  18. public static function init() {
  19. if ( ! self::$initiated ) {
  20. self::init_hooks();
  21. }
  22. }
  23. /**
  24. * Initializes WordPress hooks
  25. */
  26. private static function init_hooks() {
  27. self::$initiated = true;
  28. add_action( 'wp_insert_comment', array( 'Akismet', 'auto_check_update_meta' ), 10, 2 );
  29. add_filter( 'preprocess_comment', array( 'Akismet', 'auto_check_comment' ), 1 );
  30. add_filter( 'rest_pre_insert_comment', array( 'Akismet', 'rest_auto_check_comment' ), 1 );
  31. add_action( 'comment_form', array( 'Akismet', 'load_form_js' ) );
  32. add_action( 'do_shortcode_tag', array( 'Akismet', 'load_form_js_via_filter' ), 10, 4 );
  33. add_action( 'akismet_scheduled_delete', array( 'Akismet', 'delete_old_comments' ) );
  34. add_action( 'akismet_scheduled_delete', array( 'Akismet', 'delete_old_comments_meta' ) );
  35. add_action( 'akismet_scheduled_delete', array( 'Akismet', 'delete_orphaned_commentmeta' ) );
  36. add_action( 'akismet_schedule_cron_recheck', array( 'Akismet', 'cron_recheck' ) );
  37. add_action( 'comment_form', array( 'Akismet', 'add_comment_nonce' ), 1 );
  38. add_action( 'comment_form', array( 'Akismet', 'output_custom_form_fields' ) );
  39. add_filter( 'script_loader_tag', array( 'Akismet', 'set_form_js_async' ), 10, 3 );
  40. add_filter( 'comment_moderation_recipients', array( 'Akismet', 'disable_moderation_emails_if_unreachable' ), 1000, 2 );
  41. add_filter( 'pre_comment_approved', array( 'Akismet', 'last_comment_status' ), 10, 2 );
  42. add_action( 'transition_comment_status', array( 'Akismet', 'transition_comment_status' ), 10, 3 );
  43. // Run this early in the pingback call, before doing a remote fetch of the source uri
  44. add_action( 'xmlrpc_call', array( 'Akismet', 'pre_check_pingback' ) );
  45. // Jetpack compatibility
  46. add_filter( 'jetpack_options_whitelist', array( 'Akismet', 'add_to_jetpack_options_whitelist' ) );
  47. add_filter( 'jetpack_contact_form_html', array( 'Akismet', 'inject_custom_form_fields' ) );
  48. add_filter( 'jetpack_contact_form_akismet_values', array( 'Akismet', 'prepare_custom_form_values' ) );
  49. // Gravity Forms
  50. add_filter( 'gform_get_form_filter', array( 'Akismet', 'inject_custom_form_fields' ) );
  51. add_filter( 'gform_akismet_fields', array( 'Akismet', 'prepare_custom_form_values' ) );
  52. // Contact Form 7
  53. add_filter( 'wpcf7_form_elements', array( 'Akismet', 'append_custom_form_fields' ) );
  54. add_filter( 'wpcf7_akismet_parameters', array( 'Akismet', 'prepare_custom_form_values' ) );
  55. // Formidable Forms
  56. add_filter( 'frm_filter_final_form', array( 'Akismet', 'inject_custom_form_fields' ) );
  57. add_filter( 'frm_akismet_values', array( 'Akismet', 'prepare_custom_form_values' ) );
  58. // Fluent Forms
  59. /*
  60. * The Fluent Forms hook names were updated in version 5.0.0. The last version that supported
  61. * the original hook names was 4.3.25, and version 4.3.25 was tested up to WordPress version 6.1.
  62. *
  63. * The legacy hooks are fired before the new hooks. See
  64. * https://github.com/fluentform/fluentform/commit/cc45341afcae400f217470a7bbfb15efdd80454f
  65. *
  66. * The legacy Fluent Forms hooks will be removed when Akismet no longer supports WordPress version 6.1.
  67. * This will provide compatibility with previous versions of Fluent Forms for a reasonable amount of time.
  68. */
  69. add_filter( 'fluentform_form_element_start', array( 'Akismet', 'output_custom_form_fields' ) );
  70. add_filter( 'fluentform_akismet_fields', array( 'Akismet', 'prepare_custom_form_values' ), 10, 2 );
  71. // Current Fluent Form hooks.
  72. add_filter( 'fluentform/form_element_start', array( 'Akismet', 'output_custom_form_fields' ) );
  73. add_filter( 'fluentform/akismet_fields', array( 'Akismet', 'prepare_custom_form_values' ), 10, 2 );
  74. add_action( 'update_option_wordpress_api_key', array( 'Akismet', 'updated_option' ), 10, 2 );
  75. add_action( 'add_option_wordpress_api_key', array( 'Akismet', 'added_option' ), 10, 2 );
  76. add_action( 'comment_form_after', array( 'Akismet', 'display_comment_form_privacy_notice' ) );
  77. }
  78. public static function get_api_key() {
  79. return apply_filters( 'akismet_get_api_key', defined('WPCOM_API_KEY') ? constant('WPCOM_API_KEY') : get_option('wordpress_api_key') );
  80. }
  81. /**
  82. * Exchange the API key for a token that can only be used to access stats pages.
  83. *
  84. * @return string
  85. */
  86. public static function get_access_token() {
  87. static $access_token = null;
  88. if ( is_null( $access_token ) ) {
  89. $request_args = array( 'api_key' => self::get_api_key() );
  90. $request_args = apply_filters( 'akismet_request_args', $request_args, 'token' );
  91. $response = self::http_post( self::build_query( $request_args ), 'token' );
  92. $access_token = $response[1];
  93. }
  94. return $access_token;
  95. }
  96. public static function check_key_status( $key, $ip = null ) {
  97. $request_args = array(
  98. 'key' => $key,
  99. 'blog' => get_option( 'home' ),
  100. );
  101. $request_args = apply_filters( 'akismet_request_args', $request_args, 'verify-key' );
  102. return self::http_post( self::build_query( $request_args ), 'verify-key', $ip );
  103. }
  104. public static function verify_key( $key, $ip = null ) {
  105. // Shortcut for obviously invalid keys.
  106. if ( strlen( $key ) != 12 ) {
  107. return 'invalid';
  108. }
  109. $response = self::check_key_status( $key, $ip );
  110. if ( $response[1] != 'valid' && $response[1] != 'invalid' )
  111. return 'failed';
  112. return $response[1];
  113. }
  114. public static function deactivate_key( $key ) {
  115. $request_args = array(
  116. 'key' => $key,
  117. 'blog' => get_option( 'home' ),
  118. );
  119. $request_args = apply_filters( 'akismet_request_args', $request_args, 'deactivate' );
  120. $response = self::http_post( self::build_query( $request_args ), 'deactivate' );
  121. if ( $response[1] != 'deactivated' )
  122. return 'failed';
  123. return $response[1];
  124. }
  125. /**
  126. * Add the akismet option to the Jetpack options management whitelist.
  127. *
  128. * @param array $options The list of whitelisted option names.
  129. * @return array The updated whitelist
  130. */
  131. public static function add_to_jetpack_options_whitelist( $options ) {
  132. $options[] = 'wordpress_api_key';
  133. return $options;
  134. }
  135. /**
  136. * When the akismet option is updated, run the registration call.
  137. *
  138. * This should only be run when the option is updated from the Jetpack/WP.com
  139. * API call, and only if the new key is different than the old key.
  140. *
  141. * @param mixed $old_value The old option value.
  142. * @param mixed $value The new option value.
  143. */
  144. public static function updated_option( $old_value, $value ) {
  145. // Not an API call
  146. if ( ! class_exists( 'WPCOM_JSON_API_Update_Option_Endpoint' ) ) {
  147. return;
  148. }
  149. // Only run the registration if the old key is different.
  150. if ( $old_value !== $value ) {
  151. self::verify_key( $value );
  152. }
  153. }
  154. /**
  155. * Treat the creation of an API key the same as updating the API key to a new value.
  156. *
  157. * @param mixed $option_name Will always be "wordpress_api_key", until something else hooks in here.
  158. * @param mixed $value The option value.
  159. */
  160. public static function added_option( $option_name, $value ) {
  161. if ( 'wordpress_api_key' === $option_name ) {
  162. return self::updated_option( '', $value );
  163. }
  164. }
  165. public static function rest_auto_check_comment( $commentdata ) {
  166. return self::auto_check_comment( $commentdata, 'rest_api' );
  167. }
  168. /**
  169. * Check a comment for spam.
  170. *
  171. * @param array $commentdata
  172. * @param string $context What kind of request triggered this comment check? Possible values are 'default', 'rest_api', and 'xml-rpc'.
  173. * @return array|WP_Error Either the $commentdata array with additional entries related to its spam status
  174. * or a WP_Error, if it's a REST API request and the comment should be discarded.
  175. */
  176. public static function auto_check_comment( $commentdata, $context = 'default' ) {
  177. // If no key is configured, then there's no point in doing any of this.
  178. if ( ! self::get_api_key() ) {
  179. return $commentdata;
  180. }
  181. self::$last_comment_result = null;
  182. $comment = $commentdata;
  183. $comment['user_ip'] = self::get_ip_address();
  184. $comment['user_agent'] = self::get_user_agent();
  185. $comment['referrer'] = self::get_referer();
  186. $comment['blog'] = get_option( 'home' );
  187. $comment['blog_lang'] = get_locale();
  188. $comment['blog_charset'] = get_option('blog_charset');
  189. $comment['permalink'] = get_permalink( $comment['comment_post_ID'] );
  190. if ( ! empty( $comment['user_ID'] ) ) {
  191. $comment['user_role'] = Akismet::get_user_roles( $comment['user_ID'] );
  192. }
  193. /** See filter documentation in init_hooks(). */
  194. $akismet_nonce_option = apply_filters( 'akismet_comment_nonce', get_option( 'akismet_comment_nonce' ) );
  195. $comment['akismet_comment_nonce'] = 'inactive';
  196. if ( $akismet_nonce_option == 'true' || $akismet_nonce_option == '' ) {
  197. $comment['akismet_comment_nonce'] = 'failed';
  198. if ( isset( $_POST['akismet_comment_nonce'] ) && wp_verify_nonce( $_POST['akismet_comment_nonce'], 'akismet_comment_nonce_' . $comment['comment_post_ID'] ) )
  199. $comment['akismet_comment_nonce'] = 'passed';
  200. // comment reply in wp-admin
  201. if ( isset( $_POST['_ajax_nonce-replyto-comment'] ) && check_ajax_referer( 'replyto-comment', '_ajax_nonce-replyto-comment' ) )
  202. $comment['akismet_comment_nonce'] = 'passed';
  203. }
  204. if ( self::is_test_mode() )
  205. $comment['is_test'] = 'true';
  206. foreach( $_POST as $key => $value ) {
  207. if ( is_string( $value ) )
  208. $comment["POST_{$key}"] = $value;
  209. }
  210. foreach ( $_SERVER as $key => $value ) {
  211. if ( ! is_string( $value ) ) {
  212. continue;
  213. }
  214. if ( preg_match( "/^HTTP_COOKIE/", $key ) ) {
  215. continue;
  216. }
  217. // Send any potentially useful $_SERVER vars, but avoid sending junk we don't need.
  218. if ( preg_match( "/^(HTTP_|REMOTE_ADDR|REQUEST_URI|DOCUMENT_URI)/", $key ) ) {
  219. $comment[ "$key" ] = $value;
  220. }
  221. }
  222. $post = get_post( $comment['comment_post_ID'] );
  223. if ( ! is_null( $post ) ) {
  224. // $post can technically be null, although in the past, it's always been an indicator of another plugin interfering.
  225. $comment[ 'comment_post_modified_gmt' ] = $post->post_modified_gmt;
  226. // Tags and categories are important context in which to consider the comment.
  227. $comment['comment_context'] = array();
  228. $tag_names = wp_get_post_tags( $post->ID, array( 'fields' => 'names' ) );
  229. if ( $tag_names && ! is_wp_error( $tag_names ) ) {
  230. foreach ( $tag_names as $tag_name ) {
  231. $comment['comment_context'][] = $tag_name;
  232. }
  233. }
  234. $category_names = wp_get_post_categories( $post->ID, array( 'fields' => 'names' ) );
  235. if ( $category_names && ! is_wp_error( $category_names ) ) {
  236. foreach ( $category_names as $category_name ) {
  237. $comment['comment_context'][] = $category_name;
  238. }
  239. }
  240. }
  241. /**
  242. * Filter the data that is used to generate the request body for the API call.
  243. *
  244. * @since 5.3.1
  245. *
  246. * @param array $comment An array of request data.
  247. * @param string $endpoint The API endpoint being requested.
  248. */
  249. $comment = apply_filters( 'akismet_request_args', $comment, 'comment-check' );
  250. $response = self::http_post( self::build_query( $comment ), 'comment-check' );
  251. do_action( 'akismet_comment_check_response', $response );
  252. $commentdata['comment_as_submitted'] = array_intersect_key( $comment, self::$comment_as_submitted_allowed_keys );
  253. // Also include any form fields we inject into the comment form, like ak_js
  254. foreach ( $_POST as $key => $value ) {
  255. if ( is_string( $value ) && strpos( $key, 'ak_' ) === 0 ) {
  256. $commentdata['comment_as_submitted'][ 'POST_' . $key ] = $value;
  257. }
  258. }
  259. $commentdata['akismet_result'] = $response[1];
  260. if ( isset( $response[0]['x-akismet-pro-tip'] ) )
  261. $commentdata['akismet_pro_tip'] = $response[0]['x-akismet-pro-tip'];
  262. if ( isset( $response[0]['x-akismet-guid'] ) ) {
  263. $commentdata['akismet_guid'] = $response[0]['x-akismet-guid'];
  264. }
  265. if ( isset( $response[0]['x-akismet-error'] ) ) {
  266. // An error occurred that we anticipated (like a suspended key) and want the user to act on.
  267. // Send to moderation.
  268. self::$last_comment_result = '0';
  269. }
  270. else if ( 'true' == $response[1] ) {
  271. // akismet_spam_count will be incremented later by comment_is_spam()
  272. self::$last_comment_result = 'spam';
  273. $discard = ( isset( $commentdata['akismet_pro_tip'] ) && $commentdata['akismet_pro_tip'] === 'discard' && self::allow_discard() );
  274. do_action( 'akismet_spam_caught', $discard );
  275. if ( $discard ) {
  276. // The spam is obvious, so we're bailing out early.
  277. // akismet_result_spam() won't be called so bump the counter here
  278. if ( $incr = apply_filters( 'akismet_spam_count_incr', 1 ) ) {
  279. update_option( 'akismet_spam_count', get_option( 'akismet_spam_count' ) + $incr );
  280. }
  281. if ( 'rest_api' === $context ) {
  282. return new WP_Error( 'akismet_rest_comment_discarded', __( 'Comment discarded.', 'akismet' ) );
  283. } else if ( 'xml-rpc' === $context ) {
  284. // If this is a pingback that we're pre-checking, the discard behavior is the same as the normal spam response behavior.
  285. return $commentdata;
  286. } else {
  287. // Redirect back to the previous page, or failing that, the post permalink, or failing that, the homepage of the blog.
  288. $redirect_to = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : ( $post ? get_permalink( $post ) : home_url() );
  289. wp_safe_redirect( esc_url_raw( $redirect_to ) );
  290. die();
  291. }
  292. }
  293. else if ( 'rest_api' === $context ) {
  294. // The way the REST API structures its calls, we can set the comment_approved value right away.
  295. $commentdata['comment_approved'] = 'spam';
  296. }
  297. }
  298. // if the response is neither true nor false, hold the comment for moderation and schedule a recheck
  299. if ( 'true' != $response[1] && 'false' != $response[1] ) {
  300. if ( !current_user_can('moderate_comments') ) {
  301. // Comment status should be moderated
  302. self::$last_comment_result = '0';
  303. }
  304. if ( ! wp_next_scheduled( 'akismet_schedule_cron_recheck' ) ) {
  305. wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
  306. do_action( 'akismet_scheduled_recheck', 'invalid-response-' . $response[1] );
  307. }
  308. self::$prevent_moderation_email_for_these_comments[] = $commentdata;
  309. }
  310. // Delete old comments daily
  311. if ( ! wp_next_scheduled( 'akismet_scheduled_delete' ) ) {
  312. wp_schedule_event( time(), 'daily', 'akismet_scheduled_delete' );
  313. }
  314. self::set_last_comment( $commentdata );
  315. self::fix_scheduled_recheck();
  316. return $commentdata;
  317. }
  318. public static function get_last_comment() {
  319. return self::$last_comment;
  320. }
  321. public static function set_last_comment( $comment ) {
  322. if ( is_null( $comment ) ) {
  323. self::$last_comment = null;
  324. }
  325. else {
  326. // We filter it here so that it matches the filtered comment data that we'll have to compare against later.
  327. // wp_filter_comment expects comment_author_IP
  328. self::$last_comment = wp_filter_comment(
  329. array_merge(
  330. array( 'comment_author_IP' => self::get_ip_address() ),
  331. $comment
  332. )
  333. );
  334. }
  335. }
  336. // this fires on wp_insert_comment. we can't update comment_meta when auto_check_comment() runs
  337. // because we don't know the comment ID at that point.
  338. public static function auto_check_update_meta( $id, $comment ) {
  339. // wp_insert_comment() might be called in other contexts, so make sure this is the same comment
  340. // as was checked by auto_check_comment
  341. if ( is_object( $comment ) && !empty( self::$last_comment ) && is_array( self::$last_comment ) ) {
  342. if ( self::matches_last_comment( $comment ) ) {
  343. load_plugin_textdomain( 'akismet' );
  344. // normal result: true or false
  345. if ( self::$last_comment['akismet_result'] == 'true' ) {
  346. update_comment_meta( $comment->comment_ID, 'akismet_result', 'true' );
  347. self::update_comment_history( $comment->comment_ID, '', 'check-spam' );
  348. if ( $comment->comment_approved != 'spam' ) {
  349. self::update_comment_history(
  350. $comment->comment_ID,
  351. '',
  352. 'status-changed-' . $comment->comment_approved
  353. );
  354. }
  355. } elseif ( self::$last_comment['akismet_result'] == 'false' ) {
  356. update_comment_meta( $comment->comment_ID, 'akismet_result', 'false' );
  357. self::update_comment_history( $comment->comment_ID, '', 'check-ham' );
  358. // Status could be spam or trash, depending on the WP version and whether this change applies:
  359. // https://core.trac.wordpress.org/changeset/34726
  360. if ( $comment->comment_approved == 'spam' || $comment->comment_approved == 'trash' ) {
  361. if ( function_exists( 'wp_check_comment_disallowed_list' ) ) {
  362. if ( wp_check_comment_disallowed_list( $comment->comment_author, $comment->comment_author_email, $comment->comment_author_url, $comment->comment_content, $comment->comment_author_IP, $comment->comment_agent ) ) {
  363. self::update_comment_history( $comment->comment_ID, '', 'wp-disallowed' );
  364. } else {
  365. self::update_comment_history( $comment->comment_ID, '', 'status-changed-' . $comment->comment_approved );
  366. }
  367. } else if ( function_exists( 'wp_blacklist_check' ) && wp_blacklist_check( $comment->comment_author, $comment->comment_author_email, $comment->comment_author_url, $comment->comment_content, $comment->comment_author_IP, $comment->comment_agent ) ) {
  368. self::update_comment_history( $comment->comment_ID, '', 'wp-blacklisted' );
  369. } else {
  370. self::update_comment_history( $comment->comment_ID, '', 'status-changed-' . $comment->comment_approved );
  371. }
  372. }
  373. } else {
  374. // abnormal result: error
  375. update_comment_meta( $comment->comment_ID, 'akismet_error', time() );
  376. self::update_comment_history(
  377. $comment->comment_ID,
  378. '',
  379. 'check-error',
  380. array( 'response' => substr( self::$last_comment['akismet_result'], 0, 50 ) )
  381. );
  382. }
  383. // record the complete original data as submitted for checking
  384. if ( isset( self::$last_comment['comment_as_submitted'] ) ) {
  385. update_comment_meta( $comment->comment_ID, 'akismet_as_submitted', self::$last_comment['comment_as_submitted'] );
  386. }
  387. if ( isset( self::$last_comment['akismet_pro_tip'] ) ) {
  388. update_comment_meta( $comment->comment_ID, 'akismet_pro_tip', self::$last_comment['akismet_pro_tip'] );
  389. }
  390. if ( isset( self::$last_comment['akismet_guid'] ) ) {
  391. update_comment_meta( $comment->comment_ID, 'akismet_guid', self::$last_comment['akismet_guid'] );
  392. }
  393. }
  394. }
  395. }
  396. public static function delete_old_comments() {
  397. global $wpdb;
  398. /**
  399. * Determines how many comments will be deleted in each batch.
  400. *
  401. * @param int The default, as defined by AKISMET_DELETE_LIMIT.
  402. */
  403. $delete_limit = apply_filters( 'akismet_delete_comment_limit', defined( 'AKISMET_DELETE_LIMIT' ) ? AKISMET_DELETE_LIMIT : 10000 );
  404. $delete_limit = max( 1, intval( $delete_limit ) );
  405. /**
  406. * Determines how many days a comment will be left in the Spam queue before being deleted.
  407. *
  408. * @param int The default number of days.
  409. */
  410. $delete_interval = apply_filters( 'akismet_delete_comment_interval', 15 );
  411. $delete_interval = max( 1, intval( $delete_interval ) );
  412. 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 ) ) ) {
  413. if ( empty( $comment_ids ) )
  414. return;
  415. $wpdb->queries = array();
  416. $comments = array();
  417. foreach ( $comment_ids as $comment_id ) {
  418. $comments[ $comment_id ] = get_comment( $comment_id );
  419. do_action( 'delete_comment', $comment_id, $comments[ $comment_id ] );
  420. do_action( 'akismet_batch_delete_count', __FUNCTION__ );
  421. }
  422. // Prepared as strings since comment_id is an unsigned BIGINT, and using %d will constrain the value to the maximum signed BIGINT.
  423. $format_string = implode( ', ', array_fill( 0, is_countable( $comment_ids ) ? count( $comment_ids ) : 0, '%s' ) );
  424. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->comments} WHERE comment_id IN ( " . $format_string . " )", $comment_ids ) );
  425. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->commentmeta} WHERE comment_id IN ( " . $format_string . " )", $comment_ids ) );
  426. foreach ( $comment_ids as $comment_id ) {
  427. do_action( 'deleted_comment', $comment_id, $comments[ $comment_id ] );
  428. unset( $comments[ $comment_id ] );
  429. }
  430. clean_comment_cache( $comment_ids );
  431. do_action( 'akismet_delete_comment_batch', is_countable( $comment_ids ) ? count( $comment_ids ) : 0 );
  432. }
  433. if ( apply_filters( 'akismet_optimize_table', ( mt_rand(1, 5000) == 11), $wpdb->comments ) ) // lucky number
  434. $wpdb->query("OPTIMIZE TABLE {$wpdb->comments}");
  435. }
  436. public static function delete_old_comments_meta() {
  437. global $wpdb;
  438. $interval = apply_filters( 'akismet_delete_commentmeta_interval', 15 );
  439. # enforce a minimum of 1 day
  440. $interval = absint( $interval );
  441. if ( $interval < 1 )
  442. $interval = 1;
  443. // akismet_as_submitted meta values are large, so expire them
  444. // after $interval days regardless of the comment status
  445. 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 ) ) ) {
  446. if ( empty( $comment_ids ) )
  447. return;
  448. $wpdb->queries = array();
  449. foreach ( $comment_ids as $comment_id ) {
  450. delete_comment_meta( $comment_id, 'akismet_as_submitted' );
  451. do_action( 'akismet_batch_delete_count', __FUNCTION__ );
  452. }
  453. do_action( 'akismet_delete_commentmeta_batch', is_countable( $comment_ids ) ? count( $comment_ids ) : 0 );
  454. }
  455. if ( apply_filters( 'akismet_optimize_table', ( mt_rand(1, 5000) == 11), $wpdb->commentmeta ) ) // lucky number
  456. $wpdb->query("OPTIMIZE TABLE {$wpdb->commentmeta}");
  457. }
  458. // Clear out comments meta that no longer have corresponding comments in the database
  459. public static function delete_orphaned_commentmeta() {
  460. global $wpdb;
  461. $last_meta_id = 0;
  462. $start_time = isset( $_SERVER['REQUEST_TIME_FLOAT'] ) ? $_SERVER['REQUEST_TIME_FLOAT'] : microtime( true );
  463. $max_exec_time = max( ini_get('max_execution_time') - 5, 3 );
  464. 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 ) ) ) {
  465. if ( empty( $commentmeta_results ) )
  466. return;
  467. $wpdb->queries = array();
  468. $commentmeta_deleted = 0;
  469. foreach ( $commentmeta_results as $commentmeta ) {
  470. if ( 'akismet_' == substr( $commentmeta->meta_key, 0, 8 ) ) {
  471. delete_comment_meta( $commentmeta->comment_id, $commentmeta->meta_key );
  472. do_action( 'akismet_batch_delete_count', __FUNCTION__ );
  473. $commentmeta_deleted++;
  474. }
  475. $last_meta_id = $commentmeta->meta_id;
  476. }
  477. do_action( 'akismet_delete_commentmeta_batch', $commentmeta_deleted );
  478. // If we're getting close to max_execution_time, quit for this round.
  479. if ( microtime(true) - $start_time > $max_exec_time )
  480. return;
  481. }
  482. if ( apply_filters( 'akismet_optimize_table', ( mt_rand(1, 5000) == 11), $wpdb->commentmeta ) ) // lucky number
  483. $wpdb->query("OPTIMIZE TABLE {$wpdb->commentmeta}");
  484. }
  485. // how many approved comments does this author have?
  486. public static function get_user_comments_approved( $user_id, $comment_author_email, $comment_author, $comment_author_url ) {
  487. global $wpdb;
  488. /**
  489. * Which comment types should be ignored when counting a user's approved comments?
  490. *
  491. * Some plugins add entries to the comments table that are not actual
  492. * comments that could have been checked by Akismet. Allow these comments
  493. * to be excluded from the "approved comment count" query in order to
  494. * avoid artificially inflating the approved comment count.
  495. *
  496. * @param array $comment_types An array of comment types that won't be considered
  497. * when counting a user's approved comments.
  498. *
  499. * @since 4.2.2
  500. */
  501. $excluded_comment_types = apply_filters( 'akismet_excluded_comment_types', array() );
  502. $comment_type_where = '';
  503. if ( is_array( $excluded_comment_types ) && ! empty( $excluded_comment_types ) ) {
  504. $excluded_comment_types = array_unique( $excluded_comment_types );
  505. foreach ( $excluded_comment_types as $excluded_comment_type ) {
  506. $comment_type_where .= $wpdb->prepare( ' AND comment_type <> %s ', $excluded_comment_type );
  507. }
  508. }
  509. if ( ! empty( $user_id ) ) {
  510. return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->comments} WHERE user_id = %d AND comment_approved = 1" . $comment_type_where, $user_id ) );
  511. }
  512. if ( ! empty( $comment_author_email ) ) {
  513. 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_type_where, $comment_author_email, $comment_author, $comment_author_url ) );
  514. }
  515. return 0;
  516. }
  517. // get the full comment history for a given comment, as an array in reverse chronological order
  518. public static function get_comment_history( $comment_id ) {
  519. $history = get_comment_meta( $comment_id, 'akismet_history', false );
  520. if ( empty( $history ) || empty( $history[ 0 ] ) ) {
  521. return false;
  522. }
  523. /*
  524. // To see all variants when testing.
  525. $history[] = array( 'time' => 445856401, 'message' => 'Old versions of Akismet stored the message as a literal string in the commentmeta.', 'event' => null );
  526. $history[] = array( 'time' => 445856402, 'event' => 'recheck-spam' );
  527. $history[] = array( 'time' => 445856403, 'event' => 'check-spam' );
  528. $history[] = array( 'time' => 445856404, 'event' => 'recheck-ham' );
  529. $history[] = array( 'time' => 445856405, 'event' => 'check-ham' );
  530. $history[] = array( 'time' => 445856406, 'event' => 'wp-blacklisted' );
  531. $history[] = array( 'time' => 445856406, 'event' => 'wp-disallowed' );
  532. $history[] = array( 'time' => 445856407, 'event' => 'report-spam' );
  533. $history[] = array( 'time' => 445856408, 'event' => 'report-spam', 'user' => 'sam' );
  534. $history[] = array( 'message' => 'sam reported this comment as spam (hardcoded message).', 'time' => 445856400, 'event' => 'report-spam', 'user' => 'sam' );
  535. $history[] = array( 'time' => 445856409, 'event' => 'report-ham', 'user' => 'sam' );
  536. $history[] = array( 'message' => 'sam reported this comment as ham (hardcoded message).', 'time' => 445856400, 'event' => 'report-ham', 'user' => 'sam' ); //
  537. $history[] = array( 'time' => 445856410, 'event' => 'cron-retry-spam' );
  538. $history[] = array( 'time' => 445856411, 'event' => 'cron-retry-ham' );
  539. $history[] = array( 'time' => 445856412, 'event' => 'check-error' ); //
  540. $history[] = array( 'time' => 445856413, 'event' => 'check-error', 'meta' => array( 'response' => 'The server was taking a nap.' ) );
  541. $history[] = array( 'time' => 445856414, 'event' => 'recheck-error' ); // Should not generate a message.
  542. $history[] = array( 'time' => 445856415, 'event' => 'recheck-error', 'meta' => array( 'response' => 'The server was taking a nap.' ) );
  543. $history[] = array( 'time' => 445856416, 'event' => 'status-changedtrash' );
  544. $history[] = array( 'time' => 445856417, 'event' => 'status-changedspam' );
  545. $history[] = array( 'time' => 445856418, 'event' => 'status-changedhold' );
  546. $history[] = array( 'time' => 445856419, 'event' => 'status-changedapprove' );
  547. $history[] = array( 'time' => 445856420, 'event' => 'status-changed-trash' );
  548. $history[] = array( 'time' => 445856421, 'event' => 'status-changed-spam' );
  549. $history[] = array( 'time' => 445856422, 'event' => 'status-changed-hold' );
  550. $history[] = array( 'time' => 445856423, 'event' => 'status-changed-approve' );
  551. $history[] = array( 'time' => 445856424, 'event' => 'status-trash', 'user' => 'sam' );
  552. $history[] = array( 'time' => 445856425, 'event' => 'status-spam', 'user' => 'sam' );
  553. $history[] = array( 'time' => 445856426, 'event' => 'status-hold', 'user' => 'sam' );
  554. $history[] = array( 'time' => 445856427, 'event' => 'status-approve', 'user' => 'sam' );
  555. */
  556. usort( $history, array( 'Akismet', '_cmp_time' ) );
  557. return $history;
  558. }
  559. /**
  560. * Log an event for a given comment, storing it in comment_meta.
  561. *
  562. * @param int $comment_id The ID of the relevant comment.
  563. * @param string $message The string description of the event. No longer used.
  564. * @param string $event The event code.
  565. * @param array $meta Metadata about the history entry. e.g., the user that reported or changed the status of a given comment.
  566. */
  567. public static function update_comment_history( $comment_id, $message, $event=null, $meta=null ) {
  568. global $current_user;
  569. $user = '';
  570. $event = array(
  571. 'time' => self::_get_microtime(),
  572. 'event' => $event,
  573. );
  574. if ( is_object( $current_user ) && isset( $current_user->user_login ) ) {
  575. $event['user'] = $current_user->user_login;
  576. }
  577. if ( ! empty( $meta ) ) {
  578. $event['meta'] = $meta;
  579. }
  580. // $unique = false so as to allow multiple values per comment
  581. $r = add_comment_meta( $comment_id, 'akismet_history', $event, false );
  582. }
  583. public static function check_db_comment( $id, $recheck_reason = 'recheck_queue' ) {
  584. global $wpdb;
  585. if ( ! self::get_api_key() ) {
  586. return new WP_Error( 'akismet-not-configured', __( 'Akismet is not configured. Please enter an API key.', 'akismet' ) );
  587. }
  588. $c = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $id ), ARRAY_A );
  589. if ( ! $c ) {
  590. return new WP_Error( 'invalid-comment-id', __( 'Comment not found.', 'akismet' ) );
  591. }
  592. $c['user_ip'] = $c['comment_author_IP'];
  593. $c['user_agent'] = $c['comment_agent'];
  594. $c['referrer'] = '';
  595. $c['blog'] = get_option( 'home' );
  596. $c['blog_lang'] = get_locale();
  597. $c['blog_charset'] = get_option('blog_charset');
  598. $c['permalink'] = get_permalink($c['comment_post_ID']);
  599. $c['recheck_reason'] = $recheck_reason;
  600. $c['user_role'] = '';
  601. if ( ! empty( $c['user_ID'] ) ) {
  602. $c['user_role'] = Akismet::get_user_roles( $c['user_ID'] );
  603. }
  604. if ( self::is_test_mode() )
  605. $c['is_test'] = 'true';
  606. $c = apply_filters( 'akismet_request_args', $c, 'comment-check' );
  607. $response = self::http_post( self::build_query( $c ), 'comment-check' );
  608. if ( ! empty( $response[1] ) ) {
  609. return $response[1];
  610. }
  611. return false;
  612. }
  613. public static function recheck_comment( $id, $recheck_reason = 'recheck_queue' ) {
  614. add_comment_meta( $id, 'akismet_rechecking', true );
  615. $api_response = self::check_db_comment( $id, $recheck_reason );
  616. if ( is_wp_error( $api_response ) ) {
  617. // Invalid comment ID.
  618. }
  619. else if ( 'true' === $api_response ) {
  620. wp_set_comment_status( $id, 'spam' );
  621. update_comment_meta( $id, 'akismet_result', 'true' );
  622. delete_comment_meta( $id, 'akismet_error' );
  623. delete_comment_meta( $id, 'akismet_delayed_moderation_email' );
  624. Akismet::update_comment_history( $id, '', 'recheck-spam' );
  625. }
  626. elseif ( 'false' === $api_response ) {
  627. update_comment_meta( $id, 'akismet_result', 'false' );
  628. delete_comment_meta( $id, 'akismet_error' );
  629. delete_comment_meta( $id, 'akismet_delayed_moderation_email' );
  630. Akismet::update_comment_history( $id, '', 'recheck-ham' );
  631. }
  632. else {
  633. // abnormal result: error
  634. update_comment_meta( $id, 'akismet_result', 'error' );
  635. Akismet::update_comment_history(
  636. $id,
  637. '',
  638. 'recheck-error',
  639. array( 'response' => substr( $api_response, 0, 50 ) )
  640. );
  641. }
  642. delete_comment_meta( $id, 'akismet_rechecking' );
  643. return $api_response;
  644. }
  645. public static function transition_comment_status( $new_status, $old_status, $comment ) {
  646. if ( $new_status == $old_status )
  647. return;
  648. if ( 'spam' === $new_status || 'spam' === $old_status ) {
  649. // Clear the cache of the "X comments in your spam queue" count on the dashboard.
  650. wp_cache_delete( 'akismet_spam_count', 'widget' );
  651. }
  652. # we don't need to record a history item for deleted comments
  653. if ( $new_status == 'delete' )
  654. return;
  655. if ( !current_user_can( 'edit_post', $comment->comment_post_ID ) && !current_user_can( 'moderate_comments' ) )
  656. return;
  657. if ( defined('WP_IMPORTING') && WP_IMPORTING == true )
  658. return;
  659. // if this is present, it means the status has been changed by a re-check, not an explicit user action
  660. if ( get_comment_meta( $comment->comment_ID, 'akismet_rechecking' ) )
  661. return;
  662. // Assumption alert:
  663. // We want to submit comments to Akismet only when a moderator explicitly spams or approves it - not if the status
  664. // is changed automatically by another plugin. Unfortunately WordPress doesn't provide an unambiguous way to
  665. // determine why the transition_comment_status action was triggered. And there are several different ways by which
  666. // to spam and unspam comments: bulk actions, ajax, links in moderation emails, the dashboard, and perhaps others.
  667. // We'll assume that this is an explicit user action if certain POST/GET variables exist.
  668. if (
  669. // status=spam: Marking as spam via the REST API or...
  670. // 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?...
  671. // status=approved: Unspamming via the REST API (Calypso) or...
  672. ( isset( $_POST['status'] ) && in_array( $_POST['status'], array( 'spam', 'unspam', 'approved', ) ) )
  673. // spam=1: Clicking "Spam" underneath a comment in wp-admin and allowing the AJAX request to happen.
  674. || ( isset( $_POST['spam'] ) && (int) $_POST['spam'] == 1 )
  675. // 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.
  676. || ( isset( $_POST['unspam'] ) && (int) $_POST['unspam'] == 1 )
  677. // comment_status=spam/unspam: It's unclear where this is happening.
  678. || ( isset( $_POST['comment_status'] ) && in_array( $_POST['comment_status'], array( 'spam', 'unspam' ) ) )
  679. // action=spam: Choosing "Mark as Spam" from the Bulk Actions dropdown in wp-admin (or the "Spam it" link in notification emails).
  680. // action=unspam: Choosing "Not Spam" from the Bulk Actions dropdown in wp-admin.
  681. // action=spamcomment: Following the "Spam" link below a comment in wp-admin (not allowing AJAX request to happen).
  682. // action=unspamcomment: Following the "Not Spam" link below a comment in wp-admin (not allowing AJAX request to happen).
  683. || ( isset( $_GET['action'] ) && in_array( $_GET['action'], array( 'spam', 'unspam', 'spamcomment', 'unspamcomment', ) ) )
  684. // action=editedcomment: Editing a comment via wp-admin (and possibly changing its status).
  685. || ( isset( $_POST['action'] ) && in_array( $_POST['action'], array( 'editedcomment' ) ) )
  686. // for=jetpack: Moderation via the WordPress app, Calypso, anything powered by the Jetpack connection.
  687. || ( isset( $_GET['for'] ) && ( 'jetpack' == $_GET['for'] ) && ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) )
  688. // Certain WordPress.com API requests
  689. || ( defined( 'REST_API_REQUEST' ) && REST_API_REQUEST )
  690. // WordPress.org REST API requests
  691. || ( defined( 'REST_REQUEST' ) && REST_REQUEST )
  692. ) {
  693. if ( $new_status == 'spam' && ( $old_status == 'approved' || $old_status == 'unapproved' || !$old_status ) ) {
  694. return self::submit_spam_comment( $comment->comment_ID );
  695. } elseif ( $old_status == 'spam' && ( $new_status == 'approved' || $new_status == 'unapproved' ) ) {
  696. return self::submit_nonspam_comment( $comment->comment_ID );
  697. }
  698. }
  699. self::update_comment_history( $comment->comment_ID, '', 'status-' . $new_status );
  700. }
  701. public static function submit_spam_comment( $comment_id ) {
  702. global $wpdb, $current_user, $current_site;
  703. $comment_id = (int) $comment_id;
  704. $comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $comment_id ) );
  705. if ( !$comment ) // it was deleted
  706. return;
  707. if ( 'spam' != $comment->comment_approved )
  708. return;
  709. self::update_comment_history( $comment_id, '', 'report-spam' );
  710. // If the user hasn't configured Akismet, there's nothing else to do at this point.
  711. if ( ! self::get_api_key() ) {
  712. return;
  713. }
  714. // use the original version stored in comment_meta if available
  715. $as_submitted = self::sanitize_comment_as_submitted( get_comment_meta( $comment_id, 'akismet_as_submitted', true ) );
  716. if ( $as_submitted && is_array( $as_submitted ) && isset( $as_submitted['comment_content'] ) )
  717. $comment = (object) array_merge( (array)$comment, $as_submitted );
  718. $comment->blog = get_option( 'home' );
  719. $comment->blog_lang = get_locale();
  720. $comment->blog_charset = get_option('blog_charset');
  721. $comment->permalink = get_permalink($comment->comment_post_ID);
  722. if ( is_object($current_user) )
  723. $comment->reporter = $current_user->user_login;
  724. if ( is_object($current_site) )
  725. $comment->site_domain = $current_site->domain;
  726. $comment->user_role = '';
  727. if ( ! empty( $comment->user_ID ) ) {
  728. $comment->user_role = Akismet::get_user_roles( $comment->user_ID );
  729. }
  730. if ( self::is_test_mode() )
  731. $comment->is_test = 'true';
  732. $post = get_post( $comment->comment_post_ID );
  733. if ( ! is_null( $post ) ) {
  734. $comment->comment_post_modified_gmt = $post->post_modified_gmt;
  735. }
  736. $comment = apply_filters( 'akismet_request_args', $comment, 'submit-spam' );
  737. $response = self::http_post( self::build_query( $comment ), 'submit-spam' );
  738. update_comment_meta( $comment_id, 'akismet_user_result', 'true' );
  739. if ( $comment->reporter ) {
  740. update_comment_meta( $comment_id, 'akismet_user', $comment->reporter );
  741. }
  742. do_action('akismet_submit_spam_comment', $comment_id, $response[1]);
  743. }
  744. public static function submit_nonspam_comment( $comment_id ) {
  745. global $wpdb, $current_user, $current_site;
  746. $comment_id = (int) $comment_id;
  747. $comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->comments} WHERE comment_ID = %d", $comment_id ) );
  748. if ( !$comment ) // it was deleted
  749. return;
  750. self::update_comment_history( $comment_id, '', 'report-ham' );
  751. // If the user hasn't configured Akismet, there's nothing else to do at this point.
  752. if ( ! self::get_api_key() ) {
  753. return;
  754. }
  755. // use the original version stored in comment_meta if available
  756. $as_submitted = self::sanitize_comment_as_submitted( get_comment_meta( $comment_id, 'akismet_as_submitted', true ) );
  757. if ( $as_submitted && is_array($as_submitted) && isset($as_submitted['comment_content']) )
  758. $comment = (object) array_merge( (array)$comment, $as_submitted );
  759. $comment->blog = get_option( 'home' );
  760. $comment->blog_lang = get_locale();
  761. $comment->blog_charset = get_option('blog_charset');
  762. $comment->permalink = get_permalink( $comment->comment_post_ID );
  763. $comment->user_role = '';
  764. if ( is_object($current_user) )
  765. $comment->reporter = $current_user->user_login;
  766. if ( is_object($current_site) )
  767. $comment->site_domain = $current_site->domain;
  768. if ( ! empty( $comment->user_ID ) ) {
  769. $comment->user_role = Akismet::get_user_roles( $comment->user_ID );
  770. }
  771. if ( Akismet::is_test_mode() )
  772. $comment->is_test = 'true';
  773. $post = get_post( $comment->comment_post_ID );
  774. if ( ! is_null( $post ) ) {
  775. $comment->comment_post_modified_gmt = $post->post_modified_gmt;
  776. }
  777. $comment = apply_filters( 'akismet_request_args', $comment, 'submit-ham' );
  778. $response = self::http_post( self::build_query( $comment ), 'submit-ham' );
  779. update_comment_meta( $comment_id, 'akismet_user_result', 'false' );
  780. if ( $comment->reporter ) {
  781. update_comment_meta( $comment_id, 'akismet_user', $comment->reporter );
  782. }
  783. do_action('akismet_submit_nonspam_comment', $comment_id, $response[1]);
  784. }
  785. public static function cron_recheck() {
  786. global $wpdb;
  787. $api_key = self::get_api_key();
  788. $status = self::verify_key( $api_key );
  789. if ( get_option( 'akismet_alert_code' ) || $status == 'invalid' ) {
  790. // since there is currently a problem with the key, reschedule a check for 6 hours hence
  791. wp_schedule_single_event( time() + 21600, 'akismet_schedule_cron_recheck' );
  792. do_action( 'akismet_scheduled_recheck', 'key-problem-' . get_option( 'akismet_alert_code' ) . '-' . $status );
  793. return false;
  794. }
  795. delete_option('akismet_available_servers');
  796. $comment_errors = $wpdb->get_col( "SELECT comment_id FROM {$wpdb->commentmeta} WHERE meta_key = 'akismet_error' LIMIT 100" );
  797. load_plugin_textdomain( 'akismet' );
  798. foreach ( (array) $comment_errors as $comment_id ) {
  799. // if the comment no longer exists, or is too old, remove the meta entry from the queue to avoid getting stuck
  800. $comment = get_comment( $comment_id );
  801. if (
  802. ! $comment // Comment has been deleted
  803. || strtotime( $comment->comment_date_gmt ) < strtotime( "-15 days" ) // Comment is too old.
  804. || $comment->comment_approved !== "0" // Comment is no longer in the Pending queue
  805. ) {
  806. delete_comment_meta( $comment_id, 'akismet_error' );
  807. delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
  808. continue;
  809. }
  810. add_comment_meta( $comment_id, 'akismet_rechecking', true );
  811. $status = self::check_db_comment( $comment_id, 'retry' );
  812. $event = '';
  813. if ( $status == 'true' ) {
  814. $event = 'cron-retry-spam';
  815. } elseif ( $status == 'false' ) {
  816. $event = 'cron-retry-ham';
  817. }
  818. // If we got back a legit response then update the comment history
  819. // other wise just bail now and try again later. No point in
  820. // re-trying all the comments once we hit one failure.
  821. if ( !empty( $event ) ) {
  822. delete_comment_meta( $comment_id, 'akismet_error' );
  823. self::update_comment_history( $comment_id, '', $event );
  824. update_comment_meta( $comment_id, 'akismet_result', $status );
  825. // make sure the comment status is still pending. if it isn't, that means the user has already moved it elsewhere.
  826. $comment = get_comment( $comment_id );
  827. if ( $comment && 'unapproved' == wp_get_comment_status( $comment_id ) ) {
  828. if ( $status == 'true' ) {
  829. wp_spam_comment( $comment_id );
  830. } elseif ( $status == 'false' ) {
  831. // comment is good, but it's still in the pending queue. depending on the moderation settings
  832. // we may need to change it to approved.
  833. 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) )
  834. wp_set_comment_status( $comment_id, 1 );
  835. else if ( get_comment_meta( $comment_id, 'akismet_delayed_moderation_email', true ) )
  836. wp_notify_moderator( $comment_id );
  837. }
  838. }
  839. delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
  840. } else {
  841. // If this comment has been pending moderation for longer than MAX_DELAY_BEFORE_MODERATION_EMAIL,
  842. // send a moderation email now.
  843. if ( ( intval( gmdate( 'U' ) ) - strtotime( $comment->comment_date_gmt ) ) < self::MAX_DELAY_BEFORE_MODERATION_EMAIL ) {
  844. delete_comment_meta( $comment_id, 'akismet_delayed_moderation_email' );
  845. wp_notify_moderator( $comment_id );
  846. }
  847. delete_comment_meta( $comment_id, 'akismet_rechecking' );
  848. wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
  849. do_action( 'akismet_scheduled_recheck', 'check-db-comment-' . $status );
  850. return;
  851. }
  852. delete_comment_meta( $comment_id, 'akismet_rechecking' );
  853. }
  854. $remaining = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->commentmeta} WHERE meta_key = 'akismet_error'" );
  855. if ( $remaining && !wp_next_scheduled('akismet_schedule_cron_recheck') ) {
  856. wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' );
  857. do_action( 'akismet_scheduled_recheck', 'remaining' );
  858. }
  859. }
  860. public static function fix_scheduled_recheck() {
  861. $future_check = wp_next_scheduled( 'akismet_schedule_cron_recheck' );
  862. if ( !$future_check ) {
  863. return;
  864. }
  865. if ( get_option( 'akismet_alert_code' ) > 0 ) {
  866. return;
  867. }
  868. $check_range = time() + 1200;
  869. if ( $future_check > $check_range ) {
  870. wp_clear_scheduled_hook( 'akismet_schedule_cron_recheck' );
  871. wp_schedule_single_event( time() + 300, 'akismet_schedule_cron_recheck' );
  872. do_action( 'akismet_scheduled_recheck', 'fix-scheduled-recheck' );
  873. }
  874. }
  875. public static function add_comment_nonce( $post_id ) {
  876. /**
  877. * To disable the Akismet comment nonce, add a filter for the 'akismet_comment_nonce' tag
  878. * and return any string value that is not 'true' or '' (empty string).
  879. *
  880. * Don't return boolean false, because that implies that the 'akismet_comment_nonce' option
  881. * has not been set and that Akismet should just choose the default behavior for that
  882. * situation.
  883. */
  884. if ( ! self::get_api_key() ) {
  885. return;
  886. }
  887. $akismet_comment_nonce_option = apply_filters( 'akismet_comment_nonce', get_option( 'akismet_comment_nonce' ) );
  888. if ( $akismet_comment_nonce_option == 'true' || $akismet_comment_nonce_option == '' ) {
  889. echo '<p style="display: none;">';
  890. wp_nonce_field( 'akismet_comment_nonce_' . $post_id, 'akismet_comment_nonce', FALSE );
  891. echo '</p>';
  892. }
  893. }
  894. public static function is_test_mode() {
  895. return defined('AKISMET_TEST_MODE') && AKISMET_TEST_MODE;
  896. }
  897. public static function allow_discard() {
  898. if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
  899. return false;
  900. if ( is_user_logged_in() )
  901. return false;
  902. return ( get_option( 'akismet_strictness' ) === '1' );
  903. }
  904. public static function get_ip_address() {
  905. return isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : null;
  906. }
  907. /**
  908. * Do these two comments, without checking the comment_ID, "match"?
  909. *
  910. * @param mixed $comment1 A comment object or array.
  911. * @param mixed $comment2 A comment object or array.
  912. * @return bool Whether the two comments should be treated as the same comment.
  913. */
  914. private static function comments_match( $comment1, $comment2 ) {
  915. $comment1 = (array) $comment1;
  916. $comment2 = (array) $comment2;
  917. // Set default values for these strings that we check in order to simplify
  918. // the checks and avoid PHP warnings.
  919. if ( ! isset( $comment1['comment_author'] ) ) {
  920. $comment1['comment_author'] = '';
  921. }
  922. if ( ! isset( $comment2['comment_author'] ) ) {
  923. $comment2['comment_author'] = '';
  924. }
  925. if ( ! isset( $comment1['comment_author_email'] ) ) {
  926. $comment1['comment_author_email'] = '';
  927. }
  928. if ( ! isset( $comment2['comment_author_email'] ) ) {
  929. $comment2['comment_author_email'] = '';
  930. }
  931. $comments_match = (
  932. isset( $comment1['comment_post_ID'], $comment2['comment_post_ID'] )
  933. && intval( $comment1['comment_post_ID'] ) == intval( $comment2['comment_post_ID'] )
  934. && (
  935. // The comment author length max is 255 characters, limited by the TINYTEXT column type.
  936. // If the comment author includes multibyte characters right around the 255-byte mark, they
  937. // may be stripped when the author is saved in the DB, so a 300+ char author may turn into
  938. // a 253-char author when it's saved, not 255 exactly. The longest possible character is
  939. // theoretically 6 bytes, so we'll only look at the first 248 bytes to be safe.
  940. substr( $comment1['comment_author'], 0, 248 ) == substr( $comment2['comment_author'], 0, 248 )
  941. || substr( stripslashes( $comment1['comment_author'] ), 0, 248 ) == substr( $comment2['comment_author'], 0, 248 )
  942. || substr( $comment1['comment_author'], 0, 248 ) == substr( stripslashes( $comment2['comment_author'] ), 0, 248 )
  943. // Certain long comment author names will be truncated to nothing, depending on their encoding.
  944. || ( ! $comment1['comment_author'] && strlen( $comment2['comment_author'] ) > 248 )
  945. || ( ! $comment2['comment_author'] && strlen( $comment1['comment_author'] ) > 248 )
  946. )
  947. && (
  948. // The email max length is 100 characters, limited by the VARCHAR(100) column type.
  949. // Same argument as above for only looking at the first 93 characters.
  950. substr( $comment1['comment_author_email'], 0, 93 ) == substr( $comment2['comment_author_email'], 0, 93 )
  951. || substr( stripslashes( $comment1['comment_author_email'] ), 0, 93 ) == substr( $comment2['comment_author_email'], 0, 93 )
  952. || substr( $comment1['comment_author_email'], 0, 93 ) == substr( stripslashes( $comment2['comment_author_email'] ), 0, 93 )
  953. // Very long emails can be truncated and then stripped if the [0:100] substring isn't a valid address.
  954. || ( ! $comment1['comment_author_email'] && strlen( $comment2['comment_author_email'] ) > 100 )
  955. || ( ! $comment2['comment_author_email'] && strlen( $comment1['comment_author_email'] ) > 100 )
  956. )
  957. );
  958. return $comments_match;
  959. }
  960. // Does the supplied comment match the details of the one most recently stored in self::$last_comment?
  961. public static function matches_last_comment( $comment ) {
  962. return self::comments_match( self::$last_comment, $comment );
  963. }
  964. private static function get_user_agent() {
  965. return isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : null;
  966. }
  967. private static function get_referer() {
  968. return isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : null;
  969. }
  970. // return a comma-separated list of role names for the given user
  971. public static function get_user_roles( $user_id ) {
  972. $comment_user = null;
  973. $roles = false;
  974. if ( !class_exists('WP_User') )
  975. return false;
  976. if ( $user_id > 0 ) {
  977. $comment_user = new WP_User( $user_id );
  978. if ( isset( $comment_user->roles ) )
  979. $roles = implode( ',', $comment_user->roles );
  980. }
  981. if ( is_multisite() && is_super_admin( $user_id ) ) {
  982. if ( empty( $roles ) ) {
  983. $roles = 'super_admin';
  984. } else {
  985. $comment_user->roles[] = 'super_admin';
  986. $roles = implode( ',', $comment_user->roles );
  987. }
  988. }
  989. return $roles;
  990. }
  991. // filter handler used to return a spam result to pre_comment_approved
  992. public static function last_comment_status( $approved, $comment ) {
  993. if ( is_null( self::$last_comment_result ) ) {
  994. // We didn't have reason to store the result of the last check.
  995. return $approved;
  996. }
  997. // Only do this if it's the correct comment
  998. if ( ! self::matches_last_comment( $comment ) ) {
  999. self::log( "comment_is_spam mismatched comment, returning unaltered $approved" );
  1000. return $approved;
  1001. }
  1002. if ( 'trash' === $approved ) {
  1003. // If the last comment we checked has had its approval set to 'trash',
  1004. // then it failed the comment blacklist check. Let that blacklist override
  1005. // the spam check, since users have the (valid) expectation that when
  1006. // they fill out their blacklists, comments that match it will always
  1007. // end up in the trash.
  1008. return $approved;
  1009. }
  1010. // bump the counter here instead of when the filter is added to reduce the possibility of overcounting
  1011. if ( $incr = apply_filters('akismet_spam_count_incr', 1) )
  1012. update_option( 'akismet_spam_count', get_option('akismet_spam_count') + $incr );
  1013. return self::$last_comment_result;
  1014. }
  1015. /**
  1016. * If Akismet is temporarily unreachable, we don't want to "spam" the blogger with
  1017. * moderation emails for comments that will be automatically cleared or spammed on
  1018. * the next retry.
  1019. *
  1020. * For comments that will be rechecked later, empty the list of email addresses that
  1021. * the moderation email would be sent to.
  1022. *
  1023. * @param array $emails An array of email addresses that the moderation email will be sent to.
  1024. * @param int $comment_id The ID of the relevant comment.
  1025. * @return array An array of email addresses that the moderation email will be sent to.
  1026. */
  1027. public static function disable_moderation_emails_if_unreachable( $emails, $comment_id ) {
  1028. if ( ! empty( self::$prevent_moderation_email_for_these_comments ) && ! empty( $emails ) ) {
  1029. $comment = get_comment( $comment_id );
  1030. if ( $comment ) {
  1031. foreach ( self::$prevent_moderation_email_for_these_comments as $possible_match ) {
  1032. if ( self::comments_match( $possible_match, $comment ) ) {
  1033. update_comment_meta( $comment_id, 'akismet_delayed_moderation_email', true );
  1034. return array();
  1035. }
  1036. }
  1037. }
  1038. }
  1039. return $emails;
  1040. }
  1041. public static function _cmp_time( $a, $b ) {
  1042. return $a['time'] > $b['time'] ? -1 : 1;
  1043. }
  1044. public static function _get_microtime() {
  1045. $mtime = explode( ' ', microtime() );
  1046. return $mtime[1] + $mtime[0];
  1047. }
  1048. /**
  1049. * Make a POST request to the Akismet API.
  1050. *
  1051. * @param string $request The body of the request.
  1052. * @param string $path The path for the request.
  1053. * @param string $ip The specific IP address to hit.
  1054. * @return array A two-member array consisting of the headers and the response body, both empty in the case of a failure.
  1055. */
  1056. public static function http_post( $request, $path, $ip=null ) {
  1057. $akismet_ua = sprintf( 'WordPress/%s | Akismet/%s', $GLOBALS['wp_version'], constant( 'AKISMET_VERSION' ) );
  1058. $akismet_ua = apply_filters( 'akismet_ua', $akismet_ua );
  1059. $host = self::API_HOST;
  1060. $api_key = self::get_api_key();
  1061. if ( $api_key ) {
  1062. $request = add_query_arg( 'api_key', $api_key, $request );
  1063. }
  1064. $http_host = $host;
  1065. // use a specific IP if provided
  1066. // needed by Akismet_Admin::check_server_connectivity()
  1067. if ( $ip && long2ip( ip2long( $ip ) ) ) {
  1068. $http_host = $ip;
  1069. }
  1070. $http_args = array(
  1071. 'body' => $request,
  1072. 'headers' => array(
  1073. 'Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' ),
  1074. 'Host' => $host,
  1075. 'User-Agent' => $akismet_ua,
  1076. ),
  1077. 'httpversion' => '1.0',
  1078. 'timeout' => 15
  1079. );
  1080. $akismet_url = $http_akismet_url = "http://{$http_host}/1.1/{$path}";
  1081. /**
  1082. * Try SSL first; if that fails, try without it and don't try it again for a while.
  1083. */
  1084. $ssl = $ssl_failed = false;
  1085. // Check if SSL requests were disabled fewer than X hours ago.
  1086. $ssl_disabled = get_option( 'akismet_ssl_disabled' );
  1087. if ( $ssl_disabled && $ssl_disabled < ( time() - 60 * 60 * 24 ) ) { // 24 hours
  1088. $ssl_disabled = false;
  1089. delete_option( 'akismet_ssl_disabled' );
  1090. }
  1091. else if ( $ssl_disabled ) {
  1092. do_action( 'akismet_ssl_disabled' );
  1093. }
  1094. if ( ! $ssl_disabled && ( $ssl = wp_http_supports( array( 'ssl' ) ) ) ) {
  1095. $akismet_url = set_url_scheme( $akismet_url, 'https' );
  1096. do_action( 'akismet_https_request_pre' );
  1097. }
  1098. $response = wp_remote_post( $akismet_url, $http_args );
  1099. Akismet::log( compact( 'akismet_url', 'http_args', 'response' ) );
  1100. if ( $ssl && is_wp_error( $response ) ) {
  1101. do_action( 'akismet_https_request_failure', $response );
  1102. // Intermittent connection problems may cause the first HTTPS
  1103. // request to fail and subsequent HTTP requests to succeed randomly.
  1104. // Retry the HTTPS request once before disabling SSL for a time.
  1105. $response = wp_remote_post( $akismet_url, $http_args );
  1106. Akismet::log( compact( 'akismet_url', 'http_args', 'response' ) );
  1107. if ( is_wp_error( $response ) ) {
  1108. $ssl_failed = true;
  1109. do_action( 'akismet_https_request_failure', $response );
  1110. do_action( 'akismet_http_request_pre' );
  1111. // Try the request again without SSL.
  1112. $response = wp_remote_post( $http_akismet_url, $http_args );
  1113. Akismet::log( compact( 'http_akismet_url', 'http_args', 'response' ) );
  1114. }
  1115. }
  1116. if ( is_wp_error( $response ) ) {
  1117. do_action( 'akismet_request_failure', $response );
  1118. return array( '', '' );
  1119. }
  1120. if ( $ssl_failed ) {
  1121. // The request failed when using SSL but succeeded without it. Disable SSL for future requests.
  1122. update_option( 'akismet_ssl_disabled', time() );
  1123. do_action( 'akismet_https_disabled' );
  1124. }
  1125. $simplified_response = array( $response['headers'], $response['body'] );
  1126. self::update_alert( $simplified_response );
  1127. return $simplified_response;
  1128. }
  1129. // given a response from an API call like check_key_status(), update the alert code options if an alert is present.
  1130. public static function update_alert( $response ) {
  1131. $alert_option_prefix = 'akismet_alert_';
  1132. $alert_header_prefix = 'x-akismet-alert-';
  1133. $alert_header_names = array(
  1134. 'code',
  1135. 'msg',
  1136. 'api-calls',
  1137. 'usage-limit',
  1138. 'upgrade-plan',
  1139. 'upgrade-url',
  1140. 'upgrade-type',
  1141. );
  1142. foreach ( $alert_header_names as $alert_header_name ) {
  1143. $value = null;
  1144. if ( isset( $response[0][ $alert_header_prefix . $alert_header_name ] ) ) {
  1145. $value = $response[0][ $alert_header_prefix . $alert_header_name ];
  1146. }
  1147. $option_name = $alert_option_prefix . str_replace( '-', '_', $alert_header_name );
  1148. if ( $value != get_option( $option_name ) ) {
  1149. if ( ! $value ) {
  1150. delete_option( $option_name );
  1151. } else {
  1152. update_option( $option_name, $value );
  1153. }
  1154. }
  1155. }
  1156. }
  1157. /**
  1158. * Mark akismet-frontend.js as deferred. Because nothing depends on it, it can run at any time
  1159. * after it's loaded, and the browser won't have to wait for it to load to continue
  1160. * parsing the rest of the page.
  1161. */
  1162. public static function set_form_js_async( $tag, $handle, $src ) {
  1163. if ( 'akismet-frontend' !== $handle ) {
  1164. return $tag;
  1165. }
  1166. return preg_replace( '/^<script /i', '<script defer ', $tag );
  1167. }
  1168. public static function get_akismet_form_fields() {
  1169. $fields = '';
  1170. $prefix = 'ak_';
  1171. // Contact Form 7 uses _wpcf7 as a prefix to know which fields to exclude from comment_content.
  1172. if ( 'wpcf7_form_elements' === current_filter() ) {
  1173. $prefix = '_wpcf7_ak_';
  1174. }
  1175. $fields .= '<p style="display: none !important;" class="akismet-fields-container" data-prefix="' . esc_attr( $prefix ) . '">';
  1176. $fields .= '<label>&#916;<textarea name="' . $prefix . 'hp_textarea" cols="45" rows="8" maxlength="100"></textarea></label>';
  1177. if ( ! function_exists( 'amp_is_request' ) || ! amp_is_request() ) {
  1178. // Keep track of how many ak_js fields are in this page so that we don't re-use
  1179. // the same ID.
  1180. static $field_count = 0;
  1181. $field_count++;
  1182. $fields .= '<input type="hidden" id="ak_js_' . $field_count . '" name="' . $prefix . 'js" value="' . mt_rand( 0, 250 ) . '"/>';
  1183. $fields .= '<script>document.getElementById( "ak_js_' . $field_count . '" ).setAttribute( "value", ( new Date() ).getTime() );</script>';
  1184. }
  1185. $fields .= '</p>';
  1186. return $fields;
  1187. }
  1188. public static function output_custom_form_fields( $post_id ) {
  1189. if ( 'fluentform/form_element_start' === current_filter() && did_action( 'fluentform_form_element_start' ) ) {
  1190. // Already did this via the legacy filter.
  1191. return;
  1192. }
  1193. // phpcs:ignore WordPress.Security.EscapeOutput
  1194. echo self::get_akismet_form_fields();
  1195. }
  1196. public static function inject_custom_form_fields( $html ) {
  1197. $html = str_replace( '</form>', self::get_akismet_form_fields() . '</form>', $html );
  1198. return $html;
  1199. }
  1200. public static function append_custom_form_fields( $html ) {
  1201. $html .= self::get_akismet_form_fields();
  1202. return $html;
  1203. }
  1204. /**
  1205. * Ensure that any Akismet-added form fields are included in the comment-check call.
  1206. *
  1207. * @param array $form
  1208. * @param array $data Some plugins will supply the POST data via the filter, since they don't
  1209. * read it directly from $_POST.
  1210. * @return array $form
  1211. */
  1212. public static function prepare_custom_form_values( $form, $data = null ) {
  1213. if ( 'fluentform/akismet_fields' === current_filter() && did_filter( 'fluentform_akismet_fields' ) ) {
  1214. // Already updated the form fields via the legacy filter.
  1215. return $form;
  1216. }
  1217. if ( is_null( $data ) ) {
  1218. // phpcs:ignore WordPress.Security.NonceVerification.Missing
  1219. $data = $_POST;
  1220. }
  1221. $prefix = 'ak_';
  1222. // Contact Form 7 uses _wpcf7 as a prefix to know which fields to exclude from comment_content.
  1223. if ( 'wpcf7_akismet_parameters' === current_filter() ) {
  1224. $prefix = '_wpcf7_ak_';
  1225. }
  1226. foreach ( $data as $key => $val ) {
  1227. if ( 0 === strpos( $key, $prefix ) ) {
  1228. $form[ 'POST_ak_' . substr( $key, strlen( $prefix ) ) ] = $val;
  1229. }
  1230. }
  1231. return $form;
  1232. }
  1233. private static function bail_on_activation( $message, $deactivate = true ) {
  1234. ?>
  1235. <!doctype html>
  1236. <html>
  1237. <head>
  1238. <meta charset="<?php bloginfo( 'charset' ); ?>" />
  1239. <style>
  1240. * {
  1241. text-align: center;
  1242. margin: 0;
  1243. padding: 0;
  1244. font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
  1245. }
  1246. p {
  1247. margin-top: 1em;
  1248. font-size: 18px;
  1249. }
  1250. </style>
  1251. </head>
  1252. <body>
  1253. <p><?php echo esc_html( $message ); ?></p>
  1254. </body>
  1255. </html>
  1256. <?php
  1257. if ( $deactivate ) {
  1258. $plugins = get_option( 'active_plugins' );
  1259. $akismet = plugin_basename( AKISMET__PLUGIN_DIR . 'akismet.php' );
  1260. $update = false;
  1261. foreach ( $plugins as $i => $plugin ) {
  1262. if ( $plugin === $akismet ) {
  1263. $plugins[$i] = false;
  1264. $update = true;
  1265. }
  1266. }
  1267. if ( $update ) {
  1268. update_option( 'active_plugins', array_filter( $plugins ) );
  1269. }
  1270. }
  1271. exit;
  1272. }
  1273. public static function view( $name, array $args = array() ) {
  1274. $args = apply_filters( 'akismet_view_arguments', $args, $name );
  1275. foreach ( $args AS $key => $val ) {
  1276. $$key = $val;
  1277. }
  1278. load_plugin_textdomain( 'akismet' );
  1279. $file = AKISMET__PLUGIN_DIR . 'views/'. $name . '.php';
  1280. include( $file );
  1281. }
  1282. /**
  1283. * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
  1284. * @static
  1285. */
  1286. public static function plugin_activation() {
  1287. if ( version_compare( $GLOBALS['wp_version'], AKISMET__MINIMUM_WP_VERSION, '<' ) ) {
  1288. load_plugin_textdomain( 'akismet' );
  1289. $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/');
  1290. Akismet::bail_on_activation( $message );
  1291. } elseif ( ! empty( $_SERVER['SCRIPT_NAME'] ) && false !== strpos( $_SERVER['SCRIPT_NAME'], '/wp-admin/plugins.php' ) ) {
  1292. add_option( 'Activated_Akismet', true );
  1293. }
  1294. }
  1295. /**
  1296. * Removes all connection options
  1297. * @static
  1298. */
  1299. public static function plugin_deactivation( ) {
  1300. self::deactivate_key( self::get_api_key() );
  1301. // Remove any scheduled cron jobs.
  1302. $akismet_cron_events = array(
  1303. 'akismet_schedule_cron_recheck',
  1304. 'akismet_scheduled_delete',
  1305. );
  1306. foreach ( $akismet_cron_events as $akismet_cron_event ) {
  1307. $timestamp = wp_next_scheduled( $akismet_cron_event );
  1308. if ( $timestamp ) {
  1309. wp_unschedule_event( $timestamp, $akismet_cron_event );
  1310. }
  1311. }
  1312. }
  1313. /**
  1314. * Essentially a copy of WP's build_query but one that doesn't expect pre-urlencoded values.
  1315. *
  1316. * @param array $args An array of key => value pairs
  1317. * @return string A string ready for use as a URL query string.
  1318. */
  1319. public static function build_query( $args ) {
  1320. return _http_build_query( $args, '', '&' );
  1321. }
  1322. /**
  1323. * Log debugging info to the error log.
  1324. *
  1325. * Enabled when WP_DEBUG_LOG is enabled (and WP_DEBUG, since according to
  1326. * core, "WP_DEBUG_DISPLAY and WP_DEBUG_LOG perform no function unless
  1327. * WP_DEBUG is true), but can be disabled via the akismet_debug_log filter.
  1328. *
  1329. * @param mixed $akismet_debug The data to log.
  1330. */
  1331. public static function log( $akismet_debug ) {
  1332. if ( apply_filters( 'akismet_debug_log', defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG && defined( 'AKISMET_DEBUG' ) && AKISMET_DEBUG ) ) {
  1333. error_log( print_r( compact( 'akismet_debug' ), true ) );
  1334. }
  1335. }
  1336. public static function pre_check_pingback( $method ) {
  1337. $pingback_args = array();
  1338. if ( $method !== 'pingback.ping' )
  1339. return;
  1340. // A lot of this code is tightly coupled with the IXR class because the xmlrpc_call action doesn't pass along any information besides the method name.
  1341. // This ticket should hopefully fix that: https://core.trac.wordpress.org/ticket/52524
  1342. // Until that happens, when it's a system.multicall, pre_check_pingback will be called once for every internal pingback call.
  1343. // Keep track of how many times this function has been called so we know which call to reference in the XML.
  1344. static $call_count = 0;
  1345. $call_count++;
  1346. global $wp_xmlrpc_server;
  1347. if ( !is_object( $wp_xmlrpc_server ) )
  1348. return false;
  1349. $is_multicall = false;
  1350. $multicall_count = 0;
  1351. if ( 'system.multicall' === $wp_xmlrpc_server->message->methodName ) {
  1352. $is_multicall = true;
  1353. if ( 0 === $call_count ) {
  1354. // Only pass along the number of entries in the multicall the first time we see it.
  1355. $multicall_count = is_countable( $wp_xmlrpc_server->message->params ) ? count( $wp_xmlrpc_server->message->params ) : 0;
  1356. }
  1357. /*
  1358. * $wp_xmlrpc_server->message looks like this:
  1359. *
  1360. (
  1361. [message] =>
  1362. [messageType] => methodCall
  1363. [faultCode] =>
  1364. [faultString] =>
  1365. [methodName] => system.multicall
  1366. [params] => Array
  1367. (
  1368. [0] => Array
  1369. (
  1370. [methodName] => pingback.ping
  1371. [params] => Array
  1372. (
  1373. [0] => http://www.example.net/?p=1 // Site that created the pingback.
  1374. [1] => https://www.example.com/?p=1 // Post being pingback'd on this site.
  1375. )
  1376. )
  1377. [1] => Array
  1378. (
  1379. [methodName] => pingback.ping
  1380. [params] => Array
  1381. (
  1382. [0] => http://www.example.net/?p=1 // Site that created the pingback.
  1383. [1] => https://www.example.com/?p=2 // Post being pingback'd on this site.
  1384. )
  1385. )
  1386. )
  1387. )
  1388. */
  1389. // Use the params from the nth pingback.ping call in the multicall.
  1390. $pingback_calls_found = 0;
  1391. foreach ( $wp_xmlrpc_server->message->params as $xmlrpc_action ) {
  1392. if ( 'pingback.ping' === $xmlrpc_action['methodName'] ) {
  1393. $pingback_calls_found++;
  1394. }
  1395. if ( $call_count === $pingback_calls_found ) {
  1396. $pingback_args = $xmlrpc_action['params'];
  1397. break;
  1398. }
  1399. }
  1400. } else {
  1401. /*
  1402. * $wp_xmlrpc_server->message looks like this:
  1403. *
  1404. (
  1405. [message] =>
  1406. [messageType] => methodCall
  1407. [faultCode] =>
  1408. [faultString] =>
  1409. [methodName] => pingback.ping
  1410. [params] => Array
  1411. (
  1412. [0] => http://www.example.net/?p=1 // Site that created the pingback.
  1413. [1] => https://www.example.com/?p=2 // Post being pingback'd on this site.
  1414. )
  1415. )
  1416. */
  1417. $pingback_args = $wp_xmlrpc_server->message->params;
  1418. }
  1419. if ( ! empty( $pingback_args[1] ) ) {
  1420. $post_id = url_to_postid( $pingback_args[1] );
  1421. // If pingbacks aren't open on this post, we'll still check whether this request is part of a potential DDOS,
  1422. // but indicate to the server that pingbacks are indeed closed so we don't include this request in the user's stats,
  1423. // since the user has already done their part by disabling pingbacks.
  1424. $pingbacks_closed = false;
  1425. $post = get_post( $post_id );
  1426. if ( ! $post || ! pings_open( $post ) ) {
  1427. $pingbacks_closed = true;
  1428. }
  1429. // Note: If is_multicall is true and multicall_count=0, then we know this is at least the 2nd pingback we've processed in this multicall.
  1430. $comment = array(
  1431. 'comment_author_url' => $pingback_args[0],
  1432. 'comment_post_ID' => $post_id,
  1433. 'comment_author' => '',
  1434. 'comment_author_email' => '',
  1435. 'comment_content' => '',
  1436. 'comment_type' => 'pingback',
  1437. 'akismet_pre_check' => '1',
  1438. 'comment_pingback_target' => $pingback_args[1],
  1439. 'pingbacks_closed' => $pingbacks_closed ? '1' : '0',
  1440. 'is_multicall' => $is_multicall,
  1441. 'multicall_count' => $multicall_count,
  1442. );
  1443. $comment = self::auto_check_comment( $comment, 'xml-rpc' );
  1444. if ( isset( $comment['akismet_result'] ) && 'true' == $comment['akismet_result'] ) {
  1445. // Sad: tightly coupled with the IXR classes. Unfortunately the action provides no context and no way to return anything.
  1446. $wp_xmlrpc_server->error( new IXR_Error( 0, 'Invalid discovery target' ) );
  1447. // Also note that if this was part of a multicall, a spam result will prevent the subsequent calls from being executed.
  1448. // This is probably fine, but it raises the bar for what should be acceptable as a false positive.
  1449. }
  1450. }
  1451. }
  1452. /**
  1453. * Ensure that we are loading expected scalar values from akismet_as_submitted commentmeta.
  1454. *
  1455. * @param mixed $meta_value
  1456. * @return mixed
  1457. */
  1458. private static function sanitize_comment_as_submitted( $meta_value ) {
  1459. if ( empty( $meta_value ) ) {
  1460. return $meta_value;
  1461. }
  1462. $meta_value = (array) $meta_value;
  1463. foreach ( $meta_value as $key => $value ) {
  1464. if ( ! is_scalar( $value ) ) {
  1465. unset( $meta_value[ $key ] );
  1466. } else {
  1467. // These can change, so they're not explicitly listed in comment_as_submitted_allowed_keys.
  1468. if ( strpos( $key, 'POST_ak_' ) === 0 ) {
  1469. continue;
  1470. }
  1471. if ( ! isset( self::$comment_as_submitted_allowed_keys[ $key ] ) ) {
  1472. unset( $meta_value[ $key ] );
  1473. }
  1474. }
  1475. }
  1476. return $meta_value;
  1477. }
  1478. public static function predefined_api_key() {
  1479. if ( defined( 'WPCOM_API_KEY' ) ) {
  1480. return true;
  1481. }
  1482. return apply_filters( 'akismet_predefined_api_key', false );
  1483. }
  1484. /**
  1485. * Controls the display of a privacy related notice underneath the comment form using the `akismet_comment_form_privacy_notice` option and filter respectively.
  1486. * Default is top not display the notice, leaving the choice to site admins, or integrators.
  1487. */
  1488. public static function display_comment_form_privacy_notice() {
  1489. if ( 'display' !== apply_filters( 'akismet_comment_form_privacy_notice', get_option( 'akismet_comment_form_privacy_notice', 'hide' ) ) ) {
  1490. return;
  1491. }
  1492. echo apply_filters(
  1493. 'akismet_comment_form_privacy_notice_markup',
  1494. '<p class="akismet_comment_form_privacy_notice">' . sprintf(
  1495. __( 'This site uses Akismet to reduce spam. <a href="%s" target="_blank" rel="nofollow noopener">Learn how your comment data is processed</a>.', 'akismet' ),
  1496. 'https://akismet.com/privacy/'
  1497. ) . '</p>'
  1498. );
  1499. }
  1500. public static function load_form_js() {
  1501. if (
  1502. ! is_admin()
  1503. && ( ! function_exists( 'amp_is_request' ) || ! amp_is_request() )
  1504. && self::get_api_key()
  1505. ) {
  1506. wp_register_script( 'akismet-frontend', plugin_dir_url( __FILE__ ) . '_inc/akismet-frontend.js', array(), filemtime( plugin_dir_path( __FILE__ ) . '_inc/akismet-frontend.js' ), true );
  1507. wp_enqueue_script( 'akismet-frontend' );
  1508. }
  1509. }
  1510. /**
  1511. * Add the form JavaScript when we detect that a supported form shortcode is being parsed.
  1512. */
  1513. public static function load_form_js_via_filter( $return_value, $tag, $attr, $m ) {
  1514. if ( in_array( $tag, array( 'contact-form', 'gravityform', 'contact-form-7', 'formidable', 'fluentform' ) ) ) {
  1515. self::load_form_js();
  1516. }
  1517. return $return_value;
  1518. }
  1519. }