registry = $registry; $this->page = $page; } /** * Register hooks. * * @return void */ public function boot() { add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } /** * Register the routes. * * @return void */ public function register_routes() { register_rest_route( self::NAMESPACE_V1, '/settings', array( 'methods' => 'POST', 'callback' => array( $this, 'save_settings' ), 'permission_callback' => array( $this, 'can_manage' ), ) ); register_rest_route( self::NAMESPACE_V1, '/comments/purge', array( 'methods' => 'POST', 'callback' => array( $this, 'purge_comments' ), 'permission_callback' => array( $this, 'can_moderate' ), 'args' => array( 'include_approved' => array( 'type' => 'boolean', 'default' => false, ), 'include_woo' => array( 'type' => 'boolean', 'default' => false, ), ), ) ); } /** * Whether the current user may change settings. * * @return bool */ public function can_manage() { return current_user_can( SettingsPage::CAPABILITY ); } /** * Whether the current user may delete comments. * * @return bool */ public function can_moderate() { return current_user_can( SettingsPage::CAPABILITY ) && current_user_can( 'moderate_comments' ); } /** * Save settings. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public function save_settings( $request ) { $posted = $request->get_param( 'adminkeep' ); $posted = is_array( $posted ) ? $posted : array(); $this->page->save_values( $posted ); return rest_ensure_response( array( 'saved' => true, 'state' => $this->state(), ) ); } /** * Delete one batch of comments. * * Returns what remains so the caller can drive a progress bar and come back for more. The * batching lives here rather than in the client so a closed tab cannot leave a half-run in a * strange state — each request is complete on its own. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public function purge_comments( $request ) { $include_approved = (bool) $request->get_param( 'include_approved' ); $include_woo = (bool) $request->get_param( 'include_woo' ); $deleted = CommentPurger::delete_batch( CommentPurger::BATCH_SIZE, $include_approved, $include_woo ); $remaining = CommentPurger::count( $include_approved, $include_woo ); return rest_ensure_response( array( 'deleted' => $deleted, 'remaining' => $remaining, 'done' => 0 === $remaining || 0 === $deleted, 'state' => $this->state(), ) ); } /** * The bits of state the screen re-renders after an action. * * @return array */ private function state() { $features = array(); foreach ( $this->registry->all() as $id => $feature ) { $features[ $id ] = array( 'enabled' => Settings::is_enabled( $id ), 'state' => $this->page->state_label( $feature ), 'link' => $this->page->panel_link_for( $feature ), 'notice' => $this->page->panel_notice_for( $feature ), ); } return array( 'features' => $features, 'comments' => CommentPurger::counts(), ); } }