function widget($args, $instance) { $facebook = $instance['facebook']; $title = $instance['label']; $twitter = $instance['twitter']; $consumer_key = isset($instance['consumer_key']) ? $instance['consumer_key'] : ''; $consumer_secret = isset($instance['consumer_secret']) ? $instance['consumer_secret'] : ''; $access_token = isset($instance['access_token']) ? $instance['access_token'] : ''; $access_token_secret = isset($instance['access_token_secret']) ? $instance['access_token_secret'] : ''; $last_twitter_save = get_option('ts_last_twitter_follower_count_save_' . $twitter); $last_twitter_reponse = get_option('ts_last_twitter_follower_count_response_' . $twitter); $last_twitter_reponse = $last_twitter_reponse ? json_decode($last_twitter_reponse, true) : ''; if ($last_twitter_save && time() - $last_twitter_save < 600 && $last_twitter_reponse && count($last_twitter_reponse) > 0) { //$last_twitter_reponse = json_decode($last_twitter_reponse, true); } else { $twitter_config = array('consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, 'token' => $access_token, 'secret' => $access_token_secret); $tmhOAuth = new tmhOAuth($twitter_config); $params = array('screen_name' => $twitter); $code = $tmhOAuth->user_request(array('method' => 'GET', 'url' => $tmhOAuth->url("1.1/users/show"), 'params' => $params)); if ($code == 200) { $last_twitter_reponse = $tmhOAuth->response['response']; $last_twitter_reponse_error = $last_twitter_reponse; update_option('ts_last_twitter_follower_count_save_' . $twitter, time()); update_option('ts_last_twitter_follower_count_response_' . $twitter, $last_twitter_reponse); $last_twitter_reponse = json_decode($last_twitter_reponse, true); } } echo ts_essentials_escape($args['before_widget']); echo '<div class="inner clearfix">'; if (!empty($title)) { echo ts_essentials_escape($args['before_title'] . apply_filters('widget_title', $title) . $args['after_title']); } if ($facebook) { $data = wp_remote_get('https://api.facebook.com/method/links.getStats?urls=' . urlencode('https://www.facebook.com/' . $facebook) . '&format=json'); $fb_error = is_object($data) && get_class($data) == 'WP_Error' ? true : false; if (!$fb_error && isset($data['body'])) { $data = json_decode($data['body']); $data = isset($data[0]) && is_object($data[0]) ? $data[0] : $data; if (isset($data->like_count)) { echo '<div class="inline-block"><a href="https://facebook.com/' . esc_attr($facebook) . '" class="facebook">'; echo '<i class="fa fa-facebook facebook-bg-color"></i>'; echo '<h4 class="sp1" title="' . esc_attr($data->like_count) . '">' . ts_essentials_num2str($data->like_count) . '</h4>'; echo '<span class="sp2 small">Likes</span>'; echo '</a></div>'; } } } if ($twitter && is_array($last_twitter_reponse)) { $data = $last_twitter_reponse; if (isset($data['followers_count'])) { echo '<div class="inline-block"><a href="https://twitter.com/' . esc_attr($twitter) . '" class="twitter">'; echo '<i class="fa fa-twitter twitter-bg-color"></i>'; echo '<h4 class="sp1" title="' . esc_attr($data['followers_count']) . '">' . ts_essentials_num2str($data['followers_count']) . '</h4>'; echo '<span class="sp2 small">Followers</span>'; echo '</a></div>'; } } echo '</div>'; echo ts_essentials_escape($args['after_widget']); }
public function execute() { $app = Application::instance(); $cacheDriver = $app->getCacheDriver(); $twitterOAuthConf = Config::$a['oauth']['providers']['twitter']; $tmhOAuth = new \tmhOAuth(array('consumer_key' => $twitterOAuthConf['clientId'], 'consumer_secret' => $twitterOAuthConf['clientSecret'], 'token' => $twitterOAuthConf['token'], 'secret' => $twitterOAuthConf['secret'], 'curl_connecttimeout' => Config::$a['curl']['connecttimeout'], 'curl_timeout' => Config::$a['curl']['timeout'], 'curl_ssl_verifypeer' => Config::$a['curl']['verifypeer'])); /** @noinspection PhpVoidFunctionResultUsedInspection */ $code = $tmhOAuth->user_request(array('url' => $tmhOAuth->url('1.1/statuses/user_timeline.json'), 'params' => array('screen_name' => Config::$a['twitter']['user'], 'count' => 3, 'trim_user' => true))); if ($code == 200) { $result = json_decode($tmhOAuth->response['response'], true); $tweets = array(); foreach ($result as $tweet) { $html = $tweet['text']; if (isset($tweet['entities']['user_mentions'])) { foreach ($tweet['entities']['user_mentions'] as $ment) { $l = '<a href="http://twitter.com/' . $ment['screen_name'] . '">' . $ment['name'] . '</a>'; $html = str_replace('@' . $ment['screen_name'], $l, $html); } } if (isset($tweet['entities']) && isset($tweet['entities']['urls'])) { foreach ($tweet['entities']['urls'] as $url) { $l = '<a href="' . $url['url'] . '" rev="' . $url['expanded_url'] . '">' . $url['display_url'] . '</a>'; $html = str_replace($url['url'], $l, $html); } } $tweet['user']['screen_name'] = Config::$a['twitter']['user']; $tweet['html'] = $html; $tweets[] = $tweet; } $cacheDriver->save('twitter', $tweets); } }
function search($idlist) { global $twitter_keys, $current_key, $all_users, $all_tweet_ids, $bin_name, $dbh, $tweetQueue; $keyinfo = getRESTKey(0); $current_key = $keyinfo['key']; $ratefree = $keyinfo['remaining']; print "current key {$current_key} ratefree {$ratefree}\n"; $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret'])); // by hundred for ($i = 0; $i < sizeof($idlist); $i += 100) { if ($ratefree <= 0 || $ratefree % 10 == 0) { $keyinfo = getRESTKey($current_key); $current_key = $keyinfo['key']; $ratefree = $keyinfo['remaining']; $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret'])); } $q = $idlist[$i]; $n = $i + 1; while ($n < $i + 100) { if (!isset($idlist[$n])) { break; } $q .= "," . $idlist[$n]; $n++; } $params = array('id' => $q); $code = $tmhOAuth->user_request(array('method' => 'GET', 'url' => $tmhOAuth->url('1.1/statuses/lookup'), 'params' => $params)); $ratefree--; if ($tmhOAuth->response['code'] == 200) { $data = json_decode($tmhOAuth->response['response'], true); if (is_array($data) && empty($data)) { // all tweets in set are deleted continue; } $tweets = $data; $tweet_ids = array(); foreach ($tweets as $tweet) { $t = new Tweet(); $t->fromJSON($tweet); if (!$t->isInBin($bin_name)) { $all_users[] = $t->from_user_id; $all_tweet_ids[] = $t->id; $tweet_ids[] = $t->id; $tweetQueue->push($t, $bin_name); } print "."; } sleep(1); } else { echo "Failure with code " . $tmhOAuth->response['response']['code'] . "\n"; var_dump($tmhOAuth->response['response']['info']); var_dump($tmhOAuth->response['response']['error']); var_dump($tmhOAuth->response['response']['errno']); die; } $tweetQueue->insertDB(); } }
public function publish(ISocialStatus $status) { $params = array('status' => $status->getStatusString()); $tmhOAuthEngine = new tmhOAuth($this->_config); $response = $tmhOAuthEngine->user_request(array('method' => 'POST', 'url' => $tmhOAuthEngine->url("1.1/statuses/update"), 'params' => $params, 'multipart' => true)); if ($response != 200) { throw new Exception('Unable to publish on Twitter (ERR: ' . $response . ')'); } }
function search($keywords, $max_id = null) { global $twitter_keys, $current_key, $ratefree, $bin_name, $dbh, $tweetQueue; $ratefree--; if ($ratefree < 1 || $ratefree % 10 == 0) { $keyinfo = getRESTKey($current_key, 'search', 'tweets'); $current_key = $keyinfo['key']; $ratefree = $keyinfo['remaining']; } $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret'])); $params = array('q' => $keywords, 'count' => 100); if (isset($max_id)) { $params['max_id'] = $max_id; } $code = $tmhOAuth->user_request(array('method' => 'GET', 'url' => $tmhOAuth->url('1.1/search/tweets'), 'params' => $params)); if ($tmhOAuth->response['code'] == 200) { $data = json_decode($tmhOAuth->response['response'], true); $tweets = $data['statuses']; $tweet_ids = array(); foreach ($tweets as $tweet) { $t = new Tweet(); $t->fromJSON($tweet); $tweet_ids[] = $t->id; if (!$t->isInBin($bin_name)) { $tweetQueue->push($t, $bin_name); if ($tweetQueue->length() > 100) { $tweetQueue->insertDB(); } print "."; } } if (!empty($tweet_ids)) { print "\n"; if (count($tweet_ids) <= 1) { print "no more tweets found\n\n"; return false; } $max_id = min($tweet_ids); print "max id: " . $max_id . "\n"; } else { print "0 tweets found\n\n"; return false; } sleep(1); search($keywords, $max_id); } else { echo $tmhOAuth->response['response'] . "\n"; if ($tmhOAuth->response['response']['errors']['code'] == 130) { // over capacity sleep(1); search($keywords, $max_id); } } }
function get_friends($screen_name, $cursor = -1) { print "getting friends of {$screen_name}\n"; global $twitter_keys, $current_key, $ratefree, $bin_name, $dbh; $ratefree--; if ($ratefree < 1 || $ratefree % 10 == 0) { $keyinfo = getRESTKey($current_key, 'friends', 'list'); $current_key = $keyinfo['key']; $ratefree = $keyinfo['remaining']; } $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret'])); $params = array('cursor' => $cursor, 'skip_status' => true, 'count' => 200, 'include_user_entities' => false, 'screen_name' => $screen_name); $tmhOAuth->user_request(array('method' => 'GET', 'url' => $tmhOAuth->url('1.1/friends/list'), 'params' => $params)); if ($tmhOAuth->response['code'] == 200) { $data = json_decode($tmhOAuth->response['response'], true); $observed_at = strftime("%Y-%m-%d %H-%M-%S", date('U')); $friends = $data['users']; $cursor = $data['next_cursor']; echo count($friends) . " users found\n"; // store in db $tr = new TwitterRelations($screen_name, $friends, "friend", $observed_at); $tr->save($dbh, $bin_name); // continue if there are still things to do if (!empty($cursor) && $cursor != -1) { sleep(1); get_friends($screen_name, $cursor); } } else { $error_code = json_decode($tmhOAuth->response['response'])->errors[0]->code; if ($error_code == 130) { print "Twitter is over capacity, sleeping 5 seconds before retry\n"; sleep(5); get_friends($screen_name, $cursor); } elseif ($error_code == 88) { print "API key rate limit exceeded, sleeping 60 seconds before retry\n"; sleep(60); get_friends($screen_name, $cursor); } else { echo "\nAPI error: " . $tmhOAuth->response['response'] . "\n"; } } }
/** * @param array $params * @return string * @throws Exception */ public function authenticate(array $params) { if (!isset($params['oauth_token']) || empty($params['oauth_token']) || !isset($params['oauth_verifier']) || empty($params['oauth_verifier'])) { throw new Exception('Authentication failed'); } $oauth = Session::set('oauth'); if ($params['oauth_token'] !== $oauth['oauth_token']) { throw new Exception('Invalid login session'); } $twitterOAuthConf = Config::$a['oauth']['providers']['twitter']; $tmhOAuth = new \tmhOAuth(array('consumer_key' => $twitterOAuthConf['clientId'], 'consumer_secret' => $twitterOAuthConf['clientSecret'], 'token' => $oauth['oauth_token'], 'secret' => $oauth['oauth_token_secret'], 'curl_connecttimeout' => Config::$a['curl']['connecttimeout'], 'curl_timeout' => Config::$a['curl']['timeout'], 'curl_ssl_verifypeer' => Config::$a['curl']['verifypeer'])); /** @noinspection PhpVoidFunctionResultUsedInspection */ $code = $tmhOAuth->user_request(array('method' => 'POST', 'url' => $tmhOAuth->url('oauth/access_token', ''), 'params' => array('oauth_verifier' => trim($params['oauth_verifier'])))); if ($code != 200) { throw new Exception('Failed to retrieve user data'); } $data = $tmhOAuth->extract_params($tmhOAuth->response['response']); $authCreds = $this->getAuthCredentials($oauth['oauth_token'], $data); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); }
$params = getopt($shortopts, $longopts); if (isset($params['list'])) { $list_name = $params['list']; } else { die("Error: unable to parse the user list name in your request. Please use the 'list' parameter in your request."); } } else { die("Error: missing user list name in your request. Please use the 'list' parameter in your request."); } } /******************************************************************* * OAuth ********************************************************************/ $tmhOAuth = new tmhOAuth(array('consumer_key' => $my_consumer_key, 'consumer_secret' => $my_consumer_secret, 'user_token' => $my_access_token, 'user_secret' => $my_access_token_secret, 'curl_ssl_verifypeer' => false)); // request the user information $code = $tmhOAuth->user_request(array('url' => $tmhOAuth->url('1.1/account/verify_credentials'))); // Display error response if do not receive 200 response code if ($code != 200) { if ($code == 429) { die("Exceeded Twitter API rate limit"); } echo $tmhOAuth->response['error']; die("verify_credentials connection failure"); } // Decode JSON $data = json_decode($tmhOAuth->response['response'], true); // Parse information from response $twitterName = $data['screen_name']; $fullName = $data['name']; $twitterAvatarUrl = $data['profile_image_url']; /*******************************************************************
********************************************************************/ // Matt Harris' Twitter OAuth library require 'tldlib/tmhOAuth.php'; require 'tldlib/tmhUtilities.php'; // include user keys require 'tldlib/keys/tweetledee_keys.php'; // include Geoff Smith's utility functions require 'tldlib/tldUtilities.php'; // include Martín Lucas Golini's pretty print functions require 'tldlib/tldPrettyPrint.php'; /******************************************************************* * OAuth ********************************************************************/ $tmhOAuth = new tmhOAuth(array('consumer_key' => $my_consumer_key, 'consumer_secret' => $my_consumer_secret, 'user_token' => $my_access_token, 'user_secret' => $my_access_token_secret, 'curl_ssl_verifypeer' => false)); // request the user information $code = $tmhOAuth->user_request(array('url' => $tmhOAuth->url('1.1/account/verify_credentials'))); // Display error response if do not receive 200 response code if ($code != 200) { if ($code == 429) { die("Exceeded Twitter API rate limit"); } echo $tmhOAuth->response['error']; die("verify_credentials connection failure"); } // Decode JSON $data = json_decode($tmhOAuth->response['response'], true); /******************************************************************* * Defaults ********************************************************************/ $count = 25; //default tweet number = 25
function widget($args, $instance) { $title = $instance['title']; $username = isset($instance['username']) ? preg_replace("/[^a-zA-Z0-9\\-_]+/", "", $instance['username']) : ''; $number = isset($instance['number']) ? $instance['number'] : 3; $consumer_key = isset($instance['consumer_key']) ? $instance['consumer_key'] : ''; $consumer_secret = isset($instance['consumer_secret']) ? $instance['consumer_secret'] : ''; $access_token = isset($instance['access_token']) ? $instance['access_token'] : ''; $access_token_secret = isset($instance['access_token_secret']) ? $instance['access_token_secret'] : ''; $links_in_new_tab = isset($instance['links_in_new_tab']) && $instance['links_in_new_tab'] == 1 ? true : false; $exclude_replies = isset($instance['exclude_replies']) && $instance['exclude_replies'] == 1 ? 1 : 0; $include_retweets = isset($instance['include_retweets']) && $instance['include_retweets'] == 1 ? 1 : 0; $follow_us_text = isset($instance['follow_us_text']) ? $instance['follow_us_text'] : ''; echo ts_essentials_escape($args['before_widget']); if (!empty($title)) { echo ts_essentials_escape($args['before_title'] . apply_filters('widget_title', $title) . $args['after_title']); } $last_twitter_save = get_option('ts_last_twitter_save_' . $username); $last_twitter_reponse = get_option('ts_last_twitter_response_' . $username); $last_twitter_reponse = $last_twitter_reponse ? json_decode($last_twitter_reponse, true) : ''; if ($last_twitter_save && time() - $last_twitter_save < 120 && $last_twitter_reponse && count($last_twitter_reponse) > 0) { //$last_twitter_reponse = json_decode($last_twitter_reponse, true); } else { $twitter_config = array('consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, 'token' => $access_token, 'secret' => $access_token_secret); $tmhOAuth = new tmhOAuth($twitter_config); $params = array('count' => $number, 'screen_name' => $username, 'exclude_replies' => $exclude_replies, 'include_rts' => $include_retweets); $code = $tmhOAuth->user_request(array('method' => 'GET', 'url' => $tmhOAuth->url("1.1/statuses/user_timeline"), 'params' => $params)); if ($code == 200) { $last_twitter_reponse = $tmhOAuth->response['response']; $last_twitter_reponse_error = $last_twitter_reponse; update_option('ts_last_twitter_save_' . $username, time()); update_option('ts_last_twitter_response_' . $username, $last_twitter_reponse); $last_twitter_reponse = json_decode($last_twitter_reponse, true); } else { //echo '<div><pre>'.$tmhOAuth->response['raw'].'</pre></div>'; } } echo '<div class="ts-twitter-widget">'; echo count($last_twitter_reponse) ? '<ul>' : ''; $i = 1; if (is_array($last_twitter_reponse)) { foreach ($last_twitter_reponse as $tweet) { $tweet['text'] = trim($tweet['text']); $actual_tweet = ts_essentials_clean_tweet($tweet['text'], $links_in_new_tab); $multi_line_class = $tweet['text'] == nl2br($tweet['text']) ? '' : 'white-space-pre-wrap'; $urls = $tweet['entities']['urls']; foreach ($urls as $url) { $seek = $url['url']; $replace = $url['expanded_url']; $replace_display = $url['display_url']; $actual_tweet = str_replace($seek, $replace, $actual_tweet); $actual_tweet = str_replace('>' . $replace . '<', '>' . $replace_display . '<', $actual_tweet); } echo '<li><p class="' . esc_attr($multi_line_class) . '">' . strip_tags($actual_tweet, '<a>') . '</p>'; $target = $links_in_new_tab ? 'target="_blank"' : ''; echo '<small class="small"><a href="' . esc_url('https://twitter.com/' . $tweet['user']['screen_name'] . '/status/' . $tweet['id_str']) . '" ' . $target . '>' . ts_essentials_time2str($tweet['created_at']) . '</a></small><i class="fa fa-twitter color-primary"></i></li>'; $i++; if ($i > $number) { break; } } } echo count($last_twitter_reponse) ? '</ul>' : ''; if (trim($follow_us_text)) { echo '<div class="follow-link mimic-smaller uppercase"><a href="' . esc_url('https://twitter.com/' . $username) . '" target="_blank">' . $follow_us_text . '</a></div>'; } echo '</div><!-- end: .ts-twitter-widget -->'; echo ts_essentials_escape($args['after_widget']) . '<!-- end: .widget -->'; }
function post() { global $dbh; $query = $dbh->prepare("select accounts_queue.*, accounts.type, accounts.data1, accounts.data2, accounts.data3 from accounts_queue join accounts on accounts_queue.accountid = accounts.id where scheduled_time <= ? and (sent_time is null or sent_time = '') and accounts.active = 1 limit 10"); $query->execute(array(time())); $posts = $query->fetchAll(); foreach ($posts as $post) { $error = ''; if ($post['type'] == 'facebook') { try { $params = array("access_token" => $post['data2'], "message" => $post['message']); $facebook = new Facebook(array('appId' => FB_APPID, 'secret' => FB_APPSECRET)); if (!empty($post['image'])) { $params['url'] = $post['image']; $ret = $facebook->api('/' . $post['data1'] . '/photos', 'POST', $params); } else { unset($matches); preg_match_all('!(http|ftp|scp)(s)?:\\/\\/[a-zA-Z0-9.?&_/]+!', $post['message'], $matches); $link = ''; if (!empty($matches[0][0])) { $link = $matches[0][0]; $params['link'] = $link; } $ret = $facebook->api('/' . $post['data1'] . '/feed', 'POST', $params); } } catch (Exception $e) { $error = print_r($e, true); } } if ($post['type'] == 'twitter') { if (empty($post['media'])) { $twitter = new TwitterOAuth(TWITTER_APIKEY, TWITTER_APISECRET, $post['data2'], $post['data3']); $account = $twitter->get('account/verify_credentials'); $status = $twitter->post('statuses/update', array('status' => $post['message'])); if (!empty($status->errors[0]->message)) { $error = $status->errors[0]->message; } } else { $file = $post['media']; $params = array('media[]' => file_get_contents($file)); if (null !== $post['message']) { $params['status'] = $post['message']; } $tmhOAuth = new \tmhOAuth(array('user_agent' => 'SocialTurn', 'consumer_key' => TWITTER_APIKEY, 'consumer_secret' => TWITTER_APISECRET, 'token' => $post['data2'], 'secret' => $post['data3'])); $response = $tmhOAuth->user_request(array('method' => 'POST', 'url' => $tmhOAuth->url("1.1/statuses/update_with_media"), 'params' => $params, 'multipart' => true)); if ($response == 200 && isset($tmhOAuth->response['response'])) { $json = json_decode($tmhOAuth->response['response']); $lastTweetId = $json->id_str; } if (isset($tmhOAuth->response['response'])) { $json = json_decode($tmhOAuth->response['response']); if (isset($json->errors)) { $error = array(); foreach ($json->errors as $err) { $error[] = '[' . $err->code . '] ' . $err->message; } $error = $err->message; } } } } $update = $dbh->prepare("update accounts_queue set sent_time = ?, error = ? where id = ?"); $update->execute(array(time(), $error, $post['id'])); } exit; }
return; } // store the params into the session so they are there when we come back after the redirect $_SESSION['oauth'] = $tmhOAuth->extract_params($tmhOAuth->response['response']); // check the callback has been confirmed if ($_SESSION['oauth']['oauth_callback_confirmed'] !== 'true') { error('The callback was not confirmed by Twitter so we cannot continue.'); } else { $url = $tmhOAuth->url('oauth/authorize', '') . "?oauth_token={$_SESSION['oauth']['oauth_token']}"; header("Location: " . $url); exit; } } else { // Step 3: This is the code that runs when Twitter redirects the user to the callback. Exchange the temporary token for a permanent access token $tmhOAuth = new tmhOAuth(array('consumer_key' => CONSUMER_KEY, 'consumer_secret' => CONSUMER_SECRET, 'user_token' => $_SESSION['oauth']['oauth_token'], 'user_secret' => $_SESSION['oauth']['oauth_token_secret'])); $code = $tmhOAuth->user_request(array('method' => 'POST', 'url' => $tmhOAuth->url('oauth/access_token', ''), 'params' => array('oauth_verifier' => trim($_REQUEST['oauth_verifier'])))); if ($code == 200) { $oauth_creds = $tmhOAuth->extract_params($tmhOAuth->response['response']); header("refresh:3; url=admin.php"); echo "Account <b>" . $oauth_creds['screen_name'] . "</b> verified!"; $oauth_token = $oauth_creds['oauth_token']; $oauth_token_secret = $oauth_creds['oauth_token_secret']; $id = $_SESSION['id']; if (!($upd_token = $mysqli->prepare("UPDATE destination SET oauth_token = ? , oauth_token_secret = ? WHERE id = ?"))) { die("Prepare an SQL statement error: (" . $mysqli->errno . ") " . $mysqli->error); } if (!$upd_token->bind_param("ssi", $oauth_token, $oauth_token_secret, $id)) { die("Error binding parameters: (" . $upd_token->errno . ") " . $upd_token->error); } if (!$upd_token->execute()) { echo "Token update error: (" . $upd_token->errno . ") " . $upd_token->error;
/******************************************************************* * Includes ********************************************************************/ // Matt Harris' Twitter OAuth library require 'tldlib/tmhOAuth.php'; require 'tldlib/tmhUtilities.php'; // include user keys require 'tldlib/keys/tweetledee_keys.php'; // include Geoff Smith's utility functions require 'tldlib/tldUtilities.php'; /******************************************************************* * OAuth ********************************************************************/ $tmhOAuth = new tmhOAuth(array('consumer_key' => $my_consumer_key, 'consumer_secret' => $my_consumer_secret, 'user_token' => $my_access_token, 'user_secret' => $my_access_token_secret, 'curl_ssl_verifypeer' => false)); // request the user information $code = $tmhOAuth->user_request(array('url' => $tmhOAuth->url('1.1/account/verify_credentials'))); // Display error response if do not receive 200 response code if ($code != 200) { if ($code == 429) { die("Exceeded Twitter API rate limit"); } echo $tmhOAuth->response['error']; die("verify_credentials connection failure"); } // Decode JSON $data = json_decode($tmhOAuth->response['response'], true); /******************************************************************* * Defaults ********************************************************************/ $count = 25; //default tweet number = 25
function getTwitterData($cfg) { $data = get_transient("twitter_data_" . $cfg['mode']); if (!$data) { require_once 'tmhOAuth/tmhOAuth.php'; $tmhOAuth = new tmhOAuth(array('consumer_key' => $cfg['consumer_key'], 'consumer_secret' => $cfg['consumer_secret'], 'token' => $cfg['token'], 'secret' => $cfg['secret'])); $code = $tmhOAuth->user_request(array('url' => $tmhOAuth->url(twitter_get_mode_url($cfg['mode'])))); if ($code == 200) { $data = json_decode($tmhOAuth->response['response'], true); if (isset($data['status'])) { $code = $tmhOAuth->user_request(array('url' => $tmhOAuth->url(twitter_get_mode_url($cfg['oembed'])), 'params' => array('id' => $data['status']['id_str']))); if ($code == 200) { $data = json_decode($tmhOAuth->response['response'], true); } } set_transient("twitter_data_" . $cfg['mode'], $data, 60 * 60); } } return $data; }
function getRemainingForKey($current_key, $resource = 'statuses', $query = 'lookup') { global $twitter_keys; // rate limit test $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret'])); $params = array('resources' => $resource); $code = $tmhOAuth->user_request(array('method' => 'GET', 'url' => $tmhOAuth->url('1.1/application/rate_limit_status'), 'params' => $params)); if ($tmhOAuth->response['code'] == 200) { $data = json_decode($tmhOAuth->response['response'], true); return $data['resources'][$resource]["/{$resource}/{$query}"]['remaining']; } else { if ($tmhOAuth->response['code'] != 429) { // 419 is too many requests logit("cli", "Warning: API key {$current_key} got response code " . $tmhOAuth->response['code']); } return 0; } }
<?php require_once 'config.php'; if (!isset($_GET['file'])) { print_r('Error file'); } $filePath = TEXT_TOOL_TMP_PATH . $_GET['file']; if (!file_exists($filePath)) { print_r('Error file exists' . $_GET['file']); exit; } if (isset($_GET['twitter']) && $_GET['twitter'] == 1) { include 'lib/tmhOAuth/tmhOAuth.php'; $tmhOAuth = new tmhOAuth(array('consumer_key' => $tw_consumer_key, 'consumer_secret' => $tw_consumer_secret, 'user_token' => $tw_user_token, 'user_secret' => $tw_user_secret)); $params = array('media[]' => "@{$filePath};type=image/png;filename=" . basename($filePath), 'status' => "New Feedback"); $code = $tmhOAuth->user_request(array('method' => 'POST', 'url' => $tmhOAuth->url("1.1/statuses/update_with_media"), 'params' => $params, 'multipart' => true)); print_r("Uploaded to twitter<br>"); } if (isset($_GET['facebook']) && $_GET['facebook'] == 1) { include 'lib/facebook.php'; $name = urldecode("ebayfeedback"); $fbConf = array('appId' => $fbApId, 'secret' => $fbAppSecret, 'cookie' => true); $facebook = new Facebook($fbConf); $session = $facebook->getUser(); //print_r($session); exit; $me = null; if ($session) { try { $me = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e);
function get_timeline($user_id, $type, $max_id = null) { print "doing {$user_id}\n"; global $twitter_keys, $current_key, $ratefree, $looped, $bin_name, $dbh, $tweetQueue; $ratefree--; if ($ratefree < 1 || $ratefree % 10 == 0) { $keyinfo = getRESTKey($current_key, 'statuses', 'user_timeline'); $current_key = $keyinfo['key']; $ratefree = $keyinfo['remaining']; } $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret'])); $params = array('count' => 200, 'trim_user' => false, 'exclude_replies' => false, 'contributor_details' => true, 'include_rts' => 1); if ($type == "user_id") { $params['user_id'] = $user_id; } else { $params['screen_name'] = $user_id; } if (isset($max_id)) { $params['max_id'] = $max_id; } $tmhOAuth->user_request(array('method' => 'GET', 'url' => $tmhOAuth->url('1.1/statuses/user_timeline'), 'params' => $params)); //var_export($params); print "\n"; if ($tmhOAuth->response['code'] == 200) { $tweets = json_decode($tmhOAuth->response['response'], true); // store in db $tweet_ids = array(); foreach ($tweets as $tweet) { $t = new Tweet(); $t->fromJSON($tweet); $tweet_ids[] = $t->id; if (!$t->isInBin($bin_name)) { $tweetQueue->push($t, $bin_name); print "."; if ($tweetQueue->length() > 100) { $tweetQueue->insertDB(); } } } if (!empty($tweet_ids)) { print "\n"; if (count($tweet_ids) <= 1) { print "no more tweets found\n\n"; return false; } $max_id = min($tweet_ids); print "max id: " . $max_id . "\n"; } else { print "0 tweets found\n\n"; return false; } sleep(1); get_timeline($user_id, $type, $max_id); } else { $error_code = json_decode($tmhOAuth->response['response'])->errors[0]->code; if ($error_code == 130) { print "Twitter is over capacity, sleeping 5 seconds before retry\n"; sleep(5); get_timeline($user_id, $type, $max_id); } elseif ($error_code == 88) { print "API key rate limit exceeded, sleeping 60 seconds before retry\n"; sleep(60); get_timeline($user_id, $type, $max_id); } else { echo "\nAPI error: " . $tmhOAuth->response['response'] . "\n"; } } }
/** * @param $name * @param string $requestMethod * @param array $parameters * @param bool $multipart * * @return array|mixed * @throws Exception */ public function query($name, $requestMethod = 'GET', $parameters = [], $multipart = false) { $this->config['host'] = $this->tconfig['API_URL']; if ($multipart) { $this->config['host'] = $this->tconfig['UPLOAD_URL']; } $url = parent::url($this->tconfig['API_VERSION'] . '/' . $name); $this->log('METHOD : ' . $requestMethod); $this->log('QUERY : ' . $name); $this->log('URL : ' . $url); $this->log('PARAMETERS : ' . http_build_query($parameters)); $this->log('MULTIPART : ' . ($multipart ? 'true' : 'false')); parent::user_request(['method' => $requestMethod, 'host' => $name, 'url' => $url, 'params' => $parameters, 'multipart' => $multipart]); $response = $this->response; $format = 'object'; if (isset($parameters['format'])) { $format = $parameters['format']; } $this->log('FORMAT : ' . $format); $this->error = $response['error']; if ($this->error) { $this->log('ERROR_CODE : ' . $response['errno']); $this->log('ERROR_MSG : ' . $response['error']); } if (isset($response['code']) && ($response['code'] < 200 || $response['code'] > 206)) { $_response = $this->jsonDecode($response['response'], true); if (is_array($_response)) { if (array_key_exists('errors', $_response)) { $error_code = $_response['errors'][0]['code']; $error_msg = $_response['errors'][0]['message']; } else { $error_code = $response['code']; $error_msg = $response['error']; } } else { $error_code = $response['code']; $error_msg = $error_code == 503 ? 'Service Unavailable' : 'Unknown error'; } $this->log('ERROR_CODE : ' . $error_code); $this->log('ERROR_MSG : ' . $error_msg); throw new Exception('[' . $error_code . '] ' . $error_msg, $response['code']); } switch ($format) { default: case 'object': $response = $this->jsonDecode($response['response']); break; case 'json': $response = $response['response']; break; case 'array': $response = $this->jsonDecode($response['response'], true); break; } return $response; }
function axiom_get_twitter_data($cfg) { $data = get_transient("twitter_data_" . $cfg['mode']); if (!$data) { require_once axiom_get_file_dir('lib/tmhOAuth/tmhOAuth.php'); $tmhOAuth = new tmhOAuth(array('consumer_key' => $cfg['consumer_key'], 'consumer_secret' => $cfg['consumer_secret'], 'token' => $cfg['token'], 'secret' => $cfg['secret'])); $code = $tmhOAuth->user_request(array('url' => $tmhOAuth->url(axiom_get_twitter_mode_url($cfg['mode'])))); if ($code == 200) { $data = json_decode($tmhOAuth->response['response'], true); if (isset($data['status'])) { $code = $tmhOAuth->user_request(array('url' => $tmhOAuth->url(axiom_get_twitter_mode_url($cfg['oembed'])), 'params' => array('id' => $data['status']['id_str']))); if ($code == 200) { $data = json_decode($tmhOAuth->response['response'], true); } } set_transient("twitter_data_" . $cfg['mode'], $data, 60 * 60); } } else { if (!is_array($data) && axiom_substr($data, 0, 2) == 'a:') { $data = unserialize($data); } } return $data; }
$params = getopt($shortopts); if (isset($params['q'])) { $query = urlencode($params['q']); } else { die("Error: unable to parse the search query term in your request. Please use the 'q' parameter in your request."); } } else { die("Error: missing search query term in your request. Please use the 'q' parameter in your request."); } } /******************************************************************* * OAuth ********************************************************************/ $tmhOAuth = new tmhOAuth(array('consumer_key' => $my_consumer_key, 'consumer_secret' => $my_consumer_secret, 'user_token' => $my_access_token, 'user_secret' => $my_access_token_secret, 'curl_ssl_verifypeer' => false)); // request the user information $code = $tmhOAuth->user_request(array('url' => $tmhOAuth->url('1.1/account/verify_credentials'))); // Display error response if do not receive 200 response code if ($code != 200) { if ($code == 429) { die("Exceeded Twitter API rate limit"); } echo $tmhOAuth->response['error']; die("verify_credentials connection failure"); } // Decode JSON $data = json_decode($tmhOAuth->response['response'], true); /******************************************************************* * Defaults ********************************************************************/ $count = 25; //default tweet number = 25
function authorize_twitter() { if (!App::import('Lib', 'tmh_oauth')) { $this->Session->setFlash(sprintf(__('Failed to load the %s library! Contact your system administrator.', true), 'Twitter OAuth'), 'default', array('class' => 'error')); $this->redirect(array('action' => 'preferences')); } define('__DIR__', ROOT . DS . APP_DIR . DS . 'libs'); $tmhOAuth = new tmhOAuth(array('consumer_key' => Configure::read('twitter.consumer_key'), 'consumer_secret' => Configure::read('twitter.consumer_secret'))); if (!empty($this->params['url']['oauth_token'])) { $response = $this->Session->read('Twitter.response'); $this->Session->delete('Twitter.response'); if ($this->params['url']['oauth_token'] !== $response['oauth_token']) { $this->Session->setFlash(__('The oauth token you started with doesn\'t match the one you\'ve been redirected with. Do you have multiple tabs open?', true), 'default', array('class' => 'warning')); $this->redirect(array('action' => 'preferences')); } if (!isset($this->params['url']['oauth_verifier'])) { $this->Session->setFlash(__('The oauth verifier is missing so we cannot continue. Did you deny the appliction access?', true), 'default', array('class' => 'warning')); $this->redirect(array('action' => 'preferences')); } // Update with the temporary token and secret $tmhOAuth->reconfigure(array_merge($tmhOAuth->config, array('token' => $response['oauth_token'], 'secret' => $response['oauth_token_secret']))); $code = $tmhOAuth->user_request(array('method' => 'POST', 'url' => $tmhOAuth->url('oauth/access_token', ''), 'params' => array('oauth_verifier' => trim($this->params['url']['oauth_verifier'])))); if ($code == 200) { $oauth_creds = $tmhOAuth->extract_params($tmhOAuth->response['response']); if ($this->Person->updateAll(array('twitter_token' => "'{$oauth_creds['oauth_token']}'", 'twitter_secret' => "'{$oauth_creds['oauth_token_secret']}'"), array('Person.id' => $this->UserCache->currentId()))) { $this->Session->setFlash(sprintf(__('Your Twitter authorization has been completed. You can always revoke this at any time through the preferences page.', true), __('person', true)), 'default', array('class' => 'success')); } else { $this->Session->setFlash(sprintf(__('Twitter authorization was received, but the database failed to update.', true), __('person', true)), 'default', array('class' => 'warning')); } } else { $this->Session->setFlash(__('There was an error communicating with Twitter.', true) . ' ' . $tmhOAuth->response['response'], 'default', array('class' => 'warning')); } $this->redirect(array('action' => 'preferences')); } else { $code = $tmhOAuth->apponly_request(array('without_bearer' => true, 'method' => 'POST', 'url' => $tmhOAuth->url('oauth/request_token', ''), 'params' => array('oauth_callback' => Router::url(Router::normalize($this->here), true)))); if ($code != 200) { $this->Session->setFlash(__('There was an error communicating with Twitter.', true) . ' ' . $tmhOAuth->response['response'], 'default', array('class' => 'warning')); $this->redirect(array('action' => 'preferences')); } // store the params into the session so they are there when we come back after the redirect $response = $tmhOAuth->extract_params($tmhOAuth->response['response']); // check the callback has been confirmed if ($response['oauth_callback_confirmed'] !== 'true') { $this->Session->setFlash(__('The callback was not confirmed by Twitter so we cannot continue.', true) . ' ' . $tmhOAuth->response['response'], 'default', array('class' => 'warning')); $this->redirect(array('action' => 'preferences')); } else { $this->Session->write('Twitter.response', $response); $this->redirect($tmhOAuth->url('oauth/authorize', '') . "?oauth_token={$response['oauth_token']}"); } } }
function search($idlist) { global $twitter_keys, $current_key, $all_users, $all_tweet_ids, $bin_name, $dbh, $tweetQueue; $keyinfo = getRESTKey(0); $current_key = $keyinfo['key']; $ratefree = $keyinfo['remaining']; print "\ncurrent key {$current_key} ratefree {$ratefree}\n"; $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret'])); // by hundred for ($i = 0; $i < sizeof($idlist); $i += 100) { if ($ratefree <= 0 || $ratefree % 10 == 0) { print "\n"; $keyinfo = getRESTKey($current_key); $current_key = $keyinfo['key']; $ratefree = $keyinfo['remaining']; $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret'])); } $q = $idlist[$i]; $n = $i + 1; while ($n < $i + 100) { if (!isset($idlist[$n])) { break; } $q .= "," . $idlist[$n]; $n++; } $params = array('id' => $q); $code = $tmhOAuth->user_request(array('method' => 'GET', 'url' => $tmhOAuth->url('1.1/statuses/lookup'), 'params' => $params)); $ratefree--; $reset_connection = false; if ($tmhOAuth->response['code'] == 200) { $data = json_decode($tmhOAuth->response['response'], true); if (is_array($data) && empty($data)) { // all tweets in set are deleted continue; } $tweets = $data; $tweet_ids = array(); foreach ($tweets as $tweet) { $t = new Tweet(); $t->fromJSON($tweet); if (!$t->isInBin($bin_name)) { $all_users[] = $t->from_user_id; $all_tweet_ids[] = $t->id; $tweet_ids[] = $t->id; $tweetQueue->push($t, $bin_name); } print "."; } sleep(1); $retries = 0; // reset retry counter on success } else { if ($retries < 4 && $tmhOAuth->response['code'] == 503) { /* this indicates problems on the Twitter side, such as overcapacity. we slow down and retry the connection */ print "!"; sleep(7); $i--; // rewind $retries++; $reset_connection = true; } else { if ($retries < 4) { print "\n"; print "Failure with code " . $tmhOAuth->response['response']['code'] . "\n"; var_dump($tmhOAuth->response['response']['info']); var_dump($tmhOAuth->response['response']['error']); var_dump($tmhOAuth->response['response']['errno']); print "The above error may not be permanent. We will sleep and retry the request.\n"; sleep(7); $i--; // rewind $retries++; $reset_connection = true; } else { print "\n"; print "Permanent error when querying the Twitter API. Please investigate the error output. Now stopping.\n"; exit(1); } } } if ($reset_connection) { $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret'])); $reset_connection = false; } else { $tweetQueue->insertDB(); } } }