function Medieteknik_Save_Token()
{
    //assume we have been authorized and returned
    //first check if we have a logged in user
    //äckliga wordpress vill att man gör såhär
    global $user_ID;
    get_currentuserinfo();
    if (!$user_ID) {
        die('Du är inte inloggad i wordpress. LOGGA IN FFS!!!!');
    }
    //get our temporary token
    $token = $_SESSION['oauth_token'];
    $secret = $_SESSION['oauth_token_secret'];
    //kolla att vi faktiskt har en token
    if (!$token || !$secret) {
        die('Kunde inte hitta en sparad token. Gör om gör rätt!');
    }
    //request a permanent token
    $oauth = new TwitterOAuth($token, $secret);
    $new_token = $oauth->access_token();
    //check our reply
    if (!$new_token['oauth_token'] || !$new_token['oauth_token_secret']) {
        die('Du blev inte autoriserad. Prova igen?');
    }
    //insert token and secret into the usermeta database
    update_usermeta($user_ID, 'twitter_token', $new_token['oauth_token']);
    update_usermeta($user_ID, 'twitter_token_secret', $new_token['oauth_token_secret']);
    //echo 'Välkommen ' . $new_token['screen_name'];
    //istället redirecta till index
    header('location: index.php');
}
function Medieteknik_post_tweet($tweet, $hashtag)
{
    //get current user
    global $user_ID;
    get_currentuserinfo();
    //get the saved token for this user
    $token = get_usermeta($user_ID, 'twitter_token');
    $secret = get_usermeta($user_ID, 'twitter_token_secret');
    $oauth = new TwitterOAuth($token, $secret);
    $url = 'http://api.twitter.com/1/statuses/update.xml';
    if ($hashtag && strpos(strtolower($tweet), '#medieteknik') == false) {
        //add the hashtag
        $tweet = rtrim($tweet) . ' #medieteknik';
    }
    $params = array('status' => $tweet);
    $reply = $oauth->oauth_request($url, 'POST', $params);
    //Check our request came out ok
    if ($reply['status'] != 200) {
        if ($reply['status'] == 403) {
            die('Twitter tillåter endast 150 statusuppdateringar i timmen. Försök igen senare');
        } else {
            die('Något är galet med twitter. Försök igen senare eller kontakta sidansvarig');
        }
    }
    header('location: index.php');
}
Exemple #3
0
 public static function post($user, $text)
 {
     $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());
     $connection->post('statuses/update', array('status' => $text));
 }
Exemple #4
0
 function post($message)
 {
     error_reporting(0);
     $acces = array('consumer_key' => $this->auth['consumer_key'], 'consumer_secret' => $this->auth['consumer_secret'], 'access_token' => $this->auth['access_token'], 'access_secret' => $this->auth['access_secret']);
     $twitter = new TwitterOAuth($acces['consumer_key'], $acces['consumer_secret'], $acces['access_token'], $acces['access_secret']);
     $response = $twitter->post('statuses/update', array('status' => $message));
 }
 public function push($Account, $TwitterStatus)
 {
     $NGPushIni = eZINI::instance('ngpush.ini');
     $Token = self::getToken($Account);
     if (!$Token) {
         self::requestToken($Account);
         $Token = self::getToken($Account);
     }
     if ($Token) {
         $tokenCredentials = explode('%%%', $Token);
         $connection = new TwitterOAuth($NGPushIni->variable($Account, 'ConsumerKey'), $NGPushIni->variable($Account, 'ConsumerSecret'), $tokenCredentials[0], $tokenCredentials[1]);
         $connection->host = "https://api.twitter.com/1.1/";
         $TwitterResponse = $connection->post('statuses/update', array('status' => $TwitterStatus));
         self::$response['response'] = $TwitterResponse;
         //Let's analyize some Twitter JSON response (lots of data but no clear structure and no status)
         if ($TwitterResponse->error) {
             self::$response['status'] = 'error';
             self::$response['messages'][] = $TwitterResponse->error;
         } elseif ($TwitterResponse->errors) {
             self::$response['status'] = 'error';
             foreach ($TwitterResponse->errors as $TwitterResponseError) {
                 self::$response['messages'][] = $TwitterResponseError->message;
             }
         } else {
             self::$response['status'] = 'success';
             if ($TwitterResponse->created_at) {
                 self::$response['messages'][] = 'Status is published!';
             }
         }
     } else {
         self::$response['status'] = 'error';
         self::$response['messages'][] = 'You need access token to use this application with Twitter.';
     }
     return self::$response;
 }
 /**
  * @Route("/souphpsp/x")
  */
 public function xAction()
 {
     $oauth = new \TwitterOAuth('qPLsh4YhO2Ui8KmM6vRtw', 'CbtjJPSD1yxxJfbbr4TPKX7K0UCExnffk5Qg', '18179550-Z6V17Ly1tvyOEiqCjuq1NfenI71FacvFrlqYT8Bqb', 'CkS51WZMERauimVxZBOxVQVLtBeDzIZCFLzCQpGzlg');
     $res = $oauth->post('http://api.twitter.com/1/direct_messages/new.json', array('screen_name' => 'rdohms', 'text' => 'mytext'));
     var_dump($res);
     return new \Symfony\Component\HttpFoundation\Response();
 }
