Advertisement
Guest User

drupal twitter patch images

a guest
Oct 28th, 2015
364
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 13.32 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * @file
  5.  * Twitter API functions
  6.  */
  7.  
  8. module_load_include('php', 'oauth_common', 'lib/OAuth');
  9.  
  10. /**
  11.  * Connect to the Twitter API.
  12.  *
  13.  * @param object $twitter_account
  14.  *   An authenticated twitter_account object to be used to authenticate against
  15.  *   Twitter.
  16.  * @param bool $access_global
  17.  *   Whether or not to load the global accounts too.
  18.  * @param bool $force
  19.  *   Loads accounts regardless of other access limits. Should be used with care
  20.  *   and only for limited scenarios that do would not pose a security risk.
  21.  *
  22.  * @return
  23.  *   A Twitter object ready to be used to query the Twitter API or FALSE.
  24.  */
  25. function twitter_connect($twitter_account = NULL, $access_global = FALSE, $force = FALSE) {
  26.   // If no account was specified, load the first authenticated account.
  27.   if (empty($twitter_account)) {
  28.     // Load all authenticated accounts, passing in the same access requirements.
  29.     $accounts = twitter_load_authenticated_accounts(NULL, $access_global, $force);
  30.  
  31.     // If no accounts were found, there's a problem.
  32.     if (empty($accounts)) {
  33.       watchdog('twitter', 'There are no authenticated Twitter accounts to use for API connections.');
  34.     }
  35.  
  36.     // Grab the first authenticated account.
  37.     else {
  38.       $twitter_account = reset($accounts);
  39.     }
  40.   }
  41.  
  42.   if (!empty($twitter_account)) {
  43.     $auth = $twitter_account->get_auth();
  44.     if (isset($auth['oauth_token']) && isset($auth['oauth_token_secret'])) {
  45.       return new Twitter(
  46.         variable_get('twitter_consumer_key', ''),
  47.         variable_get('twitter_consumer_secret', ''),
  48.         $auth['oauth_token'],
  49.         $auth['oauth_token_secret']
  50.       );
  51.     }
  52.   }
  53.  
  54.   return FALSE;
  55. }
  56.  
  57. /**
  58.  * Saves a TwitterUser object to {twitter_account}
  59.  */
  60. function twitter_account_save($twitter_user, $save_auth = FALSE) {
  61.   $values = (array) $twitter_user;
  62.   $values['twitter_uid'] = $values['id'];
  63.   foreach (array('protected', 'verified', 'profile_background_tile') as $k) {
  64.     if (isset($values[$k])) {
  65.       $values[$k] = (int) $values[$k];
  66.     }
  67.   }
  68.  
  69.   if ($save_auth) {
  70.     $values += $twitter_user->get_auth();
  71.   }
  72.   $schema = drupal_get_schema('twitter_account');
  73.   foreach ($values as $k => $v) {
  74.     if (!isset($schema['fields'][$k])) {
  75.       unset($values[$k]);
  76.     }
  77.   }
  78.   db_merge('twitter_account')
  79.     ->key(array('twitter_uid' => $values['twitter_uid']))
  80.     ->fields($values)
  81.     ->execute();
  82.  
  83.   // Notify other modules of the twitter account save
  84.   module_invoke_all('twitter_account_save', $values);
  85. }
  86.  
  87. /**
  88.  * Load a Twitter account from {twitter_account}.
  89.  *
  90.  * @param mixed $id
  91.  *   Either the Twitter User ID or screen name.
  92.  * @param boolean $type
  93.  *   By default the $id is assumed to be a Twitter UID, set to FALSE if $id is a
  94.  *   screen name.
  95.  *
  96.  * @return
  97.  *   TwitterUser object or NULL.
  98.  */
  99. function twitter_account_load($id, $is_uid = TRUE) {
  100.   // The ID is the Twitter UID.
  101.   if ($is_uid) {
  102.     $query = db_query('SELECT *
  103.                       FROM {twitter_account}
  104.                       WHERE twitter_uid = :twitter_uid',
  105.                        array(':twitter_uid' => $id));
  106.   }
  107.   // Otherwise use the screen name.
  108.   else {
  109.     $query = db_query('SELECT *
  110.                       FROM {twitter_account}
  111.                       WHERE screen_name = :screen_name',
  112.                        array(':screen_name' => $id));
  113.   }
  114.   $values = $query->fetchAssoc();
  115.   if (!empty($values)) {
  116.     $values['id'] = $values['twitter_uid'];
  117.     $account = new TwitterUser($values);
  118.     $account->set_auth($values);
  119.     $account->import = $values['import'];
  120.     $account->mentions = $values['mentions'];
  121.     $account->is_global = $values['is_global'];
  122.     return $account;
  123.   }
  124.   return NULL;
  125. }
  126.  
  127. /**
  128.  * Loads all Twitter accounts added by a Drupal user.
  129.  *
  130.  * This excludes Twitter accounts added automatically when e.g. pulling mentions
  131.  * of an account from the Twitter API.
  132.  *
  133.  * @return array
  134.  *   A list of TwitterUser objects.
  135.  */
  136. function twitter_load_accounts() {
  137.   $accounts = array();
  138.   $result = db_query('SELECT twitter_uid
  139.    FROM {twitter_account}
  140.    WHERE uid <> 0
  141.    ORDER BY screen_name');
  142.   foreach ($result as $account) {
  143.     $accounts[] = twitter_account_load($account->twitter_uid);
  144.   }
  145.   return $accounts;
  146. }
  147.  
  148. /**
  149.  * Bare list of all account names, keyed by Twitter ID.
  150.  *
  151.  * @return array
  152.  *   A list of TwitterUser objects.
  153.  */
  154. function twitter_load_account_names() {
  155.   $accounts = array();
  156.   foreach (twitter_load_accounts() as $account) {
  157.     $accounts[$account->id] = check_plain($account->name);
  158.   }
  159.   return $accounts;
  160. }
  161.  
  162. /**
  163.  * Returns a list of authenticated global or user-specific Twitter accounts.
  164.  *
  165.  * @param int $uid
  166.  *   Optional Drupal user ID to limit the results against.
  167.  * @param bool $access_global
  168.  *   Whether or not to load the global accounts too.
  169.  * @param bool $force
  170.  *   Loads accounts regardless of other access limits. Should be used with care
  171.  *   and only for limited scenarios that do would not pose a security risk.
  172.  *
  173.  * @return array
  174.  *   List of TwitterUser objects. Will always include global accounts, will
  175.  *   optionally include accounts from a specific user.
  176.  */
  177. function twitter_load_authenticated_accounts($uid = NULL, $access_global = TRUE, $force = FALSE) {
  178.   $auth_accounts = array();
  179.  
  180.   // Load every Twitter account, check to see if each one is suitable.
  181.   foreach (twitter_load_accounts() as $index => $twitter_account) {
  182.     // Only include authenticated accounts.
  183.     if ($twitter_account->is_auth()) {
  184.       // Only include either global accounts or, if a $uid was passed in,
  185.       // accounts that are owned by the requested user.
  186.       if ($force
  187.         || ($access_global && $twitter_account->is_global)
  188.         || (isset($uid) && $uid == $twitter_account->uid)) {
  189.         $auth_accounts[] = $twitter_account;
  190.       }
  191.     }
  192.   }
  193.  
  194.   return $auth_accounts;
  195. }
  196.  
  197. /**
  198.  * Load a Twitter status.
  199.  *
  200.  * @param $status_id
  201.  *   The status id of this tweet.
  202.  *
  203.  * @return
  204.  *   An instance of stdClass object with the Tweet data or FALSE.
  205.  */
  206. function twitter_status_load($status_id) {
  207.   $row = db_query("SELECT * FROM {twitter} WHERE twitter_id = :status_id",
  208.             array(':status_id' => $status_id))->fetchObject();
  209.  
  210.   if (!empty($row->entities)) {
  211.     $row->entities = unserialize($row->entities);
  212.   }
  213.  
  214.   return $row;
  215. }
  216.  
  217. /**
  218.  * Saves a TwitterStatus object to {twitter}
  219.  */
  220. function twitter_status_save($status) {
  221.   // RT's get special handling.
  222.   if (!empty($status->retweeted_status)) {
  223.     $text = 'RT @' . $status->retweeted_status->user->screen_name . ': ' . $status->retweeted_status->text;
  224.   }
  225.   else {
  226.     $text = $status->text;
  227.   }
  228.  
  229.   $row = array(
  230.     'twitter_id' => $status->id,
  231.     'screen_name' => $status->user->screen_name,
  232.     'created_time' => strtotime($status->created_at),
  233.     'text' => $text,
  234.     'source' => $status->source,
  235.     'in_reply_to_status_id' => ($status->in_reply_to_status_id > 0) ? (string) $status->in_reply_to_status_id : NULL,
  236.     'in_reply_to_user_id' => $status->in_reply_to_user_id,
  237.     'in_reply_to_screen_name' => $status->in_reply_to_screen_name,
  238.     'truncated' => (int) $status->truncated,
  239.     'entities' => isset($status->entities) ? serialize($status->entities) : NULL,
  240.   );
  241.   db_merge('twitter')
  242.     ->key(array('twitter_id' => $row['twitter_id']))
  243.     ->fields($row)
  244.     ->execute();
  245.   // Let other modules know that a status has been saved.
  246.   module_invoke_all('twitter_status_save', $status);
  247. }
  248.  
  249. /**
  250.  * Post a message to twitter
  251.  *
  252.  * @param $twitter_account
  253.  *   object with a Twitter account.
  254.  * @param $status
  255.  *   string message to publish.
  256.  * @return
  257.  *   array response from Twitter API.
  258.  */
  259. function twitter_set_status($twitter_account, $status) {
  260.   $twitter = twitter_connect($twitter_account);
  261.   if (empty($twitter)) {
  262.     return FALSE;
  263.   }
  264.   return $twitter->statuses_update($status);
  265. }
  266.  
  267. /**
  268.  * Retrieve an embedded Tweet.
  269.  *
  270.  * @param int $tweet_id
  271.  *   Status ID of the tweet.
  272.  *
  273.  * @return array
  274.  *   Response from Twitter API.
  275.  */
  276. function twitter_statuses_oembed($tweet_id) {
  277.   // Need to request any global account, though preferably a global account.
  278.   $twitter = twitter_connect(NULL, TRUE, TRUE);
  279.   if (empty($twitter)) {
  280.     watchdog('twitter', 'Unable to load an authenticated Twitter account to embed a tweet.');
  281.     return FALSE;
  282.   }
  283.  
  284.   else {
  285.     $params = array(
  286.       'hide_media' => !variable_get('twitter_media', FALSE),
  287.       'hide_thread' => !variable_get('twitter_conversation', FALSE),
  288.       'align' => variable_get('twitter_align', 'none'),
  289.     );
  290.     return $twitter->statuses_oembed($tweet_id, $params);
  291.   }
  292. }
  293.  
  294. /**
  295.  * Upload media (image) to twitter
  296.  *
  297.  * @param $twitter_account
  298.  *   object with a Twitter account.
  299.  * @param $media
  300.  *   raw binary file content being uploaded.
  301.  * @return
  302.  *   array response from Twitter API.
  303.  */
  304. function twitter_upload_media($twitter_account, $filename, $filemime, $media) {
  305.   $twitter = twitter_connect($twitter_account);
  306.   return $twitter->media_upload($filename, $filemime, $media);
  307. }
  308.  
  309. /**
  310.  * Fetches a user's timeline.
  311.  */
  312. function twitter_fetch_user_timeline($id) {
  313.   $twitter_account = twitter_account_load($id);
  314.   $since = db_query("SELECT MAX(twitter_id) FROM {twitter} WHERE screen_name = :screen_name", array(':screen_name' => $twitter_account->screen_name))->fetchField();
  315.  
  316.   // Connect to the Twitter's API. If the account is authenticated, use that
  317.   // account, otherwise grab the first authenticated account.
  318.   if ($twitter_account->is_auth()) {
  319.     $twitter = twitter_connect($twitter_account);
  320.   }
  321.   else {
  322.     $twitter = twitter_connect(NULL, TRUE, TRUE);
  323.   }
  324.  
  325.   // That should have worked, but there might have been a problem.
  326.   if (empty($twitter)) {
  327.     watchdog('twitter', 'Unable to authenticate to download tweets for the %name account.', array('%name' => $twitter_account->screen_name));
  328.     return FALSE;
  329.   }
  330.  
  331.   // Fetch tweets.
  332.   $params = array();
  333.   if (!empty($since)) {
  334.     $params['since_id'] = $since;
  335.   }
  336.  
  337.   // Trigger hook_twitter_prefetch_timeline().
  338.   // Doing it this way so that the hook may adjust the parameters.
  339.   $hook = 'twitter_prefetch_timeline';
  340.   foreach (module_implements($hook) as $module) {
  341.     $function = $module . '_' . $hook;
  342.     if (function_exists($function)) {
  343.       $function($twitter_account, $params);
  344.     }
  345.   }
  346.  
  347.   // Load the timeline.
  348.   $statuses = $twitter->user_timeline($id, $params);
  349.  
  350.   // Trigger hook_twitter_statuses_alter().
  351.   drupal_alter('twitter_statuses', $statuses, $twitter_account);
  352.  
  353.   // Save each tweet.
  354.   if (count($statuses) > 0) {
  355.     watchdog('twitter', 'Downloaded %count tweets for the %name account.', array('%count' => count($statuses), '%name' => $twitter_account->screen_name));
  356.  
  357.     foreach ($statuses as $status) {
  358.       twitter_status_save($status);
  359.     }
  360.   }
  361.  
  362.   // Trigger hook_twitter_insert_statuses().
  363.   module_invoke_all('twitter_insert_statuses', $statuses, $twitter_account);
  364.  
  365.   // Update account details.
  366.   if (count($statuses) > 0) {
  367.     twitter_account_save($statuses[0]->user);
  368.   }
  369. }
  370.  
  371. /**
  372.  * Retweet a tweet.
  373.  */
  374. function twitter_retweet($twitter_account, $tweet_id) {
  375.   module_load_include('lib.php', 'twitter');
  376.  
  377.   $twitter = twitter_connect($twitter_account);
  378.   $twitter->retweet($tweet_id, $twitter_account);
  379. }
  380.  
  381. /**
  382.  * Fetches user's mentions of an authenticated account.
  383.  */
  384. function twitter_fetch_mentions_timeline($id) {
  385.   $twitter_account = twitter_account_load($id);
  386.  
  387.   // Connect to Twitter's API using the authenticated account to fetch mentions.
  388.   $twitter = twitter_connect($twitter_account);
  389.   if (empty($twitter)) {
  390.     watchdog('twitter', 'Unable to authenticate to download mentions for the %name account.', array('%name' => $twitter_account->screen_name));
  391.     return FALSE;
  392.   }
  393.  
  394.   $params = array();
  395.   $statuses = $twitter->mentions_timeline($params);
  396.   foreach ($statuses as $status) {
  397.     if (!twitter_account_load($status->user->id)) {
  398.       twitter_account_save($status->user);
  399.     }
  400.     twitter_status_save($status);
  401.   }
  402. }
  403.  
  404. /**
  405.  * Pulls tweets from the database.
  406.  *
  407.  * @param string $screen_name
  408.  *   Optionally provide a screen_name to filter.
  409.  */
  410. function twitter_tweets($screen_name = NULL) {
  411.   $query = db_select('twitter', 't')
  412.     ->fields('t');
  413.   if (isset($screen_name)) {
  414.     $query->condition('t.screen_name', $screen_name);
  415.   }
  416.   $result = $query->execute();
  417.  
  418.   $tweets = array();
  419.   foreach ($result as $row) {
  420.     if (!empty($row->entitites)) {
  421.       $row->entities = unserialize($row->entities);
  422.     }
  423.     $tweets[] = $row;
  424.   }
  425.   return $tweets;
  426. }
  427.  
  428. /**
  429.  * Delete a twitter account and its statuses.
  430.  *
  431.  * @param $twitter_uid
  432.  *   An integer with the Twitter UID.
  433.  */
  434. function twitter_account_delete($twitter_uid) {
  435.   $twitter_account = twitter_account_load($twitter_uid);
  436.  
  437.   // Delete from {twitter_account}.
  438.   $query = db_delete('twitter_account');
  439.   $query->condition('twitter_uid', $twitter_uid);
  440.   $query->execute();
  441.  
  442.   // Delete from {twitter}.
  443.   $query = db_delete('twitter');
  444.   $query->condition('screen_name', $twitter_account->screen_name);
  445.   $query->execute();
  446.  
  447.   // Delete from {authmap}.
  448.   $query = db_delete('authmap');
  449.   $query->condition('authname', $twitter_uid);
  450.   $query->condition('module', 'twitter');
  451.   $query->execute();
  452. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement