get() public method

GET wrapper for oAuthRequest.
public get ( $url, $parameters = [] )
コード例 #1
0
ファイル: controller.php プロジェクト: night-coder/ignite
 public function test()
 {
     $aModel = TuiyoLoader::model("applications", true);
     $aUser = TuiyoAPI::get("user", null);
     $aDocument = TuiyoAPI::get("document", null);
     $aParams = $aModel->getSingleUserPlugin($aUser->id, "twitter");
     if (!is_object($aParams)) {
         $aDocument->enqueMessage(_("Cannot Load the service for this user"), "error");
         return false;
     }
     echo $aParams->get("oauth_verifier");
     /* Build TwitterOAuth object with client credentials. */
     $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
     $view =& $this->getView("twitter", "html");
     /* Get temporary credentials. */
     $access_token = $connection->getAccessToken($aParams->get('oauth_verifier', false));
     /* Create a TwitterOauth object with consumer/user tokens. */
     $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
     /* If method is set change API call made. Test is called by default. */
     $content = $connection->get('account/verify_credentials');
     //print_R($content);
     $user = $connection->get('account/verify_credentials');
     $userPublicFeeds = $connection->get('statuses/public_timeline');
     print_R($userPublicFeeds);
 }
コード例 #2
0
ファイル: TwitterAccess.php プロジェクト: sg3tester/songator
 protected function get($url, array $params = null)
 {
     $result = $this->oauth->get($url, $params);
     if (isset($result->errors)) {
         foreach ($result->errors as $error) {
             throw new TwitterException($error->message, $error->code);
         }
     }
     return $result;
 }
コード例 #3
0
function updateTwitter($db, $twitter, $hashtag)
{
    $db_con = mysqli_connect($db['host'], $db['user'], $db['password'], $db['name']);
    $connection = new TwitterOAuth($twitter['consumer_key'], $twitter['consumer_secret'], $twitter['access_token'], $twitter['access_token_secret']);
    $content['twitter'] = $connection->get("search/tweets", array('q' => '#' . $hashtag . ' filter:images', 'since_id' => $twitter['last_id'], 'include_entities' => true, 'lang' => 'en', 'count' => 100));
    $content['vine'] = $connection->get("search/tweets", array('q' => '#' . $hashtag . ' vine.co filter:links', 'since_id' => $twitter['last_id'], 'include_entities' => true, 'lang' => 'en', 'count' => 100));
    foreach ($content as $name => $media) {
        if (isset($media->statuses)) {
            foreach ($media->statuses as $tweet) {
                if ($tweet->id > $twitter['last_id'] && (!empty($tweet->entities->urls) || isset($tweet->entities->media))) {
                    $twitter_id = $tweet->id;
                    $tweet_id = $tweet->id_str;
                    $created_at = $tweet->created_at;
                    $user_id = $tweet->user->id;
                    $this_name = mysqli_real_escape_string($db_con, stripEmojis($tweet->user->name));
                    $screen_name = mysqli_real_escape_string($db_con, $tweet->user->screen_name);
                    $user_location = mysqli_real_escape_string($db_con, stripEmojis($tweet->user->location));
                    $text = mysqli_real_escape_string($db_con, stripEmojis($tweet->text));
                    $link_post = 'https://twitter.com/' . $screen_name . '/status/' . $tweet_id;
                    $time_now = time();
                    $is_vine = false;
                    $is_tweet = false;
                    $type = 'photo';
                    if ($name == 'twitter' && isset($tweet->entities->media)) {
                        $is_tweet = true;
                        $media_url = $tweet->entities->media[0]->media_url;
                        $media_url_https = $tweet->entities->media[0]->media_url_https;
                    } else {
                        if (strpos($tweet->entities->urls[0]->expanded_url, 'vine.co') !== false && $name == 'vine' && !empty($tweet->entities->urls) && isset($tweet->entities->urls[0]->expanded_url)) {
                            $is_vine = true;
                            $type = 'video';
                            $media_url = $tweet->entities->urls[0]->expanded_url;
                            $dom = new DomFinder($media_url);
                            $video_cell = $dom->find("//meta[@property='twitter:player:stream']", 'content');
                            $picture_cell = $dom->find("//meta[@property='twitter:image']", 'content');
                            $media_url = $picture_cell[0];
                            $media_url_https = $video_cell[0];
                        }
                    }
                    if ($is_tweet || $is_vine) {
                        if (mysqli_query($db_con, "insert into media (time_now, source_id, created_at, user_id, name, screen_name, user_location, text, media_url, media_url_https, source, type, hashtag, post_url) " . "values('{$time_now}', '{$twitter_id}', '{$created_at}','{$user_id}','{$this_name}','{$screen_name}', '{$user_location}', '{$text}', '{$media_url}', '{$media_url_https}', 'twitter', '{$type}', '{$hashtag}', '{$link_post}')")) {
                        }
                    }
                }
            }
        }
    }
    mysqli_close($db_con);
}
コード例 #4
0
 public static function render_instance(BlockInstance $instance, $editing = false)
 {
     $configdata = $instance->get('configdata');
     require_once 'twitter_api/twitteroauth.php';
     require_once 'twitter_api/config.php';
     $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
     $result = '';
     if (isset($configdata['widget'])) {
         switch ($configdata['widget']) {
             case "tweet":
                 if (isset($configdata['twitter_id'])) {
                     $data = $connection->get('statuses/show/' . $configdata['twitter_id'], '', 'tweet');
                     if (isset($data->error)) {
                         switch ($data->error) {
                             case "Not found":
                                 return get_string('error_404_id', 'blocktype.twitter');
                                 break;
                             default:
                                 return get_string('error', 'blocktype.twitter');
                                 break;
                         }
                     } else {
                         if (isset($data->id)) {
                             $result = self::create_single_tweet($configdata['twitter_id'], $data);
                         }
                     }
                 }
                 break;
             case "timeline":
                 if (isset($configdata['twitter_screen_name'])) {
                     $data = $connection->get('statuses/user_timeline.json?screen_name=' . $configdata['twitter_screen_name'] . "&count=5", '', 'timeline');
                     if (isset($data->error)) {
                         switch ($data->error) {
                             case "Not found":
                                 return get_string('error_404_tl', 'blocktype.twitter');
                                 break;
                             default:
                                 return get_string('error', 'blocktype.twitter');
                                 break;
                         }
                     } else {
                         $result = self::create_timeline($data);
                     }
                 }
                 break;
         }
     }
     return $result;
 }