Exemple #7
0
/**
 * 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;
}
Exemple #8
0
 function getUserAccessToken()
 {
     $session_access_token = $this->constructSessionVariableName("access_token");
     $token = NULL;
     if (isset($_SESSION[$session_access_token])) {
         $token = $_SESSION[$session_access_token];
         if (!$token || !isset($token["oauth_token"])) {
             unset($_SESSION[$session_access_token]);
         }
     }
     if (!$token) {
         $session_request_token = $this->constructSessionVariableName("oauth_request_token");
         $session_request_token_secret = $this->constructSessionVariableName("oauth_request_token_secret");
         if (isset($_SESSION[$session_request_token]) && isset($_SESSION[$session_request_token_secret])) {
             $to = new TwitterOAuth($this->getTwitter()->consumer->key, $this->getTwitter()->consumer->secret, $_SESSION[$session_request_token], $_SESSION[$session_request_token_secret]);
             $token = $to->getAccessToken($_REQUEST['oauth_verifier']);
             if (!$token || !isset($token["oauth_token"])) {
                 unset($_SESSION[$session_request_token]);
                 unset($_SESSION[$session_request_token_secret]);
             } else {
                 $session_var_name = $this->constructSessionVariableName("access_token");
                 $_SESSION[$session_var_name] = $token;
             }
         }
     }
     return $token;
 }
Exemple #9
0
 function index()
 {
     require APPPATH . 'modules/twitter/libraries/twitteroauth.php';
     /* If the oauth_token is old redirect to the connect page. */
     if ($this->input->get('oauth_token') && $this->session->userdata('twitter_oauth_token') !== $this->input->get('oauth_token')) {
         return redirect('admincp/twitter');
     }
     /* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
     $connection = new TwitterOAuth(setting('twitter_consumer_key'), setting('twitter_consumer_secret'), $this->session->userdata('twitter_oauth_token'), $this->session->userdata('twitter_oauth_token_secret'));
     /* Request access tokens from twitter */
     $access_token = $connection->getAccessToken($this->input->get('oauth_verifier'));
     /* Save the access tokens. Normally these would be saved in a database for future use. */
     $this->settings_model->update_setting('twitter_oauth_token', $access_token['oauth_token']);
     $this->settings_model->update_setting('twitter_oauth_token_secret', $access_token['oauth_token_secret']);
     /* Remove no longer needed request tokens */
     $this->session->unset_userdata('twitter_oauth_token');
     $this->session->unset_userdata('twitter_oauth_token_secret');
     /* If HTTP response is 200 continue otherwise send to connect page to retry */
     if (200 == $connection->http_code) {
         $this->notices->SetNotice('OAuthorization retrieved successfully.');
         return redirect('admincp/twitter');
     } else {
         $this->notices->SetError('Error making connection in OAuth callback.');
         return redirect('admincp/twitter');
     }
 }
