You are here

function socialfeed_twitter_posts in Social Feed 7.2

Same name and namespace in other branches
  1. 7 socialfeed.module \socialfeed_twitter_posts()

Uses socialfeed_twitter_posts() for fetching Twitter tweets.

Return value

array Returns Twitter Feed.

Throws

\Exception

File

./socialfeed.block.inc, line 265
File include for Social Feed module.

Code

function socialfeed_twitter_posts() {
  $twitter_tweets = [];
  $tweets_count = variable_get('socialfeed_twitter_tweets_count');
  $twitter_username = variable_get('socialfeed_twitter_username');
  $display_time = variable_get('socialfeed_twitter_time_stamp');
  $display_date_twitter_style = variable_get('socialfeed_twitter_time_ago');
  $twitter_hash_tag = variable_get('socialfeed_twitter_hashtag');
  $teaser_text = variable_get('socialfeed_twitter_teaser_text');
  $twitter_consumer_key = variable_get('socialfeed_twitter_consumer_key');
  $twitter_consumer_secrete = variable_get('socialfeed_twitter_consumer_secret');

  // Authentication Parameters.
  $api_key = urlencode($twitter_consumer_key);
  $api_secret = urlencode($twitter_consumer_secrete);
  $auth_url = 'https://api.twitter.com/oauth2/token';
  if (!empty($api_key) && !empty($api_secret)) {

    // What we want?
    $data_username = $twitter_username;
    $data_count = $tweets_count;
    $data_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';

    // Get API Access Token.
    $api_credentials = base64_encode($api_key . ':' . $api_secret);
    $auth_headers = 'Authorization: Basic ' . $api_credentials . "\r\n" . 'Content-Type: application/x-www-form-urlencoded;charset=UTF-8' . "\r\n";
    $auth_context = stream_context_create([
      'http' => [
        'header' => $auth_headers,
        'method' => 'POST',
        'content' => http_build_query([
          'grant_type' => 'client_credentials',
        ]),
      ],
    ]);
    $auth_response = json_decode(file_get_contents($auth_url, 0, $auth_context), TRUE);
    $auth_token = $auth_response['access_token'];

    // Get Tweets.
    $data_context = stream_context_create([
      'http' => [
        'header' => 'Authorization: Bearer ' . $auth_token . "\r\n",
      ],
    ]);
    $twitter_values = json_decode(file_get_contents($data_url . '?count=' . $data_count . '&tweet_mode=extended&screen_name=' . urlencode($data_username), 0, $data_context), TRUE);

    // Results - Do what you want!
    foreach ($twitter_values as $key => $twitter_value) {
      $twitter_tweets[$key]['username'] = $twitter_value['user']['screen_name'];
      $twitter_tweets[$key]['full_username'] = 'http://twitter.com/' . $twitter_value['user']['screen_name'];
      preg_match_all('#\\bhttps?://[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/))#', $twitter_value['full_text'], $extra_links);
      foreach ($extra_links[0] as $extra_link) {
        $twitter_tweets[$key]['extra_links'][] = $extra_link;
      }
      if (isset($twitter_value['full_text'])) {
        if (!empty($extra_link)) {
          $twitter_tweets[$key]['tweet'] = substr(rtrim($twitter_value['full_text'], $extra_link), 0, variable_get('socialfeed_twitter_trim_length'));
        }
        else {
          $twitter_tweets[$key]['tweet'] = substr(rtrim($twitter_value['full_text']), 0, variable_get('socialfeed_twitter_trim_length'));
        }
      }
      if (isset($teaser_text) && !empty($teaser_text)) {
        if (array_key_exists('media', $twitter_value['entities'])) {
          $twitter_tweets[$key]['tweet_url'] = l(t('@teaser_text', [
            '@teaser_text' => $teaser_text,
          ]), $twitter_value['entities']['media'][0]['url'], [
            'attributes' => [
              'target' => '_blank',
            ],
          ]);
        }
      }
      if (!empty($twitter_value['entities']['media'])) {
        $twitter_tweets[$key]['media'] = $twitter_value['entities']['media'];
      }
      if ($display_time == 1) {
        $formatted_twitter_date = new DateTime($twitter_value['created_at']);
        $reflection_object = new ReflectionObject($formatted_twitter_date
          ->setTimezone(new DateTimeZone(drupal_get_user_timezone())));
        $get_property = $reflection_object
          ->getProperty('date');
        $date = $get_property
          ->getValue($formatted_twitter_date);
        if ($display_date_twitter_style == 1) {
          $twitter_tweets[$key]['twitter_date'] = socialfeed_time_elapsed_string($date);
        }
        else {
          $twitter_tweets[$key]['twitter_date'] = $formatted_twitter_date
            ->format(variable_get('socialfeed_twitter_time_format'));
        }
      }
      if ($twitter_hash_tag == 1) {
        $twitter_tweets[$key]['tweet'] = preg_replace_callback('/#(\\w+)|@(\\w+)/', function ($hash) {
          if ($hash[0][0] == '#') {
            return l($hash[0], '//twitter.com/hashtag/' . $hash[1], [
              'attributes' => [
                'target' => '_blank',
              ],
            ]);
          }
          if ($hash[0][0] == '@') {
            return l($hash[0], '//twitter.com/' . $hash[2], [
              'attributes' => [
                'target' => '_blank',
              ],
            ]);
          }
        }, $twitter_tweets[$key]['tweet']);
      }
    }
    return $twitter_tweets;
  }
  drupal_set_message(t('Please provide your Twitter credentials <a href="@twitter">here</a>.', [
    '@twitter' => url('admin/config/services/socialfeed/twitter'),
  ]), 'warning');
  return [];
}