コード例 #5
0
ファイル: maintenanceCycle.php プロジェクト: stereoket/twical
function sendTweetByUser($event, $alertPeriod)
{
    require_once TWOAUTH_CLASS_PATH . '/twitteroauth.php';
    $systemMessages = '<div id="systemMessageHeader">';
    stringDump($event);
    // Build Tweet message up
    if (isset($event['url'])) {
        $url = "http://api.bit.ly/v3/shorten?login="******"&apiKey=" . DEFAULT_BITLY_API_KEY . "&longUrl=" . urlencode($event['url']) . "&format=txt&history=1";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $surl = curl_exec($curl);
        $last_response_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
    }
    switch ($alertPeriod) {
        case 24:
            $tPeriod = 'in 24 hours';
            break;
        case 1:
            $tPeriod = 'in 1 hour';
            break;
        case 0:
            $tPeriod = 'now';
            break;
    }
    if (isset($event['summary'])) {
        $tweet = $event['summary'] . ' ';
    } else {
        $tweet = 'Event ';
    }
    $tweet .= $tPeriod;
    if (isset($event['location'])) {
        // Reverse Geo Lookup if no geo data attached to ics file
        $tweet .= ' at ' . substr($event['location'], 0, 20);
        if (isset($event['latitude']) && isset($event['longitude'])) {
            $parameters = array('lat' => $event['latitude'], 'long' => $event['longitude']);
        }
    }
    if (isset($surl)) {
        $tweet .= ', see ' . $surl;
    }
    $tweet .= ' #twical';
    stringDump($tweet);
    /* Create a TwitterOauth object with consumer/user tokens. */
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $event['twitter_token'], $event['twitter_secret']);
    /* If method is set change API call made. Test is called by default. */
    $content = $connection->get('account/rate_limit_status');
    $systemMessages .= '<span class="notice">Current API hits remaining: ' . $content->remaining_hits . '</span>';
    $systemMessages .= '<span class="notice">Number of tweets to send out: ' . count($event) . '</span>';
    $parameters['status'] = $tweet;
    $content = $connection->post('statuses/update', $parameters);
    stringDump($content);
    if (isset($content->{'error'})) {
        $systemMessages .= '<p class="failureMessage">' . $content->{'error'} . '</p>';
    } else {
        $systemMessages .= '<p class="notice"> Status ID:' . $content->{'id'} . ' <br/> Geo Enabled: ' . $content->{'user'}->{'geo_enabled'} . '<br /> Text Sent' . $content->{'text'} . '</p>';
    }
    return $systemMessages;
}
コード例 #6
0
function updateTwitterFeed($lastupdate)
{
    // Twitter!
    global $preferences;
    global $twit;
    require_once 'oauth/twitteroauth.php';
    $twit = new TwitterOAuth($preferences->CONSUMER_KEY, $preferences->CONSUMER_SECRET_KEY, $preferences->OAUTH_TOKEN, $preferences->OAUTH_SECRET_TOKEN);
    // Update the following/followed balance
    updateTwitterFollowing();
    // Update user information for those who require it
    updateTwitterUsers();
    // Get mentions since the last update
    $args = array();
    $lastreadid = getPreference("last_twitter_id");
    if ($lastreadid) {
        $args['since_id'] = $lastreadid;
    }
    $tweets = $twit->get('statuses/mentions_timeline', $args);
    // if we have no tweets, stop here
    if (!is_array($tweets)) {
        loginfo("No tweets to read!");
        return false;
    }
    // process tweets individually
    uasort($tweets, 'cmpTweetId');
    foreach ($tweets as $tweet) {
        $lastreadid = processTweet($tweet);
    }
    // Save the last updated tweet id
    setPreference("last_twitter_id", $lastreadid);
    return true;
}
コード例 #7
0
 private function get_tweets_from_api($username, $args)
 {
     if (!class_exists('TwitterOAuth')) {
         //you need to reference the TwitterOAuth class for this to work
         $this->error = 'The TwitterOAuth class cannot be found. Please include twitteroauth.php!';
         return false;
     }
     $twitter_oauth = new TwitterOAuth($this->consumer_key, $this->consumer_secret, $this->access_key, $this->access_secret);
     //setup params
     $params = array();
     $params['screen_name'] = strip_tags(sanitize_user($username));
     if (array_key_exists('limit', $args)) {
         $params['count'] = intval($args['limit']);
     }
     if (array_key_exists('include_rts', $args)) {
         $params['include_rts'] = $args['include_rts'];
     }
     if (array_key_exists('exclude_replies', $args)) {
         $params['exclude_replies'] = $args['exclude_replies'];
     }
     $response = $twitter_oauth->get('statuses/user_timeline', $params);
     if (is_wp_error($response)) {
         $this->error = $response->get_error_message();
         return false;
     } else {
         if (isset($response->errors)) {
             $this->error = $response->errors;
             return false;
         } else {
             return $response;
         }
     }
 }
 public function update_twitter()
 {
     $consumer_key = ESSBSocialFollowersCounterHelper::get_option('twitter_consumer_key');
     $consumer_secret = ESSBSocialFollowersCounterHelper::get_option('twitter_consumer_secret');
     $access_token = ESSBSocialFollowersCounterHelper::get_option('twitter_access_token');
     $access_token_secret = ESSBSocialFollowersCounterHelper::get_option('twitter_access_token_secret');
     $id = ESSBSocialFollowersCounterHelper::get_option('twitter_id');
     if (empty($consumer_key) || empty($consumer_secret) || empty($access_token) || empty($access_token_secret) || empty($id)) {
         return 0;
     }
     if (!class_exists('TwitterOAuth')) {
         include_once ESSB3_PLUGIN_ROOT . 'lib/modules/social-followers-counter/twitter/twitteroauth.php';
     }
     $api = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);
     $response = $api->get('users/lookup', array('screen_name' => trim($id)));
     if (isset($response->errors)) {
         return null;
     }
     if (isset($response[0]) && is_array($response[0])) {
         return $response[0]['followers_count'];
     }
     if (isset($response[0]->followers_count)) {
         return $response[0]->followers_count;
     }
 }
