/** * Login to facebook and get the associated cloudrexx user. */ public function login() { // fixing timestamp issue with twitter // it is necessary that the twitter server has the same time as our system date_default_timezone_set('UTC'); $tmhOAuth = new \tmhOAuth(array('consumer_key' => $this->applicationData[0], 'consumer_secret' => $this->applicationData[1])); // set the timestamp $tmhOAuth->config['force_timestamp'] = true; $tmhOAuth->config['timestamp'] = time(); if (isset($_GET['oauth_verifier'])) { $tmhOAuth->config['user_token'] = $_SESSION['oauth']['oauth_token']; $tmhOAuth->config['user_secret'] = $_SESSION['oauth']['oauth_token_secret']; $tmhOAuth->request('POST', $tmhOAuth->url('oauth/access_token', ''), array('oauth_verifier' => $_GET['oauth_verifier'], 'x_auth_access_type' => 'read')); $access_token = $tmhOAuth->extract_params($tmhOAuth->response['response']); $tmhOAuth->config['user_token'] = $access_token['oauth_token']; $tmhOAuth->config['user_secret'] = $access_token['oauth_token_secret']; $tmhOAuth->request('GET', $tmhOAuth->url('1.1/account/verify_credentials')); $resp = json_decode($tmhOAuth->response['response']); unset($_SESSION['oauth']); $name = explode(' ', $resp->name); self::$userdata = array('first_name' => $name[0], 'last_name' => $name[1], 'email' => $resp->screen_name . '@twitter.com'); $this->getContrexxUser($resp->id); } else { $tmhOAuth->request('POST', $tmhOAuth->url('oauth/request_token', ""), array('oauth_callback' => \Cx\Lib\SocialLogin::getLoginUrl(self::OAUTH_PROVIDER))); $_SESSION['oauth'] = $tmhOAuth->extract_params($tmhOAuth->response['response']); $url = 'https://api.twitter.com/oauth/authenticate?oauth_token=' . $_SESSION['oauth']['oauth_token']; \Cx\Core\Csrf\Controller\Csrf::header("Location: " . $url); exit; } }
function nextend_api_auth_flow() { $api_key = NextendRequest::getVar('api_key'); $api_secret = NextendRequest::getVar('api_secret'); $redirect_uri = NextendRequest::getVar('redirect_uri'); if (session_id() == "") { @session_start(); } if (!$api_key || !$api_secret || !$redirect_uri) { $api_key = isset($_SESSION['api_key']) ? $_SESSION['api_key'] : null; $api_secret = isset($_SESSION['api_secret']) ? $_SESSION['api_secret'] : null; $redirect_uri = isset($_SESSION['redirect_uri']) ? $_SESSION['redirect_uri'] : null; } else { $_SESSION['api_key'] = $api_key; $_SESSION['api_secret'] = $api_secret; $_SESSION['redirect_uri'] = $redirect_uri; } if ($api_key && $api_secret) { require_once dirname(__FILE__) . "/api/tmhOAuth.php"; $tmhOAuth = new tmhOAuth(array('consumer_key' => $api_key, 'consumer_secret' => $api_secret)); if (isset($_REQUEST['oauth_verifier'])) { $tmhOAuth->config['user_token'] = $_SESSION['t_oauth']['oauth_token']; $tmhOAuth->config['user_secret'] = $_SESSION['t_oauth']['oauth_token_secret']; $code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/access_token', ''), array('oauth_verifier' => $_REQUEST['oauth_verifier'])); if ($code == 200) { $access_token = $tmhOAuth->extract_params($tmhOAuth->response['response']); unset($_SESSION['api_key']); unset($_SESSION['api_secret']); unset($_SESSION['redirect_uri']); unset($_SESSION['t_oauth']); echo '<script type="text/javascript">'; echo 'window.opener.setToken("' . $access_token['oauth_token'] . '", "' . $access_token['oauth_token_secret'] . '");'; echo '</script>'; } else { echo '<h3>Error</h3><br />'; echo $tmhOAuth->response['response']; exit; } } else { $code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/request_token', ''), array('oauth_callback' => $redirect_uri)); if ($code == 200) { $oauth = $tmhOAuth->extract_params($tmhOAuth->response['response']); $_SESSION['t_oauth'] = $oauth; $authurl = $tmhOAuth->url("oauth/authenticate", '') . "?oauth_token=" . $oauth['oauth_token'] . "&force_login=1"; header('Location: ' . $authurl); exit; } else { echo '<h3>Error</h3><br />'; echo $tmhOAuth->response['response']; exit; } } } }
public function LatestTweetsList($limit = '5') { $conf = SiteConfig::current_site_config(); if (empty($conf->TwitterName) || empty($conf->TwitterConsumerKey) || empty($conf->TwitterConsumerSecret) || empty($conf->TwitterAccessToken) || empty($conf->TwitterAccessTokenSecret)) { return new ArrayList(); } $cache = SS_Cache::factory('LatestTweets_cache'); if (!($results = unserialize($cache->load(__FUNCTION__)))) { $results = new ArrayList(); require_once dirname(__FILE__) . '/tmhOAuth/tmhOAuth.php'; require_once dirname(__FILE__) . '/tmhOAuth/tmhUtilities.php'; $tmhOAuth = new tmhOAuth(array('consumer_key' => $conf->TwitterConsumerKey, 'consumer_secret' => $conf->TwitterConsumerSecret, 'user_token' => $conf->TwitterAccessToken, 'user_secret' => $conf->TwitterAccessTokenSecret, 'curl_ssl_verifypeer' => false)); $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $conf->TwitterName, 'count' => $limit)); $tweets = $tmhOAuth->response['response']; $json = new JSONDataFormatter(); if (($arr = $json->convertStringToArray($tweets)) && is_array($arr) && isset($arr[0]['text'])) { foreach ($arr as $tweet) { try { $here = new DateTime(SS_Datetime::now()->getValue()); $there = new DateTime($tweet['created_at']); $there->setTimezone($here->getTimezone()); $date = $there->Format('Y-m-d H:i:s'); } catch (Exception $e) { $date = 0; } $results->push(new ArrayData(array('Text' => nl2br(tmhUtilities::entify_with_options($tweet, array('target' => '_blank'))), 'Date' => SS_Datetime::create_field('SS_Datetime', $date)))); } } $cache->save(serialize($results), __FUNCTION__); } return $results; }
/** * * @param array $data * @param array $services */ public function sendToSocialMedia(array $data, array $services = array('facebook', 'twitter')) { // init output $ids = array('facebook' => null, 'twitter' => null); // Facebook if (in_array('facebook', $services) && $this->confirmFacebookAccess()) { $facebook = new Facebook(array('appId' => static::$conf->FacebookAppId, 'secret' => static::$conf->FacebookAppSecret)); $facebook->setAccessToken(static::$conf->FacebookPageAccessToken); try { $post_id = $facebook->api("/" . static::$conf->FacebookPageId . "/feed", "post", $data); $ids['facebook'] = $post_id['id']; } catch (FacebookApiException $e) { SS_Log::log('Error ' . $e->getCode() . ' : ' . $e->getFile() . ' Line ' . $e->getLine() . ' : ' . $e->getMessage() . "\n" . 'BackTrace: ' . "\n" . $e->getTraceAsString(), SS_Log::ERR); } } // Twitter if (in_array('twitter', $services) && $this->confirmTwitterAccess()) { $connection = new tmhOAuth(array('consumer_key' => static::$conf->TwitterConsumerKey, 'consumer_secret' => static::$conf->TwitterConsumerSecret, 'user_token' => static::$conf->TwitterOAuthToken, 'user_secret' => static::$conf->TwitterOAuthSecret)); $tweet = $data['name'] . ": " . $data['link']; $code = $connection->request('POST', $connection->url('1.1/statuses/update'), array('status' => $tweet)); if ($code == 200) { $data = json_decode($connection->response['response']); $ids['twitter'] = $data->id_str; } } return $ids; }
/** * This method uses the Twitter API to get specified amount of Tweet Responses * from Twitter for a specified Twitter User. * * @param screenName :: The Twitter Handle for which we require the tweets * @param count :: The number of recent tweets needed for the Twitter User * * @return response :: Array of Twitter Response Objects */ function getTweet($screenName, $count) { $parameters = array(); $parameters['screen_name'] = $screenName; $parameters['count'] = $count; $connection = new tmhOAuth(array('consumer_key' => 'C8U6aOYWFkfuPxOiFBxoF87jF', 'consumer_secret' => 'cODzOUcJSqd3ATG15J25GXZlz7AyhK6gHbRCmsCiMIn0rfMKIu', 'user_token' => '2261472366-CPKf4pZ9fosiZ2zCQfXi7tiexIzbiNfzJ8lEcoC', 'user_secret' => 'gH6qWAAOCrmS38sf5ipaXIxHZHLHNGtYOmCZcJrFli0M9')); $twitterPath = '1.1/statuses/user_timeline.json'; $http_code = $connection->request('GET', $connection->url($twitterPath), $parameters); // If everything is good if ($http_code === 200) { $response = strip_tags($connection->response['response']); $twitterResp = json_decode($response, true); // Log Success if (count($twitterResp) == 200) { logSuccess('tweetylogs.txt', 'Grabbed 200 Tweets for ' . $screenName . ' from the Twitter API.'); logSuccess('success.txt', 'Grabbed 200 Tweets for ' . $screenName . ' from the Twitter API.'); logSuccess('tweetylogs.html', 'Grabbed <b>200</b> Tweets for <b>' . $screenName . '</b> from the Twitter API.'); } else { logWarning('tweetylogs.txt', 'Grabbed ' . (string) count($twitterResp) . ' Tweets for' . $screenName . ' from the Twitter API.'); logWarning('warning.txt', 'Grabbed ' . (string) count($twitterResp) . ' Tweets for' . $screenName . ' from the Twitter API.'); logWarning('tweetylogs.html', 'Grabbed <b>' . (string) count($twitterResp) . '</b> Tweets for <b>' . $screenName . '</b> from the Twitter API.'); } return $twitterResp; } else { logError('tweetylogs.txt', 'Error in the function refreshData.php/getTweet() for Twitter User: '******'. HTTP Code not 200. HTTP Code/Error ID: ' . $http_code . '. Error: ' . $connection->response['error']); logError('error.txt', 'Error in the function refreshData.php/getTweet() for Twitter User: '******'. HTTP Code not 200. HTTP Code/Error ID: ' . $http_code . '. Error: ' . $connection->response['error']); logError('tweetylogs.html', 'Error in the function refreshData.php/getTweet() for Twitter User: <b>' . $screenName . '</b>. HTTP Code not 200. <b>HTTP Code/Error ID:</b> ' . $http_code . '. <b>Error:</b> ' . $connection->response['error']); } }
/** * Checks if the authentication credentials currently stored in hydra.yml are correct or not. * * @return boolean */ public function isAccessTokenValid() { if (empty($this->authentication['accessToken'])) { return false; } $this->api->request('GET', $this->api->url('v1/users/self/feed'), array('access_token' => $this->authentication['accessToken'])); // HTTP 200 means we were successful return $this->api->response['code'] == 200; }
function get_twitter_timeline($user) { //global $user; $tmhOAuth = new tmhOAuth(array('consumer_key' => CONSUMER_KEY, 'consumer_secret' => CONSUMER_SECRET, 'token' => USER_TOKEN, 'secret' => USER_SECRET)); if ($tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline.json'), array('include_entities' => 'false', 'include_rts' => 'false', 'trim_user' => 'true', 'screen_name' => $user, 'exclude_replies' => 'false', 'count' => TL_COUNT), true) != 200) { header("Content-Type: text/html; charset=utf-8"); die('Could not connect to Twitter'); } return json_decode($tmhOAuth->response['response'], true); }
function tweetFromCoffeeMachine($message) { $tmhOAuth = new tmhOAuth(array('consumer_key' => 'yBqPMCfmM59Rbglvz1Ulaw', 'consumer_secret' => 'emXtf7PDoYURANce1RqRE2FaZpgJeaQixRlCafpQ0', 'user_token' => '576073937-gZokaOQgJwY3U64frIV1MkzHfnelx3XvxMC2FHOM', 'user_secret' => 'ursK27EZa2nZliVBBFdfEjpiTwMkqdQoqpnTZG07Sgc')); $code = $tmhOAuth->request('POST', $tmhOAuth->url('1/statuses/update'), array('status' => $message)); /* don't care about the response in this case if ($code == 200) { tmhUtilities::pr(json_decode($tmhOAuth->response['response'])); } else { tmhUtilities::pr($tmhOAuth->response['response']); }*/ }
/** * Returns an array with the permanent access token and access secret * * @param string $code the verification code receivied from authorization request * @return array the keys of the returned array are accessToken */ public function getAccessToken($code, $callBackUrl) { // send request for an access token $status = $this->api->request('POST', 'https://accounts.google.com/o/oauth2/token', array('client_id' => $this->authentication['consumer_key'], 'client_secret' => $this->authentication['consumer_secret'], 'grant_type' => 'authorization_code', 'redirect_uri' => $callBackUrl, 'code' => $code)); if ($status == 200) { // get the access token and store it in a cookie $response = json_decode($this->api->response['response'], true); $return = array('accessToken' => $response['access_token'], 'refreshToken' => $response['refresh_token'], 'expiresIn' => $response['expires_in']); return $return; } throw new ApiException('Obtaining the access token did not work! Status code: ' . $status . '. Response was: ' . $this->api->response['response']); }
function checkTwitter($username) { require_once 'libs/Twitter/tmhOAuth-master/tmhOAuth.php'; require_once 'libs/Twitter/tmhOAuth-master/tmhUtilities.php'; $tmhOAuth = new tmhOAuth(array('consumer_key' => TWITTER_CONSUMER_KEY, 'consumer_secret' => TWITTER_CONSUMER_SECRET, 'user_token' => TWITTER_USER_TOKEN, 'user_secret' => TWITTER_USER_SECRET)); $code = $tmhOAuth->request('GET', 'https://api.twitter.com/1.1/users/lookup.json', array('screen_name' => $username)); if ($code == 200) { return json_decode($tmhOAuth->response['response'], true); } else { return false; } }
function tfuse_get_tweets($username, $count = 20) { $tweets_cache_path = get_template_directory() . '/cache/twitter_json_' . $username . '_rpp_' . $count . '.cache'; if (file_exists($tweets_cache_path)) { $tweets_cache_timer = intval((time() - filemtime($tweets_cache_path)) / 60); } else { $tweets_cache_timer = 0; } if ((!file_exists($tweets_cache_path) or $tweets_cache_timer > 15) && function_exists('curl_init')) { require_once dirname(__FILE__) . '/libs/twitter/tmhOAuth.php'; require_once dirname(__FILE__) . '/libs/twitter/tmhUtilities.php'; $tmhOAuth = new tmhOAuth(array('consumer_key' => tfuse_options('twitter_consumer_key', ''), 'consumer_secret' => tfuse_options('twitter_consumer_secret', ''), 'user_token' => tfuse_options('twitter_user_token', ''), 'user_secret' => tfuse_options('twitter_user_secret', ''))); $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $username)); $response = $tmhOAuth->response; $JsonTweets = json_decode($response['response']); if (is_array($JsonTweets)) { $JsonTweets = array_slice($JsonTweets, 0, $count); foreach ($JsonTweets as $JsonKey => $JsonVal) { // Some reformatting $pattern = array('/[^(:\\/\\/)](www\\.[^ \\n\\r]+)/', '/(https?:\\/\\/[^ \\n\\r]+)/', '/@(\\w+)/', '/^' . $username . ':\\s*/i'); $replace = array('<a href="http://$1" rel="nofollow" target="_blank">$1</a>', '<a href="$1" rel="nofollow" target="_blank">$1</a>', '<a href="http://twitter.com/$1" rel="nofollow" target="_blank">@$1</a>' . ''); $JsonTweets[$JsonKey]->text = preg_replace($pattern, $replace, $JsonTweets[$JsonKey]->text); $JsonTweets[$JsonKey]->created_at = tfuse_since($JsonTweets[$JsonKey]->created_at); } } else { return array(); } // Some error? Return an empty array // You may want to extend this to know the exact error echo curl_error($curl_handle); // or know the http status echo curl_getinfo($curl_handle, CURLINFO_HTTP_CODE); if (file_exists($tweets_cache_path)) { unlink($tweets_cache_path); } $myFile = $tweets_cache_path; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = json_encode($JsonTweets); fwrite($fh, $stringData); fclose($fh); } else { error_reporting(0); $file = file_get_contents($tweets_cache_path, true); if (!empty($file)) { $JsonTweets = json_decode($file); if (!is_array($JsonTweets)) { $JsonTweets = array(); } } } return $JsonTweets; }
/** * Call API * * @param string $method * @param string $uri * @param array $params * @param string $fmt * @return array * @throws \FuelException */ protected function call($method, $uri, $params, $fmt) { $code = $this->tmhoauth->request($method, $this->tmhoauth->url($uri, $fmt), $params); if ($code != 200) { throw new \FuelException('Code:' . $code . ' Response:' . $this->tmhoauth->response['response']); } switch ($fmt) { case 'json': return json_decode($this->tmhoauth->response['response']); default: return $this->tmhoauth->extract_params($this->tmhoauth->response['response']); } }
protected function getTweets($number) { $items = array(); $twitter = new tmhOAuth(array('consumer_key' => TWITTER_CONSUMER_KEY, 'consumer_secret' => TWITTER_CONSUMER_SECRET, 'user_token' => TWITTER_USER_TOKEN, 'user_secret' => TWITTER_USER_SECRET)); $responseCode = $twitter->request('GET', $twitter->url('1/statuses/home_timeline'), array('count' => $number, 'contributor_details' => true)); if (200 == $responseCode) { $tweets = json_decode($twitter->response['response']); foreach ($tweets as $tweet) { $items[] = $this->makeBalloonFromTweet($tweet); } } return $items; }
/** @see WP_Widget::widget */ function widget($args, $instance) { extract($args); //these are our widget options $title = isset($instance['title']) ? $instance['title'] : ""; $animation = isset($instance['animation']) ? $instance['animation'] : ""; $login = isset($instance['login']) ? $instance['login'] : ""; $count = isset($instance['count']) ? $instance['count'] : ""; $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'] : ""; echo $before_widget; require_once locate_template("/libraries/tmhOAuth/tmhOAuth.php"); require_once locate_template("/libraries/tmhOAuth/tmhUtilities.php"); $tmhOAuth = new tmhOAuth(array('consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, 'user_token' => $access_token, 'user_secret' => $access_token_secret)); $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $login, 'count' => $count, 'include_rts' => 'true')); $response = $tmhOAuth->response; ?> <div class="clearfix"> <div class="header_left"> <?php if ($title) { echo ((int) $animation ? str_replace("box_header", "box_header animation-slide", $before_title) : str_replace("animation-slide", "", $before_title)) . apply_filters("widget_title", $title) . $after_title; } ?> </div> <div class="header_right"> <a href="#" id="latest_tweets_prev" class="scrolling_list_control_left icon_small_arrow left_white"></a> <a href="#" id="latest_tweets_next" class="scrolling_list_control_right icon_small_arrow right_white"></a> </div> </div> <div class="scrolling_list_wrapper"> <ul class="scrolling_list latest_tweets"> <?php // require_once(get_template_directory() . "/libraries/lib_autolink.php"); require_once locate_template("/libraries/lib_autolink.php"); $tweets = json_decode($response['response']); if (count($tweets->errors)) { echo '<li class="icon_small_arrow right_white"><p>' . $tweets->errors[0]->message . '! ' . __('Please check your config under Appearance->Widgets->Twitter Feed!', 'medicenter') . '</p></li>'; } else { foreach ($tweets as $tweet) { echo '<li class="icon_small_arrow right_white"><p>' . autolink($tweet->text, 20, ' target="_blank"') . '<abbr title="' . date('c', strtotime($tweet->created_at)) . '" class="timeago">' . $tweet->created_at . '</abbr></p></li>'; } } ?> </ul> </div> <?php echo $after_widget; }
public function getAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json'); /* Set locale to Dutch */ setlocale(LC_ALL, 'nl_NL'); $cacheId = 'Mobile_Twitter'; $cache = Zend_Registry::get('cache'); if (true == ($result = $cache->load($cacheId))) { if ($result->timestamp + 240 < time()) { // vernieuwen om de 4 minuten oftewel 240 seconden $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('Twitter_Webservice')); } $output = $result->output; if ($this->_getParam('version', '1') == '2') { foreach ($output as $key => $tweet) { $output[$key]['text'] = $this->processLinks($tweet['text']); } } } else { $config = Zend_Registry::get('config'); require APPLICATION_ROOT . '/library/Twitter/tmhOAuth.php'; require APPLICATION_ROOT . '/library/Twitter/tmhUtilities.php'; $tmhOAuth = new tmhOAuth(array('consumer_key' => $config->twitter->customer_key, 'consumer_secret' => $config->twitter->customer_secret, 'user_token' => $config->twitter->user_token, 'user_secret' => $config->twitter->user_secret, 'debug' => false)); $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => 'NAAM VAN USER INVULLEN')); if ($tmhOAuth->response['code'] == 200) { $content = json_decode($tmhOAuth->response['response']); } else { $tmhOAuth->pr(htmlentities($tmhOAuth->response['response'])); } $output = array(); foreach ($content as $entry) { $output[] = array('text' => $entry->text, 'created_at' => date('d/m/Y G:i', strtotime($entry->created_at))); } $object = new stdClass(); $object->output = $output; $object->timestamp = time(); $cache->save($object, $cacheId, array('Twitter_Webservice')); if ($this->_getParam('version', '1') == '2') { foreach ($output as $key => $tweet) { $output[$key]['text'] = $this->processLinks($tweet['text']); } } } echo json_encode($output); }
function tweet($message) { $tmhOAuth = new tmhOAuth($config); $tmhOAuth->request('POST', $tmhOAuth->url('1.1/statuses/update'), array('status' => $message)); if ($tmhOAuth->response['code'] == 200) { // En cours de dév, afficher les informations retournées : //$tmhOAuth->pr(json_decode($tmhOAuth->response['response'])); return TRUE; } else { // En cours de dév, afficher les informations retournées : //$tmhOAuth->pr(htmlentities($tmhOAuth->response['response'])); print_r($tmhOAuth->response['response']); return FALSE; } }
public function api($method, $url, $params = null) { $config = Configure::read('Opauth.Strategy.Twitter'); $tmhOAuth = new tmhOAuth(array('consumer_key' => $config['key'], 'consumer_secret' => $config['secret'], 'user_token' => $this->Session->read('Auth.Twitter.access_token'), 'user_secret' => $this->Session->read('Auth.Twitter.secret'), 'curl_ssl_verifypeer' => false)); $url = $tmhOAuth->url($url); $status = $tmhOAuth->request($method, $url, $params); if ($status != 200) { return false; } if (strpos($url, '.json') !== false) { $response = json_decode($tmhOAuth->response['response']); } else { $response = $tmhOAuth->extract_params($this->tmhOAuth->response['response']); } return $response; }
function post_tweet($tweet_text) { // Use Matt Harris' OAuth library to make the connection // This lives at: https://github.com/themattharris/tmhOAuth require_once 'tmhoauth/tmhOAuth.php'; // Set the authorization values // In keeping with the OAuth tradition of maximum confusion, // the names of some of these values are different from the Twitter Dev interface // user_token is called Access Token on the Dev site // user_secret is called Access Token Secret on the Dev site // The values here have asterisks to hide the true contents // You need to use the actual values from Twitter $connection = new tmhOAuth(array('consumer_key' => '******', 'consumer_secret' => '******', 'user_token' => '******', 'user_secret' => '******')); // Make the API call $connection->request('POST', $connection->url('1/statuses/update'), array('status' => $tweet_text)); return $connection->response['code']; }
function post_tweet($tweet_text) { // Use Matt Harris' OAuth library to make the connection // This lives at: https://github.com/themattharris/tmhOAuth require_once 'twitlib/tmhOAuth.php'; // Set the authorization values // In keeping with the OAuth tradition of maximum confusion, // the names of some of these values are different from the Twitter Dev interface // user_token is called Access Token on the Dev site // user_secret is called Access Token Secret on the Dev site // The values here have asterisks to hide the true contents // You need to use the actual values from Twitter $connection = new tmhOAuth(array('consumer_key' => 'Z6EiKT7pZq6OVqvWtZqxg', 'consumer_secret' => '3VyLFSlQg70ZOvj2QAY0egPFB0etNAE8kTOQygZ7kew', 'user_token' => '280185832-LiJ78IFzm1SolSZMaFuAkK5yu1XFMs5hhN48cXS1', 'user_secret' => 'vOlhWfm9sCXYPoMPZUCZY5RlqEOJECcz6LtlIb4C2XE')); // Make the API call $connection->request('POST', $connection->url('1/statuses/update'), array('status' => $tweet_text)); return $connection->response['code']; }
/** @see WP_Widget::widget */ function widget($args, $instance) { extract($args); //these are our widget options $title = $instance['title']; $login = $instance['login']; $count = $instance['count']; $consumer_key = $instance['consumer_key']; $consumer_secret = $instance['consumer_secret']; $access_token = $instance['access_token']; $access_token_secret = $instance['access_token_secret']; echo $before_widget; require_once get_template_directory() . '/libraries/tmhOAuth/tmhOAuth.php'; require_once get_template_directory() . '/libraries/tmhOAuth/tmhUtilities.php'; $tmhOAuth = new tmhOAuth(array('consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, 'user_token' => $access_token, 'user_secret' => $access_token_secret)); $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $login, 'count' => $count, 'include_rts' => 'true')); $response = $tmhOAuth->response; ?> <div class="clearfix"> <div class="header_left"> <?php if ($title) { echo $before_title . $title . $after_title; } ?> </div> <div class="header_right"> <a href="#" id="latest_tweets_prev" class="scrolling_list_control_left icon_small_arrow left_white"></a> <a href="#" id="latest_tweets_next" class="scrolling_list_control_right icon_small_arrow right_white"></a> </div> </div> <div class="scrolling_list_wrapper"> <ul class="scrolling_list latest_tweets"> <?php require_once get_template_directory() . "/libraries/lib_autolink.php"; $tweets = json_decode($response['response']); foreach ($tweets as $tweet) { echo '<li class="icon_small_arrow right_white"><p>' . autolink($tweet->text, 20, ' target="_blank"') . '<abbr title="' . date('c', strtotime($tweet->created_at)) . '" class="timeago">' . $tweet->created_at . '</abbr></p></li>'; } ?> </ul> </div> <?php echo $after_widget; }
public function postTweet($msg) { $msg = clearData($msg); $msg = substr($msg, 0, 140); session_start(); define("USER_TOKEN", $_SESSION['USER_TOKEN']); define("USER_SECRET", $_SESSION['USER_SECRET']); $tmhOAuth = new tmhOAuth(array('consumer_key' => CONSUMER_KEY, 'consumer_secret' => CONSUMER_SECRET, 'user_token' => USER_TOKEN, 'user_secret' => USER_SECRET, 'debug' => true)); $tmhOAuth->request('POST', $tmhOAuth->url('1/statuses/update'), array('status' => $msg)); $code = $tmhOAuth->response['code']; $datetime = $tmhOAuth->config['timestamp']; if ($code == 200) { $FieldValuePairs = array('msg' => $msg, 'datetime' => $datetime, 'user_token' => USER_TOKEN, 'user_secret' => USER_SECRET); $this->insert($FieldValuePairs); return $_SESSION["account"]; } else { echo "There was an error communicating with Twitter. {$tmhOAuth->response['response']}" . PHP_EOL; } }
function get_json_from_twitter($username, $count) { require 'tmhOAuth.php'; $configFilePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . "twitter.api.keys.json"; if (!file_exists($configFilePath)) { die("Could not find config file ({$configFilePath})"); } $rawConfig = file_get_contents($configFilePath); if (!$rawConfig) { die("Could not read config file ({$configFilePath})"); } $config = json_decode($rawConfig); $tmhOAuth = new tmhOAuth(array('consumer_key' => $config->consumer_key, 'consumer_secret' => $config->consumer_secret, 'user_token' => $config->user_token, 'user_secret' => $config->user_secret)); $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $username)); $json = $tmhOAuth->response["response"]; if (!$json) { die("Could not get JSON data from Twitter"); } return $json; }
public static function get_json_from_twitter($username, $count) { require 'tmhOAuth.php'; $configFilePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'twitter.api.keys.json'; if (!file_exists($configFilePath)) { die(esc_html("Could not find config file ({$configFilePath})")); } $rawConfig = file_get_contents($configFilePath); if (!$rawConfig) { die(esc_html("Could not read config file ({$configFilePath})")); } $config = json_decode($rawConfig); $tmhOAuth = new tmhOAuth(array('consumer_key' => $config->consumer_key, 'consumer_secret' => $config->consumer_secret, 'user_token' => $config->user_token, 'user_secret' => $config->user_secret)); $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $username)); $json = $tmhOAuth->response['response']; if (!$json) { die('Please Connect to Internet to get the latest tweets'); } return $json; }
public function display_tweets() { require_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/twitter_api/tmhOAuth.php'; // Use the data from http://dev.twitter.com/apps to fill out this info // notice the slight name difference in the last two items) define('CONSUMER_KEY', '6WRzQSWJQn40FDFAvuJA34c2d'); define('CONSUMER_SECRET', 'J3VaoeoL6btZek1h6jbucLe06WpGbIBtgE1TyA7uOiTwnLeent'); define('ACCESS_TOKEN', '2732477607-2Z0GSIUhoN8W6YBa9OPbau2k7LIr6llzH30Mdz3'); define('ACCESS_TOKEN_SECRET', 'rlVk4ik3KV1J4dbng8jP911xCf7wTZpFMc07W8i3jScR3'); $connection = new tmhOAuth(array('consumer_key' => CONSUMER_KEY, 'consumer_secret' => CONSUMER_SECRET, 'user_token' => ACCESS_TOKEN, 'user_secret' => ACCESS_TOKEN_SECRET)); // set up parameters to pass $parameters = array(); $_GET["count"] = 1; if (isset($_GET['count'])) { $parameters['count'] = strip_tags($_GET['count']); } if (isset($_GET['screen_name'])) { $parameters['screen_name'] = "Cyberwatchcafe"; } if (isset($_GET['twitter_path'])) { $twitter_path = $_GET['twitter_path']; } else { $twitter_path = '1.1/statuses/user_timeline.json'; } $http_code = $connection->request('GET', $connection->url($twitter_path), $parameters); if ($http_code === 200) { // if everything's good $response = strip_tags($connection->response['response']); if (isset($_GET['callback'])) { // if we ask for a jsonp callback function echo $_GET['callback'], '(', $response, ');'; } else { $this->display_response($response); } } else { echo "Error ID: ", $http_code, "\n"; echo "Error: ", $connection->response['error'], "\n"; } // You may have to download and copy http://curl.haxx.se/ca/cacert.pem exit; }
/** * This is called after setup() returns * @return void */ public function start() { $post = $this->post; // Send to Twitter: $tmhOAuth = new \tmhOAuth(array()); $code = $tmhOAuth->request('POST', $tmhOAuth->url('1/statuses/update'), array('status' => $post['content'])); // There is no special handling of API errors. // Right now we just dump the response to MongoDB $post['code'] = $code; $post['response'] = json_decode($tmhOAuth->response['response'], true); // Move this post to another collection named archive: unset($post['processing']); unset($post['processing_time']); $m = new \Mongo(); $m->tampon->archive->insert($post); $m->tampon->posts->remove(array('_id' => $post['_id'])); if ($code == 200) { $this->daemon->log(sprintf("Sent post %s to Twitter, Twitter id: %s by user %s", $post['_id'], (string) $post['response']['id'], $post['response']['screen_name'])); } else { $this->daemon->log(sprintf("Failed sending post %s to Twitter, error code %s: %s", $post['_id'], (string) $code, $post['response']['error']), "warning"); } }
public function getTweets($params = array()) { /* Set locale to Dutch */ setlocale(LC_ALL, 'nl_NL'); $cacheId = 'Model_Twitter'; $cache = Zend_Registry::get('cache'); if (true == ($result = $cache->load($cacheId))) { if ($result->timestamp + $this->options['caching_ttl'] < time()) { $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('Twitter_Webservice')); } return $result->data; } else { require APPLICATION_ROOT . '/library/Twitter/tmhOAuth.php'; require APPLICATION_ROOT . '/library/Twitter/tmhUtilities.php'; $tmhOAuth = new tmhOAuth(array('consumer_key' => $this->options['consumer_key'], 'consumer_secret' => $this->options['consumer_secret'], 'user_token' => $this->options['user_token'], 'user_secret' => $this->options['user_secret'], 'debug' => $this->options['debug'])); $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), $params); if ($tmhOAuth->response['code'] == 200) { $content = json_decode($tmhOAuth->response['response']); } else { // $tmhOAuth->pr(htmlentities($tmhOAuth->response['response'])); } $data = array(); if (!isset($content)) { $content = array(); $content[0] = new stdClass(); $content[0]->text = 'Kon twitter feeds niet laden'; $content[0]->created_at = date("Y-m-d H:i:s"); } foreach ($content as $entry) { $data[] = array('text' => $entry->text, 'created_at' => date('d/m/Y G:i', strtotime($entry->created_at))); } $object = new stdClass(); $object->data = $data; $object->timestamp = time(); $cache->save($object, $cacheId, array('Twitter_Webservice')); return $data; } }
/** * Pull down latest tweets using the twitter API * * @return ArrayList */ public function LatestTweets($limit = 3) { $config = SiteConfig::current_site_config(); $output = new ArrayList(); if ($config->TwitterConsumerKey) { $tmhOAuth = new tmhOAuth(array('consumer_key' => $config->TwitterConsumerKey, 'consumer_secret' => $config->TwitterConsumerSecret, 'user_token' => $config->TwitterAccessToken, 'user_secret' => $config->TwitterAccessTokenSecret, 'curl_ssl_verifypeer' => false)); $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $config->TwitterUsername, 'count' => $limit)); $response = $tmhOAuth->response['response']; $tweets = json_decode($response, true); if (!$tweets) { return false; } if ($this->errorCheck($tweets)) { return false; } foreach ($tweets as &$tweet) { $date = new SS_Datetime(); $date->setValue($tweet['created_at']); $output->push(new ArrayData(array('ID' => $tweet['id'], 'Date' => $date, 'Content' => $this->tweetConvert($tweet['text']), 'User' => new ArrayData(array('ID' => $tweet['user']['id'], 'Name' => $tweet['user']['name'], 'ProfileImg' => $tweet['user']['profile_image_url'], 'ScreenName' => $tweet['user']['screen_name']))))); } } return $output; }
function getLatestTweets() { require Director::baseFolder() . '/twitter-feed/libs/tmhOAuth.php'; require Director::baseFolder() . '/twitter-feed/libs/tmhUtilities.php'; $tmhOAuth = new tmhOAuth(array('consumer_key' => self::get_consumer_key(), 'consumer_secret' => self::get_consumer_secret(), 'user_token' => self::get_user_token(), 'user_secret' => self::get_user_secret(), 'curl_ssl_verifypeer' => false)); $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => self::get_username(), 'count' => self::get_tweetcount() + 10, 'exclude_replies' => true)); $response = $tmhOAuth->response['response']; $tweets = json_decode($response, true); if ($this->_errorCheck($tweets)) { return false; } $output = new ArrayList(); foreach ($tweets as &$tweet) { $tweet['text'] = $this->tweetConvert($tweet['text']); $time = SS_Datetime::create('SS_Datetime'); $time->setValue($tweet['created_at']); $tweet['created_at'] = $time; // $tweet['username'] = self::get_username(); $output->push(new ArrayData($tweet)); } return $output->limit(self::get_tweetcount()); }
/** * 此函数,供Callback处调用,如果返回false,认证失败,否则返回以下哈希表: * last_key -> callback得到的last_key * oauth_token -> 上述lastkey中的oauth_token * oauth_token_secret -> 上述lastkey中的oauth_token_secret * user_id -> 用户ID * user_name -> 用户昵称 * user_email -> 暂不提供 */ function AuthCallback_twitter() { $tmhOAuth = new tmhOAuth(array('consumer_key' => TW_AKEY, 'consumer_secret' => TW_SKEY)); $tmhOAuth->config['user_token'] = $_SESSION['tw_user_token']; $tmhOAuth->config['user_secret'] = $_SESSION['tw_user_secret']; unset($_SESSION['tw_user_token']); unset($_SESSION['tw_user_secret']); $pin = JRequest::getCmd('oobpin'); $code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/access_token', ''), array('oauth_verifier' => trim($pin))); if ($code == 200) { $oauth_creds = $tmhOAuth->extract_params($tmhOAuth->response['response']); $tmhOAuth->config['user_token'] = $oauth_creds['oauth_token']; $tmhOAuth->config['user_secret'] = $oauth_creds['oauth_token_secret']; $rtn = array(); $rtn['last_key'] = $oauth_creds; $rtn['oauth_token'] = $oauth_creds['oauth_token']; $rtn['oauth_token_secret'] = $oauth_creds['oauth_token_secret']; $rtn['user_id'] = $oauth_creds['screen_name']; $rtn['user_name'] = $oauth_creds['screen_name']; return $rtn; } else { return false; } }
function twitter_upload_page($query) { $content = ""; if ($_POST['message'] && $_FILES['image']['tmp_name']) { require 'class.upload.php'; list($oauth_token, $oauth_token_secret) = explode('|', $GLOBALS['user']['password']); $tmhOAuth = new tmhOAuth(array('consumer_key' => OAUTH_KEY, 'consumer_secret' => OAUTH_SECRET, 'user_token' => $oauth_token, 'user_secret' => $oauth_token_secret)); $image = "{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}"; $status = $_POST['message']; $code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json', array('media[]' => "@{$image}", 'status' => " " . $_POST['message']), true, true); if ($code == 200) { $json = json_decode($tmhOAuth->response['response']); if ($_SERVER['HTTPS'] == "on") { $image_url = $json->entities->media[0]->media_url_https; } else { $image_url = $json->entities->media[0]->media_url; } $text = $json->text; $content = "<p>" . __("Upload success. Image posted to Twitter.") . "</p>"; return theme('page', __('Upload Picture'), $content); } else { $content = __("Damn! Something went wrong. Sorry :-(") . "<br /> code=" . $code . "<br /> status=" . $status . "<br /> image=" . $image . "<br /> response=<pre>" . print_r($tmhOAuth->response['response'], TRUE) . "</pre><br /> info=<pre>" . print_r($tmhOAuth->response['info'], TRUE) . "</pre><br /> code=<pre>" . print_r($tmhOAuth->response['code'], TRUE) . "</pre>"; } } if ($_POST) { if (!$_POST['message']) { $content .= "<p>" . __("Please enter a message to go with your image.") . "</p>"; } if (!$_FILES['image']['tmp_name']) { $content .= "<p>" . __("Please select an image to upload.") . "</p>"; } } $content .= "<form method='post' action='" . BASE_URL . "upload' enctype='multipart/form-data'>\n\t\t\t\t\t\t" . __("Image: ") . "<input type='file' name='image' /><br />\n\t\t\t\t\t\t" . __("Content: ") . "<br />\n\t\t\t\t\t\t<textarea name='message' style='width:90%; max-width: 400px;' rows='3' id='message'>" . $_POST['message'] . "</textarea><br>\n\t\t\t\t\t\t<input type='submit' value='" . __("Send") . "'><span id='remaining'>120</span>\n\t\t\t\t\t</form>"; $content .= js_counter("message", "120"); return theme('page', __('Upload Picture'), $content); }