Exemple #10
0
function post_on_behalf_of($user, $message) {
	if (!empty($user['tw_oauth_token']) && !empty($user['tw_oauth_token_secret'])) {
		$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $user['tw_oauth_token'], $user['tw_oauth_token_secret']);
		$resp = $connection->post('statuses/update', array('status' => $message));
		return (200 == $connection->http_code);
	}
}
/**
 * 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;
}
 function testIDsList()
 {
     global $THINKTANK_CFG;
     $to = new TwitterOAuth('', '', '', '');
     $result = $to->oAuthRequest('https://twitter.com/followers/ids.xml', array(), 'GET');
     $r = array();
     $r["id"] = 0;
     $r['network_username'] = '******';
     $r['network_user_id'] = 0;
     $r['last_status_id'] = 0;
     $r['last_page_fetched_replies'] = 0;
     $r['last_page_fetched_tweets'] = 0;
     $r['total_posts_in_system'] = 0;
     $r['total_replies_in_system'] = 0;
     $r['total_follows_in_system'] = 0;
     $r['total_users_in_system'] = 0;
     $r['is_archive_loaded_replies'] = 0;
     $r['is_archive_loaded_follows'] = 0;
     $r['crawler_last_run'] = '1/1/2007';
     $r['earliest_reply_in_system'] = 0;
     $r['api_calls_to_leave_unmade_per_minute'] = 5;
     $r['avg_replies_per_day'] = 0;
     $r['is_public'] = 1;
     $r['is_active'] = 1;
     $r['network'] = 'twitter';
     $i = new Instance($r);
     $api = new CrawlerTwitterAPIAccessorOAuth('111', '222', $THINKTANK_CFG['oauth_consumer_key'], $THINKTANK_CFG['oauth_consumer_secret'], $i, $THINKTANK_CFG['archive_limit']);
     $users = $api->parseXML($result);
     $next_cursor = $api->getNextCursor();
     //echo 'Next cursor is ' . $next_cursor;
     $this->assertTrue($next_cursor == '1326272872342936860');
 }
function twitter_oauth_login_test(&$vars)
{
    extract($vars);
    $success = false;
    $TwitterUser =& $db->model('TwitterUser');
    $tu = $TwitterUser->find_by(array('profile_id' => get_profile_id()), 1);
    if ($tu) {
        // http://abrah.am
        if (!class_exists('oauthexception')) {
            lib_include('twitteroauth');
        }
        $key = $tu->oauth_key;
        $secret = $tu->oauth_secret;
        $consumer_key = environment('twitterKey');
        $consumer_secret = environment('twitterSecret');
        $to = new TwitterOAuth($consumer_key, $consumer_secret, $tu->oauth_key, $tu->oauth_secret);
        $timelineurl = 'https://twitter.com/statuses/friends_timeline.atom';
        $response = $to->OAuthRequest($timelineurl, array(), 'GET');
        if (strpos($response, '<subtitle>')) {
            $success = true;
        }
    }
    if ($success) {
        echo 1;
    } else {
        echo 0;
    }
    exit;
}
Exemple #14
0
 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);
     }
 }
/**
 * Method for Twitter login
 */
function ie_api_twitter_login()
{
    // Test user is logged in
    if (!iewp_api_user_is_logged_in()) {
        die('Error: please sign in');
    }
    // Twitter app credentials
    $consumer_key = trim(get_option('iewp_api_twitterapp_consumer_key', ''));
    $consumer_secret = trim(get_option('iewp_api_twitterapp_consumer_secret', ''));
    $callback_url = site_url('wp-json/ie-api/twitter-callback');
    // Test app creds have been set
    if ($consumer_key == '' || $consumer_secret == '') {
        die('Error: invalid twitter app credentials');
    }
    // Get a request token
    $connection = new TwitterOAuth($consumer_key, $consumer_secret);
    $request_token = $connection->getRequestToken($callback_url);
    // Store the request token for use in callback
    $user_id = iewp_api_id_from_hash();
    update_user_meta($user_id, 'twitter_oauth_token', $request_token['oauth_token']);
    update_user_meta($user_id, 'twitter_oauth_token_secret', $request_token['oauth_token_secret']);
    // Redirect to Twitter app approval page
    $redirect_url = $connection->getAuthorizeURL($request_token);
    wp_redirect($redirect_url);
    exit;
}
 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;
     }
 }
 protected function authTwitter($save_name)
 {
     $config = $this->config;
     $conn = new TwitterOAuth($config['consumer_key'], $config['consumer_secret']);
     $request_token = $conn->getRequestToken();
     if ($request_token === false || $conn->lastStatusCode() != 200) {
         throw new RuntimeException("Error fetching Twitter auth token: Status code " . $conn->lastStatusCode() . '; ' . $conn->http_error);
     }
     $url = $conn->getAuthorizeURL($request_token);
     // Automatically send the user to the auth page.
     $ui = new UI();
     $ui->openBrowser($url);
     $pin = $ui->readline("Please visit {$url} then type the pin number: ");
     $conn = new TwitterOAuth($config['consumer_key'], $config['consumer_secret'], $request_token['oauth_token'], $request_token['oauth_token_secret']);
     $access_token = $conn->getAccessToken($pin);
     if ($access_token === false || $conn->lastStatusCode() != 200) {
         throw new RuntimeException("Error fetching Twitter access token: Status code " . $conn->lastStatusCode() . '; ' . $conn->http_error);
     }
     $this->config['oauth_token'] = $access_token['oauth_token'];
     $this->config['oauth_token_secret'] = $access_token['oauth_token_secret'];
     echo "Your Twitter token is " . $access_token['oauth_token'] . "\n";
     echo "Your Twitter token secret is " . $access_token['oauth_token_secret'] . "\n";
     echo "(Written to twitter-{$save_name}.txt)\n";
     if (file_put_contents("twitter-{$save_name}.txt", $access_token['oauth_token'] . "\n" . $access_token['oauth_token_secret'])) {
         return;
     }
     throw new RuntimeException("Failed to save oauth token to twitter-{$save_name}.txt");
 }
 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;
         }
     }
 }
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'])));
}
Exemple #20
0
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;
}
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;
}
Exemple #22
0
 public static function postMessage($params, $data)
 {
     $attachment = array('message' => $data['message']);
     $message = array();
     if (!class_exists('TwitterOAuth')) {
         require_once dirname(__FILE__) . '/elements/twitter/twitteroauth.php';
     }
     $user = $params->params->get('groupid');
     $checked = 0;
     $log = '';
     $publish = 1;
     if (isset($user->checked)) {
         $checked = 1;
         $twitter = unserialize($params->params->get('access_token'));
         $connection = new TwitterOAuth($params->params->get('app_appid'), $params->params->get('app_secret'), $twitter['oauth_token'], $twitter['oauth_token_secret']);
         $parameters = array('status' => $attachment['message']);
         $status = $connection->post('statuses/update', $parameters);
         if (isset($status->errors)) {
             $log = Jtext::_('PUBLISHED_TWITTER_PROFILE_SENDMESSAGE') . ' <a href="https://twitter.com/' . $user->screen_name . '" target="_blank" style="text-decoration: underline;">' . $user->name . '</a>  - ' . $status->errors[0]->message . ' <br/>';
             $publish = 0;
         } else {
             $log = Jtext::_('PUBLISHED_TWITTER_PROFILE_SENDMESSAGE') . ' <a href="https://twitter.com/' . $user->screen_name . '" target="_blank" style="text-decoration: underline;">' . $user->name . '</a>  - ' . JTEXT::_('PUBLISHED_TWITTER_PROFILE_SENDMESSAGE_SUCCESSFULL') . '<br/>';
             $publish = 1;
         }
     }
     $message['log'] = $log;
     $message['publish'] = $publish;
     $message['checked'] = $checked;
     $message['type'] = 'twitter';
     return $message;
 }