コード例 #9
0
/**
 * Authenticate to Twitter using oAuth, and retrieve tweets
 */
function twiget_get_tweets()
{
    require_once TWIGET_PLUGIN_PATH . '/lib/twitteroauth.php';
    $twiget_options = get_option('twiget_options');
    $defaults = array('user_id' => NULL, 'screen_name' => NULL, 'since_id' => NULL, 'count' => 5, 'max_id' => NULL, 'trim_user' => NULL, 'exclude_replies' => NULL, 'include_rts' => NULL, 'contributor_details' => NULL, 'widget_id' => NULL);
    $options = array_intersect_key(array_merge($defaults, $_POST), $defaults);
    $cache_period = $twiget_options['cache_period'] ? $twiget_options['cache_period'] : ceil(15 * 60 / 180 * twiget_count_instances());
    $cache_disabled = $cache_period == 0 ? true : false;
    if (!$cache_disabled) {
        $tweets = get_transient('tweets-' . $options['widget_id']);
    } else {
        $tweets = false;
    }
    if ($tweets === false) {
        $consumerkey = $twiget_options['consumer_key'];
        $consumersecret = $twiget_options['consumer_secret'];
        $accesstoken = $twiget_options['access_token'];
        $accesstokensecret = $twiget_options['access_token_secret'];
        session_start();
        $connection = new TwitterOAuth($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
        $tweets = $connection->get('https://api.twitter.com/1.1/statuses/user_timeline.json?' . http_build_query($options));
        $tweets = json_encode($tweets);
        if (!$cache_disabled) {
            set_transient('tweets-' . $options['widget_id'], $tweets, $cache_period);
        }
    }
    echo $tweets;
    exit;
}
コード例 #10
0
ファイル: socialmodel.php プロジェクト: INFOnews/infonews
 public function TwitterData($access_token = false)
 {
     require_once ROOTPATH . "data/third_party/twitteroauth/src/TwitterOAuth.php";
     $connection = new TwitterOAuth($this->twitter_config['ckey'], $this->twitter_config['csecret'], $access_token['oauth_token'], $access_token['oauth_token_secret']);
     $data = $connection->get("account/verify_credentials", array("include_email" => 'true'));
     $this->SaveUser('twitter:' . $data->screen_name, 2, json_encode($access_token), json_encode($data));
 }
コード例 #11
0
ファイル: TwitterLogin.php プロジェクト: knedle/social-login
 /**
  * Return info about login user
  * @param $oauthToken
  * @param $oauthVerifier
  * @return \API|mixed
  * @throws Exception
  */
 public function getMe($oauthToken, $oauthVerifier)
 {
     $sessionSection = $this->session->getSection("twitter");
     if ($oauthToken != "" && $sessionSection->oauth_token !== $oauthToken) {
         //$sessionSection->oauth_status = 'oldtoken';
         throw new Exception("Twitter token is old. Try again login");
     }
     //Create TwitteroAuth object with app key/secret and token key/secret from default phase
     $this->twitterOAuth = new \TwitterOAuth($this->params["consumerKey"], $this->params["consumerSecret"], $sessionSection->oauth_token, $sessionSection->oauth_token_secret);
     //Request access tokens from twitter
     $access_token = $this->twitterOAuth->getAccessToken($oauthVerifier);
     //Save the access tokens
     $sessionSection->access_token = $access_token;
     // Remove no longer needed request tokens
     unset($sessionSection->oauth_token);
     unset($sessionSection->oauth_token_secret);
     if (200 != $this->twitterOAuth->http_code) {
         //Save HTTP status for error dialog on connnect page.
         throw new Exception("Twitter login. Something is wrong");
     }
     //The user has been verified
     //$sessionSection->status = 'verified';
     $user_info = $this->twitterOAuth->get('account/verify_credentials');
     $this->setSocialLoginCookie(self::SOCIAL_NAME);
     return $user_info;
 }
コード例 #12
0
ファイル: helper.php プロジェクト: educakanchay/educa
 public static function getList(&$params)
 {
     $list = array();
     if (!class_exists('TwitterOAuth')) {
         require_once dirname(__FILE__) . '/twitteroauth.php';
     }
     $consumerKey = trim($params->get('consumekey'));
     $consumerSecret = trim($params->get('consumersecret'));
     $oAuthToken = trim($params->get('access_token'));
     $oAuthSecret = trim($params->get('access_token_secret'));
     $screenName = $params->get('screenname');
     $notweets = $params->get('count', 6);
     if (!$consumerKey || !$consumerSecret || !$screenName) {
         return;
     }
     $_time = time();
     $Tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret);
     $tweets = $Tweet->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $screenName . "&count=" . $notweets);
     $items = json_decode($tweets);
     if (empty($items) || isset($items->errors)) {
         return;
     }
     foreach ($items as $item) {
         $text = preg_replace('@(https?://([-\\w\\.]+)+(/([\\w/_\\.]*(\\?\\S+)?(#\\S+)?)?)?)@', '<a target="_blank" href="$1">$1</a>', $item->text);
         $text = preg_replace('/@(\\w+)/', '<a target="_blank" href="http://twitter.com/$1">@$1</a>', $text);
         $text = preg_replace('/(?:^|\\s)+#(\\w+)/', ' <a target="_blank" href="http://search.twitter.com/search?q=%23$1">#$1</a>', $text);
         $item->_text = $text;
         $item->_full_name = $item->user->name;
         $item->_username = '******' . $item->user->screen_name;
         $item->_twitter_link = 'http://www.twitter.com/' . $item->user->screen_name;
         $item->_image = $item->user->profile_image_url;
         $list[] = $item;
     }
     return $list;
 }
