publisher = $publisher; } /** * Hook route registration. */ public function register() { add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } /** * Register routes. */ public function register_routes() { register_rest_route( self::NS, '/publish', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'handle_publish' ), 'permission_callback' => array( $this, 'check_token' ), 'args' => array( 'title' => array( 'required' => true, 'type' => 'string', ), 'content' => array( 'required' => true, 'type' => 'string', ), ), ) ); register_rest_route( self::NS, '/status', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'handle_status' ), 'permission_callback' => array( $this, 'check_token' ), ) ); register_rest_route( self::NS, '/disconnect', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'handle_disconnect' ), 'permission_callback' => array( $this, 'check_token' ), ) ); } /** * Permission callback: constant-time token check. * * @param WP_REST_Request $request Request. * @return true|WP_Error */ public function check_token( WP_REST_Request $request ) { $token = $request->get_header( 'X-AdMetric-Token' ); if ( AdMetric_Token::verify( (string) $token ) ) { return true; } return new WP_Error( 'admetric_unauthorized', __( 'Invalid or missing AdMetric connection token.', 'admetric' ), array( 'status' => 401 ) ); } /** * POST /publish — create or update a post. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function handle_publish( WP_REST_Request $request ) { if ( ! AdMetric_Settings::publishing_enabled() ) { return new WP_Error( 'admetric_publishing_disabled', __( 'Publishing is disabled in the AdMetric plugin settings on this site.', 'admetric' ), array( 'status' => 403 ) ); } $result = $this->publisher->publish_from_request( $request ); if ( is_wp_error( $result ) ) { return $result; } return new WP_REST_Response( $result, $result['updated'] ? 200 : 201 ); } /** * GET /status — connection and capability summary. * * @return WP_REST_Response */ public function handle_status() { return new WP_REST_Response( array( 'ok' => true, 'plugin_version' => ADMETRIC_VERSION, 'wp_version' => get_bloginfo( 'version' ), 'site_name' => get_bloginfo( 'name' ), 'site_url' => home_url(), 'publishing_enabled' => AdMetric_Settings::publishing_enabled(), 'default_post_status' => AdMetric_Settings::default_post_status(), 'tracker_enabled' => AdMetric_Settings::tracker_enabled(), 'connected_at' => AdMetric_Token::connected_at(), ), 200 ); } /** * POST /disconnect — clear the stored token. * * @return WP_REST_Response */ public function handle_disconnect() { AdMetric_Token::clear(); return new WP_REST_Response( array( 'ok' => true ), 200 ); } }