Exemple #23
0
 public function requestToken($Account)
 {
     $NGPushIni = eZINI::instance('ngpush.ini');
     $ConsumerKey = $NGPushIni->variable($Account, 'ConsumerKey');
     $ConsumerSecret = $NGPushIni->variable($Account, 'ConsumerSecret');
     $AccessToken = $NGPushIni->variable($Account, 'AccessToken');
     $AccessTokenSecret = $NGPushIni->variable($Account, 'AccessTokenSecret');
     // If access tokens are given
     if ($AccessToken && $AccessTokenSecret) {
         // Save request signing tokens to cache
         ngPushBase::save_token($Account, $AccessToken, 'request_sign_oauth_token');
         ngPushBase::save_token($Account, $AccessTokenSecret, 'request_sign_oauth_token_secret');
         ngPushBase::save_token($Account, $AccessToken . '%%%' . $AccessTokenSecret, 'main_token');
     } else {
         $connection = new TwitterOAuth($ConsumerKey, $ConsumerSecret);
         $connection->host = "https://api.twitter.com/1.1/";
         $AdministrationUrl = '/';
         eZURI::transformURI($AdministrationUrl, false, 'full');
         $AdministrationUrl = base64_encode($AdministrationUrl);
         $SettingsBlock = base64_encode($Account);
         $temporary_credentials = $connection->getRequestToken('http://' . $NGPushIni->variable('PushNodeSettings', 'ConnectURL') . '/redirect.php/' . $AdministrationUrl . '/' . $SettingsBlock . '?case=twitter');
         // Save request signing tokens to cache
         ngPushBase::save_token($Account, $temporary_credentials['oauth_token'], 'request_sign_oauth_token');
         ngPushBase::save_token($Account, $temporary_credentials['oauth_token_secret'], 'request_sign_oauth_token_secret');
         $redirect_url = $connection->getAuthorizeURL($temporary_credentials, FALSE);
         self::$response['RequestPermissionsUrl'] = $redirect_url;
     }
 }
