No Description

class.akismet.php 62KB

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