'POST', 'callback' => array( $this, 'purge' ), 'permission_callback' => array( $this, 'can_manage' ), ) ); register_rest_route( self::NS, '/status', array( 'methods' => 'GET', 'callback' => array( $this, 'status' ), 'permission_callback' => array( $this, 'can_manage' ), ) ); register_rest_route( self::NS, '/health', array( 'methods' => 'GET', 'callback' => array( $this, 'health' ), 'permission_callback' => array( $this, 'can_manage' ), ) ); register_rest_route( self::NS, '/settings', array( 'methods' => 'GET', 'callback' => array( $this, 'settings' ), 'permission_callback' => array( $this, 'can_manage' ), ) ); } public function can_manage() { return current_user_can( 'manage_options' ); } /** * Rate-limit key for current user. * * @return string */ public static function purge_rate_key() { $uid = function_exists( 'get_current_user_id' ) ? (int) get_current_user_id() : 0; return 'qwsc_rest_purge_' . $uid; } /** * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function purge( $request ) { $key = self::purge_rate_key(); $count = (int) get_transient( $key ); if ( ! \QWSpeedCache\Admin\ActionGuard::rate_limit_allows( $count, self::PURGE_MAX, self::PURGE_WINDOW ) ) { return new \WP_Error( 'qwsc_rate_limited', 'Too many purge requests. Try again in a minute.', array( 'status' => 429 ) ); } set_transient( $key, $count + 1, self::PURGE_WINDOW ); // Use the same page, memory and CDN purge path as the toolbar. // Do not return success when the filesystem purge failed. $result = \QWSpeedCache\Cache\Purge::purge_all(); if ( is_wp_error( $result ) ) { return new \WP_Error( 'qwsc_purge_failed', $result->get_error_message(), array( 'status' => 500 ) ); } return rest_ensure_response( array( 'success' => true, 'message' => 'Cache purged', ) ); } /** * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public function status( $request ) { return rest_ensure_response( \QWSpeedCache\Stats\Metrics::snapshot() ); } /** * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public function settings( $request ) { $all = \QWSpeedCache\Plugin::instance()->get_all_settings(); $schema = \QWSpeedCache\Settings\Schema::all(); $out = array(); foreach ( $all as $k => $v ) { if ( ! empty( $schema[ $k ]['secret'] ) ) { continue; } $out[ $k ] = $v; } return rest_ensure_response( $out ); } /** * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public function health( $request ) { return rest_ensure_response( \QWSpeedCache\Stats\Metrics::health() ); } }