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


Generated : Sun Jun 14 08:20:09 2026 Cross-referenced by PHPXref