示例#1
0
 /**
  * fetch the tweets from Twitter using the specified query params in the DB
  * the query params are specific to the passed in hash
  * @param string $campaign_hash the md5 hash of the campaign
  */
 static function fetch_tweets_from_twitter($campaign_hash)
 {
     $app = \maverick\maverick::getInstance();
     $queries = db::table('campaigns AS c')->leftJoin('queries AS q', array('c.id', '=', 'q.campaign_id'))->where('c.campaign_hash', '=', db::raw($campaign_hash))->get(array('c.id', 'c.name', 'c.url', 'q.type', 'q.content'))->fetch();
     // build up the query
     if (count($queries)) {
         $campaign_id = $queries[0]['id'];
         $q_parts = array();
         foreach ($queries as $q) {
             switch ($q['type']) {
                 case 'or':
                     $q_parts[] = "OR {$q['content']}";
                     break;
                 case 'not':
                     $q_parts[] = "-{$q['content']}";
                     break;
                 case 'hashtag':
                     $q_parts[] = "#{$q['content']}";
                     break;
                 case 'to':
                     $q_parts[] = "to:{$q['content']}";
                     break;
                 case 'from':
                     $q_parts[] = "from:{$q['content']}";
                     break;
                 case 'at':
                     $q_parts[] = "@{$q['content']}";
                     break;
                 case 'question':
                     $q_parts[] = '?';
                     break;
                 default:
                     // ands and sentiment as the latter two will have their respective values in the content field
                     $q_parts[] = $q['content'];
             }
         }
         $query = implode(' ', $q_parts);
         // https://twitteroauth.com/
         $connection = new \Abraham\TwitterOAuth\TwitterOAuth($app->get_config('twitter.consumer_key'), $app->get_config('twitter.consumer_secret'), $app->get_config('twitter.access_token'), $app->get_config('twitter.access_token_secret'));
         $search = $connection->get('search/tweets', array('q' => "#crestonexpo #tweetput", 'result_type' => 'recent', 'count' => 100));
         if (!empty($search->statuses)) {
             foreach ($search->statuses as $status) {
                 $data = array('campaign_id' => $campaign_id, 'iso_lang' => $status->lang, 'user_id' => $status->user->id_str, 'user_name' => $status->user->name, 'user_screen_name' => $status->user->screen_name, 'user_location' => $status->user->location, 'tweet_id' => $status->id_str, 'created_at' => date("Y-m-d H:i:s", strtotime($status->created_at)), 'content' => !empty($status->retweeted_status) ? $status->retweeted_status->text : $status->text, 'source' => $status->source, 'in_reply_to_id' => (int) $status->in_reply_to_user_id_str, 'in_reply_to_screen_name' => $status->in_reply_to_screen_name, 'retweet_count' => $status->retweet_count);
                 $tweet_id = db::table('tweets')->insert($data)->fetch();
                 var_dump($status, $tweet_id);
                 $data = array();
                 foreach (array('hashtags', 'urls', 'media') as $entity_type) {
                     if (!empty($status->entities->{$entity_type})) {
                         foreach ($status->entities->{$entity_type} as $entity) {
                             $data[] = array('tweet_id' => $tweet_id, 'entity_type' => rtrim($entity_type, 's'), 'content' => $entity_type == 'hashtag' ? $entity->text : null, 'url' => $entity_type == 'urls' ? $entity->expanded_url : ($entity_type == 'media' ? $entity->media_url_https : null));
                         }
                     }
                 }
                 $tweet_entities = db::table('tweet_entities')->insert($data)->fetch();
             }
         }
     }
 }
 /**
  * @param string $oauth_verifier
  * @return array
  */
 public function getToken($oauth_verifier)
 {
     $connection = new \Abraham\TwitterOAuth\TwitterOAuth($this->app_key, $this->app_secret, $this->session->getData('oauth_token'), $this->session->getData('oauth_token_secret'));
     $access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $oauth_verifier));
     $connection = new \Abraham\TwitterOAuth\TwitterOAuth($this->app_key, $this->app_secret, $access_token['oauth_token'], $access_token['oauth_token_secret']);
     $credentials = $connection->get('/account/verify_credentials', ['include_entities' => true, 'skip_status' => true, 'include_email' => true]);
     $access_token['since_id'] = $credentials;
     return $access_token;
 }
 public static function updateTwitterPosts()
 {
     $connection = new \Abraham\TwitterOAuth\TwitterOAuth(Config::get('laravel-social-feeder::twitterCredentials.consumerKey'), Config::get('laravel-social-feeder::twitterCredentials.consumerSecret'), Config::get('laravel-social-feeder::twitterCredentials.accessToken'), Config::get('laravel-social-feeder::twitterCredentials.accessTokenSecret'));
     $params = array('screen_name' => Config::get('laravel-social-feeder::twitterCredentials.screen_name'), 'count' => 10);
     $lastTwitterPost = \SocialPost::type('twitter')->latest('published_at')->limit('1')->get()->first();
     if ($lastTwitterPost) {
         $params['since_id'] = $lastTwitterPost->social_id;
     }
     try {
         $tweets = $connection->get('statuses/user_timeline', $params);
     } catch (Exception $e) {
         $tweets = array();
     }
     foreach ($tweets as $tweet) {
         if (!is_object($tweet)) {
             continue;
         }
         $newPostData = ['type' => 'twitter', 'social_id' => $tweet->id_str, 'url' => 'https://twitter.com/' . $params['screen_name'] . '/status/' . $tweet->id_str, 'text' => $tweet->text, 'show_on_page' => 1, 'published_at' => date('Y-m-d H:i:s', strtotime($tweet->created_at))];
         $newPostEntity = new \SocialPost();
         $newPostEntity->fill($newPostData)->save();
     }
     return true;
 }
 public static function getEntriesByHashtag()
 {
     //Start - get all hashtags from the database
     $sql = rex_sql::factory();
     $hashtags = $sql->getArray('SELECT `hashtag`, `twitter_next_id` FROM `' . rex::getTablePrefix() . 'socialhub_twitter_hashtag`');
     unset($sql);
     if (empty($hashtags)) {
         return false;
     }
     //End - get all hashtags from the database
     //Start - get all accounts from the database
     $sql = rex_sql::factory();
     $accounts = $sql->getArray('SELECT * FROM `' . rex::getTablePrefix() . 'socialhub_twitter_account` ORDER BY `id` ASC');
     unset($sql);
     if (empty($accounts)) {
         return false;
     }
     //End - get all accounts from the database
     //Start - get entries by hashtag from twitter
     foreach ($hashtags as $hashtag) {
         $connection = new Abraham\TwitterOAuth\TwitterOAuth($accounts[0]['consumer_token'], $accounts[0]['consumer_secret_token'], $accounts[0]['access_token'], $accounts[0]['secret_token']);
         if ($hashtag['twitter_next_id'] != 0) {
             $response = $connection->get("search/tweets", ['q' => '#' . $hashtag['hashtag'], 'since_id' => $hashtag['twitter_next_id']]);
         } else {
             $response = $connection->get("search/tweets", ['q' => '#' . $hashtag['hashtag']]);
         }
         foreach ($response->statuses as $data) {
             $lastId = $data->id;
             if (empty($data->retweeted_status)) {
                 $sql = rex_sql::factory();
                 $sql->setTable(rex::getTablePrefix() . 'socialhub_entry_hashtag');
                 $sql->setValue('source', 'twitter');
                 $sql->setValue('source_id', $data->id);
                 $sql->setValue('caption', urlencode($data->text ? addslashes($data->text) : ''));
                 if (!empty($data->entities->media)) {
                     $sql->setValue('image', $data->entities->media[0]->media_url);
                 }
                 $sql->setValue('created_time', date('Y-m-d H:i:s', strtotime($data->created_at)));
                 $sql->setValue('author_id', $data->user->id);
                 $sql->setValue('author_name', $data->user->screen_name);
                 $sql->setValue('query', $hashtag['hashtag']);
                 try {
                     $sql->insert();
                 } catch (rex_sql_exception $e) {
                     echo rex_view::warning($e->getMessage());
                 }
                 unset($sql);
             }
         }
         //Start - update next_id
         $sql = rex_sql::factory();
         $sql->setTable(rex::getTablePrefix() . 'socialhub_twitter_hashtag');
         $sql->setWhere('hashtag = "' . addslashes($hashtag['hashtag']) . '"');
         $sql->setValue('twitter_next_id', $lastId);
         try {
             $sql->update();
         } catch (rex_sql_exception $e) {
             echo rex_view::warning($e->getMessage());
         }
         unset($sql);
         //End - update next_id
     }
     //End - get entries by hashtag from twitter
 }
