|null */ private $adaptersCache = null; public function __construct( SourceRepository $sources, PostRepository $posts, Scheduler $scheduler, MediaRepository $media, FeedRepository $feeds, SourceStatsRepository $stats ) { $this->sources = $sources; $this->posts = $posts; $this->media = $media; $this->feeds = $feeds; $this->stats = $stats; $this->scheduler = $scheduler; } /** * 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, '/sources', [ 'methods' => 'GET', 'callback' => [ $this, 'getItems' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], ] ); register_rest_route( self::NAMESPACE, '/sources/(?P[\d]+)', [ 'methods' => 'DELETE', 'callback' => [ $this, 'deleteItem' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => [ 'id' => [ 'type' => 'integer', 'minimum' => 1, 'required' => true, ], ], ] ); register_rest_route( self::NAMESPACE, '/sources/(?P[\d]+)/posts', [ 'methods' => 'GET', 'callback' => [ $this, 'getSourcePosts' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => $this->sourcePostsArgs(), ] ); register_rest_route( self::NAMESPACE, '/sources/(?P[\d]+)/refresh', [ 'methods' => 'POST', 'callback' => [ $this, 'refreshItem' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => [ 'id' => [ 'type' => 'integer', 'minimum' => 1, 'required' => true, ], ], ] ); } /** * GET /sources — lists all connected sources. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response */ public function getItems( \WP_REST_Request $request ): \WP_REST_Response { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found $rows = $this->sources->findAll(); $items = []; foreach ( $rows as $row ) { $items[] = $this->formatSource( $row ); } return new \WP_REST_Response( $items, 200 ); } /** * DELETE /sources/{id} — removes a source and all its data. * * @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']; $source = $this->sources->findById( $id ); if ( null === $source ) { return new \WP_Error( 'feednetic/not_found', __( 'Source not found.', 'feednetic' ), [ 'status' => 404 ] ); } $this->sources->delete( $id ); return new \WP_REST_Response( [ 'deleted' => true, 'id' => $id, ], 200 ); } /** * POST /sources/{id}/refresh — enqueues an immediate fetch for a source. * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function refreshItem( \WP_REST_Request $request ) { $id = (int) $request['id']; $source = $this->sources->findById( $id ); if ( null === $source ) { return new \WP_Error( 'feednetic/not_found', __( 'Source not found.', 'feednetic' ), [ 'status' => 404 ] ); } // Run the fetch synchronously so the caller sees fresh data immediately. // The recurring schedule is re-confirmed afterwards. // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- slash-namespaced hook per project convention do_action( 'feednetic/fetch_source', (int) $source['id'] ); $this->scheduler->scheduleFetchSource( (int) $source['id'] ); $updated = $this->sources->findById( $id ); if ( null === $updated ) { return new \WP_REST_Response( [ 'scheduled' => true, 'id' => $id, ], 200 ); } return new \WP_REST_Response( $this->formatSource( $updated ), 200 ); } /** * Request args for GET /sources/{id}/posts, extensible via feednetic/rest/source_posts_args. * * @return array> */ private function sourcePostsArgs(): array { $args = [ 'id' => [ 'type' => 'integer', 'minimum' => 1, 'required' => true, ], 'page' => [ 'type' => 'integer', 'minimum' => 1, 'default' => 1, ], 'per_page' => [ 'type' => 'integer', 'minimum' => 1, 'maximum' => 50, 'default' => 24, ], ]; // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores $filtered = apply_filters( 'feednetic/rest/source_posts_args', $args ); return is_array( $filtered ) ? $filtered : $args; } /** * GET /sources/{id}/posts — returns paginated posts for a source (admin post moderation). * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function getSourcePosts( \WP_REST_Request $request ) { $id = (int) $request['id']; $source = $this->sources->findById( $id ); if ( null === $source ) { return new \WP_Error( 'feednetic/not_found', __( 'Source not found.', 'feednetic' ), [ 'status' => 404 ] ); } $page = max( 1, (int) $request->get_param( 'page' ) ); $perPage = min( 50, max( 1, (int) $request->get_param( 'per_page' ) ) ); $offset = ( $page - 1 ) * $perPage; /** * Extra prepared SQL (starting with "AND") appended to the WHERE clause of the * admin posts list. Lets add-ons filter the list by their own request params. * * @param string $where Prepared SQL fragment, default ''. * @param \WP_REST_Request $request The GET request. */ // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores $extraWhere = (string) apply_filters( 'feednetic/rest/source_posts_where', '', $request ); $rows = $this->posts->findBySourceFiltered( $id, $perPage, $offset, 'timeline', $extraWhere ); $total = $this->posts->countBySourceFiltered( $id, 'timeline', $extraWhere ); $postIds = array_map( 'intval', array_column( $rows, 'id' ) ); $mediaMap = $this->media->findFirstDoneByPostIds( $postIds ); $anyMediaMap = $this->media->findFirstAnyByPostIds( $postIds ); $mediaCount = $this->media->countByPostIds( $postIds ); $uploadDir = wp_upload_dir(); $base = trailingslashit( $uploadDir['baseurl'] ); $items = []; foreach ( $rows as $row ) { $thumbnail = null; $mediaRow = $mediaMap[ (int) $row['id'] ] ?? null; if ( null !== $mediaRow && ! empty( $mediaRow['variants'] ) ) { $variants = json_decode( (string) $mediaRow['variants'], true ); if ( is_array( $variants ) ) { foreach ( [ '320', '640', '800', '1080' ] as $size ) { if ( isset( $variants[ $size ] ) ) { $formats = $variants[ $size ]; if ( ! empty( $formats['webp'] ) ) { $thumbnail = $base . $formats['webp']; break; } foreach ( [ 'jpg', 'jpeg', 'png', 'gif' ] as $ext ) { if ( ! empty( $formats[ $ext ] ) ) { $thumbnail = $base . $formats[ $ext ]; break 2; } } break; } } } } $metrics = []; if ( ! empty( $row['metrics'] ) ) { $decoded = json_decode( (string) $row['metrics'], true ); $metrics = is_array( $decoded ) ? $decoded : []; } $extra = []; if ( ! empty( $row['extra'] ) ) { $decoded = json_decode( (string) $row['extra'], true ); $extra = is_array( $decoded ) ? $decoded : []; } $linkUrl = isset( $extra['fb_link_url'] ) && '' !== $extra['fb_link_url'] ? (string) $extra['fb_link_url'] : null; $linkTitle = isset( $extra['fb_link_title'] ) && '' !== $extra['fb_link_title'] ? (string) $extra['fb_link_title'] : null; $text = isset( $row['text'] ) ? trim( (string) $row['text'] ) : ''; if ( '' !== $text ) { $text = mb_substr( $text, 0, 200 ); } // media_status: 'none' for text posts; 'done' when thumbnail exists; // otherwise reflect pending/failed from anyMediaMap. $postType = (string) $row['type']; if ( 'text' === $postType ) { $mediaStatus = 'none'; } elseif ( null !== $thumbnail ) { $mediaStatus = 'done'; } else { $anyRow = $anyMediaMap[ (int) $row['id'] ] ?? null; $mediaStatus = null !== $anyRow ? (string) $anyRow['status'] : 'none'; } $items[] = [ 'id' => (int) $row['id'], 'network' => (string) $row['network'], 'external_id' => (string) $row['external_id'], 'type' => $postType, 'published_at' => (string) $row['published_at'], 'text' => '' !== $text ? $text : null, 'thumbnail' => $thumbnail, 'media_count' => $mediaCount[ (int) $row['id'] ] ?? 0, 'media_status' => $mediaStatus, 'link_url' => $linkUrl, 'link_title' => $linkTitle, 'likes' => isset( $metrics['likes'] ) ? (int) $metrics['likes'] : null, 'comments' => isset( $metrics['comments'] ) ? (int) $metrics['comments'] : null, ]; /** * Filters one post item of the admin posts list. * * @param array $item Response item. * @param array $row Raw posts table row. */ // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores $items[ count( $items ) - 1 ] = (array) apply_filters( 'feednetic/rest/source_post_item', end( $items ), $row ); } return new \WP_REST_Response( [ 'posts' => $items, 'total' => $total, 'page' => $page, 'per_page' => $perPage, ], 200 ); } /** * 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 { $id = (int) ( $row['id'] ?? 0 ); $computed = SourceStatus::compute( $row ); $uiStatus = $computed['ui_status']; $nextFetch = $computed['next_fetch_at']; // For active sources next_fetch_at comes from Action Scheduler, not from meta. if ( null === $nextFetch && 'active' === $uiStatus ) { $asNext = as_next_scheduled_action( 'feednetic/fetch_source', [ 'source_id' => $id ], Scheduler::GROUP ); if ( false !== $asNext && (int) $asNext > time() ) { $nextFetch = (int) $asNext; } } // Compute the local avatar URL from avatar_path (never expose the CDN URL). // Null when the stored file is missing (it is downloaded again in the background). $avatarUrl = \Feednetic\Media\AvatarFile::url( $row ); $avatarUrl = '' !== $avatarUrl ? $avatarUrl : null; // Followers delta over the last 7 days (null if <7 days of stats). $followersCount = isset( $row['followers_count'] ) ? (int) $row['followers_count'] : null; $delta7d = null; if ( null !== $followersCount ) { $oldCount = $this->stats->getFollowersDeltaDays( $id, 7 ); if ( null !== $oldCount ) { $delta7d = $followersCount - $oldCount; } } // Feeds that include this source. $feedRows = $this->feeds->findBySourceId( $id ); $feedsList = array_map( static function ( array $f ): array { return [ 'id' => (int) $f['id'], 'name' => (string) $f['name'], ]; }, $feedRows ); // Expose per-network capability flags. A source-level meta override takes // precedence (e.g. biography was confirmed unavailable on the last profile // fetch); fall back to the adapter's declared capabilities. $sourceMeta = []; if ( ! empty( $row['meta'] ) ) { $decoded = json_decode( (string) $row['meta'], true ); $sourceMeta = is_array( $decoded ) ? $decoded : []; } if ( array_key_exists( 'can_biography', $sourceMeta ) ) { $canBiography = (bool) $sourceMeta['can_biography']; } else { $canBiography = $this->networkHasCapability( (string) ( $row['network'] ?? '' ), 'profile.biography' ); } return [ 'id' => $id, 'network' => (string) ( $row['network'] ?? '' ), 'platform' => (string) preg_replace( '/^fake_/', '', (string) ( $row['network'] ?? '' ) ), 'external_id' => (string) ( $row['external_id'] ?? '' ), 'name' => (string) ( $row['name'] ?? '' ), 'username' => (string) ( $row['username'] ?? '' ), 'biography' => isset( $row['biography'] ) ? (string) $row['biography'] : null, 'profile_url' => isset( $row['profile_url'] ) ? (string) $row['profile_url'] : null, 'avatar_url' => $avatarUrl, 'auth_type' => (string) ( $row['auth_type'] ?? '' ), 'status' => (string) ( $row['status'] ?? '' ), 'ui_status' => $uiStatus, 'next_fetch_at' => $nextFetch, // The account's own next scheduled sync (recurring job only). 'next_sync_at' => 'expired' === $uiStatus ? null : ( new Scheduler() )->nextScheduledSync( $id ), '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, 'profile_fetched_at' => isset( $row['profile_fetched_at'] ) ? (string) $row['profile_fetched_at'] : null, 'followers_count' => $followersCount, 'followers_delta_7d' => $delta7d, 'media_count' => isset( $row['media_count'] ) ? (int) $row['media_count'] : null, 'posts_count' => $this->posts->countBySource( $id ), 'feeds' => $feedsList, 'can_biography' => $canBiography, 'created_at' => (string) ( $row['created_at'] ?? '' ), 'updated_at' => (string) ( $row['updated_at'] ?? '' ), ]; } /** * Returns true if the adapter for the given network declares a capability. */ private function networkHasCapability( string $network, string $capability ): bool { if ( null === $this->adaptersCache ) { // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores $this->adaptersCache = (array) apply_filters( 'feednetic/adapters', [] ); } $adapter = $this->adaptersCache[ $network ] ?? null; if ( ! $adapter instanceof SourceAdapterInterface ) { return false; } return in_array( $capability, $adapter->capabilities(), true ); } }