示例#1
0
 public function fetch($limit = FALSE)
 {
     // XXX: Store state in database config for now
     $config = Kohana::$config;
     $this->_initialize($config);
     //Check if data provider is available
     $providers_available = $config->load('features.data-providers');
     if (!$providers_available['twitter']) {
         Kohana::$log->add(Log::WARNING, 'The twitter data source is not currently available. It can be accessed by upgrading to a higher Ushahidi tier.');
         return 0;
     }
     // check if we have reached our rate limit
     if (!$this->_can_make_request()) {
         Kohana::$log->add(Log::WARNING, 'You have reached your rate limit for this window');
         return 0;
     }
     $options = $this->options();
     // Check we have the required config
     if (!isset($options['consumer_key']) || !isset($options['consumer_secret']) || !isset($options['oauth_access_token']) || !isset($options['oauth_access_token_secret']) || !isset($options['twitter_search_terms'])) {
         Kohana::$log->add(Log::WARNING, 'Could not fetch messages from twitter, incomplete config');
         return 0;
     }
     $connection = new TwitterOAuth($options['consumer_key'], $options['consumer_secret'], $options['oauth_access_token'], $options['oauth_access_token_secret']);
     // Increase curl timeout values
     $connection->setTimeouts(100, 150);
     $count = 0;
     try {
         $results = $connection->get("search/tweets", ["q" => $this->_construct_get_query($options['twitter_search_terms']), "since_id" => $this->since_id, "count" => $limit, "result_type" => 'recent']);
         if (!$results->statuses) {
             return 0;
         }
         $statuses = $results->statuses;
         // Store the highest id
         $this->since_id = $statuses[0]->id;
         foreach ($statuses as $status) {
             $id = $status->id;
             $user = $status->user;
             $screen_name = $user->screen_name;
             $text = $status->text;
             // Try to connect with some service for structure data
             $payload = array('message' => $text);
             $twtan = new TwitterAnalyzer();
             $result_json = $twtan->analyze($payload);
             $text = $text . "\n\n" . $result_json;
             // @todo Check for similar messages in the database before saving
             $this->receive(Message_Type::TWITTER, $screen_name, $text, $to = NULL, $title = NULL, $id);
             $count++;
         }
         $this->request_count++;
         //Increment for successful request
         $this->_update($config);
     } catch (TwitterOAuthException $toe) {
         Kohana::$log->add(Log::ERROR, $toe->getMessage());
     } catch (Exception $e) {
         Kohana::$log->add(Log::ERROR, $e->getMessage());
     }
     return $count;
 }
 public function getTweets()
 {
     $toa = new TwitterOAuth($this->consumerKey, $this->consumerSecret, $this->accessToken, $this->accessTokenSecret);
     $toa->setTimeouts(10, 15);
     $hashtag = '#4LTrophy';
     $query = ['q' => $hashtag];
     $results = $toa->get('search/tweets', $query);
     return $results->statuses;
 }
 /**
  * Initialize TwitterOauth depending is the user is logged in or not.
  *
  * @param   int  $sOathType the type of initizalization of TwitterOath
  * @return  bool
  */
 private function _initializeTwitterOauth($sOathType = self::OAUTH_BASIC)
 {
     if ($sOathType == self::OAUTH_BASIC) {
         $this->_oTwitterOAth = new TwitterOAuth(TwitterAPI::KEY, TwitterAPI::SECRET);
     } elseif ($sOathType == self::OAUTH_VERIFIED) {
         $aAccessToken = $this->getLoggedInAccessToken();
         $this->_oTwitterOAth = new TwitterOAuth(TwitterAPI::KEY, TwitterAPI::SECRET, $aAccessToken['oauth_token'], $aAccessToken['oauth_token_secret']);
     } elseif ($sOathType == self::OAUTH_VERIFIER) {
         $sOathToken = AppSessionHandler::i()->get('oauth_token');
         $sOathTokenSecret = AppSessionHandler::i()->get('oauth_token_secret');
         $this->_oTwitterOAth = new TwitterOAuth(TwitterAPI::KEY, TwitterAPI::SECRET, $sOathToken, $sOathTokenSecret);
     } elseif ($sOathType == self::OAUTH_VERIFIER_CONVERTED) {
         $sOathVerifier = AppSessionHandler::i()->get('oauth_verifier');
         $aAccessToken = $this->getAccessToken($sOathVerifier);
         if (isset($aAccessToken['oauth_token']) && isset($aAccessToken['oauth_token_secret'])) {
             $this->_oTwitterOAth = new TwitterOAuth(TwitterAPI::KEY, TwitterAPI::SECRET, $aAccessToken['oauth_token'], $aAccessToken['oauth_token_secret']);
         }
     }
     $this->_oTwitterOAth->setTimeouts(10, 15);
     return $this->_oTwitterOAth instanceof TwitterOAuth;
 }
 public static function Connection()
 {
     if (self::$connection) {
         return self::$connection;
     }
     $config = self::config();
     $consumer_key = $config->consumer_key;
     $consumer_secret = $config->consumer_secret;
     $oauth_token = $config->oauth_token;
     $oauth_token_secret = $config->oauth_token_secret;
     if (empty($consumer_key) || empty($consumer_secret) || empty($oauth_token) || empty($oauth_token_secret)) {
         throw new Exception(__METHOD__ . '(): Twitter credentials do not exist in the configuration.');
     }
     self::$connection = new TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
     self::$connection->setTimeouts(30, 30);
     //Test the connection
     $response = self::$connection->get('account/verify_credentials');
     if (self::Error()) {
         throw new Exception(__METHOD__ . '(): Connection failed. ' . self::ErrorMessage($response));
     }
     return self::$connection;
 }
 public static function get_tweets($username, $limit = 5, $includeRetweets = FALSE, $excludeReplies = TRUE)
 {
     $config = self::config();
     $connection = new TwitterOAuth($config->twitter_consumer_key, $config->twitter_consumer_secret, $config->twitter_oauth_token, $config->twitter_oauth_token_secret);
     $connection->setTimeouts(30, 30);
     $parameters = array('count' => $limit, 'include_entities' => TRUE, 'include_rts' => $includeRetweets, 'exclude_replies' => $excludeReplies, 'screen_name' => $username);
     $tweets = $connection->get('statuses/user_timeline', $parameters);
     $tweetList = new ArrayList();
     if (count($tweets) > 0 && !isset($tweets->error)) {
         foreach ($tweets as $i => $tweet) {
             $tweetList->push(self::create_tweet($tweet));
         }
     }
     return $tweetList;
 }
 public function testPostStatusesUpdateWithMedia()
 {
     $this->twitter->setTimeouts(60, 30);
     // Image source https://www.flickr.com/photos/titrans/8548825587/
     $file_path = __DIR__ . '/kitten.jpg';
     $result = $this->twitter->upload('media/upload', array('media' => $file_path));
     $this->assertEquals(200, $this->twitter->getLastHttpCode());
     $this->assertObjectHasAttribute('media_id_string', $result);
     $parameters = array('status' => 'Hello World ' . time(), 'media_ids' => $result->media_id_string);
     $result = $this->twitter->post('statuses/update', $parameters);
     $this->assertEquals(200, $this->twitter->getLastHttpCode());
     if ($this->twitter->getLastHttpCode() == 200) {
         $result = $this->twitter->post('statuses/destroy/' . $result->id_str);
     }
     return $result;
 }