示例#5
0
 public function twittercallback()
 {
     $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']) {
         // Abort! Something is wrong.
         die("Some Thing went wrong");
     }
     $connection = new Abraham\TwitterOAuth\TwitterOAuth('5Gd9l295ZAkm6TP9HbTApXYb6', 'y7rXUAv2aqszUsn1O4t3SCmDlcJnWUuXqpj3kmgs3c10W9QIKV', $request_token['oauth_token'], $request_token['oauth_token_secret']);
     $access_token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_REQUEST['oauth_verifier']]);
     $_SESSION['access_token'] = $access_token;
     $connection = new Abraham\TwitterOAuth\TwitterOAuth('5Gd9l295ZAkm6TP9HbTApXYb6', 'y7rXUAv2aqszUsn1O4t3SCmDlcJnWUuXqpj3kmgs3c10W9QIKV', $access_token['oauth_token'], $access_token['oauth_token_secret']);
     $user = $connection->get("account/verify_credentials");
     //login callback
     $loginData = array();
     $loginData['name'] = $user->screen_name;
     $loginData['login_provider'] = 'twitter';
     $this->save_and_login($loginData);
 }
示例#6
0
 * This example is made for myself, if I loose my code
*/
session_start();
require_once __DIR__ . '/../vendor/autoload.php';
//Edit the following config variables
$consumer_key = 'consumer_key';
$consumer_secret = 'consumer_secret';
//callback url. In this example it is using current url
$callback = "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s://" : "://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if (isset($_SESSION['oauth_token'])) {
    $oauth_token = $_SESSION['oauth_token'];
    unset($_SESSION['oauth_token']);
    $connection = new Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret);
    //necessary to get access token other wise u will not have permision to get user info
    $params = array("oauth_verifier" => $_GET['oauth_verifier'], 'oauth_token' => $_GET['oauth_token']);
    $access_token = $connection->oauth('oauth/access_token', $params);
    //now again create new instance using updated return oauth_token and oauth_token_secret because old one expired if u dont u this u will also get token expired error
    $connection = new Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret, $access_token['oauth_token'], $access_token['oauth_token_secret']);
    $content = $connection->get('account/verify_credentials');
    //Printing the profile data
    print_r($content);
} else {
    //this code will return your valid url which u can use in iframe src to popup or can directly view the page as its happening in this example
    $connection = new Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret);
    $temporary_credentials = $connection->oauth('oauth/request_token', array("oauth_callback" => $callback));
    $_SESSION['oauth_token'] = $temporary_credentials['oauth_token'];
    $_SESSION['oauth_token_secret'] = $temporary_credentials['oauth_token_secret'];
    $url = $connection->url('oauth/authenticate', array('oauth_token' => $temporary_credentials['oauth_token']));
    // REDIRECTING TO THE URL
    header('Location: ' . $url);
}
<?php

