sources = $sources; $this->feeds = $feeds; $this->posts = $posts; $this->media = $media; $this->stats = $stats; $this->placements = $placements; } public function register(): void { add_action( 'rest_api_init', [ $this, 'registerRoutes' ] ); } public function registerRoutes(): void { register_rest_route( self::NAMESPACE, '/dashboard', [ 'methods' => 'GET', 'callback' => [ $this, 'getItem' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], ] ); register_rest_route( self::NAMESPACE, '/dashboard/alerts/dismiss', [ 'methods' => 'POST', 'callback' => [ $this, 'dismissAlerts' ], 'permission_callback' => [ Permissions::class, 'adminOnly' ], 'args' => [ // Not "required": WordPress validates args before the permission // check, so a visitor would get 400 instead of 401. Empty → 400 below. 'keys' => [ 'type' => 'array', 'maxItems' => 200, 'items' => [ 'type' => 'string', 'maxLength' => 64, ], ], ], ] ); } /** * GET /dashboard * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response */ public function getItem( \WP_REST_Request $request ): \WP_REST_Response { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found $allSources = $this->sources->findAll(); $allFeeds = $this->feeds->findAll(); // Resolved once per feed; reused by onboarding, attention and the feed list. $placementsByFeed = []; foreach ( $allFeeds as $feed ) { $feedId = (int) $feed['id']; $placementsByFeed[ $feedId ] = $this->placements->getPublishedPlacements( $feedId ); } $attention = $this->buildAttention( $allSources, $allFeeds, $placementsByFeed ); return new \WP_REST_Response( [ 'onboarding' => $this->buildOnboarding( $allSources, $allFeeds, $placementsByFeed ), 'attention' => $attention, 'feeds' => $this->buildRecentFeeds( $allFeeds, $attention, $placementsByFeed ), 'feeds_total' => count( $allFeeds ), 'accounts' => $this->buildAccounts( $allSources ), 'accounts_total' => count( $allSources ), 'top_posts' => $this->buildTopPosts(), 'sync' => $this->buildSync( $allSources ), ], 200 ); } /** * A feed counts as "on the site" when it is published and either rendered on * a published page/post or used in a block-theme template. * * @param array $feed Feed row. * @param array> $placementsByFeed Placements keyed by feed id. */ private function isPlaced( array $feed, array $placementsByFeed ): bool { return ! empty( $feed['is_headless'] ) || ! empty( $placementsByFeed[ (int) $feed['id'] ] ); } /** * @param array> $sources * @param array> $feeds * @param array> $placementsByFeed * @return array */ private function buildOnboarding( array $sources, array $feeds, array $placementsByFeed ): array { $dismissed = (bool) get_option( self::OPTION_DISMISSED, false ); $hasSource = ! empty( $sources ); $hasFeed = ! empty( $feeds ); $hasPlacement = false; foreach ( $feeds as $feed ) { if ( 'publish' === (string) $feed['status'] && $this->isPlaced( $feed, $placementsByFeed ) ) { $hasPlacement = true; break; } } $complete = $hasSource && $hasFeed && $hasPlacement; // "You're all set" is shown until the UI acknowledges it (POST /onboarding/ack-complete), // i.e. once. Dismissing the guide skips it. Reading never changes state. $showAllSet = $complete && ! $dismissed && ! (bool) get_option( self::OPTION_CELEBRATED, false ); return [ 'dismissed' => $dismissed, 'has_source' => $hasSource, 'source_name' => $hasSource ? (string) $sources[0]['name'] : null, 'has_feed' => $hasFeed, 'has_placement' => $hasPlacement, 'complete' => $complete, 'show_guide' => ! $dismissed && ! $complete, 'show_all_set' => $showAllSet, ]; } /** * Builds the "Needs attention" list: every alert, most severe first. * * Severity and order: errors (source_expired, source_sync_issue), warnings * (token_expiring, media_failed), info (feed_not_placed, feed_empty). Each item * carries a stable `key` and its `severity`; the dashboard groups items of the * same type and caps what it shows. Info items the current user dismissed are * left out until their condition clears (the dismissal is then forgotten, so the * alert returns if the condition happens again). A feed appears once, with its * most important message. * * Account alerts (errors: Disconnected, Sync issue / retries exhausted; warning: * access expires in N days) are raised only for accounts used by at least one * PUBLISHED feed: an account that only drafts use, or no feed at all, affects * nothing on the site. Its status still * shows in the Accounts card and on Connected Accounts. * * @param array> $sources * @param array> $feeds * @param array> $placementsByFeed * @return array> */ private function buildAttention( array $sources, array $feeds, array $placementsByFeed ): array { $expired = []; $syncIssue = []; $expiring = []; $notPlace = []; $empty = []; // Accounts that feed something visitors can see. $inPublishedFeed = []; foreach ( $feeds as $feed ) { if ( 'publish' !== (string) $feed['status'] ) { continue; } foreach ( $this->feeds->getSources( (int) $feed['id'] ) as $link ) { $inPublishedFeed[ (int) $link['source_id'] ] = true; } } foreach ( $sources as $source ) { $sourceId = (int) $source['id']; $computed = SourceStatus::compute( $source ); $base = [ 'source_id' => $sourceId, 'name' => (string) $source['name'], 'network' => (string) $source['network'], ]; $live = isset( $inPublishedFeed[ $sourceId ] ); if ( 'expired' === $computed['ui_status'] ) { if ( $live ) { $expired[] = [ 'type' => 'source_expired' ] + $base; } continue; } // Retries exhausted: the sync failed and no automatic retry is scheduled // (Sync issue → Retry now). While a retry is scheduled ("retrying") there is no alert. if ( 'sync_issue' === $computed['ui_status'] ) { if ( $live ) { $syncIssue[] = [ 'type' => 'source_sync_issue' ] + $base; } continue; } // An access token still this close to expiry means the automatic refresh did not succeed. $daysLeft = $this->daysUntilExpiry( $source ); if ( $live && null !== $daysLeft && $daysLeft > 0 && $daysLeft <= self::TOKEN_EXPIRY_DAYS ) { $expiring[] = [ 'type' => 'token_expiring', 'days_left' => $daysLeft, ] + $base; } } $failedMedia = $this->media->countFailed(); $mediaItems = []; if ( $failedMedia > 0 ) { $mediaItems[] = [ 'type' => 'media_failed', 'count' => $failedMedia, ]; } // Feed-level notices (not placed, no posts) are only actionable when at // least one account is connected. Without accounts the user must connect // first; showing feed notices alongside the setup guide is just noise. if ( ! empty( $sources ) ) { foreach ( $feeds as $feed ) { // Drafts are never public, so neither "not placed" nor "empty" applies to them. if ( 'publish' !== (string) $feed['status'] ) { continue; } $feedId = (int) $feed['id']; if ( ! $this->isPlaced( $feed, $placementsByFeed ) ) { $notPlace[] = [ 'type' => 'feed_not_placed', 'feed_id' => $feedId, 'name' => (string) $feed['name'], ]; } if ( empty( $this->posts->findByFeedForRender( $feedId, 1, 0 ) ) ) { $empty[] = [ 'type' => 'feed_empty', 'feed_id' => $feedId, 'name' => (string) $feed['name'], ]; } } } $info = array_merge( $notPlace, $empty ); // Forget dismissals whose condition cleared, then hide the rest. $dismissed = DismissedAlerts::prune( get_current_user_id(), array_map( [ $this, 'alertKey' ], $info ) ); // One row per feed: the first (most important) remaining message wins. $seenFeeds = []; $infoShown = []; foreach ( $info as $item ) { if ( in_array( $this->alertKey( $item ), $dismissed, true ) || isset( $seenFeeds[ $item['feed_id'] ] ) ) { continue; } $seenFeeds[ $item['feed_id'] ] = true; $infoShown[] = $item; } $result = []; foreach ( [ 'error' => array_merge( $expired, $syncIssue ), 'warning' => array_merge( $expiring, $mediaItems ), 'info' => $infoShown, ] as $severity => $items ) { foreach ( $items as $item ) { $result[] = [ 'key' => $this->alertKey( $item ), 'severity' => $severity, 'dismissible' => 'info' === $severity, ] + $item; } } return $result; } /** * Stable alert key: ":", or the bare type. * * @param array $item Alert item. */ private function alertKey( array $item ): string { if ( isset( $item['feed_id'] ) ) { return $item['type'] . ':' . (int) $item['feed_id']; } if ( isset( $item['source_id'] ) ) { return $item['type'] . ':' . (int) $item['source_id']; } return (string) $item['type']; } /** * POST /dashboard/alerts/dismiss — hides info alerts for the current user. * * Only `feed_not_placed:` and `feed_empty:` keys are accepted; errors * and warnings cannot be dismissed (400). * * @param \WP_REST_Request $request Incoming REST request. * @return \WP_REST_Response|\WP_Error */ public function dismissAlerts( \WP_REST_Request $request ) { $keys = array_map( 'strval', (array) $request->get_param( 'keys' ) ); if ( empty( $keys ) ) { return new \WP_Error( 'rest_missing_callback_param', __( 'Missing parameter: keys.', 'feednetic' ), [ 'status' => 400 ] ); } foreach ( $keys as $key ) { if ( ! DismissedAlerts::isDismissibleKey( $key ) ) { return new \WP_Error( 'feednetic_alert_not_dismissible', __( 'This alert cannot be dismissed.', 'feednetic' ), [ 'status' => 400 ] ); } } $stored = DismissedAlerts::add( get_current_user_id(), $keys ); return new \WP_REST_Response( [ 'dismissed' => $stored ], 200 ); } /** * Whole days until the source's earliest credential expiry, or null when neither * token_expires_at nor data_access_expires_at is set. * * Facebook page tokens never expire (token_expires_at = NULL) but the underlying * data access authorization expires 90 days from the last user OAuth login — * stored in data_access_expires_at. We return the minimum of both so the amber * warning fires for whichever deadline comes first. * * @param array $source Source row. */ private function daysUntilExpiry( array $source ): ?int { $candidates = []; foreach ( [ 'token_expires_at', 'data_access_expires_at' ] as $col ) { if ( empty( $source[ $col ] ) ) { continue; } try { $expires = new \DateTimeImmutable( (string) $source[ $col ], new \DateTimeZone( 'UTC' ) ); $candidates[] = (int) ceil( ( $expires->getTimestamp() - time() ) / 86400 ); } catch ( \Exception $e ) { unset( $e ); } } if ( empty( $candidates ) ) { return null; } return min( $candidates ); } /** * Feeds for the "Your feeds" card (at most CARD_ROWS). * * @param array> $allFeeds * @param array> $attention Alerts shown on the dashboard (dismissed ones removed). * @param array> $placementsByFeed * @return array> */ private function buildRecentFeeds( array $allFeeds, array $attention, array $placementsByFeed ): array { $result = []; // Feeds with a (not dismissed) alert first, then most recently updated. $alerted = []; foreach ( $attention as $item ) { if ( isset( $item['feed_id'] ) ) { $alerted[ (int) $item['feed_id'] ] = true; } } usort( $allFeeds, static function ( array $a, array $b ) use ( $alerted ): int { $byAlert = (int) isset( $alerted[ (int) $b['id'] ] ) <=> (int) isset( $alerted[ (int) $a['id'] ] ); if ( 0 !== $byAlert ) { return $byAlert; } $byUpdated = strcmp( (string) ( $b['updated_at'] ?? '' ), (string) ( $a['updated_at'] ?? '' ) ); return 0 !== $byUpdated ? $byUpdated : (int) $b['id'] <=> (int) $a['id']; } ); foreach ( array_slice( $allFeeds, 0, self::CARD_ROWS ) as $row ) { $feedId = (int) $row['id']; $sourceCount = count( $this->feeds->getSources( $feedId ) ); $settings = json_decode( (string) ( $row['settings'] ?? '{}' ), true ); $layout = is_array( $settings ) ? (string) ( $settings['layout'] ?? 'grid' ) : 'grid'; $result[] = [ 'id' => $feedId, 'name' => (string) $row['name'], 'status' => (string) $row['status'], 'in_templates' => ! empty( $row['is_headless'] ), 'placements' => $placementsByFeed[ $feedId ] ?? [], 'preview_thumbs' => $this->feedThumbs( $feedId ), 'updated_at' => (string) $row['updated_at'], 'source_count' => $sourceCount, 'layout' => $layout, ]; } return $result; } /** * Up to four local thumbnail URLs from a feed's newest visible posts. * * @return string[] */ private function feedThumbs( int $feedId ): array { $rows = $this->posts->findByFeedForRender( $feedId, 4, 0 ); if ( empty( $rows ) ) { return []; } $mediaMap = $this->media->findFirstDoneByPostIds( array_map( 'intval', array_column( $rows, 'id' ) ) ); $thumbs = []; foreach ( $rows as $row ) { $url = $this->thumbnailUrl( $mediaMap[ (int) $row['id'] ] ?? null ); if ( null !== $url ) { $thumbs[] = $url; } } return $thumbs; } /** * @param array> $allSources * @return array> */ private function buildAccounts( array $allSources ): array { $result = []; $uploadDir = wp_upload_dir(); $base = trailingslashit( (string) $uploadDir['baseurl'] ); // Problems first (Disconnected, Sync issue, Retrying), then Active; // within a group the most recently synced first (never synced last). $rank = [ 'expired' => 0, 'sync_issue' => 1, 'retrying' => 2, 'active' => 3, ]; $computed = []; foreach ( $allSources as $source ) { $computed[ (int) $source['id'] ] = SourceStatus::compute( $source ); } usort( $allSources, static function ( array $a, array $b ) use ( $rank, $computed ): int { $byStatus = ( $rank[ $computed[ (int) $a['id'] ]['ui_status'] ] ?? 3 ) <=> ( $rank[ $computed[ (int) $b['id'] ]['ui_status'] ] ?? 3 ); if ( 0 !== $byStatus ) { return $byStatus; } $bySync = strcmp( (string) ( $b['last_fetched_at'] ?? '' ), (string) ( $a['last_fetched_at'] ?? '' ) ); return 0 !== $bySync ? $bySync : (int) $a['id'] <=> (int) $b['id']; } ); foreach ( array_slice( $allSources, 0, self::CARD_ROWS ) as $source ) { $id = (int) $source['id']; $status = $computed[ $id ]; $avatarUrl = \Feednetic\Media\AvatarFile::url( $source ); $avatarUrl = '' !== $avatarUrl ? $avatarUrl : null; $followersCount = isset( $source['followers_count'] ) ? (int) $source['followers_count'] : null; $delta7d = null; if ( null !== $followersCount ) { $old = $this->stats->getFollowersDeltaDays( $id, 7 ); if ( null !== $old ) { $delta7d = $followersCount - $old; } } $lastFetched = isset( $source['last_fetched_at'] ) && '' !== (string) $source['last_fetched_at'] ? (string) $source['last_fetched_at'] : null; $daysUntilExpiry = $this->daysUntilExpiry( $source ); $result[] = [ 'id' => $id, 'network' => (string) $source['network'], 'platform' => (string) preg_replace( '/^fake_/', '', (string) $source['network'] ), 'name' => (string) $source['name'], 'username' => (string) $source['username'], 'avatar_url' => $avatarUrl, 'followers_count' => $followersCount, 'followers_delta_7d' => $delta7d, 'ui_status' => $status['ui_status'], 'next_fetch_at' => $status['next_fetch_at'], 'last_fetched_at' => $lastFetched, 'days_until_expiry' => $daysUntilExpiry, ]; } return $result; } /** * Up to five visible posts from the last 30 days, ranked by likes + comments. * * @return array> */ private function buildTopPosts(): array { $rows = $this->posts->findTopByDateRange( time() - 30 * DAY_IN_SECONDS, time(), 5 ); if ( empty( $rows ) ) { return []; } $mediaMap = $this->media->findFirstDoneByPostIds( array_map( 'intval', array_column( $rows, 'id' ) ) ); $result = []; foreach ( $rows as $row ) { $metrics = []; if ( ! empty( $row['metrics'] ) ) { $decoded = json_decode( (string) $row['metrics'], true ); $metrics = is_array( $decoded ) ? $decoded : []; } $text = isset( $row['text'] ) ? trim( (string) $row['text'] ) : ''; $result[] = [ 'id' => (int) $row['id'], 'network' => (string) $row['network'], 'type' => (string) $row['type'], 'permalink' => (string) $row['permalink'], 'published_at' => (string) $row['published_at'], 'caption' => '' !== $text ? mb_substr( $text, 0, 120 ) : null, 'thumbnail' => $this->thumbnailUrl( $mediaMap[ (int) $row['id'] ] ?? null ), 'likes' => isset( $metrics['likes'] ) ? (int) $metrics['likes'] : null, 'comments' => isset( $metrics['comments'] ) ? (int) $metrics['comments'] : null, ]; } return $result; } /** * Smallest processed local variant of a media row as an absolute URL, or null. * * @param array|null $mediaRow First done media row of a post. */ private function thumbnailUrl( ?array $mediaRow ): ?string { if ( null === $mediaRow || empty( $mediaRow['variants'] ) ) { return null; } $variants = json_decode( (string) $mediaRow['variants'], true ); if ( ! is_array( $variants ) ) { return null; } $uploadDir = wp_upload_dir(); $base = trailingslashit( (string) $uploadDir['baseurl'] ); foreach ( [ '320', '640', '800', '1080' ] as $size ) { if ( ! isset( $variants[ $size ] ) || ! is_array( $variants[ $size ] ) ) { continue; } $formats = $variants[ $size ]; $path = $formats['webp'] ?? reset( $formats ); if ( is_string( $path ) && '' !== $path ) { return $base . $path; } } return null; } /** * Footer data: last/next sync (derived from the sources), visible posts, image storage. * * @param array> $sources * @return array */ private function buildSync( array $sources ): array { $last = null; $next = null; foreach ( $sources as $source ) { if ( ! empty( $source['last_fetched_at'] ) && ( null === $last || (string) $source['last_fetched_at'] > $last ) ) { $last = (string) $source['last_fetched_at']; } if ( 'active' !== (string) ( $source['status'] ?? '' ) ) { continue; } $scheduled = as_next_scheduled_action( 'feednetic/fetch_source', [ 'source_id' => (int) $source['id'] ], Scheduler::GROUP ); if ( is_int( $scheduled ) && $scheduled > time() && ( null === $next || $scheduled < $next ) ) { $next = $scheduled; } } // The cleanup job refreshes this daily; compute it once on first use. $mediaBytes = get_option( 'feednetic_media_bytes', false ); if ( false === $mediaBytes ) { $mediaBytes = ( new StorageUsage() )->bytes(); update_option( 'feednetic_media_bytes', $mediaBytes, false ); } return [ 'last_sync_at' => $last, 'next_sync_at' => null !== $next ? gmdate( 'Y-m-d H:i:s', $next ) : null, 'posts_total' => $this->posts->countTotal(), 'media_bytes' => (int) $mediaBytes, ]; } }