示例#7
0
 public function testPostStatusesUpdateWithMediaChunked()
 {
     $this->twitter->setTimeouts(60, 30);
     // Video source http://www.sample-videos.com/
     $file_path = __DIR__ . '/video.mp4';
     $result = $this->twitter->upload('media/upload', array('media' => $file_path, 'media_type' => 'video/mp4'), true);
     $this->assertEquals(201, $this->twitter->getLastHttpCode());
     $this->assertObjectHasAttribute('media_id_string', $result);
     $parameters = array('status' => 'Hello World ' . time(), 'media_ids' => $result->media_id_string);
     $result = $this->twitter->post('statuses/update', $parameters);
     $this->assertEquals(200, $this->twitter->getLastHttpCode());
     if ($this->twitter->getLastHttpCode() == 200) {
         $result = $this->twitter->post('statuses/destroy/' . $result->id_str);
     }
     return $result;
 }
示例#8
0
 public function fetch($limit = FALSE)
 {
     // XXX: Store state in database config for now
     $config = Kohana::$config;
     $this->_initialize($config);
     // check if we have reached our rate limit
     if (!$this->_can_make_request()) {
         Kohana::$log->add(Log::WARNING, 'You have reached your rate limit for this window');
         return 0;
     }
     $options = $this->options();
     // Check we have the required config
     if (!isset($options['consumer_key']) || !isset($options['consumer_secret']) || !isset($options['oauth_access_token']) || !isset($options['oauth_access_token_secret']) || !isset($options['twitter_search_terms'])) {
         Kohana::$log->add(Log::WARNING, 'Could not fetch messages from twitter, incomplete config');
         return 0;
     }
     $connection = new TwitterOAuth($options['consumer_key'], $options['consumer_secret'], $options['oauth_access_token'], $options['oauth_access_token_secret']);
     // Increase curl timeout values
     $connection->setTimeouts(100, 150);
     try {
         $results = $connection->get("search/tweets", ["q" => $this->_construct_get_query($options['twitter_search_terms']), "since_id" => $this->since_id, "count" => $limit, "result_type" => 'recent']);
         if (!$results->statuses) {
             return 0;
         }
         $statuses = $results->statuses;
         // Store the highest id
         $this->since_id = $statuses[0]->id;
         $count = 0;
         foreach ($statuses as $status) {
             $id = $status->id;
             $user = $status->user;
             $screen_name = $user->screen_name;
             $text = $status->text;
             // @todo Check for similar messages in the database before saving
             $this->receive(Message_Type::TWITTER, $screen_name, $text, $to = NULL, $title = NULL, $id);
             $count++;
         }
         $this->request_count++;
         //Increment for successful request
         $this->_update($config);
     } catch (TwitterOAuthException $toe) {
         Kohana::$log->add(Log::ERROR, $toe->getMessage());
     } catch (Exception $e) {
         Kohana::$log->add(Log::ERROR, $e->getMessage());
     }
     return $count;
 }
 public function testPostStatusesUpdateWithMediaInSamePost()
 {
     $this->twitter->setTimeouts(60, 30);
     // Image source https://www.flickr.com/photos/titrans/8548825587/
     $file_path = __DIR__ . '/kitten.jpg';
     $parameters = array('status' => 'Hello World with a kitten ' . time(), 'media[]' => '@' . $file_path);
     $result = $this->twitter->post('statuses/update_with_media', $parameters, true);
     $this->assertEquals(200, $this->twitter->getLastHttpCode());
     if ($this->twitter->getLastHttpCode() == 200) {
         $result = $this->twitter->post('statuses/destroy/' . $result->id_str);
     }
     $this->assertObjectNotHasAttribute('errors', $result);
     $this->assertObjectHasAttribute('entities', $result);
     $this->assertObjectHasAttribute('media', $result->entities);
     $this->assertArrayHasKey(0, $result->entities->media);
     $media = $result->entities->media[0];
     $this->assertNotEmpty($media->media_url);
     $this->assertNotEmpty($media->media_url_https);
     return $result;
 }
 /**
  * @param TwitterCredentials $twitterCredentials
  */
 public function __construct(TwitterCredentials $twitterCredentials)
 {
     $this->twitterCredentials = $twitterCredentials;
     $this->twitterOAuth = new TwitterOAuth($twitterCredentials->getConsumerKey(), $twitterCredentials->getConsumerSecret(), $twitterCredentials->getOAuthToken(), $twitterCredentials->getOAuthSecret());
     $this->twitterOAuth->setTimeouts(10, 15);
 }