require_once __DIR__ . '/../bootstrap.php';
$options = getopt('f:');
if (empty($options['f'])) {
    exit('Must pass in a file with the f parameter.');
}
$client = new Abraham\TwitterOAuth\TwitterOAuth($config->twitter->consumer_key, $config->twitter->consumer_secret, $config->twitter->access_token, $config->twitter->access_token_secret);
$client->setDecodeJsonAsArray(true);
$idList = [];
$handle = fopen(__DIR__ . '/' . $options['f'], 'r');
while ($row = fgets($handle)) {
    array_push($idList, trim($row));
    if (count($idList) == 100) {
        $tweetLookup = $client->get('statuses/lookup', ['id' => implode(',', $idList), 'trim_user' => true]);
        foreach ($tweetLookup as $tweet) {
            $uniqueTweetCheck = $db->getRead()->fetchOne("SELECT `metadata` FROM `jpemeric_stream`.`twitter` WHERE `tweet_id` = :tweet_id LIMIT 1", ['tweet_id' => $tweet['id_str']]);
            if ($uniqueTweetCheck !== false) {
                if ($uniqueTweetCheck['metadata'] != json_encode($tweet)) {
                    $db->getWrite()->perform("UPDATE `jpemeric_stream`.`twitter` SET `metadata` = :metadata WHERE `tweet_id` = :tweet_id", ['metadata' => json_encode($tweet), 'tweet_id' => $tweet['id_str']]);
                }
                continue;
            }
            $dateTime = new DateTime($tweet['created_at']);
            $dateTime->setTimezone(new DateTimeZone('America/Phoenix'));
            $db->getWrite()->perform("INSERT INTO `jpemeric_stream`.`twitter` (`tweet_id`, `datetime`, `metadata`) " . "VALUES (:tweet_id, :datetime, :metadata)", ['tweet_id' => $tweet['id_str'], 'datetime' => $dateTime->format('Y-m-d H:i:s'), 'metadata' => json_encode($tweet)]);
        }
        $idList = [];
    }
}
fclose($handle);
示例#8
0
 public function twitter_verify_access_key($user)
 {
     $result['has_valid_access_token'] = false;
     $CI =& get_instance();
     $CI->load->model('user_account_model');
     $twitter_accounts = $CI->user_account_model->get(array('user_id' => $user->id, 'type' => 'twitter'));
     $result['accounts'] = array();
     if (sizeof($twitter_accounts) > 0) {
         foreach ($twitter_accounts as $account) {
             try {
                 $result['has_valid_access_token'] = true;
                 $access_token = json_decode($account->access_token);
                 $connection = new \Abraham\TwitterOAuth\TwitterOAuth(TWITTER_KEY, TWITTER_SECRET_KEY, $access_token->oauth_token, $access_token->oauth_token_secret);
                 $content = $connection->get("users/show", ["user_id" => $access_token->user_id]);
                 $a['user_info'] = $content;
                 $a['id'] = $account->id;
                 $result['accounts'][] = $a;
             } catch (Exception $e) {
             }
         }
     }
     $result['auth_url'] = $this->get_twitter_auth_url();
     return $result;
 }
