migrator()->run(); $this->maybeAllowLocalRequests(); $this->registerAdapters(); $this->registerLayouts(); $this->registerJobs(); $this->registerTriggers(); $this->fileCleanup()->register(); $this->oauthCallbackHandler()->register(); $this->cachePurger()->register(); $this->feedsPostsController()->register(); $this->sourcesController()->register(); $this->connectController()->register(); $this->feedsController()->register(); $this->previewController()->register(); $this->dashboardController()->register(); $this->onboardingController()->register(); $this->mediaRetryController()->register(); $this->settingsController()->register(); $this->registerFeedSettingsSchema(); $this->adminPage()->register(); ( new \Feednetic\Admin\PrivacyPolicy() )->register(); $this->feedBlock()->register(); $this->registerShortcode(); $this->registerElementorWidget(); add_action( 'action_scheduler_init', [ $this->scheduler(), 'scheduleCleanup' ] ); /** * Fires once the free plugin has wired its services. Add-ons register their * own integrations here and may use the container's public accessors. * * @param Plugin $plugin The free plugin container. */ // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores do_action( 'feednetic/register_integrations', $this ); add_action( 'wp_enqueue_scripts', [ FeedRenderer::class, 'registerAssets' ] ); } // ── Service accessors ───────────────────────────────────────────────────── public function migrator(): Migrator { if ( null === $this->migrator ) { $this->migrator = new Migrator(); } return $this->migrator; } public function httpClient(): WpHttpClient { if ( null === $this->httpClient ) { $this->httpClient = new WpHttpClient(); } return $this->httpClient; } public function sourceRepository(): SourceRepository { if ( null === $this->sourceRepository ) { $this->sourceRepository = new SourceRepository(); } return $this->sourceRepository; } public function feedRepository(): FeedRepository { if ( null === $this->feedRepository ) { $this->feedRepository = new FeedRepository(); } return $this->feedRepository; } public function postRepository(): PostRepository { if ( null === $this->postRepository ) { $this->postRepository = new PostRepository(); } return $this->postRepository; } public function mediaRepository(): MediaRepository { if ( null === $this->mediaRepository ) { $this->mediaRepository = new MediaRepository(); } return $this->mediaRepository; } public function instagramAdapter(): InstagramAdapter { if ( null === $this->instagramAdapter ) { $this->instagramAdapter = new InstagramAdapter( $this->httpClient() ); } return $this->instagramAdapter; } public function facebookAdapter(): FacebookAdapter { if ( null === $this->facebookAdapter ) { $this->facebookAdapter = new FacebookAdapter( $this->httpClient() ); } return $this->facebookAdapter; } public function tokenEncryption(): TokenEncryption { if ( null === $this->tokenEncryption ) { $this->tokenEncryption = new TokenEncryption(); } return $this->tokenEncryption; } public function logger(): WpLogger { if ( null === $this->logger ) { $this->logger = new WpLogger(); } return $this->logger; } public function scheduler(): Scheduler { if ( null === $this->scheduler ) { $this->scheduler = new Scheduler(); } return $this->scheduler; } public function fetchSourceJob(): FetchSourceJob { if ( null === $this->fetchSourceJob ) { $this->fetchSourceJob = new FetchSourceJob( $this->sourceRepository(), $this->postRepository(), $this->mediaRepository(), $this->feedRepository(), $this->scheduler(), $this->tokenEncryption(), $this->logger() ); } return $this->fetchSourceJob; } public function processMediaJob(): ProcessMediaJob { if ( null === $this->processMediaJob ) { $this->processMediaJob = new ProcessMediaJob( $this->mediaRepository(), $this->postRepository(), $this->mediaProcessor(), $this->logger() ); } return $this->processMediaJob; } public function refreshTokenJob(): RefreshTokenJob { if ( null === $this->refreshTokenJob ) { $this->refreshTokenJob = new RefreshTokenJob( $this->sourceRepository(), $this->scheduler(), $this->tokenEncryption(), $this->logger() ); } return $this->refreshTokenJob; } public function placementRegistry(): PlacementRegistry { if ( null === $this->placementRegistry ) { $this->placementRegistry = new PlacementRegistry(); } return $this->placementRegistry; } public function cleanupJob(): CleanupJob { if ( null === $this->cleanupJob ) { $this->cleanupJob = new CleanupJob( $this->postRepository(), $this->sourceStatsRepository(), $this->logger(), $this->placementRegistry() ); } return $this->cleanupJob; } public function sourceStatsRepository(): SourceStatsRepository { if ( null === $this->sourceStatsRepository ) { $this->sourceStatsRepository = new SourceStatsRepository(); } return $this->sourceStatsRepository; } public function avatarProcessor(): AvatarProcessor { if ( null === $this->avatarProcessor ) { $this->avatarProcessor = new AvatarProcessor( $this->mediaDownloader(), $this->imageProcessor() ); } return $this->avatarProcessor; } public function refreshProfileJob(): RefreshProfileJob { if ( null === $this->refreshProfileJob ) { $this->refreshProfileJob = new RefreshProfileJob( $this->sourceRepository(), $this->sourceStatsRepository(), $this->avatarProcessor(), $this->tokenEncryption(), $this->logger() ); } return $this->refreshProfileJob; } public function mediaDownloader(): MediaDownloader { if ( null === $this->mediaDownloader ) { // The dev-only Fake adapter serves fixture images as file:// URLs // (registered under the same check below), so local files are // allowed only then, and only from dev-fixtures/. $isDev = self::devAdaptersEnabled(); $this->mediaDownloader = new MediaDownloader( $this->httpClient(), $isDev, $isDev ? FEEDNETIC_DIR . 'dev-fixtures' : null ); } return $this->mediaDownloader; } public function imageProcessor(): ImageProcessor { if ( null === $this->imageProcessor ) { $this->imageProcessor = new ImageProcessor(); } return $this->imageProcessor; } public function mediaProcessor(): MediaProcessor { if ( null === $this->mediaProcessor ) { $this->mediaProcessor = new MediaProcessor( $this->mediaDownloader(), $this->imageProcessor(), $this->mediaRepository() ); } return $this->mediaProcessor; } public function fileCleanup(): FileCleanup { if ( null === $this->fileCleanup ) { $this->fileCleanup = new FileCleanup(); } return $this->fileCleanup; } public function relayAuthProvider(): RelayAuthProvider { if ( null === $this->relayAuthProvider ) { $this->relayAuthProvider = new RelayAuthProvider( $this->httpClient(), RelayAuthProvider::url() ); } return $this->relayAuthProvider; } public function oauthCallbackHandler(): OauthCallbackHandler { if ( null === $this->oauthCallbackHandler ) { $this->oauthCallbackHandler = new OauthCallbackHandler( $this->relayAuthProvider(), $this->sourceRepository(), $this->tokenEncryption(), $this->logger() ); } return $this->oauthCallbackHandler; } public function templateLocator(): TemplateLocator { if ( null === $this->templateLocator ) { $this->templateLocator = new TemplateLocator(); } return $this->templateLocator; } public function feedRenderer(): FeedRenderer { if ( null === $this->feedRenderer ) { $this->feedRenderer = new FeedRenderer( $this->feedRepository(), $this->postRepository(), $this->mediaRepository(), $this->templateLocator(), $this->placementRegistry(), $this->sourceRepository() ); } return $this->feedRenderer; } public function feedsPostsController(): FeedsPostsController { if ( null === $this->feedsPostsController ) { $this->feedsPostsController = new FeedsPostsController( $this->feedRepository(), $this->feedRenderer() ); } return $this->feedsPostsController; } public function adminPage(): AdminPage { if ( null === $this->adminPage ) { $this->adminPage = new AdminPage(); } return $this->adminPage; } public function feedBlock(): FeedBlock { if ( null === $this->feedBlock ) { $this->feedBlock = new FeedBlock( $this->feedRenderer(), $this->feedRepository() ); } return $this->feedBlock; } public function cachePurger(): CachePurger { if ( null === $this->cachePurger ) { $this->cachePurger = new CachePurger( $this->feedRepository(), $this->placementRegistry() ); } return $this->cachePurger; } public function sourcesController(): SourcesController { if ( null === $this->sourcesController ) { $this->sourcesController = new SourcesController( $this->sourceRepository(), $this->postRepository(), $this->scheduler(), $this->mediaRepository(), $this->feedRepository(), $this->sourceStatsRepository() ); } return $this->sourcesController; } public function connectController(): ConnectController { if ( null === $this->connectController ) { $this->connectController = new ConnectController( $this->relayAuthProvider(), $this->oauthCallbackHandler(), $this->sourceRepository(), $this->tokenEncryption(), $this->httpClient() ); } return $this->connectController; } public function feedsController(): FeedsController { if ( null === $this->feedsController ) { $this->feedsController = new FeedsController( $this->feedRepository(), $this->postRepository(), $this->mediaRepository(), $this->placementRegistry() ); } return $this->feedsController; } public function dashboardController(): DashboardController { if ( null === $this->dashboardController ) { $this->dashboardController = new DashboardController( $this->sourceRepository(), $this->feedRepository(), $this->postRepository(), $this->mediaRepository(), $this->sourceStatsRepository(), $this->placementRegistry() ); } return $this->dashboardController; } public function onboardingController(): OnboardingController { if ( null === $this->onboardingController ) { $this->onboardingController = new OnboardingController(); } return $this->onboardingController; } public function mediaRetryController(): MediaRetryController { if ( null === $this->mediaRetryController ) { $this->mediaRetryController = new MediaRetryController( $this->mediaRepository(), $this->scheduler() ); } return $this->mediaRetryController; } public function settingsController(): SettingsController { if ( null === $this->settingsController ) { $this->settingsController = new SettingsController( $this->sourceRepository(), $this->scheduler() ); } return $this->settingsController; } public function previewController(): PreviewController { if ( null === $this->previewController ) { $this->previewController = new PreviewController( $this->feedRenderer() ); } return $this->previewController; } // ── Private boot helpers ────────────────────────────────────────────────── /** * Development only: lets wp_safe_remote_* reach a relay on localhost or a * private IP. Registered only when FEEDNETIC_DEV_ADAPTERS is explicitly true * (like the fake adapters), never because of WP_ENVIRONMENT_TYPE alone — * hosts often mark staging sites as "development". */ private function maybeAllowLocalRequests(): void { if ( ! defined( 'FEEDNETIC_DEV_ADAPTERS' ) || true !== FEEDNETIC_DEV_ADAPTERS ) { return; } add_filter( 'http_request_host_is_external', static function (): bool { return true; } ); } /** * The dev-only Fake adapters (fake_instagram / fake_facebook) are available * only when FEEDNETIC_DEV_ADAPTERS is explicitly true AND their class * exists — it is not shipped in the release ZIP. Never enabled by * WP_ENVIRONMENT_TYPE alone. */ public static function devAdaptersEnabled(): bool { return defined( 'FEEDNETIC_DEV_ADAPTERS' ) && true === FEEDNETIC_DEV_ADAPTERS && class_exists( FakeAdapter::class ); } private function registerLayouts(): void { // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores add_filter( 'feednetic/layouts', static function ( array $layouts ): array { $layouts['grid'] = 'layouts/grid.php'; $layouts['carousel'] = 'layouts/carousel.php'; return $layouts; } ); } private function registerFeedSettingsSchema(): void { // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores add_filter( 'feednetic/feed_settings_schema', static function ( array $schema ): array { $schema['layout'] = [ 'type' => 'string', 'enum' => [ 'grid', 'carousel' ], 'default' => 'grid', ]; $schema['count'] = [ 'type' => 'integer', 'minimum' => 1, 'maximum' => 50, 'default' => 12, ]; $schema['columns_desktop'] = [ 'type' => 'integer', 'minimum' => 1, 'maximum' => 8, 'default' => 4, ]; $schema['columns_tablet'] = [ 'type' => 'integer', 'minimum' => 1, 'maximum' => 8, 'default' => 3, ]; $schema['columns_mobile'] = [ 'type' => 'integer', 'minimum' => 1, 'maximum' => 8, 'default' => 2, ]; $schema['lightbox'] = [ 'type' => 'boolean', 'default' => true, ]; $schema['header_enabled'] = [ 'type' => 'boolean', 'default' => true, ]; $schema['header_show_followers'] = [ 'type' => 'boolean', 'default' => true, ]; $schema['header_show_bio'] = [ 'type' => 'boolean', 'default' => false, ]; $schema['buttons_follow'] = [ 'type' => 'boolean', 'default' => true, ]; $schema['buttons_load_more'] = [ 'type' => 'boolean', 'default' => true, ]; $schema['load_more'] = [ 'type' => 'boolean', 'default' => true, ]; $schema['style_gap'] = [ 'type' => 'integer', 'minimum' => 0, 'maximum' => 32, 'default' => 8, ]; $schema['style_radius'] = [ 'type' => 'integer', 'minimum' => 0, 'maximum' => 24, 'default' => 6, ]; // The Style tab template the visual values came from (its id). $schema['style_template'] = [ 'type' => 'string', 'default' => '', ]; $schema['hide_fb_page_updates'] = [ 'type' => 'boolean', 'default' => true, ]; $schema['include_text_posts'] = [ 'type' => 'boolean', 'default' => false, ]; return $schema; } ); } private function registerAdapters(): void { // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores add_filter( 'feednetic/adapters', function ( array $adapters ): array { $adapters['instagram'] = $this->instagramAdapter(); $adapters['facebook'] = $this->facebookAdapter(); return $adapters; } ); if ( self::devAdaptersEnabled() ) { // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores add_filter( 'feednetic/adapters', static function ( array $adapters ): array { // Use file:// so MediaDownloader can copy images without HTTP inside wp-env. $baseImageUrl = 'file://' . FEEDNETIC_DIR . 'dev-fixtures/images/'; $fake = new FakeAdapter( $baseImageUrl ); $adapters['fake_instagram'] = $fake; $adapters['fake_facebook'] = $fake; return $adapters; } ); } } private function registerJobs(): void { $this->fetchSourceJob()->register(); $this->processMediaJob()->register(); $this->refreshTokenJob()->register(); $this->cleanupJob()->register(); $this->refreshProfileJob()->register(); } private function registerShortcode(): void { $renderer = $this->feedRenderer(); add_shortcode( 'feednetic', static function ( $atts ) use ( $renderer ): string { // Accept id plus any flat settings key as shortcode attributes. $atts = shortcode_atts( [ 'id' => 0, 'layout' => null, 'count' => null, 'columns_desktop' => null, 'columns_tablet' => null, 'columns_mobile' => null, 'load_more' => null, 'hide_fb_page_updates' => null, ], $atts, 'feednetic' ); $id = (int) $atts['id']; if ( $id <= 0 ) { return ''; } // Build overrides from non-null attributes. $overrides = []; foreach ( $atts as $key => $value ) { if ( 'id' === $key || null === $value ) { continue; } $overrides[ $key ] = $value; } return $renderer->render( $id, $overrides ); } ); } private function registerElementorWidget(): void { add_action( 'elementor/widgets/register', function ( $manager ): void { if ( ! is_object( $manager ) || ! method_exists( $manager, 'register' ) ) { return; } $manager->register( new \Feednetic\Integration\Elementor\FeedneticWidget( [], null, $this->feedRenderer(), $this->feedRepository() ) ); } ); } /** * Wires repository events to scheduling actions. * * feednetic/source_connected — start recurring fetch + run immediately. * feednetic/feed_saved — immediately enqueue a fetch for every attached source. */ /** * Schedules the token refresh for a source whose token expires. * Facebook Page tokens have no expiry and get nothing. * * @param array $source Source row. * @param bool $replace True: reschedule (new token); false: only if none pending. */ private function scheduleTokenRefresh( array $source, bool $replace ): void { if ( empty( $source['token_expires_at'] ) ) { return; } try { $expiresAt = new \DateTimeImmutable( (string) $source['token_expires_at'], new \DateTimeZone( 'UTC' ) ); } catch ( \Exception $e ) { return; } if ( $replace ) { $this->scheduler()->scheduleRefreshToken( (int) $source['id'], $expiresAt ); } else { $this->scheduler()->ensureRefreshToken( (int) $source['id'], $expiresAt ); } } private function registerTriggers(): void { // Ensure every active source has a recurring fetch scheduled. // Runs on init so Action Scheduler is ready; scheduleFetchSource() is a no-op // when the action already exists, so this is safe to run on every request. add_action( 'init', function (): void { $sources = $this->sourceRepository()->findByStatus( 'active' ); foreach ( $sources as $source ) { $this->scheduler()->scheduleFetchSource( (int) $source['id'] ); // Expiring tokens (Instagram, ~60 days) always have a refresh // pending — also for sources connected before this existed. $this->scheduleTokenRefresh( $source, false ); } // Existing schedules keep their old interval otherwise (e.g. one // left by an older version or a changed setting). $this->scheduler()->maybeReconcileFetchSchedules(); } ); // A stored avatar file is missing (seen while rendering or listing): // queue a profile refresh, which downloads it again in the background. // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores add_action( 'feednetic/avatar_missing', function ( int $sourceId ): void { if ( function_exists( 'as_enqueue_async_action' ) ) { $this->scheduler()->enqueueRefreshProfileNow( $sourceId ); } } ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores add_action( 'feednetic/source_connected', function ( int $sourceId ): void { $this->scheduler()->scheduleFetchSource( $sourceId ); $this->scheduler()->enqueueFetchNow( $sourceId ); // New token: refresh ~7 days before it expires, directly with the // network (RefreshTokenJob → adapter); the relay is not involved. $row = $this->sourceRepository()->findById( $sourceId ); if ( null !== $row ) { $this->scheduleTokenRefresh( $row, true ); } $this->scheduler()->enqueueRefreshProfileNow( $sourceId ); // Run the first fetch immediately after the current HTTP response // completes so the admin sees posts without waiting for the next // cron cycle (critical in low-traffic and local-dev environments). add_action( 'shutdown', function () use ( $sourceId ): void { // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- slash-namespaced hooks per project convention do_action( 'feednetic/refresh_profile', $sourceId ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- slash-namespaced hooks per project convention do_action( 'feednetic/fetch_source', $sourceId ); // Process any media that the fetch just enqueued so images // appear immediately instead of waiting for the next cron cycle. $pending = $this->mediaRepository()->findPendingBySource( $sourceId ); foreach ( $pending as $media ) { // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- slash-namespaced hooks per project convention do_action( 'feednetic/process_media', (int) $media['post_id'] ); } } ); } ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores add_action( 'feednetic/feed_saved', function ( int $feedId ): void { foreach ( $this->feedRepository()->getSources( $feedId ) as $source ) { $this->scheduler()->enqueueFetchNow( (int) $source['source_id'] ); } } ); } }