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) ? '
' : ''; $avatar = ('on' === $show_img && !empty($item['user']['profile_image_url_https'])) ? sprintf('%5$s %6$s