<?php

require_once __DIR__ . '/../bootstrap.php';
$client = new Abraham\TwitterOAuth\TwitterOAuth($config->twitter->consumer_key, $config->twitter->consumer_secret, $config->twitter->access_token, $config->twitter->access_token_secret);
$client->setDecodeJsonAsArray(true);
try {
    $recentTweets = $client->get('statuses/user_timeline', ['screen_name' => 'jpemeric', 'count' => 50, 'trim_user' => true]);
} catch (Exception $e) {
    $logger->addError($e->getMessage());
    exit;
}
if (isset($recentTweets['errors'])) {
    $logger->addError($recentTweets['errors'][0]['message']);
    exit;
}
foreach ($recentTweets as $tweet) {
    $uniqueTweetCheck = $db->getRead()->fetchOne("SELECT `metadata` FROM `jpemeric_stream`.`twitter` WHERE `tweet_id` = :tweet_id LIMIT 1", ['tweet_id' => $tweet['id_str']]);
    if ($uniqueTweetCheck !== false) {
        if ($uniqueTweetCheck['metadata'] != json_encode($tweet)) {
            $db->getWrite()->perform("UPDATE `jpemeric_stream`.`twitter` SET `metadata` = :metadata WHERE `tweet_id` = :tweet_id", ['metadata' => json_encode($tweet), 'tweet_id' => $tweet['id_str']]);
        }
        continue;
    }
    $dateTime = new DateTime($tweet['created_at']);
    $dateTime->setTimezone(new DateTimeZone('America/Phoenix'));
    $db->getWrite()->perform("INSERT INTO `jpemeric_stream`.`twitter` (`tweet_id`, `datetime`, `metadata`) " . "VALUES (:tweet_id, :datetime, :metadata)", ['tweet_id' => $tweet['id_str'], 'datetime' => $dateTime->format('Y-m-d H:i:s'), 'metadata' => json_encode($tweet)]);
}
示例#10
0
文件: api.php 项目: nuiz/api2
<?php