Exemple #24
0
 public function callBack()
 {
     /* If the oauth_token is old redirect to the connect page. */
     //	if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token'])
     if (isset($_REQUEST['oauth_token']) && $this->session->userdata('oauth_token') !== $_REQUEST['oauth_token']) {
         //		$_SESSION['oauth_status'] = 'oldtoken';
         //		header('Location: ./clearsessions.php');
         echo "bad oauth_token";
         return false;
     }
     /* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
     $connection = new TwitterOAuth(_TWITTER_CONSUMER_KEY_, _TWITTER_CONSUMER_SECRET_, $this->session->userdata('oauth_token'), $this->session->userdata('oauth_token_secret'));
     /* Request access tokens from twitter */
     $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
     /* Save the access tokens. Normally these would be saved in a database for future use. */
     $_SESSION['access_token'] = $access_token;
     $this->db_update("users", $access_token, array("id" => $this->session->userdata('id')));
     //		/* Remove no longer needed request tokens */
     //		unset($_SESSION['oauth_token']);
     //		unset($_SESSION['oauth_token_secret']);
     /* If HTTP response is 200 continue otherwise send to connect page to retry */
     if (200 == $connection->http_code) {
         /* The user has been verified and the access tokens can be saved for future use */
         //			$_SESSION['status'] = 'verified';
         //			header('Location: ./index.php');
         echo "TWITTER OK";
     } else {
         /* Save HTTP status for error dialog on connnect page.*/
         //			header('Location: ./clearsessions.php');
         echo "ERROR";
     }
 }
 function update($new_instance, $old_instance)
 {
     $instance = $old_instance;
     $tb_o = get_option('tweet-blender');
     $errors = array();
     // check to make sure we have oAuth token
     if (!$tb_o['oauth_access_token']) {
         // Create TwitterOAuth object and get request token
         $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
         // Get request token
         $request_token = $connection->getRequestToken(get_bloginfo('url') . '/' . PLUGINDIR . "/tweet-blender/lib/twitteroauth/callback.php");
         if ($connection->http_code == 200) {
             // Save request token to session
             $tb_o['oauth_token'] = $token = $request_token['oauth_token'];
             $tb_o['oauth_token_secret'] = $request_token['oauth_token_secret'];
             update_option('tweet-blender', $tb_o);
             $errors[] = __("Twitter API v1.1 requires authentication", 'tweetblender') . " <a href='javascript:tAuth(\"" . $connection->getAuthorizeURL($token) . "\")' title=" . __('Authorize Access', 'tweetblender') . ">" . __('Use your Twitter account to login', 'tweetblender') . "</a>.";
         } else {
             $errors[] = __("Twitter oAuth is not possible at this time.", 'tweetblender') . "<!--" . $connection->last_api_call . "-->";
         }
     }
     if (sizeof($errors) == 0) {
         $this->message = __('Settings saved', 'tweetblender');
         $instance['title'] = trim(strip_tags($new_instance['title']));
         $instance['widget_refresh_rate'] = $new_instance['widget_refresh_rate'];
         $instance['widget_tweets_num'] = $new_instance['widget_tweets_num'];
         return $instance;
     } else {
         if (sizeof($errors) > 0) {
             $this->error .= join(', ', $errors);
         }
         $this->bad_input = $new_instance;
         return false;
     }
 }
function post_twitt_news($id_news)
{
    if (Nw::$is_prod && isset(Nw::$twitter['nouweo']) && count(Nw::$twitter['nouweo']) > 0) {
        inc_lib('news/get_info_news');
        $donnees_news = get_info_news($id_news);
        $real_link_news = Nw::$site_url . $donnees_news['c_rewrite'] . '/' . rewrite($donnees_news['n_titre']) . '-' . $id_news . '/';
        $fields = array('source' => $real_link_news);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, 'http://shr.im/api/post/');
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($curl);
        curl_close($curl);
        $end_twitt = ' http://shr.im/' . $result . ' #' . strtolower(Nw::$site_name) . ' #' . strtolower($donnees_news['c_rewrite']);
        $longueur_twitt = 145 - strlen($end_twitt);
        if ($donnees_news['n_titre'] > $longueur_twitt) {
            $add_titre = CoupeChar($donnees_news['n_titre'], '...', $longueur_twitt);
        } else {
            $add_titre = $donnees_news['n_titre'];
        }
        $twitt2post = $add_titre . $end_twitt;
        // Postage du twitt sur le compte de base
        $to = new TwitterOAuth(Nw::$twitter['nouweo']['consumer_key'], Nw::$twitter['nouweo']['consumer_secret'], Nw::$twitter['nouweo']['token'], Nw::$twitter['nouweo']['token_secret']);
        $to->OAuthRequest('https://twitter.com/statuses/update.xml', array('status' => $twitt2post), 'POST');
        return $result;
    } else {
        return false;
    }
}
 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));
 }
 /**
  * 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;
 }
Exemple #29
0
 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;
 }
 /**
  * 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;
 }