コード例 #13
0
ファイル: TwitterSvc.php プロジェクト: berliozd/cherbouquin
 public function getContent()
 {
     try {
         $dataKey = self::CONTENT;
         $content = $this->getData($dataKey);
         if ($content === false) {
             require_once 'Twitter/twitteroauth.php';
             $consumer_key = $this->config->getTwitterConsummerKey();
             $consumer_secret = $this->config->getTwitterConsummerSecret();
             $oauth_token = $this->config->getTwitterAuthToken();
             $oauth_token_secret = $this->config->getTwitterAuthTokenSecret();
             /* Create a TwitterOauth object with consumer/user tokens. */
             $connection = new \TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
             $user = "******";
             /* Nom d'utilisateur sur Twitter */
             $count = 10;
             /* Nombre de message à afficher */
             $query = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' . $user . '&count=' . $count;
             // Your Twitter API query
             $content = $connection->get($query);
             $this->setData($dataKey, $content);
         }
         return $content;
     } catch (\Exception $exc) {
         $this->logException(get_class(), __FUNCTION__, $exc);
     }
 }
コード例 #14
0
ファイル: shortcodes.php プロジェクト: severnrescue/web
/**
 * Twitter Shortcode using aouth
 */
function IOAgetTweets($count = 20, $username = false, $ioa_options = false)
{
    global $super_options;
    require_once HPATH . '/lib/twitteroauth/twitteroauth.php';
    $settings = array('oauth_access_token' => $super_options[SN . '_twitter_token'], 'oauth_access_token_secret' => $super_options[SN . '_twitter_secret_token'], 'consumer_key' => $super_options[SN . '_twitter_key'], 'consumer_secret' => $super_options[SN . '_twitter_secret_key']);
    $data = array();
    if (get_transient(SN . '_ioa_tweets')) {
        $data = get_transient(SN . '_ioa_tweets');
    } else {
        $connection = new TwitterOAuth($super_options[SN . '_twitter_key'], $super_options[SN . '_twitter_secret_key'], $super_options[SN . '_twitter_token'], $super_options[SN . '_twitter_secret_token']);
        $data = $connection->get('statuses/user_timeline');
        set_transient(SN . '_ioa_tweets', $data, 60 * 60 * 3);
    }
    $i = 0;
    $filter_array = array();
    if (!isset($data->errors)) {
        foreach ($data as $d) {
            if ($i > $count) {
                break;
            }
            $filter_array[] = array("text" => $d->text);
            $i++;
        }
    }
    return $filter_array;
}
コード例 #15
0
 public function getProfile()
 {
     $twitter = new TwitterOAuth(LeapTwitter::API_KEY, LeapTwitter::API_SECRET, LeapTwitter::ACCESS_TOKEN, LeapTwitter::ACCESS_TOKEN_SECRET);
     $url = LeapTwitter::TWITTER_TIMELINE . "screen_name=" . LeapTwitter::TWITTER_DISPLAY_NAME . "&count=" . LeapTwitter::TWITTER_COUNT;
     $urlImg = LeapTwitter::TWITTER_IMG . "screen_name=" . LeapTwitter::TWITTER_DISPLAY_NAME;
     return json_encode($twitter->get($urlImg));
 }
