lastUpsertWasInsert; } /** * Inserts or updates a normalized post and returns its DB id. * * API-derived fields are always refreshed. Columns not derived from the API (moderation, * linked_object_*) are never touched, so values written by add-ons survive a re-fetch. */ public function upsert( int $sourceId, string $stream, Post $post ): int { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed $existingId = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}feednetic_posts WHERE source_id = %d AND stream = %s AND external_id = %s", $sourceId, $stream, $post->externalId ) ); $now = gmdate( 'Y-m-d H:i:s' ); $data = $this->postToRow( $sourceId, $stream, $post ); if ( 0 === $existingId ) { $data['fetched_at'] = $now; $data['updated_at'] = $now; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed $wpdb->insert( "{$wpdb->prefix}feednetic_posts", $data, $this->formatFor( $data ) ); $this->lastUpsertWasInsert = true; return (int) $wpdb->insert_id; } $data['updated_at'] = $now; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed $wpdb->update( "{$wpdb->prefix}feednetic_posts", $data, [ 'id' => $existingId ], $this->formatFor( $data ), [ '%d' ] ); $this->lastUpsertWasInsert = false; return $existingId; } /** * Returns a single post row by primary key, or null. * * @return array|null */ public function findById( int $id ): ?array { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}feednetic_posts WHERE id = %d", $id ), ARRAY_A ); return is_array( $row ) ? $row : null; } /** * Returns posts for a source, ordered newest-first. * * @return array> */ public function findBySource( int $sourceId, string $stream = 'timeline', int $limit = 20, int $offset = 0 ): array { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `{$wpdb->prefix}feednetic_posts` WHERE source_id = %d AND stream = %s ORDER BY published_at DESC LIMIT %d OFFSET %d", $sourceId, $stream, $limit, $offset ), ARRAY_A ); return is_array( $rows ) ? $rows : []; } /** * Returns posts for a source for the admin Posts screen, newest-first. * * $extraWhere is a prepared SQL fragment (starting with "AND") supplied through * feednetic/rest/source_posts_where; it runs before LIMIT/OFFSET so add-on * filters never leave pagination gaps. * * @return array> */ public function findBySourceFiltered( int $sourceId, int $limit = 24, int $offset = 0, string $stream = 'timeline', string $extraWhere = '' ): array { global $wpdb; $sql = (string) $wpdb->prepare( "SELECT * FROM `{$wpdb->prefix}feednetic_posts` WHERE source_id = %d AND stream = %s", $sourceId, $stream ); $sql .= '' !== trim( $extraWhere ) ? ' ' . trim( $extraWhere ) : ''; $sql .= $wpdb->prepare( ' ORDER BY published_at DESC, id DESC LIMIT %d OFFSET %d', $limit, $offset ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- fragments prepared above; $extraWhere must be prepared by the caller $rows = $wpdb->get_results( $sql, ARRAY_A ); return is_array( $rows ) ? $rows : []; } /** * Counts posts for the admin Posts screen (same filter as findBySourceFiltered). */ public function countBySourceFiltered( int $sourceId, string $stream = 'timeline', string $extraWhere = '' ): int { global $wpdb; $sql = (string) $wpdb->prepare( "SELECT COUNT(*) FROM `{$wpdb->prefix}feednetic_posts` WHERE source_id = %d AND stream = %s", $sourceId, $stream ); $sql .= '' !== trim( $extraWhere ) ? ' ' . trim( $extraWhere ) : ''; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- fragments prepared above; $extraWhere must be prepared by the caller return (int) $wpdb->get_var( $sql ); } /** * Returns the number of posts for a source/stream. */ public function countBySource( int $sourceId, string $stream = 'timeline' ): int { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM `{$wpdb->prefix}feednetic_posts` WHERE source_id = %d AND stream = %s", $sourceId, $stream ) ); } /** * Deletes posts for a source/stream whose external_id is NOT in $fetchedIds * and whose published_at falls within [$windowStart, $windowEnd] (Unix timestamps). * Deletes associated media rows first (no FK cascade). * * Only runs when $fetchedIds is non-empty so an empty API response never wipes the window. * * @param string[] $fetchedIds External IDs returned by the most recent API call. */ public function deleteRemovedFromWindow( int $sourceId, string $stream, array $fetchedIds, int $windowStart, int $windowEnd ): int { if ( empty( $fetchedIds ) ) { return 0; } return $this->deleteByIds( $this->findIdsNotFetched( $sourceId, $stream, $fetchedIds, $windowStart, $windowEnd ) ); } /** * Row ids of the stored posts of a source/stream whose external_id is not * in $fetchedIds. With a window, only posts published inside * [$windowStart, $windowEnd] (Unix timestamps); without one, all of them * (an empty $fetchedIds then returns every post of the source/stream). * * @param string[] $fetchedIds External IDs returned by the API. * @return int[] */ public function findIdsNotFetched( int $sourceId, string $stream, array $fetchedIds, ?int $windowStart = null, ?int $windowEnd = null ): array { global $wpdb; // No external id is empty, so NOT IN ('') keeps every post. $fetchedIds = array_values( array_map( 'strval', $fetchedIds ) ); if ( empty( $fetchedIds ) ) { $fetchedIds = [ '' ]; } if ( null !== $windowStart && null !== $windowEnd ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table $ids = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}feednetic_posts WHERE source_id = %d AND stream = %s AND published_at BETWEEN %s AND %s AND external_id NOT IN (" . implode( ',', array_fill( 0, count( $fetchedIds ), '%s' ) ) . ')', array_merge( [ $sourceId, $stream, gmdate( 'Y-m-d H:i:s', $windowStart ), gmdate( 'Y-m-d H:i:s', $windowEnd ) ], $fetchedIds ) ) ); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table $ids = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}feednetic_posts WHERE source_id = %d AND stream = %s AND external_id NOT IN (" . implode( ',', array_fill( 0, count( $fetchedIds ), '%s' ) ) . ')', array_merge( [ $sourceId, $stream ], $fetchedIds ) ) ); } return array_map( 'intval', (array) $ids ); } /** * Deletes posts by row id, with their media rows (no FK cascade). * Returns the number of posts deleted. * * @param int[] $ids */ public function deleteByIds( array $ids ): int { global $wpdb; $ids = array_values( array_unique( array_filter( array_map( 'intval', $ids ) ) ) ); if ( empty( $ids ) ) { return 0; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}feednetic_media WHERE post_id IN (" . implode( ',', array_fill( 0, count( $ids ), '%d' ) ) . ')', $ids ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table return (int) $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}feednetic_posts WHERE id IN (" . implode( ',', array_fill( 0, count( $ids ), '%d' ) ) . ')', $ids ) ); } /** * Deletes posts for a source/stream beyond the newest $maxPosts rows. * Also deletes their associated media rows. Returns the count of posts deleted. */ public function pruneBySource( int $sourceId, string $stream, int $maxPosts ): int { global $wpdb; if ( $maxPosts <= 0 ) { return 0; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed $row = $wpdb->get_row( $wpdb->prepare( "SELECT id, published_at FROM `{$wpdb->prefix}feednetic_posts` WHERE source_id = %d AND stream = %s ORDER BY published_at DESC, id DESC LIMIT 1 OFFSET %d", $sourceId, $stream, $maxPosts - 1 ), ARRAY_A ); if ( ! is_array( $row ) ) { return 0; } $cutoffId = (int) $row['id']; $cutoffPublishedAt = (string) $row['published_at']; // Delete media rows for posts that will be pruned. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed $wpdb->query( $wpdb->prepare( "DELETE m FROM `{$wpdb->prefix}feednetic_media` m JOIN `{$wpdb->prefix}feednetic_posts` p ON p.id = m.post_id WHERE p.source_id = %d AND p.stream = %s AND (p.published_at < %s OR (p.published_at = %s AND p.id < %d))", $sourceId, $stream, $cutoffPublishedAt, $cutoffPublishedAt, $cutoffId ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed return (int) $wpdb->query( $wpdb->prepare( "DELETE FROM `{$wpdb->prefix}feednetic_posts` WHERE source_id = %d AND stream = %s AND (published_at < %s OR (published_at = %s AND id < %d))", $sourceId, $stream, $cutoffPublishedAt, $cutoffPublishedAt, $cutoffId ) ); } /** * Deletes all posts (and triggers cascading media deletes via the media repo). */ public function deleteBySourceId( int $sourceId ): void { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed $wpdb->delete( "{$wpdb->prefix}feednetic_posts", [ 'source_id' => $sourceId ], [ '%d' ] ); } /** * Returns the posts of a feed's account whose media is fully processed, * newest-first. Posts with no media rows at all are always included; posts * with a pending media row are excluded. Page updates / text posts are * filtered in SQL so LIMIT is applied after the filter and paging never has * gaps. * * The account is the feed's first-position feed_sources row (the "source" * clause). Add-ons extend the query through feednetic/render/query_clauses; * an add-on may replace "source" with its own prepared condition. * * $context describes a render that is not the stored feed: the editor * preview passes ['mode' => 'preview', 'source_id' => …] (and add-ons their * own unsaved state), so the default "source" clause reads that account. * * @param array $settings Merged feed settings (passed to the clauses filter). * @param array $context Render context (passed to the clauses filter). * @return array> */ public function findByFeedForRender( int $feedId, int $limit = 12, int $offset = 0, bool $hidePageUpdates = false, bool $excludeText = false, array $settings = [], array $context = [] ): array { global $wpdb; $clauses = $this->renderQueryClauses( $feedId, $settings, 'p.published_at DESC', $context ); $filters = ''; $args = []; if ( $hidePageUpdates ) { $filters .= ' AND p.is_page_update = %d'; $args[] = 0; } if ( $excludeText ) { $filters .= ' AND p.type != %s'; $args[] = 'text'; } if ( ! empty( $args ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- literal fragments + placeholders $filters = (string) $wpdb->prepare( $filters, $args ); } // The source clause is prepared SQL already (renderQueryClauses()). $where = 'WHERE ' . $clauses['source'] . $filters . " AND NOT EXISTS ( SELECT 1 FROM {$wpdb->prefix}feednetic_media m WHERE m.post_id = p.id AND m.status = 'pending' )"; $sql = "SELECT p.* FROM {$wpdb->prefix}feednetic_posts p" . $clauses['join'] . ' ' . $where . $clauses['where'] . ' ORDER BY ' . $clauses['orderby'] . $wpdb->prepare( ' LIMIT %d OFFSET %d', $limit, $offset ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- every fragment is prepared above; add-on clauses must be prepared by the add-on $rows = $wpdb->get_results( $sql, ARRAY_A ); return is_array( $rows ) ? $rows : []; } /** * The default "source" clause: posts of the feed's first-position account * (same order as FeedRepository::getPrimarySource()). Prepared SQL. */ private function primarySourceClause( int $feedId ): string { global $wpdb; return (string) $wpdb->prepare( "( p.source_id, p.stream ) = ( SELECT fs.source_id, fs.stream FROM {$wpdb->prefix}feednetic_feed_sources fs WHERE fs.feed_id = %d ORDER BY fs.position ASC, fs.source_id ASC LIMIT 1 )", $feedId ); } /** * Builds the extensible SQL clauses for the feed render query. * * Add-ons extend the query through `feednetic/render/query_clauses`. Each clause * must already be prepared SQL (run values through $wpdb->prepare()). The posts * table is aliased `p`. "source" selects the posts' account (default: the * feed's first-position account); an empty "source" keeps the default. * * @param array $settings Merged feed settings. * @param array $context Render context ('mode', 'source_id', add-on keys). * @return array{source:string,join:string,where:string,orderby:string} */ private function renderQueryClauses( int $feedId, array $settings, string $defaultOrderBy, array $context = [] ): array { global $wpdb; $sourceId = (int) ( $context['source_id'] ?? 0 ); $defaults = [ // An explicit account (unsaved editor selection), else the feed's first account. 'source' => $sourceId > 0 ? (string) $wpdb->prepare( 'p.source_id = %d AND p.stream = %s', $sourceId, 'timeline' ) : $this->primarySourceClause( $feedId ), 'join' => '', 'where' => '', 'orderby' => $defaultOrderBy, ]; // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores $clauses = apply_filters( 'feednetic/render/query_clauses', $defaults, $feedId, $settings, $context ); $clauses = is_array( $clauses ) ? array_merge( $defaults, $clauses ) : $defaults; $source = trim( (string) $clauses['source'] ); $orderby = trim( (string) $clauses['orderby'] ); return [ 'source' => '' !== $source ? $source : $defaults['source'], 'join' => '' !== trim( (string) $clauses['join'] ) ? ' ' . trim( (string) $clauses['join'] ) : '', 'where' => '' !== trim( (string) $clauses['where'] ) ? ' ' . trim( (string) $clauses['where'] ) : '', 'orderby' => '' !== $orderby ? $orderby : $defaultOrderBy, ]; } /** * Returns the total count of posts across all sources. */ public function countTotal(): int { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}feednetic_posts" // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared ); } /** * Returns the top $limit visible posts (by likes+comments) published between * two Unix timestamps, ordered descending by combined engagement score. * * @return array> */ public function findTopByDateRange( int $dateFrom, int $dateTo, int $limit = 5 ): array { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table, no caching layer needed $rows = $wpdb->get_results( $wpdb->prepare( "SELECT p.* FROM {$wpdb->prefix}feednetic_posts p WHERE p.published_at BETWEEN %s AND %s ORDER BY ( CAST(COALESCE(NULLIF(JSON_UNQUOTE(JSON_EXTRACT(p.metrics, '$.likes')), 'null'), '0') AS UNSIGNED) + CAST(COALESCE(NULLIF(JSON_UNQUOTE(JSON_EXTRACT(p.metrics, '$.comments')), 'null'), '0') AS UNSIGNED) ) DESC, p.published_at DESC, p.id DESC LIMIT %d", gmdate( 'Y-m-d H:i:s', $dateFrom ), gmdate( 'Y-m-d H:i:s', $dateTo ), $limit ), ARRAY_A ); return is_array( $rows ) ? $rows : []; } /** * Converts a Post model to a DB column → value map (no id/fetched_at/updated_at). * * @return array */ private function postToRow( int $sourceId, string $stream, Post $post ): array { return [ 'source_id' => $sourceId, 'stream' => $stream, 'network' => $post->network, 'external_id' => $post->externalId, 'type' => $post->type, 'text' => $post->text, 'permalink' => $post->permalink, 'author_name' => $post->author->name, 'author_handle' => $post->author->handle, 'author_avatar' => $post->author->avatarUrl, 'published_at' => $post->publishedAt->format( 'Y-m-d H:i:s' ), 'metrics' => null !== $post->metrics ? (string) wp_json_encode( [ 'likes' => $post->metrics->likes, 'comments' => $post->metrics->comments, 'views' => $post->metrics->views, 'shares' => $post->metrics->shares, ] ) : null, 'extra' => null !== $post->extra ? (string) wp_json_encode( $post->extra ) : null, 'is_page_update' => ( is_array( $post->extra ) && 'page_update' === (string) ( $post->extra['fb_post_subtype'] ?? '' ) ) ? 1 : 0, ]; } /** * Derives a wpdb format array from a data array. * * @param array $data * @return string[] */ private function formatFor( array $data ): array { return array_map( static function ( $value ): string { return is_int( $value ) ? '%d' : '%s'; }, $data ); } }