function PostImage() { if (!isset($_POST['source']) || $_POST['source'] == "") { return "Missing required params"; } $config = (include "/config.php"); $source = $_POST['source']; $final = ""; if (isset($_POST['message'])) { $orig = $_POST['message']; $final = FilterText($orig); } $access_token = $_SESSION['access_token']; $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); $check = new TB_Twitter_Check(); if (!$check->VerifyTweet($source, $final)) { return "Tweet is not valid"; exit; } $media1 = $connection->upload('media/upload', array('media' => $source)); $parameters = array('status' => $final, 'media_ids' => implode(',', array($media1->media_id_string))); $result = $connection->post('statuses/update', $parameters); if ($connection->getLastHttpCode() == 200) { return "success"; } else { return "An unnknown error occured"; } }
/** * @return void * @throws \Exception */ public function execute() { $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; $data = $this->getRequest()->getParams(); /* Get temporary credentials from session. */ $request_token = []; $request_token['oauth_token'] = $this->scopeConfig->getValue('sama_twitterfeed/oauth/token', $storeScope); $request_token['oauth_token_secret'] = $this->scopeConfig->getValue('sama_twitterfeed/oauth/token_secret', $storeScope); /* If denied, bail. */ if (isset($data['denied'])) { throw new Exception("Twitter denied permission"); } /* If the oauth_token is not what we expect, bail. */ if (isset($data['oauth_token']) && $request_token['oauth_token'] !== $data['oauth_token']) { throw new Exception("Unexpected Oauth token"); } /* Create TwitteroAuth object with app key/secret and token key/secret from default phase */ $connection = new TwitterOAuth($this->_oAuthkey, $this->_oAuthsecret, $request_token['oauth_token'], $request_token['oauth_token_secret']); /* Request access tokens from twitter */ $access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $data['oauth_verifier'])); /* If HTTP response is 200 continue otherwise send to connect page to retry */ if (200 == $connection->getLastHttpCode()) { $this->_objectManager->get('Magento\\Framework\\App\\MutableScopeConfig')->setValue('sama_twitterfeed/oauth/access_token', $access_token); $this->_objectManager->get('Magento\\Framework\\App\\MutableScopeConfig')->setValue('sama_twitterfeed/oauth/token_secret', null); $this->_objectManager->get('Magento\\Framework\\App\\MutableScopeConfig')->setValue('sama_twitterfeed/oauth/token', null); } else { throw new Exception("Twitter Oauth API status code: {$connection->getLastHttpCode()}"); } return; }
/** * @param Article $article * @param string $header */ public function provide(Article $article, $header = "") { $this->twitter->post("statuses/update", array("status" => "{$header} {$article->getTitle()} >> http://matomepp.net/p/{$article->getArticleId()}")); if ($this->twitter->getLastHttpCode() != 200) { throw new \RuntimeException(json_encode($this->twitter->getLastBody())); } $this->storeTweets($article); }
/** * @depends testLastResult */ public function testResetLastResponse() { $this->twitter->resetLastResponse(); $this->assertEquals('', $this->twitter->getLastApiPath()); $this->assertEquals(0, $this->twitter->getLastHttpCode()); $this->assertEquals(array(), $this->twitter->getLastBody()); }
/** * get user's twitter feed * * @return array|bool */ public function getFeed() { $oFeed = $this->_oTwitterOAth->get("statuses/home_timeline", ["count" => 25, "exclude_replies" => true]); if ($this->_oTwitterOAth->getLastHttpCode() === 200) { return $oFeed; } return false; }
/** * @return void * @throws \Exception */ public function execute() { /* Build TwitterOAuth object with client credentials. */ $connection = new TwitterOAuth($this->_oAuthkey, $this->_oAuthsecret); /* Get temporary credentials. */ $request_token = $connection->oauth('oauth/request_token', ['oauth_callback' => $this->_objectManager->get('Magento\\Framework\\Url')->getUrl('twitterfeed/oauth/callback', [])]); /* If last connection failed don't display authorization link. */ if (200 == $connection->getLastHttpCode()) { $this->_objectManager->get('Magento\\Framework\\App\\MutableScopeConfig')->setValue('sama_twitterfeed/oauth/token', $request_token['oauth_token']); $this->_objectManager->get('Magento\\Framework\\App\\MutableScopeConfig')->setValue('sama_twitterfeed/oauth/token_secret', $request_token['oauth_token_secret']); /* Build authorize URL and redirect user to Twitter. */ $url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token'])); header('location: ' . $url); exit; } else { throw new Exception("Twitter Oauth API status code: {$connection->getLastHttpCode()}"); } }
function HandleResponse() { $request_token = []; $request_token['oauth_token'] = $_SESSION['oauth_token']; $request_token['oauth_token_secret'] = $_SESSION['oauth_token_secret']; if (isset($_REQUEST['oauth_token']) && $request_token['oauth_token'] !== $_REQUEST['oauth_token']) { return false; } $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $request_token['oauth_token'], $request_token['oauth_token_secret']); $access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier'])); if ($connection->getLastHttpCode() == 200) { $_SESSION['access_token'] = $access_token; echo "<script>window.close();</script>"; die; } else { return "An error occured"; } }
function SearchTweets() { // References - https://dev.twitter.com/rest/reference/get/search/tweets // https://dev.twitter.com/rest/public/search if (!isset($_GET['search'])) { return "Missing required params"; } $searchTerms = $_GET['search']; $type = "mixed"; $count = "15"; $geo = ""; $since = ""; if (isset($_GET['type']) && $_GET['type'] != "") { $type = $_GET['type']; } if (isset($_GET['count']) && $_GET['count'] != "") { $count = $_GET['count']; } if (isset($_GET['geo']) && $_GET['geo'] != "") { $geo = $_GET['geo']; } if (isset($_GET['since']) && $_GET['since'] != "") { $since = $_GET['since']; } $requestData = array(); $requestData['q'] = $searchTerms; $requestData['count'] = $count; if ($geo != "") { $requestData['geocode'] = $geo; } if ($since != "") { $requestData['since_id'] = $since; } $requestData['result_type'] = $type; $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); $result = $connection->get("search/tweets", $requestData); if ($connection->getLastHttpCode() == 200) { return $result; } else { return "An unnknown error occured"; } }
/** * Determine first name of Target or return Handle * * @param Integer $id * @return String */ public function name($id) { $twitter = new TwitterOAuth(env('CONSUMER_KEY'), env('CONSUMER_SECRET'), env('ACCESS_TOKEN'), env('ACCESS_SECRET')); // Get Target Handle $target = Targets::find($id); $handle = $target->handle; // Attempt to get real name from Twitter $user = $twitter->get('/users/show', ['screen_name' => $handle]); if ($twitter->getLastHttpCode() === 200 && isset($user->name)) { $target->object = json_encode($user); $target->save(); // Get first name $name = explode(' ', $user->name); $fname = $name[0]; if (ctype_alpha($fname)) { $handle = $fname; } } return $handle; }
<?php require 'config.php'; use Abraham\TwitterOAuth\TwitterOAuth; /* Build TwitterOAuth object with client credentials. */ $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); /* Get temporary credentials. */ $request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK)); /* If last connection failed don't display authorization link. */ if (200 == $connection->getLastHttpCode()) { /* Save temporary credentials to session. */ $_SESSION['oauth_token'] = $request_token['oauth_token']; $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; /* Build authorize URL and redirect user to Twitter. */ $url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token'])); header('Location: ' . $url); } else { /* Show notification if something went wrong. */ echo 'Could not connect to Twitter. Refresh the page or try again later.'; exit; }
<?php require_once __DIR__ . '/config.php'; // package // - Composer use Abraham\TwitterOAuth\TwitterOAuth; $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET); // $content = $connection->get("account/verify_credentials"); // $content = $connection->get("statuses/home_timeline", ['count'=>3]); // var_dump($content); $res = $connection->post("statuses/update", ['status' => 'ドットインストールがおすすめ! http://dotinstall.com #dotinstall']); if ($connection->getLastHttpCode() === 200) { echo 'Success!' . PHP_EOL; } else { echo 'Error!' . $res->errors[0]->message . PHP_EOL; }
// Get the keys from Keys and Access tokens $oauth = new TwitterOAuth('Consumer Key', 'Consumer Secret', 'Access Token', 'Access Token Secret'); // You can fill in more names if you want. they're tweeted at randomly $screen_names[] = 'natefanaro'; $tweets = array(); $i = 0; foreach ($lines as $line) { $length = strlen($line); // making sure it will fit if (isset($tweets[$i]) && strlen($tweets[$i] . $line) > 140) { $i++; } // filling in tweets for users if (!isset($tweets[$i])) { $screen_name = $screen_names[rand(0, count($screen_names) - 1)]; $tweets[$i] = '@' . $screen_name . ' ' . $line . "\n"; } else { $tweets[$i] .= $line . "\n"; } } while (count(array_keys($tweets))) { $tweet = array_pop($tweets); // uppercase if you want to be extra annoying //$tweet = strtoupper($tweet); print $tweet; $new_id = $oauth->post('statuses/update', array('status' => $tweet)); if ($oauth->getLastHttpCode() != 200) { print_r($new_id); } sleep(30); }
// Adapted from: https://github.com/abraham/twitteroauth-demo - redirect.php // For more docuentation and explanation, see: // "Authorization flow" on: https://twitteroauth.com/ // Flow Summary: // 1. User clicks link for "Sign in with Twitter" // 2. Link opens redirect.php - which is this PHP script. // 3. Redirect opens Twitter URL, so user may (or may not) authorize our app. // 4. Upon Authorization, Twitter URL opens our callback.php page. // 5. Callback.php can access user Twitter data via collected tokens and twitteroauth library. // "bootstrap" handles session, library and constants initialization for demo require 'bootstrap.php'; use Abraham\TwitterOAuth\TwitterOAuth; /* Build TwitterOAuth object with client credentials. */ $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); /* Get temporary credentials. */ $request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK)); /* If last connection failed don't display authorization link. */ switch ($connection->getLastHttpCode()) { case 200: /* Save temporary credentials to session. */ $_SESSION['oauth_token'] = $request_token['oauth_token']; $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; /* Build authorize URL and redirect user to Twitter. */ $url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token'])); break; default: /* Show notification if something went wrong. */ exit('(redirect.php): Could not connect to Twitter. Please try again later.'); } // Go the Twitter App Authorisation page, where user says OK or No to the app header("location:" . $url);
/** * Send Tweet through Twitter API * * @return Void */ public function send() { /** * Initiate new Twitter */ $twitter = new TwitterOAuth(env('CONSUMER_KEY'), env('CONSUMER_SECRET'), env('ACCESS_TOKEN'), env('ACCESS_SECRET')); /** * Get Tweets from Queue */ $tweets = $this->next(); /** * Collate Responses */ $results = array(); /** * Generate Images and Upload/Send each Tweet */ foreach ($tweets as $tweet) { // Get Name $name = Admin::name($tweet->target); // Get Target Handle $target = Targets::find($tweet->target); $handle = $target->handle; // Remove Linebreaks from Message $tweet->message_clean = str_replace(array("\r", "\n"), ' ', $tweet->message_clean); if (trim($name) != '' && trim($tweet->message_clean != '')) { // Generate Image Image::setDetails($name, $tweet->message_clean); $image = Image::paintImage(); $details = Image::saveImage($image); // Save Tweet with Image URL $tweet->image_url = $details['image_url']; $tweet->save(); // The Message $hashtag = '#tweetthelove'; $message = '@' . $handle . ' ' . $tweet->message_clean . ' ' . $hashtag; // Upload to Twitter $media = $twitter->upload('media/upload', ['media' => $details['image_url']]); if (isset($media->media_id_string)) { // Post Tweet $status = $twitter->post('statuses/update', ['status' => $message, 'media_ids' => $media->media_id_string]); } if ($twitter->getLastHttpCode() === 200) { // Mark as Sent $tweet->sent = 1; $tweet->save(); $result = true; } else { $tweet->failed = 1; $tweet->save(); $result = json_encode($twitter->getLastBody()); } } else { $tweet->failed = 1; $tweet->save(); $result = false; } $results[$tweet->id] = array('status' => $result, 'message' => $message); } return $results; }
/** * Action wp_ajax_get_latest_tweets * * Handles AJAX request for retrieving latest tweets * * @since 4.1.0 * * @return void */ public function action_wp_ajax_get_latest_tweets() { check_ajax_referer('cw-latest-tweets-nonce', 'nonce'); $latest_tweets = get_transient('cw_latest_tweets'); if (false === $latest_tweets) { $latest_tweets = array(); $max_tweets = isset($_POST['count']) ? absint($_POST['count']) : 7; // WPCS: input var OK. // Require the twitter auth library. require CW_PLUGIN_INCLUDES . '/vendor/twitteroauth/autoload.php'; $twitter_connection = new TwitterOAuth(CW_TWITTER_OAUTH_CONSUMER_KEY, CW_TWITTER_OAUTH_CONSUMER_SECRET, CW_TWITTER_OAUTH_ACCESS_TOKEN, CW_TWITTER_OAUTH_ACCESS_SECRET); $raw_tweets = $twitter_connection->get('statuses/user_timeline', array('screen_name' => sanitize_text_field($_POST['userName']), 'count' => 200, 'exclude_replies' => true, 'include_rts' => false)); if (200 === $twitter_connection->getLastHttpCode() && !empty($raw_tweets)) { $hashtag_link_pattern = '<a href="http://twitter.com/search?q=%%23%s&src=hash" rel="nofollow" target="_blank">#%s</a>'; $url_link_pattern = '<a href="%s" rel="nofollow" target="_blank" title="%s">%s</a>'; $user_mention_link_pattern = '<a href="http://twitter.com/%s" rel="nofollow" target="_blank" title="%s">@%s</a>'; $media_link_pattern = '<a href="%s" rel="nofollow" target="_blank" title="%s">%s</a>'; $tweet_count = 0; foreach ($raw_tweets as $tweet) { if ($tweet_count >= $max_tweets) { break; } $text = $tweet->text; $entity_holder = array(); foreach ($tweet->entities->hashtags as $hashtag) { $entity = new \stdClass(); $entity->start = $hashtag->indices[0]; $entity->end = $hashtag->indices[1]; $entity->length = $hashtag->indices[1] - $hashtag->indices[0]; $entity->replace = sprintf($hashtag_link_pattern, strtolower($hashtag->text), $hashtag->text); $entity_holder[$entity->start] = $entity; } foreach ($tweet->entities->urls as $url) { $entity = new \stdClass(); $entity->start = $url->indices[0]; $entity->end = $url->indices[1]; $entity->length = $url->indices[1] - $url->indices[0]; $entity->replace = sprintf($url_link_pattern, $url->url, $url->expanded_url, $url->display_url); $entity_holder[$entity->start] = $entity; } foreach ($tweet->entities->user_mentions as $user_mention) { $entity = new \stdClass(); $entity->start = $user_mention->indices[0]; $entity->end = $user_mention->indices[1]; $entity->length = $user_mention->indices[1] - $user_mention->indices[0]; $entity->replace = sprintf($user_mention_link_pattern, strtolower($user_mention->screen_name), $user_mention->name, $user_mention->screen_name); $entity_holder[$entity->start] = $entity; } foreach ($tweet->entities->media as $media) { $entity = new \stdClass(); $entity->start = $media->indices[0]; $entity->end = $media->indices[1]; $entity->length = $media->indices[1] - $media->indices[0]; $entity->replace = sprintf($media_link_pattern, $media->url, $media->expanded_url, $media->display_url); $entity_holder[$entity->start] = $entity; } krsort($entity_holder); foreach ($entity_holder as $entity) { $text = substr_replace($text, $entity->replace, $entity->start, $entity->length); } $text = '<div class="cw_tweet"><span class="cw_tweet_text">' . $text . '</span><span class="cw_tweet_time"><a href="' . esc_url('https://twitter.com/ChrisWiegman/statuses/' . $tweet->id) . '" target="_blank">' . esc_html(date('F jS, Y g:i a', strtotime($tweet->created_at))) . '</a></span></div>'; $latest_tweets[] = $text; $tweet_count++; } } // Save our new transient. set_transient('cw_latest_tweets', $latest_tweets, 3600); } wp_send_json_success($latest_tweets); }
/** * Actually send the tweet and deals with any redirection * set in the session * * @param TwitterOAuth $connection Twitter oauth connection * * @return void */ protected function sendTweet($connection) { $formModel = $this->getModel(); $input = $this->app->input; $formdata = $this->session->get('com_' . $this->package . '.form.data'); /* * @TODO incorrect for API1.1 should implement this * https://dev.twitter.com/docs/api/1.1/get/application/rate_limit_status. For now just use error msg * $content = $connection->get('account/rate_limit_status'); if ($content->remaining_hits <= 0) { $app->enqueueMessage(FText::_('TWITTER_ACCOUNT_LIMIT_REACHED')); } */ // Get logged in user to help with tests $user = $connection->get('account/verify_credentials'); $msg = $_SESSION['msg']; $parameters = array('status' => $msg); $status = $connection->post('statuses/update', $parameters); $show_success = (int) $this->session->get('com_' . $this->package . '.form.twitter.showmessage', 0); switch ($connection->getLastHttpCode()) { case 200: case 304: if ($show_success == 1) { $this->app->enqueueMessage(FText::_('PLG_FORM_TWITTER_SUCCESS')); } break; default: $this->app->enqueueMessage(FText::_('PLG_FORM_TWITTER_ERR') . ": " . $connection->getLastHttpCode() . " : " . $status->errors[0]->message); } $url = $input->get('fabrik_referrer', '', 'string'); $context = $formModel->getRedirectContext(); $url = $this->session->get($context . 'url', array($url)); $url = array_shift($url); $this->app->redirect($url); }