コード例 #16
0
 /**
  * Returns the json_decoded response body
  *
  * @param string $endpoint
  * @param array $parameters
  */
 public function decoded_response_body($consumer_key, $consumer_secret, $access_token, $access_token_secret, $parameters)
 {
     require_once 'class-twitteroauth.php';
     $connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);
     $response = $connection->get($this->remote_get($parameters));
     return $response;
 }
コード例 #17
0
function xmt_twt_oah_drc_msg_get($acc)
{
    global $xmt_acc;
    $cls = new TwitterOAuth($xmt_acc[$acc]['cfg']['csm_key'], $xmt_acc[$acc]['cfg']['csm_sct'], $xmt_acc[$acc]['cfg']['oah_tkn'], $xmt_acc[$acc]['cfg']['oah_sct']);
    $cls->format = 'json';
    return $cls->get('direct_messages', array('count' => intval($xmt_acc[$acc]['cfg']['cnt'])));
}
コード例 #18
0
 /**
  * Constuctor function for HashtagSearchModel class
  * fetches tweets containing the given hashtag
  * 
  * @param $hashtag, Hashtag for which tweets are to be searched on Twitter
  */
 function __construct($hashtag = NULL, $next_results = NULL)
 {
     // opening an oauth connection to Twitter API
     $api_connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
     // basic search endpoint for Twitter API
     $base_url = 'https://api.twitter.com/1.1/search/tweets.json';
     if ($next_results) {
         // form the search endpoint with required parameters
         $api_url = $base_url . $next_results;
     } else {
         // form the search endpoint with required parameters
         $api_url = $base_url . '?q=' . urlencode('#' . $hashtag) . '&include_entities=false&result_type=recent&count=100';
     }
     // making API call on search endpoint along with the given hashtag
     $response = $api_connection->get($api_url);
     /**
      * Enable error-checking when this kind of response is returned
      * {"errors":[{"message":"Could not authenticate you","code":32}]}
      * {"errors":[{"message":"Rate limit exceeded","code":88}]}
      */
     if (isset($response->errors) || !isset($response->statuses)) {
         $this->error_status = true;
     }
     $this->t_response = $response;
 }
コード例 #19
0
ファイル: Twitter.php プロジェクト: Sywooch/forums
 public static function helpConfiguration($oauthToken, $oauthTokenSecret)
 {
     list($consumerKey, $consumerSecret) = bdSocialShare_Option::getTwitterConsumerPair();
     $twitter = new TwitterOAuth($consumerKey, $consumerSecret, $oauthToken, $oauthTokenSecret);
     $response = $twitter->get('help/configuration');
     $responseArray = (array) $response;
     return $responseArray;
 }
コード例 #20
0
ファイル: connect.php プロジェクト: anantgarg/kudos
function twittercallback()
{
    $twitter = new TwitterOAuth(TWITTER_APIKEY, TWITTER_APISECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
    $token = $twitter->getAccessToken($_REQUEST['oauth_verifier']);
    $account = $twitter->get('account/verify_credentials');
    header('Location: ' . BASE_URL . 'connect/add/twitter/' . base64_encode($token['user_id']) . '/' . base64_encode($token['screen_name']) . '/' . base64_encode($token['oauth_token']) . '/' . base64_encode($token['oauth_token_secret']) . '/' . base64_encode($account->profile_image_url_https));
    exit;
}
コード例 #21
0
 public function callbackAction(Request $request)
 {
     /****Check language session*******/
     $session = $request->getSession();
     $this->langsession($session);
     $lan = $session->get('language');
     $request->setLocale($lan);
     $username = $session->get('user');
     $em = $this->getDoctrine()->getManager();
     $appkey = $this->container->get('mytrip_admin.helper.twitter')->getOption('apikey');
     $appsecretkey = $this->container->get('mytrip_admin.helper.twitter')->getOption('apisecretkey');
     $twitteroauth = new \TwitterOAuth($appkey, $appsecretkey, $session->get('oauth_token'), $session->get('oauth_token_secret'));
     //\TwitterOAuth::setAuth($appkey, $appsecretkey,$session->get('oauth_token'), $session->get('oauth_token_secret'));
     $access_token = $twitteroauth->getAccessToken($_REQUEST['oauth_verifier']);
     $content = $twitteroauth->get('account/verify_credentials');
     if (!empty($content)) {
         if (!empty($username)) {
             $uid = $username['userId'];
             $check_social_link = $em->createQuery("SELECT p FROM MytripAdminBundle:UserSocialLink p WHERE p.user='******' AND p.socialLink='Twitter' AND p.id='" . $content->id . "'")->getArrayResult();
             if (empty($check_social_link)) {
                 $social_links = new \Mytrip\AdminBundle\Entity\UserSocialLink();
                 $social_links->setUser($this->getDoctrine()->getRepository('MytripAdminBundle:User')->find($uid));
                 $social_links->setSocialLink('Twitter');
                 $social_links->setId($content->id);
                 $social_links->setImage($content->profile_image_url);
                 $social_links->setCreatedDate(new \DateTime(date('Y-m-d H:i:s')));
                 $em->persist($social_links);
                 $em->flush();
             }
             return $this->redirect($this->generateUrl('mytrip_user_profile'));
         } else {
             $check_social_link = $em->createQuery("SELECT p,IDENTITY(p.user) AS user FROM MytripAdminBundle:UserSocialLink p WHERE p.socialLink='Twitter' AND p.id='" . $content->id . "'")->getArrayResult();
             if (!empty($check_social_link)) {
                 $user = $em->createQuery("SELECT p FROM MytripAdminBundle:User p WHERE p.userId='" . $check_social_link[0]['user'] . "' AND p.status NOT IN ('Trash')")->getArrayResult();
                 if (!empty($user)) {
                     $session->set('user', $user[0]);
                     $session->set('UserLogin', "True");
                     return $this->redirect($this->generateUrl('mytrip_user_profile'));
                 } else {
                     $session->set('twittercontent', $content);
                     $this->get('session')->getFlashBag()->add('twit', '1');
                     return $this->redirect($this->generateUrl('mytrip_user_homepage'));
                 }
             } else {
                 $session->set('twittercontent', $content);
                 $this->get('session')->getFlashBag()->add('twit', '1');
                 return $this->redirect($this->generateUrl('mytrip_user_homepage'));
             }
         }
     } else {
         $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('Sorry, Please try again'));
         if (empty($username)) {
             return $this->redirect($this->generateUrl('mytrip_user_homepage'));
         } else {
             return $this->redirect($this->generateUrl('mytrip_user_profile'));
         }
     }
 }
