relay = $relay; $this->callbackHandler = $callbackHandler; $this->sources = $sources; $this->encryption = $encryption; $this->httpClient = $httpClient; } /** * Registers the rest_api_init hook. */ public function register(): void { add_action( 'rest_api_init', [ $this, 'registerRoutes' ] ); } /** * Registers all routes for this controller. */ public function registerRoutes(): void { register_rest_route( self::NAMESPACE, '/oauth/callback', [ 'methods' => 'GET', 'callback' => [ $this, 'oauthCallback' ], 'permission_callback' => '__return_true', 'args' => [ 'code' => [ 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ], 'state' => [ 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ], ], ] ); register_rest_route( self::NAMESPACE, '/connect/(?P[a-z]+)', [ 'methods' => 'POST', 'callback' => [ $this, 'startConnect' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => [ 'network' => [ 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_key', ], ], ] ); register_rest_route( self::NAMESPACE, '/connect/facebook/pages', [ [ 'methods' => 'GET', 'callback' => [ $this, 'listPages' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => [ 'pages_token' => [ 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ], ], ], [ 'methods' => 'POST', 'callback' => [ $this, 'claimPages' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => [ 'pages_token' => [ 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ], 'page_ids' => [ 'type' => 'array', 'required' => true, 'items' => [ 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ], ], ], ], ] ); } /** * GET /oauth/callback — handles the redirect back from the relay. * Delegates to OauthCallbackHandler and issues an HTTP redirect; never returns JSON. * * @param \WP_REST_Request $request Incoming REST request. */ public function oauthCallback( \WP_REST_Request $request ): void { // Both are sanitized by the route's args schema (sanitize_text_field). $this->callbackHandler->handleCallback( (string) $request->get_param( 'state' ), (string) $request->get_param( 'code' ) ); } /** * POST /connect/{network} — builds and returns the relay OAuth URL. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function startConnect( \WP_REST_Request $request ) { $network = (string) $request['network']; $callbackUrl = admin_url( 'admin-post.php' ) . '?action=feednetic_oauth_callback'; try { $connectUrl = $this->relay->getConnectUrl( $network, $callbackUrl ); } catch ( \RuntimeException $e ) { // E.g. FEEDNETIC_RELAY_URL is not https:// on a production site. return new \WP_Error( 'feednetic/relay_url', $e->getMessage(), [ 'status' => 500 ] ); } return new \WP_REST_Response( [ 'connect_url' => $connectUrl ], 200 ); } /** * GET /connect/facebook/pages — returns available Pages without permanently * consuming the token. * * The original pages token is consumed by claimFacebookPages(), but a fresh * token is issued by storePagesTransient() and returned to the client so the * admin can then call POST /connect/facebook/pages with the new token. * Access tokens are never included in the response. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function listPages( \WP_REST_Request $request ) { $pagesToken = (string) $request->get_param( 'pages_token' ); $userId = get_current_user_id(); try { $pages = $this->callbackHandler->claimFacebookPages( $userId, $pagesToken ); } catch ( \Exception $e ) { return new \WP_Error( 'feednetic/invalid_token', __( 'The pages token is invalid or has expired.', 'feednetic' ), [ 'status' => 422 ] ); } // Re-store the pages under a fresh token so the client can call claimPages(). $newToken = $this->callbackHandler->storePagesTransient( $userId, $pages ); $pageList = []; foreach ( $pages as $page ) { $pageList[] = [ 'id' => $page->externalId, 'network' => $page->network, 'name' => $page->name, 'username' => $page->username, 'avatar_url' => $page->avatarUrl, ]; } return new \WP_REST_Response( [ 'pages_token' => $newToken, 'pages' => $pageList, ], 200 ); } /** * POST /connect/facebook/pages — saves the admin-selected Facebook Pages. * * Consumes the pages token, filters to only the chosen page IDs, and upserts * each page into the sources table. Fires feednetic/source_connected for * updated rows (inserts fire it inside SourceRepository::insert()). * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function claimPages( \WP_REST_Request $request ) { $pagesToken = (string) $request->get_param( 'pages_token' ); $pageIds = (array) $request->get_param( 'page_ids' ); $userId = get_current_user_id(); try { $pages = $this->callbackHandler->claimFacebookPages( $userId, $pagesToken ); } catch ( \Exception $e ) { return new \WP_Error( 'feednetic/invalid_token', __( 'The pages token is invalid or has expired.', 'feednetic' ), [ 'status' => 422 ] ); } // Keep only pages the admin selected. $selected = []; foreach ( $pages as $page ) { if ( in_array( $page->externalId, $pageIds, true ) ) { $selected[] = $page; } } if ( empty( $selected ) ) { return new \WP_Error( 'feednetic/no_pages_selected', __( 'No matching pages were found for the given page IDs.', 'feednetic' ), [ 'status' => 400 ] ); } $savedSources = []; foreach ( $selected as $page ) { $plainToken = $page->getAccessToken(); $data = [ 'network' => $page->network, 'external_id' => $page->externalId, 'name' => $page->name, 'username' => $page->username, 'avatar_url' => $page->avatarUrl, 'auth_type' => $page->authType, 'token_encrypted' => $this->encryption->encrypt( $plainToken ), 'token_expires_at' => null !== $page->tokenExpiresAt ? $page->tokenExpiresAt->format( 'Y-m-d H:i:s' ) : null, // Facebook page tokens are permanent (token_expires_at = NULL) but the // underlying data access authorization expires 90 days from the last OAuth // login. debug_token returns the exact timestamp so we can warn in advance. 'data_access_expires_at' => $this->fetchDataAccessExpiresAt( $plainToken ), 'status' => 'active', 'last_error' => null, ]; $existing = $this->sources->findByNetworkAndExternalId( $page->network, $page->externalId ); if ( null !== $existing ) { $sourceId = (int) $existing['id']; $this->sources->update( $sourceId, $data ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores do_action( 'feednetic/source_connected', $sourceId ); $row = $this->sources->findById( $sourceId ); } else { // SourceRepository::insert() fires feednetic/source_connected internally. $sourceId = $this->sources->insert( $data ); $row = $this->sources->findById( $sourceId ); } // e.g. relay_app_id: the Meta app that issued this Page token. if ( ! empty( $page->meta ) ) { $this->sources->updateMeta( $sourceId, $page->meta ); $row = $this->sources->findById( $sourceId ); } if ( is_array( $row ) ) { $savedSources[] = $this->formatSource( $row ); } } return new \WP_REST_Response( $savedSources, 200 ); } /** * Calls the Meta debug_token endpoint and returns the data_access_expires_at * value as a UTC datetime string, or null when unavailable. * * Facebook page tokens never expire (token_expires_at = NULL) but data access * authorization expires 90 days from the last user OAuth login (error code 190). * Storing it lets the dashboard warn 7 days in advance. * * @param string $token Plain-text Facebook page access token. */ private function fetchDataAccessExpiresAt( string $token ): ?string { try { $response = $this->httpClient->get( 'https://graph.facebook.com/' . self::GRAPH_VERSION . '/debug_token', [], [ 'input_token' => $token, 'access_token' => $token, ] ); if ( ! $response->isSuccessful() ) { return null; } $body = json_decode( $response->body, true ); $ts = isset( $body['data']['data_access_expires_at'] ) ? (int) $body['data']['data_access_expires_at'] : 0; if ( $ts <= 0 ) { return null; } return gmdate( 'Y-m-d H:i:s', $ts ); } catch ( \Exception $e ) { unset( $e ); return null; } } /** * Returns a safe, whitelisted representation of a source row. * * Explicitly maps allowed fields by name. token_encrypted, token_expires_at, * and meta are never included. * * @param array $row Raw database row from SourceRepository. * @return array */ private function formatSource( array $row ): array { return [ 'id' => (int) ( $row['id'] ?? 0 ), 'network' => (string) ( $row['network'] ?? '' ), 'external_id' => (string) ( $row['external_id'] ?? '' ), 'name' => (string) ( $row['name'] ?? '' ), 'username' => (string) ( $row['username'] ?? '' ), 'avatar_url' => isset( $row['avatar_url'] ) ? (string) $row['avatar_url'] : null, 'auth_type' => (string) ( $row['auth_type'] ?? '' ), 'status' => (string) ( $row['status'] ?? '' ), 'last_error' => isset( $row['last_error'] ) ? (string) $row['last_error'] : null, 'last_fetched_at' => isset( $row['last_fetched_at'] ) ? (string) $row['last_fetched_at'] : null, 'created_at' => (string) ( $row['created_at'] ?? '' ), 'updated_at' => (string) ( $row['updated_at'] ?? '' ), ]; } }