示例#11
0
 public function fetch($limit = FALSE)
 {
     // XXX: Store state in database config for now
     $config = Kohana::$config;
     $this->_initialize($config);
     //Check if data provider is available
     $providers_available = $config->load('features.data-providers');
     if (!$providers_available['twitter']) {
         Kohana::$log->add(Log::WARNING, 'The twitter data source is not currently available. It can be accessed by upgrading to a higher Ushahidi tier.');
         return 0;
     }
     // check if we have reached our rate limit
     if (!$this->_can_make_request()) {
         Kohana::$log->add(Log::WARNING, 'You have reached your rate limit for this window');
         return 0;
     }
     $options = $this->options();
     // Check we have the required config
     if (!isset($options['consumer_key']) || !isset($options['consumer_secret']) || !isset($options['oauth_access_token']) || !isset($options['oauth_access_token_secret']) || !isset($options['twitter_search_terms'])) {
         Kohana::$log->add(Log::WARNING, 'Could not fetch messages from twitter, incomplete config');
         return 0;
     }
     if ($limit === FALSE) {
         $limit = 50;
     }
     $connection = new TwitterOAuth($options['consumer_key'], $options['consumer_secret'], $options['oauth_access_token'], $options['oauth_access_token_secret']);
     $connection->setDecodeJsonAsArray(true);
     // Increase curl timeout values
     $connection->setTimeouts(100, 150);
     $count = 0;
     try {
         $results = $connection->get("search/tweets", ["q" => $this->_construct_get_query($options['twitter_search_terms']), "since_id" => $this->since_id, "count" => $limit, "result_type" => 'recent']);
         if (empty($results['statuses'])) {
             return 0;
         }
         $statuses = $results['statuses'];
         // Store the highest id
         $this->since_id = $statuses[0]['id'];
         foreach ($statuses as $status) {
             $id = $status['id'];
             $user = $status['user'];
             $screen_name = $user['screen_name'];
             $text = $status['text'];
             $additional_data = [];
             // Skip retweets
             if (array_key_exists('retweeted_status', $status) && array_key_exists('text', $status['retweeted_status'])) {
                 continue;
             }
             if ($status['coordinates'] || $status['place']) {
                 $additional_data['location'] = [];
                 if ($status['coordinates']) {
                     $additional_data['location'][] = $status['coordinates'];
                 }
                 if ($status['place'] && $status['place']['bounding_box']) {
                     // Make a valid linear ring
                     $status['place']['bounding_box']['coordinates'][0][] = $status['place']['bounding_box']['coordinates'][0][0];
                     // If we don't already have a location
                     if (empty($additional_data['location'])) {
                         // Find center of bounding box
                         $geom = GeoJSON::geomFromText(json_encode($status['place']['bounding_box']));
                         // Use mysql to run Centroid
                         $result = DB::select([DB::expr('AsText(Centroid(GeomFromText(:poly)))')->param(':poly', $geom->toWKT()), 'center'])->execute(service('kohana.db'));
                         $centerGeom = WKT::geomFromText($result->get('center', 0));
                         // Save center as location
                         $additional_data['location'][] = $centerGeom->toGeoArray();
                     }
                     // Add that to location
                     // Also save the original bounding box
                     $additional_data['location'][] = $status['place']['bounding_box'];
                 }
             } else {
                 if ($status['user'] && $status['user']['location']) {
                     # Search the provided location for matches in twitter's geocoder
                     $results = $connection->get("geo/search", ["query" => $status['user']['location']]);
                     # If there are results, get the centroid of the first one
                     if (!empty($results['result']['places'])) {
                         $geoloc = $results['result']['places'][0];
                         if ($geoloc['centroid']) {
                             $additional_data['location'][] = array('coordinates' => $geoloc['centroid'], 'type' => 'Point');
                         }
                         # Add the bounding box too (if available)
                         if ($geoloc['bounding_box']) {
                             $additional_data['location'][] = $geoloc['bounding_box'];
                         }
                     }
                 }
             }
             // @todo Check for similar messages in the database before saving
             $this->receive(Message_Type::TWITTER, $screen_name, $text, $to = NULL, $title = NULL, $id, $additional_data);
             $count++;
         }
         $this->request_count++;
         //Increment for successful request
         $this->_update($config);
     } catch (TwitterOAuthException $toe) {
         Kohana::$log->add(Log::ERROR, $toe->getMessage());
     } catch (Exception $e) {
         Kohana::$log->add(Log::ERROR, $e->getMessage());
     }
     return $count;
 }
    $ret = preg_replace("/#(\\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $ret);
    // Hash Tags
    return $ret;
}
try {
    $adapter = new Local($config['uploads_dir'] . '/twitter/');
    $filesystem = new Filesystem($adapter);
    $filesystem->addPlugin(new ListWith());
    $capsule = new Capsule();
    foreach ($config['databases'] as $name => $database) {
        $capsule->addConnection($database, $name);
    }
    $capsule->setAsGlobal();
    $capsule->bootEloquent();
    $connection = new TwitterOAuth($config['twitter_consumer_key'], $config['twitter_consumer_secret'], $config['twitter_access_token'], $config['twitter_access_secret']);
    $connection->setTimeouts(10, 15);
    if ($filesystem->has('last.tweet')) {
        $lastId = $filesystem->read('last.tweet');
        $content_search = $connection->get("search/tweets", array("q" => $config['twitter_hashtag_search'], "result_type" => "recent", "count" => "10", "since_id" => "{$lastId}"));
    } else {
        $content_search = $connection->get("search/tweets", array("q" => $config['twitter_hashtag_search'], "result_type" => "recent", "count" => "10"));
    }
    foreach ($content_search->statuses as $elem_search) {
        $id_tweet = $elem_search->id_str;
        $lastId = $id_tweet;
        // https://dev.twitter.com/overview/api/users
        $nome = $elem_search->user->name;
        $nick = $elem_search->user->screen_name;
        $profile_image_url = $elem_search->user->profile_image_url;
        $testo_tweet = $elem_search->text;
        if (isset($elem_search->retweeted_status)) {
示例#13
0
 public function search($access_token, $term)
 {
     $ret = array();
     $query = array("q" => $term, "count" => 100, "exclude_replies" => true);
     if (!empty($access_token)) {
         $connection = new TwitterOAuth($this->twitter_app_id, $this->twitter_api_secret, $access_token['oauth_token'], $access_token['oauth_token_secret']);
         $connection->setTimeouts(10, 15);
         //To prevent timeout error
         $ret = $connection->get("search/tweets", $query);
     }
     return $ret;
 }