コード例 #22
0
 /**
  * This method is used to process the second part of authentication workflow, after redirect
  *
  * @return array Array with status and user details
  */
 public function processAuth()
 {
     $ngConnectINI = eZINI::instance('ngconnect.ini');
     $http = eZHTTPTool::instance();
     $consumerKey = trim($ngConnectINI->variable('LoginMethod_twitter', 'AppConsumerKey'));
     $consumerSecret = trim($ngConnectINI->variable('LoginMethod_twitter', 'AppConsumerSecret'));
     if (empty($consumerKey) || empty($consumerSecret)) {
         return array('status' => 'error', 'message' => 'Consumer key or consumer secret undefined.');
     }
     $oAuthToken = trim($http->getVariable('oauth_token', ''));
     $oAuthVerifier = trim($http->getVariable('oauth_verifier', ''));
     $state = trim($http->getVariable('state', ''));
     if (empty($oAuthToken) || empty($oAuthVerifier) || empty($state)) {
         return array('status' => 'error', 'message' => 'oauth_token, oauth_verifier or state GET parameters undefined.');
     }
     if (!$http->hasSessionVariable('NGConnectOAuthState') || $state != $http->sessionVariable('NGConnectOAuthState')) {
         $http->removeSessionVariable('NGConnectOAuthState');
         return array('status' => 'error', 'message' => 'State parameter does not match stored value.');
     } else {
         $http->removeSessionVariable('NGConnectOAuthState');
     }
     if (!$http->hasSessionVariable('NGConnectOAuthToken') || !$http->hasSessionVariable('NGConnectOAuthTokenSecret') || $oAuthToken != $http->sessionVariable('NGConnectOAuthToken')) {
         $http->removeSessionVariable('NGConnectOAuthToken');
         $http->removeSessionVariable('NGConnectOAuthTokenSecret');
         return array('status' => 'error', 'message' => 'Token does not match stored value.');
     } else {
         $oAuthTokenSecret = $http->sessionVariable('NGConnectOAuthTokenSecret');
         $http->removeSessionVariable('NGConnectOAuthToken');
         $http->removeSessionVariable('NGConnectOAuthTokenSecret');
     }
     $connection = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthTokenSecret);
     $connection->host = self::TWITTER_API_URI;
     $accessToken = $connection->getAccessToken($oAuthVerifier);
     if (!(isset($accessToken['oauth_token']) && isset($accessToken['oauth_token_secret']))) {
         return array('status' => 'error', 'message' => 'Error while retrieving access token.');
     }
     $connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken['oauth_token'], $accessToken['oauth_token_secret']);
     $connection->host = self::TWITTER_API_URI;
     $user = $connection->get(self::TWITTER_USER_API_URI);
     if (!isset($user->id) || empty($user->id)) {
         return array('status' => 'error', 'message' => 'Invalid Twitter user.');
     }
     if (isset($user->profile_image_url) && !empty($user->profile_image_url)) {
         $pictureUri = $user->profile_image_url;
         $imageSize = trim($ngConnectINI->variable('LoginMethod_twitter', 'ImageSize'));
         if ($imageSize == 'original') {
             //Hm... it seems there's no way to get the full size image through API
             //Even https://api.twitter.com/1/users/profile_image/username never returns full version
             //Replacing is not safe, but at least we're replacing last occurrence
             $pictureUri = substr_replace($user->profile_image_url, '', strrpos($user->profile_image_url, '_normal'), 7);
         }
     } else {
         $pictureUri = '';
     }
     $result = array('status' => 'success', 'login_method' => 'twitter', 'id' => $user->id, 'first_name' => isset($user->name) ? $user->name : '', 'last_name' => '', 'email' => '', 'picture' => $pictureUri);
     return $result;
 }
コード例 #23
0
ファイル: Twitter.php プロジェクト: CanAvci/Twitter-Search
 public function SearchTweet($kelime, $count = 10)
 {
     if (empty(trim($kelime))) {
         $kelime = "merhaba";
     }
     $twitter = new TwitterOAuth($this->consumer_key, $this->consumer_secret, $this->access_token, $this->access_token_secret);
     $tweets = $twitter->get("https://api.twitter.com/1.1/search/tweets.json?q={$kelime}&result_type=recent&count={$count}&format=json");
     return $tweets;
 }
