15, 'headers' => [ 'Authorization' => 'Basic ' . base64_encode($key . ':' . $secret), // phpcs:ignore 'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8', ], 'body' => ['grant_type' => 'client_credentials'], ] ); if (is_wp_error($response)) { return ''; } $body = json_decode(wp_remote_retrieve_body($response), true); $token = $body['access_token'] ?? ''; if ('' !== $token) { // Bearer tokens are long-lived; cache for a day. set_transient($cache_key, $token, DAY_IN_SECONDS); } return $token; } /** * GET a v2 endpoint and return the decoded JSON. * * @param string $url Endpoint URL. * @param string $bearer Bearer token. * * @return array */ protected static function api_get($url, $bearer) { $response = wp_remote_get( $url, [ 'timeout' => 15, 'headers' => ['Authorization' => 'Bearer ' . $bearer], ] ); if (is_wp_error($response)) { return []; } $data = json_decode(wp_remote_retrieve_body($response), true); return is_array($data) ? $data : []; } /** * Fetch recent tweets for a username via the X API v2, normalised into the * legacy item shape and cached. * * @param string $key Consumer key. * @param string $secret Consumer secret. * @param string $username Screen name (with or without leading @). * @param int $limit Number of tweets to show. * * @return array List of items: { id, full_text, created_at, favorite_count, * retweet_count, entities, user: { name, screen_name, * profile_image_url_https } }. */ public static function get_tweets($key, $secret, $username, $limit = 8) { $username = ltrim(trim((string) $username), '@'); $limit = (int) $limit > 0 ? (int) $limit : 8; if ('' === $username || '' === $key || '' === $secret) { return []; } // Credentials are part of the key, so fixing a bad key takes effect at // once instead of waiting out a cached failure. $cache_key = 'dtq_tw_v2_' . md5($username . '|' . $limit . '|' . $key); $cached = get_transient($cache_key); if (is_array($cached)) { return $cached; } // Failures are cached too, briefly: with bad credentials or a wrong // handle, every page view would otherwise fire up to two blocking // 15-second requests at a rate-limited, paid API. $fail_ttl = (int) apply_filters('divitorque_twitter_failure_ttl', 10 * MINUTE_IN_SECONDS); $bearer = self::get_bearer($key, $secret); if ('' === $bearer) { set_transient($cache_key, [], $fail_ttl); return []; } // 1. Resolve the user (id + profile fields). $user_data = self::api_get( 'https://api.twitter.com/2/users/by/username/' . rawurlencode($username) . '?user.fields=profile_image_url,name,username', $bearer ); $user = $user_data['data'] ?? []; $uid = $user['id'] ?? ''; if ('' === $uid) { set_transient($cache_key, [], $fail_ttl); return []; } // 2. Fetch the user's recent tweets. v2 max_results is 5..100. $count = max(5, min(100, $limit + 5)); $tweets = self::api_get( 'https://api.twitter.com/2/users/' . rawurlencode($uid) . '/tweets' . '?max_results=' . $count . '&exclude=retweets,replies' . '&tweet.fields=created_at,public_metrics', $bearer ); $items = []; $profile = [ 'name' => $user['name'] ?? $username, 'screen_name' => $user['username'] ?? $username, 'profile_image_url_https' => $user['profile_image_url'] ?? '', ]; foreach (($tweets['data'] ?? []) as $tweet) { $items[] = [ 'id' => $tweet['id'] ?? '', 'full_text' => $tweet['text'] ?? '', 'created_at' => $tweet['created_at'] ?? '', 'favorite_count' => $tweet['public_metrics']['like_count'] ?? 0, 'retweet_count' => $tweet['public_metrics']['retweet_count'] ?? 0, 'entities' => [], 'user' => $profile, ]; } // An empty result is usually a failed request; retry it sooner. $ttl = $items ? (int) apply_filters('divitorque_twitter_cache_ttl', HOUR_IN_SECONDS) : $fail_ttl; set_transient($cache_key, $items, $ttl); return $items; } /** * Read a desktop attr value from a module.advanced array. * * @param array $a The module.advanced attrs. * @param string $key Sub-key. * @param mixed $fallback Fallback. * * @return mixed */ protected static function adv($a, $key, $fallback = '') { $v = $a[$key]['desktop']['value'] ?? null; return (null === $v || '' === $v) ? $fallback : $v; } /** * Build the tweet grid items HTML, shared by the Twitter Feed and Twitter * Carousel modules. Mirrors the D4 per-tweet markup. * * @param array $a The module.advanced attrs. * @param array $items Normalised tweet items. * @param bool $as_slides Wrap each item in a `.swiper-slide` (carousel). * * @return string */ public static function build_items_html($a, $items, $as_slides = false) { $user_name = ltrim(trim((string) self::adv($a, 'userName', '')), '@'); $show_icon = self::adv($a, 'showTwitterIcon', 'on'); $show_img = self::adv($a, 'showUserImage', 'on'); $show_name = self::adv($a, 'showName', 'on'); $show_user = self::adv($a, 'showUserName', 'off'); $show_date = self::adv($a, 'showDate', 'on'); $show_fav = self::adv($a, 'showFavorite', 'on'); $show_rt = self::adv($a, 'showRetweet', 'on'); $read_more = self::adv($a, 'readMore', 'on'); $rm_text = self::adv($a, 'readMoreText', 'Read More'); $profile = 'https://twitter.com/' . rawurlencode($user_name); $svg = ''; $html = ''; foreach ($items as $item) { $content = $item['full_text'] ?? ''; $icon = ('on' === $show_icon) ? '
' . $svg . '
' : ''; $avatar = ('on' === $show_img && !empty($item['user']['profile_image_url_https'])) ? sprintf('%3$s', esc_url($profile), esc_url($item['user']['profile_image_url_https']), esc_attr($item['user']['name'] ?? '')) : ''; $name = ('on' === $show_name) ? sprintf('%2$s', esc_url($profile), esc_html($item['user']['name'] ?? '')) : ''; $uname = ('on' === $show_user) ? sprintf('@%2$s', esc_url($profile), esc_html($user_name)) : ''; $rm = ('on' === $read_more) ? sprintf('%2$s', esc_url('//twitter.com/' . rawurlencode($item['user']['screen_name'] ?? $user_name) . '/status/' . rawurlencode($item['id'] ?? '')), esc_html($rm_text)) : ''; $date = ('on' === $show_date) ? sprintf('
%1$s
', esc_html(gmdate('M d Y', strtotime($item['created_at'] ?? 'now')))) : ''; $footer = ''; if ('on' === $show_fav || 'on' === $show_rt) { $fav = ('on' === $show_fav) ? sprintf('
%1$s
', esc_html($item['favorite_count'] ?? 0)) : ''; $rt = ('on' === $show_rt) ? sprintf('
%1$s
', esc_html($item['retweet_count'] ?? 0)) : ''; $footer = sprintf('', $fav, $rt); } $item = sprintf( '
%1$s
%2$s
%3$s%4$s

%5$s %6$s

%7$s
%8$s
', $icon, $avatar, $name, $uname, esc_html($content), $rm, $date, $footer ); $html .= $as_slides ? '
' . $item . '
' : $item; } return $html; } /** * Sort + limit normalised items (mirrors the D4 sort_by handling). * * @param array $items Normalised items. * @param string $sort_by recent-posts | old-posts | favorite_count | retweet_count. * @param int $limit Max items. * * @return array */ public static function sort_and_limit($items, $sort_by, $limit) { if (empty($items)) { return []; } switch ($sort_by) { case 'old-posts': usort($items, function ($a, $b) { return strtotime($a['created_at']) <=> strtotime($b['created_at']); }); break; case 'favorite_count': usort($items, function ($a, $b) { return $b['favorite_count'] <=> $a['favorite_count']; }); break; case 'retweet_count': usort($items, function ($a, $b) { return $b['retweet_count'] <=> $a['retweet_count']; }); break; // 'recent-posts' = API default order. } $limit = (int) $limit; if ($limit > 0 && count($items) > $limit) { $items = array_slice($items, 0, $limit); } return $items; } }