require "../bootstrap.php";
$twitteroauth = new Abraham\TwitterOAuth\TwitterOAuth('kcUhArVLnK6xzDpVJU85r7FJj', 'dekH6UMluN2ZCCJ0v1q95w3DaIMeczsP1l3wAEjRwbn16G43aV', $_SESSION['access_token']['oauth_token'], $_SESSION['access_token']['oauth_token_secret']);
header("Content-Type: application/json");
if ($_GET['action'] == 'followers') {
    $data = $twitteroauth->get("followers/list");
    echo json_encode($data);
} else {
    if ($_GET['action'] == 'mentions') {
        $data = $twitteroauth->get("statuses/mentions_timeline");
        echo json_encode($data);
    } else {
        if ($_GET['action'] == 'retweets') {
            $data = $twitteroauth->get("statuses/retweets_of_me");
            echo json_encode($data);
        } else {
            if ($_GET['action'] == 'search') {
                $data = $twitteroauth->get("search/tweets", array("q" => $_GET['q']));
                echo json_encode($data);
            }
        }
    }
}
示例#11
0
    session()->forget('twitter_account');
    session(['access_token' => $accessToken]);
    return redirect('twitter-profile');
}]);
Route::get('/login', ['as' => 'login_path', function (Illuminate\Http\Request $request) {
    $connection = new Abraham\TwitterOAuth\TwitterOAuth(env('TWITTER_CONSUMER_KEY'), env('TWITTER_CONSUMER_SECRET'));
    $requestToken = $connection->oauth('oauth/request_token', array('oauth_callback' => route('twitter_signin_callback')));
    session(['oauth_token' => $requestToken['oauth_token'], 'oauth_token_secret' => $requestToken['oauth_token_secret']]);
    $urlTwitter = $connection->url('oauth/authenticate', ['oauth_token' => session('oauth_token')]);
    return view('layouts.login', compact('urlTwitter'));
}]);
Route::get('/twitter-profile', function (Illuminate\Http\Request $request) {
    $accessToken = session('access_token');
    if (!session()->has('twitter_account')) {
        $connection = new Abraham\TwitterOAuth\TwitterOAuth(env('TWITTER_CONSUMER_KEY'), env('TWITTER_CONSUMER_SECRET'), $accessToken['oauth_token'], $accessToken['oauth_token_secret']);
        $twitterAccount = $connection->get("account/verify_credentials");
        session(['twitter_account' => $twitterAccount]);
    }
    $twitterAccount = session('twitter_account');
    return view('twitter.index', compact('twitterAccount'));
});
Route::post('/twitter-status', ['as' => 'twitter_status_update', function (Illuminate\Http\Request $request) {
    $connection = new Abraham\TwitterOAuth\TwitterOAuth(env('TWITTER_CONSUMER_KEY'), env('TWITTER_CONSUMER_SECRET'), session('access_token.oauth_token'), session('access_token.oauth_token_secret'));
    $statues = $connection->post("statuses/update", ["status" => $request->input('status')]);
    if ($connection->getLastHttpCode() == 200) {
        return redirect('twitter-profile')->with("message", "Update status success!")->with("success", true);
    }
    return redirect('twitter-profile')->with('message', 'Error: can"t update status')->with('success', false);
}]);
Route::post('/twitter-send-message', ['as' => 'twitter_send_message', function (Illuminate\Http\Request $request) {
    $connection = new Abraham\TwitterOAuth\TwitterOAuth(env('TWITTER_CONSUMER_KEY'), env('TWITTER_CONSUMER_SECRET'), session('access_token.oauth_token'), session('access_token.oauth_token_secret'));