コード例 #24
0
ファイル: twilogin.php プロジェクト: sergiovelayos/liveuamap
    function run()
    {
        parent::run();
        if ($_REQUEST['oauth_token']) {
            $connection = new TwitterOAuth(WRA_CONF::$twiappid, WRA_CONF::$twiappsecret, $_REQUEST['oauth_token'], $_REQUEST['oauth_verifier']);
            $token_credentials = $connection->getAccessToken($_REQUEST['oauth_verifier']);
            $connection = new TwitterOAuth(WRA_CONF::$twiappid, WRA_CONF::$twiappsecret, $token_credentials['oauth_token'], $token_credentials['oauth_token_secret']);
            $account = $connection->get('account/verify_credentials');
            // WRA::debug($ctwe);
            if ($account) {
                // WRA::debug($user);
                $nu = new wra_twu();
                $nu->display_name = htmlspecialchars($account->screen_name, ENT_QUOTES);
                //$user->name;
                $nu->regdate = WRA::getcurtime();
                $nu->twuserid = $account->id;
                // $nu->userid = $usr;
                $nu->username = htmlspecialchars($account->name, ENT_QUOTES);
                $nu->usersurname = htmlspecialchars($user['last_name'], ENT_QUOTES);
                $nu->link = $account->url;
                //$user->link;
                $nu->user_agent = wra_fbu::getbrowser();
                $nu->access_token = $token_credentials['oauth_token'];
                $nu->email = $token_credentials['oauth_token_secret'];
                $nu->photo = $account->profile_image_url;
                if ($account->notifications) {
                    $nu->gender = 0;
                } else {
                    $nu->gender = 1;
                }
                $nu->phone = '';
                if (!empty($nu->twuserid)) {
                    if (!wra_twu::istwexist($nu->twuserid)) {
                        $nu->userid = $this->addUsr($nu->username, $nu->usersurname, $nu->phone, $nu->email, "asdf" . time(), $nu->photo);
                        $nu->add();
                    } else {
                        $nu->loadbytw($nu->twuserid);
                        $nu->update();
                    }
                    wra_twu::twd($nu->twuserid, $nu->userid);
                }
                if (empty($_SESSION['lastpage'])) {
                    WRA::gotopage(WRA::base_url() . '?from=tw&show=no');
                } else {
                    WRA::gotopage(WRA::base_url() . $_SESSION['lastpage']);
                }
                $_SESSION['lastpage'] = '';
            }
        } else {
            ?>
<a href="<?php 
            WRA::e(wra_twitter::loginLink());
            ?>
">login</a><?php 
        }
    }
コード例 #25
0
ファイル: run.php プロジェクト: carriercomm/Twitterbot
/**
 * Runs tests against the configuration of this bot, to make sure everything
 * is in working order.
 */
function test()
{
    // test the database connection parameters
    echo "\n" . '==TESTING TWITTERBOT==' . "\n";
    echo 'Testing MySQL connection...';
    $db = @mysql_connect(DB_HOST, DB_USER, DB_PASS);
    if (!$db) {
        die('ERROR: Invalid MySQL connection parameters: ' . mysql_error() . "\n");
    }
    echo 'passed!' . "\n";
    mysql_close($db);
    // test the the curl libraries are installed
    echo 'Testing that you have curl installed...';
    if (!function_exists('curl_init')) {
        die('ERROR: You do not seem to have a curl library for PHP. Please ' . 'check your PHP configuration.');
    }
    echo 'passed!' . "\n";
    // test Twitter OAuth settings
    echo 'Testing OAuth credentials...';
    $obj = new TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET);
    $retval = $obj->get('account/verify_credentials');
    if (!is_object($retval) || !isset($retval->name)) {
        die('ERROR: Unable to successfully establish an OAuth connection with' . ' Twitter.' . "\n");
    }
    if ($retval->screen_name != BOT_ACCOUNT) {
        die('ERROR: The BOT_ACCOUNT indicated in configuration differs from' . ' what the Twitter API said.' . "\n");
    } else {
        echo 'passed!' . "\n";
    }
    // test the actions listed in the configuration file
    global $actions;
    foreach ($actions as $action) {
        echo 'Found action "' . $action['name'] . '", checking required fields...';
        if (isset($action['name']) && isset($action['file']) && isset($action['class']) && isset($action['active'])) {
            echo "passed!\n";
        } else {
            die('ERROR: One or more required fields are missing in your ' . 'config.php for an action.' . "\n");
        }
        echo 'Checking instantiability of ' . $action['class'] . '...';
        if (!file_exists(ACTIONS . $action['file'])) {
            die('ERROR: Unable to find class file for the custom Action.' . "\n");
        }
        include_once ACTIONS . $action['file'];
        $class = new ReflectionClass($action['class']);
        if (!$class->isInstantiable()) {
            die('ERROR: Unable to instantiate class ' . $action['class'] . ".\n");
        }
        echo 'passed!' . "\n";
    }
    // finally, test a few PHP dependencies
    echo 'Looking for pcntl_fork()...';
    if (!function_exists('pcntl_fork')) {
        die('ERROR: pcntl_fork() is undefined. Please check your PHP ' . 'configuration.' . "\n");
    }
    echo 'passed!' . "\n";
}
コード例 #26
0
 /**
  * Updates the list of tweets
  */
 public static function on_ajax_update_tweets()
 {
     $result = self::$connection->get('statuses/user_timeline');
     if (isset($result->errors)) {
         wp_mail(get_option('admin_email'), __('Error on Twitter Manager', 'wtu_framework'), '<pre>' . $result . '</pre>');
     }
     set_transient(self::$transients['tweets'], $result);
     header('Content-type: application/json');
     die(json_encode($result));
 }
