You are here

tweet_feed.module in Tweet Feed 6

File

tweet_feed.module
View source
<?php

/**
 * implementation of hook_menu()
 */
function tweet_feed_menu() {
  $items = array();
  $items['admin/settings/tweet_feed'] = array(
    'title' => 'Tweet Feed',
    'description' => 'The settings for the Tweet Feed module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'tweet_feed_settings_form',
    ),
    'access callback' => 'user_access',
    'access arguments' => array(
      'administer tweet feed settings',
    ),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * implementation of hook_permission()
 */
function tweet_feed_perm() {
  return array(
    'administer tweet feed settings',
  );
}

/**
 * tweet_feed_settings_form($form,&$form_state)
 * our settings for for oauth tokens and search queries
 */
function tweet_feed_settings_form(&$form_state) {
  $form = array();
  $form['tweet_feed_api_keys'] = array(
    '#type' => 'fieldset',
    '#title' => t('Twitter API Tokens'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#weight' => -10,
  );
  $form['tweet_feed_query_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Twitter Query Settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#weight' => -9,
  );
  $form['tweet_feed_api_keys']['tweet_feed_consumer_key'] = array(
    '#type' => 'textfield',
    '#title' => t('Consumer Key'),
    '#max_length' => 255,
    '#required' => TRUE,
    '#default_value' => variable_get('tweet_feed_consumer_key', NULL),
  );
  $form['tweet_feed_api_keys']['tweet_feed_consumer_secret'] = array(
    '#type' => 'textfield',
    '#title' => t('Consumer Secret'),
    '#max_length' => 255,
    '#required' => TRUE,
    '#default_value' => variable_get('tweet_feed_consumer_secret', NULL),
  );
  $form['tweet_feed_api_keys']['tweet_feed_oauth_token'] = array(
    '#type' => 'textfield',
    '#title' => t('Oauth Token'),
    '#max_length' => 255,
    '#required' => TRUE,
    '#default_value' => variable_get('tweet_feed_oauth_token', NULL),
  );
  $form['tweet_feed_api_keys']['tweet_feed_oauth_token_secret'] = array(
    '#type' => 'textfield',
    '#title' => t('Oauth Token Secret'),
    '#max_length' => 255,
    '#required' => TRUE,
    '#default_value' => variable_get('tweet_feed_oauth_token_secret', NULL),
  );
  $form['tweet_feed_query_settings']['tweet_feed_query_type'] = array(
    '#type' => 'radios',
    '#title' => t('Type of Twitter Query'),
    '#options' => array(
      'search' => t('Twitter Search'),
      'timeline' => t('User Timeline Display'),
    ),
    '#default_value' => variable_get('tweet_feed_query_type', 'search'),
  );
  $form['tweet_feed_query_settings']['tweet_feed_search_query'] = array(
    '#type' => 'textfield',
    '#title' => t('Twitter Search Query'),
    '#max_length' => 255,
    '#default_value' => variable_get('tweet_feed_search_query', NULL),
  );
  $form['tweet_feed_query_settings']['tweet_feed_user_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Exact Twitter User ID For Timline Query'),
    '#description' => t('You can get this by going to mytwitterid.com'),
    '#max_length' => 255,
    '#default_value' => variable_get('tweet_feed_user_id', NULL),
  );
  $form['tweet_feed_query_settings']['tweet_feed_pull_count'] = array(
    '#type' => 'select',
    '#title' => t('Number of Items to Pull'),
    '#max_length' => 2,
    '#options' => array(
      '100' => '100',
      '200' => '200',
      '300' => '300',
      '400' => '400',
      '500' => '500',
      '600' => '600',
      '700' => '700',
      '800' => '800',
      '900' => '900',
      '1000' => '1000',
    ),
    '#description' => t('Twitter limits tweet pulling to 1500 every 15 minutes. Keep this in mind when setting the pull count in conjunction with the frequency of cron runs.'),
    '#required' => TRUE,
    '#default_value' => variable_get('tweet_feed_pull_count', 100),
  );
  $form['tweet_feed_query_settings']['tweet_feed_new_window'] = array(
    '#type' => 'checkbox',
    '#title' => t('Open Links In New Window'),
    '#default_value' => variable_get('tweet_feed_new_window', 0),
  );
  $form['tweet_feed_query_settings']['tweet_feed_truncate'] = array(
    '#type' => 'checkbox',
    '#title' => t('Truncate Tweets Table on Every Import'),
    '#default_value' => variable_get('tweet_feed_truncate', 0),
  );
  return system_settings_form($form);
}

/**
 * implementation of hook_cron()
 */
function tweet_feed_cron() {
  $tweet_feed_consumer_key = variable_get('tweet_feed_consumer_key', NULL);
  $tweet_feed_consumer_secret = variable_get('tweet_feed_consumer_secret', NULL);
  $tweet_feed_oauth_token = variable_get('tweet_feed_oauth_token', NULL);
  $tweet_feed_oauth_token_secret = variable_get('tweet_feed_oauth_token_secret', NULL);

  // check to see if our api tokens are set up, if not then skip cron
  if (empty($tweet_feed_consumer_key) || empty($tweet_feed_consumer_secret) || empty($tweet_feed_oauth_token) || empty($tweet_feed_oauth_token_secret)) {
    return FALSE;
  }

  // Load in our twitter oauth class
  module_load_include('inc', 'tweet_feed', 'inc/twitter-oauth');

  // If we have selected to truncate our tweet table, then do so here
  $truncate = variable_get('tweet_feed_truncate', 0);
  if ($truncate == 1) {
    db_query('TRUNCATE TABLE {tweet_feed}');
  }

  // Build TwitterOAuth object with client credentials
  $con = new TwitterOAuth($tweet_feed_consumer_key, $tweet_feed_consumer_secret, $tweet_feed_oauth_token, $tweet_feed_oauth_token_secret);

  // get the number of tweets to pull from our list
  $number_to_get = variable_get('tweet_feed_pull_count', 100);
  $current_count = 0;
  $tweets = array();
  $params = variable_get('tweet_feed_query_type', 'search') == 'timeline' ? array(
    'user_id' => variable_get('tweet_feed_user_id', NULL),
    'count' => 100,
  ) : array(
    'q' => variable_get('tweet_feed_search_query', NULL),
    'count' => 100,
  );
  while (count($tweets) <= $number_to_get) {
    if (!empty($tdata->search_metadata->next_results)) {
      $next = substr($tdata->search_metadata->next_results, 1);
      $parts = explode('&', $next);
      foreach ($parts as $part) {
        list($key, $value) = explode('=', $part);
        if ($key == 'max_id') {
          $value = $lowest_id;
        }
        $params[$key] = $value;
      }
    }
    if (variable_get('tweet_feed_query_type', 'search') == 'timeline') {
      $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';

      /* get the tweets */
      $tdata = new stdClass();
      $tdata->statuses = json_decode($con
        ->oAuthRequest($url, 'GET', $params));
    }
    else {
      $url = 'https://api.twitter.com/1.1/search/tweets.json';

      /* get the tweets */
      $tdata = json_decode($con
        ->oAuthRequest($url, 'GET', $params));
    }
    $data = tweet_feed_process_tweets($tdata->statuses);

    // If this is FALSE, then we have hit an error and need to stop processing
    if ($data['tweets'] === FALSE) {
      break;
    }

    // merge the total tweets so we know how many we have
    $tweets = array_merge($data['tweets'], $tweets);
    $lowest_id = $data['lowest_id'];
  }
}

/**
 * process tweet data from what we have retrieved from the Twitter API 
 */
function tweet_feed_process_tweets($tdata) {
  $tweets = array();
  if (!empty($tdata)) {
    if (!empty($tdata->errors)) {
      foreach ($tdata->errors as $error) {
        drupal_set_message(t('Tweet Feed Fail: ') . $error->message . ': ' . $error->code, 'error');
        return array(
          'tweets' => FALSE,
          'lowest_id' => -1,
        );
      }
    }
    else {
      foreach ($tdata as $key => $tweet) {

        // find out if we already have this tweet, if we do, add it to the update pk
        $count = db_result(db_query("SELECT COUNT(*) FROM {tweet_feed} \n                                     WHERE tweet_id = %s", $tweet->id));
        $pk = $count > 0 ? array(
          'tweet_id',
        ) : array();
        $creation_timestamp = strtotime($tweet->created_at);
        $lowest_id = $key == 0 ? $tweet->id : $lowest_id;
        $lowest_id = $tweet->id < $lowest_id ? $tweet->id : $lowest_id;
        $tweet_html = tweet_feed_format_output($tweet->text);
        $hashtags = tweet_feed_get_hashtags($tweet->entities->hashtags);
        $data = array(
          'tweet' => utf8_encode($tweet_html),
          'created_at' => $creation_timestamp,
          'user_id' => $tweet->user->id,
          'profile_image_url' => $tweet->user->profile_image_url,
          'profile_image_https_url' => $tweet->user->profile_image_url_https,
          'screen_name' => $tweet->user->screen_name,
          'hashtags' => $hashtags,
          'tweet_id' => $tweet->id,
        );
        $tweets[] = $data;
        drupal_write_record('tweet_feed', $data, $pk);
      }
    }
  }
  else {
    return array(
      'tweets' => FALSE,
      'lowest_id' => -1,
    );
  }
  return array(
    'tweets' => $tweets,
    'lowest_id' => $lowest_id,
  );
}

/**
 * get the hashtags for our hasgtag field. surround by spaces for the purposes of
 * exact matching in our view options
 */
function tweet_feed_get_hashtags($hashtag_entities) {
  $hashtags = array();
  foreach ($hashtag_entities as $entity) {
    $hashtags[] = ' ' . $entity->text . ' ';
  }
  return join(',', $hashtags);
}

/**
 * tweet_feed_format_output($tweet)
 * makes links, hash tags, and usernames clickable.
 */
function tweet_feed_format_output($tweet) {

  /* based on our preference, assign all links to new windows or to the same window */
  $target = variable_get('tweet_feed_new_window', 0) == 1 ? '_blank' : '_self';

  /* look for links and make them clickable */
  $tweet = preg_replace('/(((f|ht){1}tp:\\/\\/)[-a-zA-Z0-9@:%_\\+.~#?&\\/\\/=]+)/i', '<a target="' . $target . '" href="\\1">\\1</a>', $tweet);
  $tweet = preg_replace('/(((f|ht){1}tps:\\/\\/)[-a-zA-Z0-9@:%_\\+.~#?&\\/\\/=]+)/i', '<a target="' . $target . '" href="\\1">\\1</a>', $tweet);
  $tweet = preg_replace('/([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\\+.~#?&\\/\\/=]+)/i', '\\1<a target="' . $target . '" href="http:\\/\\/\\2">\\2</a>', $tweet);
  $tweet = preg_replace('/([_\\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\\.)+[a-z]{2,3})/i', '<a href="mailto:\\1">\\1</a>', $tweet);
  return $tweet;
}

/**
 * implementation of hook_views_api()
 */
function tweet_feed_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'tweet_feed') . '/inc',
  );
}

Functions

Namesort descending Description
tweet_feed_cron implementation of hook_cron()
tweet_feed_format_output tweet_feed_format_output($tweet) makes links, hash tags, and usernames clickable.
tweet_feed_get_hashtags get the hashtags for our hasgtag field. surround by spaces for the purposes of exact matching in our view options
tweet_feed_menu implementation of hook_menu()
tweet_feed_perm implementation of hook_permission()
tweet_feed_process_tweets process tweet data from what we have retrieved from the Twitter API
tweet_feed_settings_form tweet_feed_settings_form($form,&$form_state) our settings for for oauth tokens and search queries
tweet_feed_views_api implementation of hook_views_api()