feeds = $feeds; $this->posts = $posts; $this->media = $media; $this->placements = $placements; } /** * 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 { $writeArgs = $this->writeArgs(); // Read-only picker list for block editor — accessible to editors/authors. register_rest_route( self::NAMESPACE, '/feeds/picker', [ 'methods' => 'GET', 'callback' => [ $this, 'getPicker' ], 'permission_callback' => static function (): bool { return current_user_can( 'edit_posts' ); }, ] ); register_rest_route( self::NAMESPACE, '/feeds', [ [ 'methods' => 'GET', 'callback' => [ $this, 'getItems' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => [ 'page' => [ 'type' => 'integer', 'minimum' => 1, ], 'per_page' => [ 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, ], 'search' => [ 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ], 'status' => [ 'type' => 'string', 'enum' => [ 'all', 'publish', 'draft' ], ], ], ], [ 'methods' => 'POST', 'callback' => [ $this, 'createItem' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => $writeArgs, ], ] ); register_rest_route( self::NAMESPACE, '/feeds/(?P[\d]+)/publish', [ 'methods' => 'POST', 'callback' => [ $this, 'publishItem' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => [ 'id' => [ 'type' => 'integer', 'minimum' => 1, 'required' => true, ], ], ] ); register_rest_route( self::NAMESPACE, '/feeds/(?P[\d]+)/duplicate', [ 'methods' => 'POST', 'callback' => [ $this, 'duplicateItem' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => [ 'id' => [ 'type' => 'integer', 'minimum' => 1, 'required' => true, ], ], ] ); register_rest_route( self::NAMESPACE, '/feeds/(?P[\d]+)', [ [ 'methods' => 'GET', 'callback' => [ $this, 'getItem' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => [ 'id' => [ 'type' => 'integer', 'minimum' => 1, 'required' => true, ], ], ], [ 'methods' => 'PUT', 'callback' => [ $this, 'updateItem' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => array_merge( [ 'id' => [ 'type' => 'integer', 'minimum' => 1, 'required' => true, ], ], $writeArgs ), ], [ 'methods' => 'DELETE', 'callback' => [ $this, 'deleteItem' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => [ 'id' => [ 'type' => 'integer', 'minimum' => 1, 'required' => true, ], ], ], ] ); } /** * GET /feeds/picker — returns id+name for all published feeds. * Used by the Gutenberg block feed-selector dropdown. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response */ public function getPicker( \WP_REST_Request $request ): \WP_REST_Response { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found $rows = $this->feeds->findAll(); $items = []; foreach ( $rows as $row ) { if ( 'publish' !== (string) $row['status'] ) { continue; } $items[] = [ 'id' => (int) $row['id'], 'name' => (string) $row['name'], ]; } return new \WP_REST_Response( $items, 200 ); } /** * GET /feeds — returns all feeds. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response */ public function getItems( \WP_REST_Request $request ): \WP_REST_Response { $paged = null !== $request->get_param( 'page' ) || null !== $request->get_param( 'per_page' ) || null !== $request->get_param( 'search' ) || null !== $request->get_param( 'status' ); // Without paging params: every feed (pickers, Posts screen), oldest first. if ( ! $paged ) { $items = []; foreach ( $this->feeds->findAll() as $row ) { $items[] = $this->formatFeed( $row ); } return new \WP_REST_Response( $items, 200 ); } $perPage = (int) ( $request->get_param( 'per_page' ) ?? 20 ); $page = (int) ( $request->get_param( 'page' ) ?? 1 ); $result = $this->feeds->findPage( (string) ( $request->get_param( 'search' ) ?? '' ), $page, $perPage, (string) ( $request->get_param( 'status' ) ?? '' ) ); $items = []; foreach ( $result['rows'] as $row ) { $items[] = $this->formatFeed( $row ); } $response = new \WP_REST_Response( $items, 200 ); $response->header( 'X-WP-Total', (string) $result['total'] ); $response->header( 'X-WP-TotalPages', (string) max( 1, (int) ceil( $result['total'] / max( 1, $perPage ) ) ) ); // Status tab counts (search not applied): All / Published / Draft. $counts = $this->feeds->countByStatus(); $response->header( 'X-Feednetic-Count-All', (string) $counts['all'] ); $response->header( 'X-Feednetic-Count-Publish', (string) $counts['publish'] ); $response->header( 'X-Feednetic-Count-Draft', (string) $counts['draft'] ); return $response; } /** * GET /feeds/{id} — returns a single feed with its sources. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function getItem( \WP_REST_Request $request ) { $id = (int) $request['id']; $row = $this->feeds->findById( $id ); if ( null === $row ) { return new \WP_Error( 'feednetic/not_found', __( 'Feed not found.', 'feednetic' ), [ 'status' => 404 ] ); } return new \WP_REST_Response( $this->formatFeedWithSources( $row, $id ), 200 ); } /** * POST /feeds — creates a new feed and returns it with HTTP 201. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function createItem( \WP_REST_Request $request ) { $unknown = KnownParams::check( $request ); if ( null !== $unknown ) { return $unknown; } $settings = $this->validateSettings( (array) ( $request->get_param( 'settings' ) ?? [] ) ); $sourceId = (int) $request->get_param( 'source_id' ); $feedId = $this->feeds->insert( [ 'name' => (string) $request->get_param( 'name' ), 'status' => (string) $request->get_param( 'status' ), 'settings' => (string) wp_json_encode( $settings ), ] ); if ( $sourceId > 0 ) { $this->feeds->setPrimarySource( $feedId, $sourceId ); } $this->ensureName( $feedId, (string) $request->get_param( 'name' ) ); $this->fireFeedSaved( $feedId, $request ); $row = $this->feeds->findById( $feedId ); if ( null === $row ) { return new \WP_Error( 'feednetic/server_error', __( 'Feed was saved but could not be retrieved.', 'feednetic' ), [ 'status' => 500 ] ); } return new \WP_REST_Response( $this->formatFeedWithSources( $row, $feedId ), 201 ); } /** * PUT /feeds/{id} — updates an existing feed. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function updateItem( \WP_REST_Request $request ) { $unknown = KnownParams::check( $request ); if ( null !== $unknown ) { return $unknown; } $id = (int) $request['id']; $row = $this->feeds->findById( $id ); if ( null === $row ) { return new \WP_Error( 'feednetic/not_found', __( 'Feed not found.', 'feednetic' ), [ 'status' => 404 ] ); } $settings = $this->keepUnknownStoredSettings( (string) ( $row['settings'] ?? '{}' ), $this->validateSettings( (array) ( $request->get_param( 'settings' ) ?? [] ) ) ); $sourceId = (int) $request->get_param( 'source_id' ); $this->feeds->update( $id, [ 'name' => (string) $request->get_param( 'name' ), 'status' => (string) $request->get_param( 'status' ), 'settings' => (string) wp_json_encode( $settings ), ] ); // Only the feed's first account row changes; other feed_sources rows // (written by an add-on) are kept. 0 = leave the account as it is. if ( $sourceId > 0 ) { $this->feeds->setPrimarySource( $id, $sourceId ); } $this->ensureName( $id, (string) $request->get_param( 'name' ) ); $this->fireFeedSaved( $id, $request ); $updated = $this->feeds->findById( $id ); if ( null === $updated ) { return new \WP_Error( 'feednetic/server_error', __( 'Feed was updated but could not be retrieved.', 'feednetic' ), [ 'status' => 500 ] ); } return new \WP_REST_Response( $this->formatFeedWithSources( $updated, $id ), 200 ); } /** * POST /feeds/{id}/publish — sets a feed's status to 'publish'. * * Lightweight alternative to a full PUT: only touches the status column, * so callers (FeedsPage kebab menu) don't need to know the full feed payload. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function publishItem( \WP_REST_Request $request ) { $id = (int) $request['id']; $row = $this->feeds->findById( $id ); if ( null === $row ) { return new \WP_Error( 'feednetic/not_found', __( 'Feed not found.', 'feednetic' ), [ 'status' => 404 ] ); } $this->feeds->update( $id, [ 'status' => 'publish' ] ); $updated = $this->feeds->findById( $id ); if ( null === $updated ) { return new \WP_Error( 'feednetic/server_error', __( 'Feed was published but could not be retrieved.', 'feednetic' ), [ 'status' => 500 ] ); } return new \WP_REST_Response( $this->formatFeedWithSources( $updated, $id ), 200 ); } /** * POST /feeds/{id}/duplicate — creates a draft copy of a feed. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function duplicateItem( \WP_REST_Request $request ) { $id = (int) $request['id']; $row = $this->feeds->findById( $id ); if ( null === $row ) { return new \WP_Error( 'feednetic/not_found', __( 'Feed not found.', 'feednetic' ), [ 'status' => 404 ] ); } $newId = $this->feeds->duplicate( $id ); if ( null === $newId ) { return new \WP_Error( 'feednetic/server_error', __( 'Feed could not be duplicated.', 'feednetic' ), [ 'status' => 500 ] ); } /** * Fires after a feed was duplicated (the copy has the feed's account). * * @param int $newId The copy. * @param int $id The original feed. */ // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores do_action( 'feednetic/rest/duplicated', $newId, $id ); $newRow = $this->feeds->findById( $newId ); if ( null === $newRow ) { return new \WP_Error( 'feednetic/server_error', __( 'Feed was duplicated but could not be retrieved.', 'feednetic' ), [ 'status' => 500 ] ); } return new \WP_REST_Response( $this->formatFeedWithSources( $newRow, $newId ), 201 ); } /** * DELETE /feeds/{id} — deletes a feed. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function deleteItem( \WP_REST_Request $request ) { $id = (int) $request['id']; $row = $this->feeds->findById( $id ); if ( null === $row ) { return new \WP_Error( 'feednetic/not_found', __( 'Feed not found.', 'feednetic' ), [ 'status' => 404 ] ); } $this->feeds->delete( $id ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores do_action( 'feednetic/rest/feed_deleted', $id ); return new \WP_REST_Response( [ 'deleted' => true, 'id' => $id, ], 200 ); } /** * @param array $settings Raw settings from the request. * @return array */ private function validateSettings( array $settings ): array { return SettingsValidator::validate( $settings ); } /** * A feed never keeps an empty name: when the saved name is empty or only * whitespace, store the default name instead. Call after setPrimarySource(). * * @return string The name now stored. */ private function ensureName( int $feedId, string $name ): string { $name = trim( $name ); if ( '' !== $name ) { return $name; } $default = self::defaultName( $feedId, $this->feeds->getSources( $feedId ) ); $this->feeds->update( $feedId, [ 'name' => $default ] ); return $default; } /** * Default feed name: " feed" — the account name as is * when it already ends with "feed" (never "… feed feed") — or "Feed #" * when the feed has no account yet. * * @param array> $sources Feed sources in position order (FeedRepository::getSources()). */ public static function defaultName( int $feedId, array $sources ): string { $first = trim( (string) ( $sources[0]['name'] ?? '' ) ); if ( '' !== $first ) { return 1 === preg_match( '/feed$/i', $first ) ? $first /* translators: %s: account name */ : sprintf( __( '%s feed', 'feednetic' ), $first ); } /* translators: %d: feed id */ return sprintf( __( 'Feed #%d', 'feednetic' ), $feedId ); } /** * Returns a safe representation of a feed row without its sources. * * @param array $row Raw database row from FeedRepository. * @return array */ private function formatFeed( array $row ): array { $feedId = (int) ( $row['id'] ?? 0 ); $settings = json_decode( (string) ( $row['settings'] ?? '{}' ), true ); // The feed's account (add-ons may extend the summary through // feednetic/rest/feed_response). $primary = $this->feeds->getPrimarySource( $feedId ); $sourceCount = null !== $primary ? 1 : 0; $networks = null !== $primary ? [ (string) $primary['network'] ] : []; // Preview thumbnails: up to 4 smallest local variant URLs from newest visible posts. $previewThumbs = $this->resolvePreviewThumbs( $feedId ); // Placements: headless flag covers block-theme templates; shortcode placements are // detected lazily on render (see FeedRenderer) and stored via markHeadless(). $inTemplates = ! empty( $row['is_headless'] ); $summary = [ 'id' => $feedId, 'name' => (string) ( $row['name'] ?? '' ), 'status' => (string) ( $row['status'] ?? '' ), 'settings' => is_array( $settings ) ? $settings : [], 'source_count' => $sourceCount, 'networks' => $networks, 'preview_thumbs' => $previewThumbs, 'in_templates' => $inTemplates, 'placements' => $this->findFeedPlacements( $feedId ), 'created_at' => (string) ( $row['created_at'] ?? '' ), 'updated_at' => (string) ( $row['updated_at'] ?? '' ), ]; /** * Filters a feed's summary (GET /feeds list items and the feed response). * * @param array $summary Summary data. * @param int $feedId Feed ID. */ // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores return (array) apply_filters( 'feednetic/rest/summary', $summary, $feedId ); } /** * Returns up to 4 thumbnail URLs from the newest visible posts in a feed. * * @return string[] */ private function resolvePreviewThumbs( int $feedId ): array { $postRows = $this->posts->findByFeedForRender( $feedId, 4, 0 ); if ( empty( $postRows ) ) { return []; } $postIds = array_map( 'intval', array_column( $postRows, 'id' ) ); $mediaMap = $this->media->findFirstDoneByPostIds( $postIds ); $uploadDir = wp_upload_dir(); $base = trailingslashit( (string) $uploadDir['baseurl'] ); $thumbs = []; foreach ( $postIds as $postId ) { $mediaRow = $mediaMap[ $postId ] ?? null; if ( null === $mediaRow || empty( $mediaRow['variants'] ) ) { continue; } $variants = json_decode( (string) $mediaRow['variants'], true ); if ( ! is_array( $variants ) ) { continue; } foreach ( [ '320', '640', '800', '1080' ] as $size ) { if ( ! isset( $variants[ $size ] ) ) { continue; } $formats = $variants[ $size ]; $path = $formats['webp'] ?? reset( $formats ); if ( is_string( $path ) && '' !== $path ) { $thumbs[] = $base . $path; break; } } if ( count( $thumbs ) >= 4 ) { break; } } return $thumbs; } /** * Returns WP posts/pages that embed this feed. * * Page IDs are recorded by PlacementRegistry at render time and backfilled * once by CleanupJob; no post_content scan happens here. * * @return array */ private function findFeedPlacements( int $feedId ): array { return $this->placements->getPublishedPlacements( $feedId ); } /** * Returns a feed row with its account (whitelisted columns). * * @param array $row Raw database row from FeedRepository. * @param int $feedId Feed primary key. * @return array */ private function formatFeedWithSources( array $row, int $feedId ): array { $formatted = $this->formatFeed( $row ); $primary = $this->feeds->getPrimarySource( $feedId ); $formatted['source_id'] = null !== $primary ? (int) $primary['source_id'] : null; $formatted['source'] = null !== $primary ? $this->formatFeedSourceRow( $primary ) : null; /** * Filters the feed object returned by GET/POST/PUT /feeds/{id}. * * @param array $formatted Response data. * @param int $feedId Feed ID. */ // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores return apply_filters( 'feednetic/rest/feed_response', $formatted, $feedId ); } /** * Keeps stored settings keys that the current schema does not know (e.g. values * written by a deactivated add-on), so saving a feed never deletes them. * * @param array $validated Settings validated against the current schema. * @return array */ private function keepUnknownStoredSettings( string $storedJson, array $validated ): array { $stored = json_decode( $storedJson, true ); if ( ! is_array( $stored ) ) { return $validated; } // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores $schema = (array) apply_filters( 'feednetic/feed_settings_schema', [] ); return array_merge( array_diff_key( $stored, $schema ), $validated ); } /** * Fires after a feed was created or updated through REST, with the request, * so add-ons can persist their own request params. */ private function fireFeedSaved( int $feedId, \WP_REST_Request $request ): void { // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores do_action( 'feednetic/rest/feed_saved', $feedId, $request ); } /** * Returns a whitelisted representation of a feed_sources JOIN row. * * Explicitly lists allowed fields so that token_encrypted and other * sensitive columns are never returned to the browser. * * @param array $row Row from FeedRepository::getSources(). * @return array */ private function formatFeedSourceRow( array $row ): array { return [ 'source_id' => (int) ( $row['source_id'] ?? 0 ), 'feed_id' => (int) ( $row['feed_id'] ?? 0 ), 'stream' => (string) ( $row['stream'] ?? 'timeline' ), 'position' => (int) ( $row['position'] ?? 0 ), 'network' => (string) ( $row['network'] ?? '' ), 'name' => (string) ( $row['name'] ?? '' ), 'username' => (string) ( $row['username'] ?? '' ), 'status' => (string) ( $row['status'] ?? '' ), ]; } /** * Returns the shared args definition for POST /feeds and PUT /feeds/{id}. * * @return array> */ private function writeArgs(): array { $args = [ // Empty / whitespace = use the default name (see defaultName()). 'name' => [ 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ], 'status' => [ 'type' => 'string', 'enum' => [ 'publish', 'draft' ], 'default' => 'publish', 'sanitize_callback' => 'sanitize_key', ], 'settings' => [ 'type' => 'object', 'properties' => [], 'default' => [], ], // The feed's one account; 0 = none (create) / unchanged (update). 'source_id' => [ 'type' => 'integer', 'minimum' => 0, 'default' => 0, ], ]; // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores $filtered = apply_filters( 'feednetic/rest/feed_args', $args ); return is_array( $filtered ) ? $filtered : $args; } }