コード例 #27
0
 public function callbackAction()
 {
     $oauth_token = $this->getRequest()->getParam('oauth_token');
     $oauth_verifier = $this->getRequest()->getParam('oauth_verifier');
     if (!$oauth_token || !$oauth_verifier) {
         return $this->_redirectUrl();
     }
     if ($oauth_token != Mage::getSingleton('core/session')->getData('oauth_token')) {
         return $this->_redirectUrl();
     }
     $connection = new TwitterOAuth(Mage::getStoreConfig('gomage_social/twitter/id'), Mage::getStoreConfig('gomage_social/twitter/secret'), Mage::getSingleton('core/session')->getData('oauth_token'), Mage::getSingleton('core/session')->getData('oauth_token_secret'));
     $access_token = $connection->getAccessToken($oauth_verifier);
     Mage::getSingleton('core/session')->unsetData('oauth_token');
     Mage::getSingleton('core/session')->unsetData('oauth_token_secret');
     $profile = null;
     switch ($connection->http_code) {
         case 200:
             $profile = $connection->get('account/verify_credentials');
             break;
         default:
             $this->getSession()->addError($this->__('Could not connect to Twitter. Refresh the page or try again later.'));
             return $this->_redirectUrl();
     }
     if ($profile) {
         if ($profile->id) {
             $social_collection = Mage::getModel('gomage_social/entity')->getCollection()->addFieldToFilter('social_id', $profile->id)->addFieldToFilter('type_id', GoMage_Social_Model_Type::TWITTER);
             if (Mage::getSingleton('customer/config_share')->isWebsiteScope()) {
                 $social_collection->addFieldToFilter('website_id', Mage::app()->getWebsite()->getId());
             }
             $social = $social_collection->getFirstItem();
             if ($social && $social->getId()) {
                 if ($social->social_id == $profile->id) {
                     $customer = Mage::getModel('customer/customer');
                     if (Mage::getSingleton('customer/config_share')->isWebsiteScope()) {
                         $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
                     }
                     $customer->load($social->getData('customer_id'));
                     if ($customer && $customer->getId()) {
                         if (!$customer->getConfirmation()) {
                             $this->getSession()->loginById($customer->getId());
                         } else {
                             $this->getSession()->addError($this->__('This account is not confirmed.'));
                         }
                     }
                 }
             } else {
                 $profile->url = Mage::getUrl('gomage_social/twitter/checkEmail', array('_secure' => true));
                 $profile->urlEmailClose = Mage::getUrl('gomage_social/twitter/emailClose', array('_secure' => true));
                 $profile->type_id = GoMage_Social_Model_Type::TWITTER;
                 Mage::getSingleton('core/session')->setGsProfile($profile);
             }
         }
     }
     return $this->_redirectUrl();
 }
コード例 #28
0
ファイル: TwitterManager.class.php プロジェクト: voota/voota
 public static function verify($user)
 {
     $culture = $user->getCulture();
     $profile = $user->getGuardUser()->getProfile();
     $connection = new TwitterOAuth(sfConfig::get("app_twitter_api_consumer_key_{$culture}"), sfConfig::get("app_twitter_api_consumer_secret_{$culture}"), $profile->getTwOauthToken(), $profile->getTwOauthTokenSecret());
     $content = $connection->get('account/verify_credentials');
     if (isset($content->error) && $content->error) {
         return false;
     }
     return $content;
 }
コード例 #29
0
ファイル: SignPresenter.php プロジェクト: exesek/nette20login
 public function actionTwitter()
 {
     $twitterConfig = $this->context->parameters['twitter'];
     $twitterSession = $this->getSession('twitter');
     $twitter = new TwitterOAuth($twitterConfig['consumerKey'], $twitterConfig['consumerSecret'], $twitterSession->oauthToken, $twitterSession->oauthTokenSecret);
     $accessToken = $twitter->getAccessToken();
     $info = $twitter->get('/users/show', array('user_id' => $accessToken['user_id']));
     $authenticator = $this->context->twitterAuthenticator;
     $identity = $authenticator->authenticate($info);
     $this->getUser()->login($identity);
 }
コード例 #30
0
ファイル: getTweets.php プロジェクト: jjkong15/gitsample
function search(array $query)
{
    //construct TwitterOAuth object. The following keys are fake keys for the sample purpose, you may get them by registering an application at https://dev.twitter.com/apps
    //
    $consumer_key = "1VswxxxxxxxxxxxxxxxxxxxxRil";
    $consumer_secret = "C3WMV0xyISP8xxxxxxxxxxxxxxxxxlgcGw";
    $oauth_token = "384927756-m32xxxxxxxxxxxxxxxxxxxxxxxxVuV";
    $oauth_token_secret = "APdxxxxxxxxxxxxxxxxxxxxxxxxxxxwFcBG";
    $toa = new TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
    return $toa->get('search/tweets', $query);
}