[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-content/plugins/akismet/ -> class.akismet-rest-api.php (source)

   1  <?php
   2  
   3  class Akismet_REST_API {
   4      /**
   5       * Register the REST API routes.
   6       */
   7  	public static function init() {
   8          register_rest_route(
   9              'akismet/v1',
  10              '/key',
  11              array(
  12                  array(
  13                      'methods'             => WP_REST_Server::READABLE,
  14                      'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
  15                      'callback'            => array( 'Akismet_REST_API', 'get_key' ),
  16                  ),
  17                  array(
  18                      'methods'             => WP_REST_Server::EDITABLE,
  19                      'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
  20                      'callback'            => array( 'Akismet_REST_API', 'set_key' ),
  21                      'args'                => array(
  22                          'key' => array(
  23                              'required'          => true,
  24                              'type'              => 'string',
  25                              'sanitize_callback' => array( 'Akismet_REST_API', 'sanitize_key' ),
  26                              'description'       => __( 'A 12-character Akismet API key. Available at akismet.com/account', 'akismet' ),
  27                          ),
  28                      ),
  29                  ),
  30                  array(
  31                      'methods'             => WP_REST_Server::DELETABLE,
  32                      'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
  33                      'callback'            => array( 'Akismet_REST_API', 'delete_key' ),
  34                  ),
  35              )
  36          );
  37  
  38          register_rest_route(
  39              'akismet/v1',
  40              '/settings/',
  41              array(
  42                  array(
  43                      'methods'             => WP_REST_Server::READABLE,
  44                      'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
  45                      'callback'            => array( 'Akismet_REST_API', 'get_settings' ),
  46                  ),
  47                  array(
  48                      'methods'             => WP_REST_Server::EDITABLE,
  49                      'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
  50                      'callback'            => array( 'Akismet_REST_API', 'set_boolean_settings' ),
  51                      'args'                => array(
  52                          'akismet_strictness'        => array(
  53                              'required'    => false,
  54                              'type'        => 'boolean',
  55                              'description' => __( 'If true, Akismet will automatically discard the worst spam automatically rather than putting it in the spam folder.', 'akismet' ),
  56                          ),
  57                          'akismet_show_user_comments_approved' => array(
  58                              'required'    => false,
  59                              'type'        => 'boolean',
  60                              'description' => __( 'If true, show the number of approved comments beside each comment author in the comments list page.', 'akismet' ),
  61                          ),
  62                          'akismet_enable_mcp_access' => array(
  63                              'required'    => false,
  64                              'type'        => 'boolean',
  65                              'description' => __( 'If true, allow MCP clients to access Akismet data and functionality.', 'akismet' ),
  66                          ),
  67                      ),
  68                  ),
  69              )
  70          );
  71  
  72          register_rest_route(
  73              'akismet/v1',
  74              '/stats',
  75              array(
  76                  'methods'             => WP_REST_Server::READABLE,
  77                  'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
  78                  'callback'            => array( 'Akismet_REST_API', 'get_stats' ),
  79                  'args'                => array(
  80                      'interval' => array(
  81                          'required'          => false,
  82                          'type'              => 'string',
  83                          'sanitize_callback' => array( 'Akismet_REST_API', 'sanitize_interval' ),
  84                          'description'       => __( 'The time period for which to retrieve stats. Options: 60-days, 6-months, all', 'akismet' ),
  85                          'default'           => 'all',
  86                      ),
  87                  ),
  88              )
  89          );
  90  
  91          register_rest_route(
  92              'akismet/v1',
  93              '/stats/(?P<interval>[\w+])',
  94              array(
  95                  'args' => array(
  96                      'interval' => array(
  97                          'description' => __( 'The time period for which to retrieve stats. Options: 60-days, 6-months, all', 'akismet' ),
  98                          'type'        => 'string',
  99                      ),
 100                  ),
 101                  array(
 102                      'methods'             => WP_REST_Server::READABLE,
 103                      'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
 104                      'callback'            => array( 'Akismet_REST_API', 'get_stats' ),
 105                  ),
 106              )
 107          );
 108  
 109          register_rest_route(
 110              'akismet/v1',
 111              '/alert',
 112              array(
 113                  array(
 114                      'methods'             => WP_REST_Server::READABLE,
 115                      'permission_callback' => array( 'Akismet_REST_API', 'remote_call_permission_callback' ),
 116                      'callback'            => array( 'Akismet_REST_API', 'get_alert' ),
 117                      'args'                => array(
 118                          'key' => array(
 119                              'required'          => false,
 120                              'type'              => 'string',
 121                              'sanitize_callback' => array( 'Akismet_REST_API', 'sanitize_key' ),
 122                              'description'       => __( 'A 12-character Akismet API key. Available at akismet.com/account', 'akismet' ),
 123                          ),
 124                      ),
 125                  ),
 126                  array(
 127                      'methods'             => WP_REST_Server::EDITABLE,
 128                      'permission_callback' => array( 'Akismet_REST_API', 'remote_call_permission_callback' ),
 129                      'callback'            => array( 'Akismet_REST_API', 'set_alert' ),
 130                      'args'                => array(
 131                          'key' => array(
 132                              'required'          => false,
 133                              'type'              => 'string',
 134                              'sanitize_callback' => array( 'Akismet_REST_API', 'sanitize_key' ),
 135                              'description'       => __( 'A 12-character Akismet API key. Available at akismet.com/account', 'akismet' ),
 136                          ),
 137                      ),
 138                  ),
 139                  array(
 140                      'methods'             => WP_REST_Server::DELETABLE,
 141                      'permission_callback' => array( 'Akismet_REST_API', 'remote_call_permission_callback' ),
 142                      'callback'            => array( 'Akismet_REST_API', 'delete_alert' ),
 143                      'args'                => array(
 144                          'key' => array(
 145                              'required'          => false,
 146                              'type'              => 'string',
 147                              'sanitize_callback' => array( 'Akismet_REST_API', 'sanitize_key' ),
 148                              'description'       => __( 'A 12-character Akismet API key. Available at akismet.com/account', 'akismet' ),
 149                          ),
 150                      ),
 151                  ),
 152              )
 153          );
 154  
 155          register_rest_route(
 156              'akismet/v1',
 157              '/webhook',
 158              array(
 159                  'methods'             => WP_REST_Server::CREATABLE,
 160                  'callback'            => array( 'Akismet_REST_API', 'receive_webhook' ),
 161                  'permission_callback' => array( 'Akismet_REST_API', 'remote_call_permission_callback' ),
 162              )
 163          );
 164      }
 165  
 166      /**
 167       * Get the current Akismet API key.
 168       *
 169       * @param WP_REST_Request $request
 170       * @return WP_Error|WP_REST_Response
 171       */
 172  	public static function get_key( $request = null ) {
 173          return rest_ensure_response( Akismet::get_api_key() );
 174      }
 175  
 176      /**
 177       * Set the API key, if possible.
 178       *
 179       * @param WP_REST_Request $request
 180       * @return WP_Error|WP_REST_Response
 181       */
 182  	public static function set_key( $request ) {
 183          if ( defined( 'WPCOM_API_KEY' ) ) {
 184              return rest_ensure_response( new WP_Error( 'hardcoded_key', __( 'This site\'s API key is hardcoded and cannot be changed via the API.', 'akismet' ), array( 'status' => 409 ) ) );
 185          }
 186  
 187          $new_api_key = $request->get_param( 'key' );
 188  
 189          if ( ! self::key_is_valid( $new_api_key ) ) {
 190              return rest_ensure_response( new WP_Error( 'invalid_key', __( 'The value provided is not a valid and registered API key.', 'akismet' ), array( 'status' => 400 ) ) );
 191          }
 192  
 193          update_option( 'wordpress_api_key', $new_api_key );
 194  
 195          return self::get_key();
 196      }
 197  
 198      /**
 199       * Unset the API key, if possible.
 200       *
 201       * @param WP_REST_Request $request
 202       * @return WP_Error|WP_REST_Response
 203       */
 204  	public static function delete_key( $request ) {
 205          if ( defined( 'WPCOM_API_KEY' ) ) {
 206              return rest_ensure_response( new WP_Error( 'hardcoded_key', __( 'This site\'s API key is hardcoded and cannot be deleted.', 'akismet' ), array( 'status' => 409 ) ) );
 207          }
 208  
 209          delete_option( 'wordpress_api_key' );
 210  
 211          return rest_ensure_response( true );
 212      }
 213  
 214      /**
 215       * Get the Akismet settings.
 216       *
 217       * @param WP_REST_Request $request
 218       * @return WP_Error|WP_REST_Response
 219       */
 220  	public static function get_settings( $request = null ) {
 221          return rest_ensure_response(
 222              array(
 223                  'akismet_strictness'                  => ( get_option( 'akismet_strictness', '1' ) === '1' ),
 224                  'akismet_show_user_comments_approved' => ( get_option( 'akismet_show_user_comments_approved', '1' ) === '1' ),
 225                  'akismet_enable_mcp_access'           => ( get_option( 'akismet_enable_mcp_access', '0' ) === '1' ),
 226              )
 227          );
 228      }
 229  
 230      /**
 231       * Update the Akismet settings.
 232       *
 233       * @param WP_REST_Request $request
 234       * @return WP_Error|WP_REST_Response
 235       */
 236  	public static function set_boolean_settings( $request ) {
 237          foreach ( array(
 238              'akismet_strictness',
 239              'akismet_show_user_comments_approved',
 240              'akismet_enable_mcp_access',
 241          ) as $setting_key ) {
 242  
 243              $setting_value = $request->get_param( $setting_key );
 244              if ( is_null( $setting_value ) ) {
 245                  // This setting was not specified.
 246                  continue;
 247              }
 248  
 249              // From 4.7+, WP core will ensure that these are always boolean
 250              // values because they are registered with 'type' => 'boolean',
 251              // but we need to do this ourselves for prior versions.
 252              $setting_value = self::parse_boolean( $setting_value );
 253  
 254              update_option( $setting_key, $setting_value ? '1' : '0' );
 255          }
 256  
 257          return self::get_settings();
 258      }
 259  
 260      /**
 261       * Parse a numeric or string boolean value into a boolean.
 262       *
 263       * @param mixed $value The value to convert into a boolean.
 264       * @return bool The converted value.
 265       */
 266  	public static function parse_boolean( $value ) {
 267          switch ( $value ) {
 268              case true:
 269              case 'true':
 270              case '1':
 271              case 1:
 272                  return true;
 273  
 274              case false:
 275              case 'false':
 276              case '0':
 277              case 0:
 278                  return false;
 279  
 280              default:
 281                  return (bool) $value;
 282          }
 283      }
 284  
 285      /**
 286       * Get the Akismet stats for a given time period.
 287       *
 288       * Possible `interval` values:
 289       * - all
 290       * - 60-days
 291       * - 6-months
 292       *
 293       * @param WP_REST_Request $request
 294       * @return WP_Error|WP_REST_Response
 295       */
 296  	public static function get_stats( $request ) {
 297          $api_key = Akismet::get_api_key();
 298  
 299          $interval = $request->get_param( 'interval' );
 300  
 301          $stat_totals = array();
 302  
 303          $request_args = array(
 304              'blog' => get_option( 'home' ),
 305              'key'  => $api_key,
 306              'from' => $interval,
 307          );
 308  
 309          $request_args = apply_filters( 'akismet_request_args', $request_args, 'get-stats' );
 310  
 311          $response = Akismet::http_post( Akismet::build_query( $request_args ), 'get-stats' );
 312  
 313          if ( ! empty( $response[1] ) ) {
 314              $stat_totals[ $interval ] = json_decode( $response[1] );
 315          }
 316  
 317          return rest_ensure_response( $stat_totals );
 318      }
 319  
 320      /**
 321       * Get the current alert code and message. Alert codes are used to notify the site owner
 322       * if there's a problem, like a connection issue between their site and the Akismet API,
 323       * invalid requests being sent, etc.
 324       *
 325       * @param WP_REST_Request $request
 326       * @return WP_Error|WP_REST_Response
 327       */
 328  	public static function get_alert( $request ) {
 329          return rest_ensure_response(
 330              array(
 331                  'code'    => get_option( 'akismet_alert_code' ),
 332                  'message' => get_option( 'akismet_alert_msg' ),
 333              )
 334          );
 335      }
 336  
 337      /**
 338       * Update the current alert code and message by triggering a call to the Akismet server.
 339       *
 340       * @param WP_REST_Request $request
 341       * @return WP_Error|WP_REST_Response
 342       */
 343  	public static function set_alert( $request ) {
 344          delete_option( 'akismet_alert_code' );
 345          delete_option( 'akismet_alert_msg' );
 346  
 347          // Make a request so the most recent alert code and message are retrieved.
 348          Akismet::verify_key( Akismet::get_api_key() );
 349  
 350          return self::get_alert( $request );
 351      }
 352  
 353      /**
 354       * Clear the current alert code and message.
 355       *
 356       * @param WP_REST_Request $request
 357       * @return WP_Error|WP_REST_Response
 358       */
 359  	public static function delete_alert( $request ) {
 360          delete_option( 'akismet_alert_code' );
 361          delete_option( 'akismet_alert_msg' );
 362  
 363          return self::get_alert( $request );
 364      }
 365  
 366  	private static function key_is_valid( $key ) {
 367          $request_args = array(
 368              'key'  => $key,
 369              'blog' => get_option( 'home' ),
 370          );
 371  
 372          $request_args = apply_filters( 'akismet_request_args', $request_args, 'verify-key' );
 373  
 374          $response = Akismet::http_post( Akismet::build_query( $request_args ), 'verify-key' );
 375  
 376          if ( $response[1] == Akismet::KEY_STATUS_VALID ) {
 377              return true;
 378          }
 379  
 380          return false;
 381      }
 382  
 383  	public static function privileged_permission_callback() {
 384          return current_user_can( 'manage_options' );
 385      }
 386  
 387      /**
 388       * For calls that Akismet.com makes to the site to clear outdated alert codes, use the API key for authorization.
 389       */
 390  	public static function remote_call_permission_callback( $request ) {
 391          $local_key = Akismet::get_api_key();
 392  
 393          return $local_key && ( strtolower( $request->get_param( 'key' ) ?? '' ) === strtolower( $local_key ) );
 394      }
 395  
 396  	public static function sanitize_interval( $interval, $request, $param ) {
 397          $interval = trim( $interval );
 398  
 399          $valid_intervals = array( '60-days', '6-months', 'all' );
 400  
 401          if ( ! in_array( $interval, $valid_intervals ) ) {
 402              $interval = 'all';
 403          }
 404  
 405          return $interval;
 406      }
 407  
 408  	public static function sanitize_key( $key, $request, $param ) {
 409          return trim( $key );
 410      }
 411  
 412      /**
 413       * Process a webhook request from the Akismet servers.
 414       *
 415       * @param WP_REST_Request $request
 416       * @return WP_Error|WP_REST_Response
 417       */
 418  	public static function receive_webhook( $request ) {
 419          Akismet::log( array( 'Webhook request received', $request->get_body() ) );
 420  
 421          /**
 422           * The request body should look like this:
 423           * array(
 424           *     'key' => '1234567890abcd',
 425           *     'endpoint' => '[comment-check|submit-ham|submit-spam]',
 426           *     'comments' => array(
 427           *         array(
 428           *             'guid' => '[...]',
 429           *             'result' => '[true|false]',
 430           *             'comment_author' => '[...]',
 431           *             [...]
 432           *         ),
 433           *         array(
 434           *             'guid' => '[...]',
 435           *             [...],
 436           *         ),
 437           *         [...]
 438           *     )
 439           * )
 440           *
 441           * Multiple comments can be included in each request, and the only truly required
 442           * field for each is the guid, although it would be friendly to include also
 443           * comment_post_ID, comment_parent, and comment_author_email, if possible to make
 444           * searching easier.
 445           */
 446  
 447          // The response will include statuses for the result of each comment that was supplied.
 448          $response = array(
 449              'comments' => array(),
 450          );
 451  
 452          $endpoint = $request->get_param( 'endpoint' );
 453  
 454          switch ( $endpoint ) {
 455              case 'comment-check':
 456                  $webhook_comments = $request->get_param( 'comments' );
 457  
 458                  if ( ! is_array( $webhook_comments ) ) {
 459                      return rest_ensure_response( new WP_Error( 'malformed_request', __( 'The \'comments\' parameter must be an array.', 'akismet' ), array( 'status' => 400 ) ) );
 460                  }
 461  
 462                  foreach ( $webhook_comments as $webhook_comment ) {
 463                      $guid = $webhook_comment['guid'];
 464  
 465                      if ( ! $guid ) {
 466                          // Without the GUID, we can't be sure that we're matching the right comment.
 467                          // We'll make it a rule that any comment without a GUID is ignored intentionally.
 468                          continue;
 469                      }
 470  
 471                      // Search on the fields that are indexed in the comments table, plus the GUID.
 472                      // The GUID is the only thing we really need to search on, but comment_meta
 473                      // is not indexed in a useful way if there are many many comments. This
 474                      // should help narrow it down first.
 475                      $queryable_fields = array(
 476                          'comment_post_ID'      => 'post_id',
 477                          'comment_parent'       => 'parent',
 478                          'comment_author_email' => 'author_email',
 479                      );
 480  
 481                      $query_args               = array();
 482                      $query_args['status']     = 'any';
 483                      $query_args['meta_key']   = 'akismet_guid';
 484                      $query_args['meta_value'] = $guid;
 485  
 486                      foreach ( $queryable_fields as $queryable_field => $wp_comment_query_field ) {
 487                          if ( isset( $webhook_comment[ $queryable_field ] ) ) {
 488                              $query_args[ $wp_comment_query_field ] = $webhook_comment[ $queryable_field ];
 489                          }
 490                      }
 491  
 492                      $comments_query = new WP_Comment_Query( $query_args );
 493                      $comments       = $comments_query->comments;
 494  
 495                      if ( ! $comments ) {
 496                          // Unexpected, although the comment could have been deleted since being submitted.
 497                          Akismet::log( 'Webhook failed: no matching comment found.' );
 498  
 499                          $response['comments'][ $guid ] = array(
 500                              'status'  => 'error',
 501                              'message' => __( 'Could not find matching comment.', 'akismet' ),
 502                          );
 503  
 504                          continue;
 505                      } if ( count( $comments ) > 1 ) {
 506                          // Two comments shouldn't be able to match the same GUID.
 507                          Akismet::log( 'Webhook failed: multiple matching comments found.', $comments );
 508  
 509                          $response['comments'][ $guid ] = array(
 510                              'status'  => 'error',
 511                              'message' => __( 'Multiple comments matched request.', 'akismet' ),
 512                          );
 513  
 514                          continue;
 515                      } else {
 516                          // We have one single match, as hoped for.
 517                          Akismet::log( 'Found matching comment.', $comments );
 518  
 519                          $comment = $comments[0];
 520  
 521                          $current_status = wp_get_comment_status( $comment );
 522  
 523                          $result = $webhook_comment['result'];
 524  
 525                          if ( 'true' == $result ) {
 526                              Akismet::log( 'Comment should be spam' );
 527  
 528                              // The comment should be classified as spam.
 529                              if ( 'spam' != $current_status ) {
 530                                  // The comment is not classified as spam. If Akismet was the one to act on it, move it to spam.
 531                                  if ( Akismet::last_comment_status_change_came_from_akismet( $comment->comment_ID ) ) {
 532                                      Akismet::log( 'Comment is not spam; marking as spam.' );
 533  
 534                                      wp_spam_comment( $comment );
 535                                      Akismet::update_comment_history( $comment->comment_ID, '', 'webhook-spam' );
 536                                  } else {
 537                                      Akismet::log( 'Comment is not spam, but it has already been manually handled by some other process.' );
 538                                      Akismet::update_comment_history( $comment->comment_ID, '', 'webhook-spam-noaction' );
 539                                  }
 540                              }
 541                          } elseif ( 'false' == $result ) {
 542                              Akismet::log( 'Comment should be ham' );
 543  
 544                              // The comment should be classified as ham.
 545                              if ( 'spam' == $current_status ) {
 546                                  Akismet::log( 'Comment is spam.' );
 547  
 548                                  // The comment is classified as spam. If Akismet was the one to label it as spam, unspam it.
 549                                  if ( Akismet::last_comment_status_change_came_from_akismet( $comment->comment_ID ) ) {
 550                                      Akismet::log( 'Akismet marked it as spam; unspamming.' );
 551  
 552                                      wp_unspam_comment( $comment );
 553  
 554                                      akismet::update_comment_history( $comment->comment_ID, '', 'webhook-ham' );
 555                                  } else {
 556                                      Akismet::log( 'Comment is not spam, but it has already been manually handled by some other process.' );
 557                                      Akismet::update_comment_history( $comment->comment_ID, '', 'webhook-ham-noaction' );
 558                                  }
 559                              } elseif ( 'unapproved' == $current_status ) {
 560                                  Akismet::log( 'Comment is pending.' );
 561  
 562                                  // The comment is in Pending. If Akismet was the one to put it there, approve it (but only if the site
 563                                  // settings dictate that).
 564                                  if ( Akismet::last_comment_status_change_came_from_akismet( $comment->comment_ID ) ) {
 565                                      Akismet::log( 'Akismet marked it as Pending; approving.' );
 566  
 567                                      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 ) ) {
 568                                          wp_set_comment_status( $comment->comment_ID, 1 );
 569                                      }
 570  
 571                                      akismet::update_comment_history( $comment->comment_ID, '', 'webhook-ham' );
 572                                  } else {
 573                                      Akismet::log( 'Comment is not spam, but it has already been manually handled by some other process.' );
 574                                      Akismet::update_comment_history( $comment->comment_ID, '', 'webhook-ham-noaction' );
 575                                  }
 576                              }
 577  
 578                              $moderation_email_was_delayed = get_comment_meta( $comment->comment_ID, 'akismet_delayed_moderation_email', true );
 579  
 580                              if ( $moderation_email_was_delayed ) {
 581                                  Akismet::log( 'Moderation email was delayed for comment #' . $comment->comment_ID . '; sending now.' );
 582  
 583                                  delete_comment_meta( $comment->comment_ID, 'akismet_delayed_moderation_email' );
 584                                  wp_new_comment_notify_moderator( $comment->comment_ID );
 585                                  wp_new_comment_notify_postauthor( $comment->comment_ID );
 586                              }
 587  
 588                              delete_comment_meta( $comment->comment_ID, 'akismet_delay_moderation_email' );
 589                          }
 590  
 591                          $response['comments'][ $guid ] = array( 'status' => 'success' );
 592                      }
 593                  }
 594  
 595                  break;
 596              case 'submit-ham':
 597              case 'submit-spam':
 598                  // Nothing to do for submit-ham or submit-spam.
 599                  break;
 600              default:
 601                  // Unsupported endpoint.
 602                  break;
 603          }
 604  
 605          /**
 606           * Allow plugins to do things with a successfully processed webhook request, like logging.
 607           *
 608           * @since 5.3.2
 609           *
 610           * @param WP_REST_Request $request The REST request object.
 611           */
 612          do_action( 'akismet_webhook_received', $request );
 613  
 614          Akismet::log( 'Done processing webhook.' );
 615  
 616          return rest_ensure_response( $response );
 617      }
 618  }


Generated : Thu Sep 3 08:20:25 2026 Cross-referenced by PHPXref