Пример #1
0
 function widget($args, $instance)
 {
     $facebook = $instance['facebook'];
     $title = $instance['label'];
     $twitter = $instance['twitter'];
     $consumer_key = isset($instance['consumer_key']) ? $instance['consumer_key'] : '';
     $consumer_secret = isset($instance['consumer_secret']) ? $instance['consumer_secret'] : '';
     $access_token = isset($instance['access_token']) ? $instance['access_token'] : '';
     $access_token_secret = isset($instance['access_token_secret']) ? $instance['access_token_secret'] : '';
     $last_twitter_save = get_option('ts_last_twitter_follower_count_save_' . $twitter);
     $last_twitter_reponse = get_option('ts_last_twitter_follower_count_response_' . $twitter);
     $last_twitter_reponse = $last_twitter_reponse ? json_decode($last_twitter_reponse, true) : '';
     if ($last_twitter_save && time() - $last_twitter_save < 600 && $last_twitter_reponse && count($last_twitter_reponse) > 0) {
         //$last_twitter_reponse = json_decode($last_twitter_reponse, true);
     } else {
         $twitter_config = array('consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, 'token' => $access_token, 'secret' => $access_token_secret);
         $tmhOAuth = new tmhOAuth($twitter_config);
         $params = array('screen_name' => $twitter);
         $code = $tmhOAuth->user_request(array('method' => 'GET', 'url' => $tmhOAuth->url("1.1/users/show"), 'params' => $params));
         if ($code == 200) {
             $last_twitter_reponse = $tmhOAuth->response['response'];
             $last_twitter_reponse_error = $last_twitter_reponse;
             update_option('ts_last_twitter_follower_count_save_' . $twitter, time());
             update_option('ts_last_twitter_follower_count_response_' . $twitter, $last_twitter_reponse);
             $last_twitter_reponse = json_decode($last_twitter_reponse, true);
         }
     }
     echo ts_essentials_escape($args['before_widget']);
     echo '<div class="inner clearfix">';
     if (!empty($title)) {
         echo ts_essentials_escape($args['before_title'] . apply_filters('widget_title', $title) . $args['after_title']);
     }
     if ($facebook) {
         $data = wp_remote_get('https://api.facebook.com/method/links.getStats?urls=' . urlencode('https://www.facebook.com/' . $facebook) . '&format=json');
         $fb_error = is_object($data) && get_class($data) == 'WP_Error' ? true : false;
         if (!$fb_error && isset($data['body'])) {
             $data = json_decode($data['body']);
             $data = isset($data[0]) && is_object($data[0]) ? $data[0] : $data;
             if (isset($data->like_count)) {
                 echo '<div class="inline-block"><a href="https://facebook.com/' . esc_attr($facebook) . '" class="facebook">';
                 echo '<i class="fa fa-facebook facebook-bg-color"></i>';
                 echo '<h4 class="sp1" title="' . esc_attr($data->like_count) . '">' . ts_essentials_num2str($data->like_count) . '</h4>';
                 echo '<span class="sp2 small">Likes</span>';
                 echo '</a></div>';
             }
         }
     }
     if ($twitter && is_array($last_twitter_reponse)) {
         $data = $last_twitter_reponse;
         if (isset($data['followers_count'])) {
             echo '<div class="inline-block"><a href="https://twitter.com/' . esc_attr($twitter) . '" class="twitter">';
             echo '<i class="fa fa-twitter twitter-bg-color"></i>';
             echo '<h4 class="sp1" title="' . esc_attr($data['followers_count']) . '">' . ts_essentials_num2str($data['followers_count']) . '</h4>';
             echo '<span class="sp2 small">Followers</span>';
             echo '</a></div>';
         }
     }
     echo '</div>';
     echo ts_essentials_escape($args['after_widget']);
 }
Пример #2
0
 public function execute()
 {
     $app = Application::instance();
     $cacheDriver = $app->getCacheDriver();
     $twitterOAuthConf = Config::$a['oauth']['providers']['twitter'];
     $tmhOAuth = new \tmhOAuth(array('consumer_key' => $twitterOAuthConf['clientId'], 'consumer_secret' => $twitterOAuthConf['clientSecret'], 'token' => $twitterOAuthConf['token'], 'secret' => $twitterOAuthConf['secret'], 'curl_connecttimeout' => Config::$a['curl']['connecttimeout'], 'curl_timeout' => Config::$a['curl']['timeout'], 'curl_ssl_verifypeer' => Config::$a['curl']['verifypeer']));
     /** @noinspection PhpVoidFunctionResultUsedInspection */
     $code = $tmhOAuth->user_request(array('url' => $tmhOAuth->url('1.1/statuses/user_timeline.json'), 'params' => array('screen_name' => Config::$a['twitter']['user'], 'count' => 3, 'trim_user' => true)));
     if ($code == 200) {
         $result = json_decode($tmhOAuth->response['response'], true);
         $tweets = array();
         foreach ($result as $tweet) {
             $html = $tweet['text'];
             if (isset($tweet['entities']['user_mentions'])) {
                 foreach ($tweet['entities']['user_mentions'] as $ment) {
                     $l = '<a href="http://twitter.com/' . $ment['screen_name'] . '">' . $ment['name'] . '</a>';
                     $html = str_replace('@' . $ment['screen_name'], $l, $html);
                 }
             }
             if (isset($tweet['entities']) && isset($tweet['entities']['urls'])) {
                 foreach ($tweet['entities']['urls'] as $url) {
                     $l = '<a href="' . $url['url'] . '" rev="' . $url['expanded_url'] . '">' . $url['display_url'] . '</a>';
                     $html = str_replace($url['url'], $l, $html);
                 }
             }
             $tweet['user']['screen_name'] = Config::$a['twitter']['user'];
             $tweet['html'] = $html;
             $tweets[] = $tweet;
         }
         $cacheDriver->save('twitter', $tweets);
     }
 }
 public function LatestTweetsList($limit = '5')
 {
     $conf = SiteConfig::current_site_config();
     if (empty($conf->TwitterName) || empty($conf->TwitterConsumerKey) || empty($conf->TwitterConsumerSecret) || empty($conf->TwitterAccessToken) || empty($conf->TwitterAccessTokenSecret)) {
         return new ArrayList();
     }
     $cache = SS_Cache::factory('LatestTweets_cache');
     if (!($results = unserialize($cache->load(__FUNCTION__)))) {
         $results = new ArrayList();
         require_once dirname(__FILE__) . '/tmhOAuth/tmhOAuth.php';
         require_once dirname(__FILE__) . '/tmhOAuth/tmhUtilities.php';
         $tmhOAuth = new tmhOAuth(array('consumer_key' => $conf->TwitterConsumerKey, 'consumer_secret' => $conf->TwitterConsumerSecret, 'user_token' => $conf->TwitterAccessToken, 'user_secret' => $conf->TwitterAccessTokenSecret, 'curl_ssl_verifypeer' => false));
         $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $conf->TwitterName, 'count' => $limit));
         $tweets = $tmhOAuth->response['response'];
         $json = new JSONDataFormatter();
         if (($arr = $json->convertStringToArray($tweets)) && is_array($arr) && isset($arr[0]['text'])) {
             foreach ($arr as $tweet) {
                 try {
                     $here = new DateTime(SS_Datetime::now()->getValue());
                     $there = new DateTime($tweet['created_at']);
                     $there->setTimezone($here->getTimezone());
                     $date = $there->Format('Y-m-d H:i:s');
                 } catch (Exception $e) {
                     $date = 0;
                 }
                 $results->push(new ArrayData(array('Text' => nl2br(tmhUtilities::entify_with_options($tweet, array('target' => '_blank'))), 'Date' => SS_Datetime::create_field('SS_Datetime', $date))));
             }
         }
         $cache->save(serialize($results), __FUNCTION__);
     }
     return $results;
 }
Пример #4
0
/**
* This method uses the Twitter API to get specified amount of Tweet Responses
* from Twitter for a specified Twitter User.
*
* @param screenName :: The Twitter Handle for which we require the tweets
* @param count :: The number of recent tweets needed for the Twitter User
*
* @return response :: Array of Twitter Response Objects
*/
function getTweet($screenName, $count)
{
    $parameters = array();
    $parameters['screen_name'] = $screenName;
    $parameters['count'] = $count;
    $connection = new tmhOAuth(array('consumer_key' => 'C8U6aOYWFkfuPxOiFBxoF87jF', 'consumer_secret' => 'cODzOUcJSqd3ATG15J25GXZlz7AyhK6gHbRCmsCiMIn0rfMKIu', 'user_token' => '2261472366-CPKf4pZ9fosiZ2zCQfXi7tiexIzbiNfzJ8lEcoC', 'user_secret' => 'gH6qWAAOCrmS38sf5ipaXIxHZHLHNGtYOmCZcJrFli0M9'));
    $twitterPath = '1.1/statuses/user_timeline.json';
    $http_code = $connection->request('GET', $connection->url($twitterPath), $parameters);
    // If everything is good
    if ($http_code === 200) {
        $response = strip_tags($connection->response['response']);
        $twitterResp = json_decode($response, true);
        // Log Success
        if (count($twitterResp) == 200) {
            logSuccess('tweetylogs.txt', 'Grabbed 200 Tweets for ' . $screenName . ' from the Twitter API.');
            logSuccess('success.txt', 'Grabbed 200 Tweets for ' . $screenName . ' from the Twitter API.');
            logSuccess('tweetylogs.html', 'Grabbed <b>200</b> Tweets for <b>' . $screenName . '</b> from the Twitter API.');
        } else {
            logWarning('tweetylogs.txt', 'Grabbed ' . (string) count($twitterResp) . ' Tweets for' . $screenName . ' from the Twitter API.');
            logWarning('warning.txt', 'Grabbed ' . (string) count($twitterResp) . ' Tweets for' . $screenName . ' from the Twitter API.');
            logWarning('tweetylogs.html', 'Grabbed <b>' . (string) count($twitterResp) . '</b> Tweets for <b>' . $screenName . '</b> from the Twitter API.');
        }
        return $twitterResp;
    } else {
        logError('tweetylogs.txt', 'Error in the function refreshData.php/getTweet() for Twitter User: '******'. HTTP Code not 200. HTTP Code/Error ID: ' . $http_code . '. Error: ' . $connection->response['error']);
        logError('error.txt', 'Error in the function refreshData.php/getTweet() for Twitter User: '******'. HTTP Code not 200. HTTP Code/Error ID: ' . $http_code . '. Error: ' . $connection->response['error']);
        logError('tweetylogs.html', 'Error in the function refreshData.php/getTweet() for Twitter User: <b>' . $screenName . '</b>. HTTP Code not 200. <b>HTTP Code/Error ID:</b> ' . $http_code . '. <b>Error:</b> ' . $connection->response['error']);
    }
}
 /**
  *
  * @param array $data
  * @param array $services
  */
 public function sendToSocialMedia(array $data, array $services = array('facebook', 'twitter'))
 {
     // init output
     $ids = array('facebook' => null, 'twitter' => null);
     // Facebook
     if (in_array('facebook', $services) && $this->confirmFacebookAccess()) {
         $facebook = new Facebook(array('appId' => static::$conf->FacebookAppId, 'secret' => static::$conf->FacebookAppSecret));
         $facebook->setAccessToken(static::$conf->FacebookPageAccessToken);
         try {
             $post_id = $facebook->api("/" . static::$conf->FacebookPageId . "/feed", "post", $data);
             $ids['facebook'] = $post_id['id'];
         } catch (FacebookApiException $e) {
             SS_Log::log('Error ' . $e->getCode() . ' : ' . $e->getFile() . ' Line ' . $e->getLine() . ' : ' . $e->getMessage() . "\n" . 'BackTrace: ' . "\n" . $e->getTraceAsString(), SS_Log::ERR);
         }
     }
     // Twitter
     if (in_array('twitter', $services) && $this->confirmTwitterAccess()) {
         $connection = new tmhOAuth(array('consumer_key' => static::$conf->TwitterConsumerKey, 'consumer_secret' => static::$conf->TwitterConsumerSecret, 'user_token' => static::$conf->TwitterOAuthToken, 'user_secret' => static::$conf->TwitterOAuthSecret));
         $tweet = $data['name'] . ": " . $data['link'];
         $code = $connection->request('POST', $connection->url('1.1/statuses/update'), array('status' => $tweet));
         if ($code == 200) {
             $data = json_decode($connection->response['response']);
             $ids['twitter'] = $data->id_str;
         }
     }
     return $ids;
 }
Пример #6
0
function search($idlist)
{
    global $twitter_keys, $current_key, $all_users, $all_tweet_ids, $bin_name, $dbh, $tweetQueue;
    $keyinfo = getRESTKey(0);
    $current_key = $keyinfo['key'];
    $ratefree = $keyinfo['remaining'];
    print "current key {$current_key} ratefree {$ratefree}\n";
    $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret']));
    // by hundred
    for ($i = 0; $i < sizeof($idlist); $i += 100) {
        if ($ratefree <= 0 || $ratefree % 10 == 0) {
            $keyinfo = getRESTKey($current_key);
            $current_key = $keyinfo['key'];
            $ratefree = $keyinfo['remaining'];
            $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret']));
        }
        $q = $idlist[$i];
        $n = $i + 1;
        while ($n < $i + 100) {
            if (!isset($idlist[$n])) {
                break;
            }
            $q .= "," . $idlist[$n];
            $n++;
        }
        $params = array('id' => $q);
        $code = $tmhOAuth->user_request(array('method' => 'GET', 'url' => $tmhOAuth->url('1.1/statuses/lookup'), 'params' => $params));
        $ratefree--;
        if ($tmhOAuth->response['code'] == 200) {
            $data = json_decode($tmhOAuth->response['response'], true);
            if (is_array($data) && empty($data)) {
                // all tweets in set are deleted
                continue;
            }
            $tweets = $data;
            $tweet_ids = array();
            foreach ($tweets as $tweet) {
                $t = new Tweet();
                $t->fromJSON($tweet);
                if (!$t->isInBin($bin_name)) {
                    $all_users[] = $t->from_user_id;
                    $all_tweet_ids[] = $t->id;
                    $tweet_ids[] = $t->id;
                    $tweetQueue->push($t, $bin_name);
                }
                print ".";
            }
            sleep(1);
        } else {
            echo "Failure with code " . $tmhOAuth->response['response']['code'] . "\n";
            var_dump($tmhOAuth->response['response']['info']);
            var_dump($tmhOAuth->response['response']['error']);
            var_dump($tmhOAuth->response['response']['errno']);
            die;
        }
        $tweetQueue->insertDB();
    }
}
 public function publish(ISocialStatus $status)
 {
     $params = array('status' => $status->getStatusString());
     $tmhOAuthEngine = new tmhOAuth($this->_config);
     $response = $tmhOAuthEngine->user_request(array('method' => 'POST', 'url' => $tmhOAuthEngine->url("1.1/statuses/update"), 'params' => $params, 'multipart' => true));
     if ($response != 200) {
         throw new Exception('Unable to publish on Twitter (ERR: ' . $response . ')');
     }
 }
Пример #8
0
function get_twitter_timeline($user)
{
    //global $user;
    $tmhOAuth = new tmhOAuth(array('consumer_key' => CONSUMER_KEY, 'consumer_secret' => CONSUMER_SECRET, 'token' => USER_TOKEN, 'secret' => USER_SECRET));
    if ($tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline.json'), array('include_entities' => 'false', 'include_rts' => 'false', 'trim_user' => 'true', 'screen_name' => $user, 'exclude_replies' => 'false', 'count' => TL_COUNT), true) != 200) {
        header("Content-Type: text/html; charset=utf-8");
        die('Could not connect to Twitter');
    }
    return json_decode($tmhOAuth->response['response'], true);
}
Пример #9
0
 /**
  * Login to facebook and get the associated contrexx user.
  */
 public function login()
 {
     // fixing timestamp issue with twitter
     // it is necessary that the twitter server has the same time as our system
     date_default_timezone_set('UTC');
     $tmhOAuth = new \tmhOAuth(array('consumer_key' => $this->applicationData[0], 'consumer_secret' => $this->applicationData[1]));
     // set the timestamp
     $tmhOAuth->config['force_timestamp'] = true;
     $tmhOAuth->config['timestamp'] = time();
     if (isset($_GET['oauth_verifier'])) {
         $tmhOAuth->config['user_token'] = $_SESSION['oauth']['oauth_token'];
         $tmhOAuth->config['user_secret'] = $_SESSION['oauth']['oauth_token_secret'];
         $tmhOAuth->request('POST', $tmhOAuth->url('oauth/access_token', ''), array('oauth_verifier' => $_GET['oauth_verifier'], 'x_auth_access_type' => 'read'));
         $access_token = $tmhOAuth->extract_params($tmhOAuth->response['response']);
         $tmhOAuth->config['user_token'] = $access_token['oauth_token'];
         $tmhOAuth->config['user_secret'] = $access_token['oauth_token_secret'];
         $tmhOAuth->request('GET', $tmhOAuth->url('1.1/account/verify_credentials'));
         $resp = json_decode($tmhOAuth->response['response']);
         unset($_SESSION['oauth']);
         $name = explode(' ', $resp->name);
         self::$userdata = array('first_name' => $name[0], 'last_name' => $name[1], 'email' => $resp->screen_name . '@twitter.com');
         $this->getContrexxUser($resp->id);
     } else {
         $tmhOAuth->request('POST', $tmhOAuth->url('oauth/request_token', ""), array('oauth_callback' => \Cx\Lib\SocialLogin::getLoginUrl(self::OAUTH_PROVIDER)));
         $_SESSION['oauth'] = $tmhOAuth->extract_params($tmhOAuth->response['response']);
         $url = 'https://api.twitter.com/oauth/authenticate?oauth_token=' . $_SESSION['oauth']['oauth_token'];
         \Cx\Core\Csrf\Controller\Csrf::header("Location: " . $url);
         exit;
     }
 }
Пример #10
0
function search($keywords, $max_id = null)
{
    global $twitter_keys, $current_key, $ratefree, $bin_name, $dbh, $tweetQueue;
    $ratefree--;
    if ($ratefree < 1 || $ratefree % 10 == 0) {
        $keyinfo = getRESTKey($current_key, 'search', 'tweets');
        $current_key = $keyinfo['key'];
        $ratefree = $keyinfo['remaining'];
    }
    $tmhOAuth = new tmhOAuth(array('consumer_key' => $twitter_keys[$current_key]['twitter_consumer_key'], 'consumer_secret' => $twitter_keys[$current_key]['twitter_consumer_secret'], 'token' => $twitter_keys[$current_key]['twitter_user_token'], 'secret' => $twitter_keys[$current_key]['twitter_user_secret']));
    $params = array('q' => $keywords, 'count' => 100);
    if (isset($max_id)) {
        $params['max_id'] = $max_id;
    }
    $code = $tmhOAuth->user_request(array('method' => 'GET', 'url' => $tmhOAuth->url('1.1/search/tweets'), 'params' => $params));
    if ($tmhOAuth->response['code'] == 200) {
        $data = json_decode($tmhOAuth->response['response'], true);
        $tweets = $data['statuses'];
        $tweet_ids = array();
        foreach ($tweets as $tweet) {
            $t = new Tweet();
            $t->fromJSON($tweet);
            $tweet_ids[] = $t->id;
            if (!$t->isInBin($bin_name)) {
                $tweetQueue->push($t, $bin_name);
                if ($tweetQueue->length() > 100) {
                    $tweetQueue->insertDB();
                }
                print ".";
            }
        }
        if (!empty($tweet_ids)) {
            print "\n";
            if (count($tweet_ids) <= 1) {
                print "no more tweets found\n\n";
                return false;
            }
            $max_id = min($tweet_ids);
            print "max id: " . $max_id . "\n";
        } else {
            print "0 tweets found\n\n";
            return false;
        }
        sleep(1);
        search($keywords, $max_id);
    } else {
        echo $tmhOAuth->response['response'] . "\n";
        if ($tmhOAuth->response['response']['errors']['code'] == 130) {
            // over capacity
            sleep(1);
            search($keywords, $max_id);
        }
    }
}
Пример #11
0
function tweetFromCoffeeMachine($message)
{
    $tmhOAuth = new tmhOAuth(array('consumer_key' => 'yBqPMCfmM59Rbglvz1Ulaw', 'consumer_secret' => 'emXtf7PDoYURANce1RqRE2FaZpgJeaQixRlCafpQ0', 'user_token' => '576073937-gZokaOQgJwY3U64frIV1MkzHfnelx3XvxMC2FHOM', 'user_secret' => 'ursK27EZa2nZliVBBFdfEjpiTwMkqdQoqpnTZG07Sgc'));
    $code = $tmhOAuth->request('POST', $tmhOAuth->url('1/statuses/update'), array('status' => $message));
    /* don't care about the response in this case
    	if ($code == 200) {
    	  tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
    	} else {
    	  tmhUtilities::pr($tmhOAuth->response['response']);
    	}*/
}
Пример #12
0
function checkTwitter($username)
{
    require_once 'libs/Twitter/tmhOAuth-master/tmhOAuth.php';
    require_once 'libs/Twitter/tmhOAuth-master/tmhUtilities.php';
    $tmhOAuth = new tmhOAuth(array('consumer_key' => TWITTER_CONSUMER_KEY, 'consumer_secret' => TWITTER_CONSUMER_SECRET, 'user_token' => TWITTER_USER_TOKEN, 'user_secret' => TWITTER_USER_SECRET));
    $code = $tmhOAuth->request('GET', 'https://api.twitter.com/1.1/users/lookup.json', array('screen_name' => $username));
    if ($code == 200) {
        return json_decode($tmhOAuth->response['response'], true);
    } else {
        return false;
    }
}
Пример #13
0
function tfuse_get_tweets($username, $count = 20)
{
    $tweets_cache_path = get_template_directory() . '/cache/twitter_json_' . $username . '_rpp_' . $count . '.cache';
    if (file_exists($tweets_cache_path)) {
        $tweets_cache_timer = intval((time() - filemtime($tweets_cache_path)) / 60);
    } else {
        $tweets_cache_timer = 0;
    }
    if ((!file_exists($tweets_cache_path) or $tweets_cache_timer > 15) && function_exists('curl_init')) {
        require_once dirname(__FILE__) . '/libs/twitter/tmhOAuth.php';
        require_once dirname(__FILE__) . '/libs/twitter/tmhUtilities.php';
        $tmhOAuth = new tmhOAuth(array('consumer_key' => tfuse_options('twitter_consumer_key', ''), 'consumer_secret' => tfuse_options('twitter_consumer_secret', ''), 'user_token' => tfuse_options('twitter_user_token', ''), 'user_secret' => tfuse_options('twitter_user_secret', '')));
        $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $username));
        $response = $tmhOAuth->response;
        $JsonTweets = json_decode($response['response']);
        if (is_array($JsonTweets)) {
            $JsonTweets = array_slice($JsonTweets, 0, $count);
            foreach ($JsonTweets as $JsonKey => $JsonVal) {
                // Some reformatting
                $pattern = array('/[^(:\\/\\/)](www\\.[^ \\n\\r]+)/', '/(https?:\\/\\/[^ \\n\\r]+)/', '/@(\\w+)/', '/^' . $username . ':\\s*/i');
                $replace = array('<a href="http://$1" rel="nofollow"  target="_blank">$1</a>', '<a href="$1" rel="nofollow" target="_blank">$1</a>', '<a href="http://twitter.com/$1" rel="nofollow"  target="_blank">@$1</a>' . '');
                $JsonTweets[$JsonKey]->text = preg_replace($pattern, $replace, $JsonTweets[$JsonKey]->text);
                $JsonTweets[$JsonKey]->created_at = tfuse_since($JsonTweets[$JsonKey]->created_at);
            }
        } else {
            return array();
        }
        // Some error? Return an empty array
        // You may want to extend this to know the exact error
        echo curl_error($curl_handle);
        // or know the http status
        echo curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
        if (file_exists($tweets_cache_path)) {
            unlink($tweets_cache_path);
        }
        $myFile = $tweets_cache_path;
        $fh = fopen($myFile, 'w') or die("can't open file");
        $stringData = json_encode($JsonTweets);
        fwrite($fh, $stringData);
        fclose($fh);
    } else {
        error_reporting(0);
        $file = file_get_contents($tweets_cache_path, true);
        if (!empty($file)) {
            $JsonTweets = json_decode($file);
            if (!is_array($JsonTweets)) {
                $JsonTweets = array();
            }
        }
    }
    return $JsonTweets;
}
Пример #14
0
 protected function getTweets($number)
 {
     $items = array();
     $twitter = new tmhOAuth(array('consumer_key' => TWITTER_CONSUMER_KEY, 'consumer_secret' => TWITTER_CONSUMER_SECRET, 'user_token' => TWITTER_USER_TOKEN, 'user_secret' => TWITTER_USER_SECRET));
     $responseCode = $twitter->request('GET', $twitter->url('1/statuses/home_timeline'), array('count' => $number, 'contributor_details' => true));
     if (200 == $responseCode) {
         $tweets = json_decode($twitter->response['response']);
         foreach ($tweets as $tweet) {
             $items[] = $this->makeBalloonFromTweet($tweet);
         }
     }
     return $items;
 }
Пример #15
0
    /** @see WP_Widget::widget */
    function widget($args, $instance)
    {
        extract($args);
        //these are our widget options
        $title = isset($instance['title']) ? $instance['title'] : "";
        $animation = isset($instance['animation']) ? $instance['animation'] : "";
        $login = isset($instance['login']) ? $instance['login'] : "";
        $count = isset($instance['count']) ? $instance['count'] : "";
        $consumer_key = isset($instance['consumer_key']) ? $instance['consumer_key'] : "";
        $consumer_secret = isset($instance['consumer_secret']) ? $instance['consumer_secret'] : "";
        $access_token = isset($instance['access_token']) ? $instance['access_token'] : "";
        $access_token_secret = isset($instance['access_token_secret']) ? $instance['access_token_secret'] : "";
        echo $before_widget;
        require_once locate_template("/libraries/tmhOAuth/tmhOAuth.php");
        require_once locate_template("/libraries/tmhOAuth/tmhUtilities.php");
        $tmhOAuth = new tmhOAuth(array('consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, 'user_token' => $access_token, 'user_secret' => $access_token_secret));
        $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $login, 'count' => $count, 'include_rts' => 'true'));
        $response = $tmhOAuth->response;
        ?>
		<div class="clearfix">
			<div class="header_left">
				<?php 
        if ($title) {
            echo ((int) $animation ? str_replace("box_header", "box_header animation-slide", $before_title) : str_replace("animation-slide", "", $before_title)) . apply_filters("widget_title", $title) . $after_title;
        }
        ?>
			</div>
			<div class="header_right">
				<a href="#" id="latest_tweets_prev" class="scrolling_list_control_left icon_small_arrow left_white"></a>
				<a href="#" id="latest_tweets_next" class="scrolling_list_control_right icon_small_arrow right_white"></a>
			</div>
		</div>
		<div class="scrolling_list_wrapper">
			<ul class="scrolling_list latest_tweets">
				<?php 
        //				require_once(get_template_directory() . "/libraries/lib_autolink.php");
        require_once locate_template("/libraries/lib_autolink.php");
        $tweets = json_decode($response['response']);
        if (count($tweets->errors)) {
            echo '<li class="icon_small_arrow right_white"><p>' . $tweets->errors[0]->message . '! ' . __('Please check your config under Appearance->Widgets->Twitter Feed!', 'medicenter') . '</p></li>';
        } else {
            foreach ($tweets as $tweet) {
                echo '<li class="icon_small_arrow right_white"><p>' . autolink($tweet->text, 20, ' target="_blank"') . '<abbr title="' . date('c', strtotime($tweet->created_at)) . '" class="timeago">' . $tweet->created_at . '</abbr></p></li>';
            }
        }
        ?>
			</ul>
		</div>
		<?php 
        echo $after_widget;
    }
Пример #16
0
 public function getAction()
 {
     $this->_helper->layout()->disableLayout();
     $this->_helper->viewRenderer->setNoRender(true);
     header('Cache-Control: no-cache, must-revalidate');
     header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
     header('Content-type: application/json');
     /* Set locale to Dutch */
     setlocale(LC_ALL, 'nl_NL');
     $cacheId = 'Mobile_Twitter';
     $cache = Zend_Registry::get('cache');
     if (true == ($result = $cache->load($cacheId))) {
         if ($result->timestamp + 240 < time()) {
             // vernieuwen om de 4 minuten oftewel 240 seconden
             $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('Twitter_Webservice'));
         }
         $output = $result->output;
         if ($this->_getParam('version', '1') == '2') {
             foreach ($output as $key => $tweet) {
                 $output[$key]['text'] = $this->processLinks($tweet['text']);
             }
         }
     } else {
         $config = Zend_Registry::get('config');
         require APPLICATION_ROOT . '/library/Twitter/tmhOAuth.php';
         require APPLICATION_ROOT . '/library/Twitter/tmhUtilities.php';
         $tmhOAuth = new tmhOAuth(array('consumer_key' => $config->twitter->customer_key, 'consumer_secret' => $config->twitter->customer_secret, 'user_token' => $config->twitter->user_token, 'user_secret' => $config->twitter->user_secret, 'debug' => false));
         $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => 'NAAM VAN USER INVULLEN'));
         if ($tmhOAuth->response['code'] == 200) {
             $content = json_decode($tmhOAuth->response['response']);
         } else {
             $tmhOAuth->pr(htmlentities($tmhOAuth->response['response']));
         }
         $output = array();
         foreach ($content as $entry) {
             $output[] = array('text' => $entry->text, 'created_at' => date('d/m/Y G:i', strtotime($entry->created_at)));
         }
         $object = new stdClass();
         $object->output = $output;
         $object->timestamp = time();
         $cache->save($object, $cacheId, array('Twitter_Webservice'));
         if ($this->_getParam('version', '1') == '2') {
             foreach ($output as $key => $tweet) {
                 $output[$key]['text'] = $this->processLinks($tweet['text']);
             }
         }
     }
     echo json_encode($output);
 }
Пример #17
0
function tweet($message)
{
    $tmhOAuth = new tmhOAuth($config);
    $tmhOAuth->request('POST', $tmhOAuth->url('1.1/statuses/update'), array('status' => $message));
    if ($tmhOAuth->response['code'] == 200) {
        // En cours de dév, afficher les informations retournées :
        //$tmhOAuth->pr(json_decode($tmhOAuth->response['response']));
        return TRUE;
    } else {
        // En cours de dév, afficher les informations retournées :
        //$tmhOAuth->pr(htmlentities($tmhOAuth->response['response']));
        print_r($tmhOAuth->response['response']);
        return FALSE;
    }
}
 public function api($method, $url, $params = null)
 {
     $config = Configure::read('Opauth.Strategy.Twitter');
     $tmhOAuth = new tmhOAuth(array('consumer_key' => $config['key'], 'consumer_secret' => $config['secret'], 'user_token' => $this->Session->read('Auth.Twitter.access_token'), 'user_secret' => $this->Session->read('Auth.Twitter.secret'), 'curl_ssl_verifypeer' => false));
     $url = $tmhOAuth->url($url);
     $status = $tmhOAuth->request($method, $url, $params);
     if ($status != 200) {
         return false;
     }
     if (strpos($url, '.json') !== false) {
         $response = json_decode($tmhOAuth->response['response']);
     } else {
         $response = $tmhOAuth->extract_params($this->tmhOAuth->response['response']);
     }
     return $response;
 }
Пример #19
0
 public function __construct($consumerKeys)
 {
     $this->consumerKeys = $consumerKeys;
     parent::__construct($consumerKeys);
     if (session_status() == PHP_SESSION_NONE) {
         session_start();
     }
 }
Пример #20
0
function post_tweet($tweet_text)
{
    // Use Matt Harris' OAuth library to make the connection
    // This lives at: https://github.com/themattharris/tmhOAuth
    require_once 'tmhoauth/tmhOAuth.php';
    // Set the authorization values
    // In keeping with the OAuth tradition of maximum confusion,
    // the names of some of these values are different from the Twitter Dev interface
    // user_token is called Access Token on the Dev site
    // user_secret is called Access Token Secret on the Dev site
    // The values here have asterisks to hide the true contents
    // You need to use the actual values from Twitter
    $connection = new tmhOAuth(array('consumer_key' => '******', 'consumer_secret' => '******', 'user_token' => '******', 'user_secret' => '******'));
    // Make the API call
    $connection->request('POST', $connection->url('1/statuses/update'), array('status' => $tweet_text));
    return $connection->response['code'];
}
Пример #21
0
function post_tweet($tweet_text)
{
    // Use Matt Harris' OAuth library to make the connection
    // This lives at: https://github.com/themattharris/tmhOAuth
    require_once 'twitlib/tmhOAuth.php';
    // Set the authorization values
    // In keeping with the OAuth tradition of maximum confusion,
    // the names of some of these values are different from the Twitter Dev interface
    // user_token is called Access Token on the Dev site
    // user_secret is called Access Token Secret on the Dev site
    // The values here have asterisks to hide the true contents
    // You need to use the actual values from Twitter
    $connection = new tmhOAuth(array('consumer_key' => 'Z6EiKT7pZq6OVqvWtZqxg', 'consumer_secret' => '3VyLFSlQg70ZOvj2QAY0egPFB0etNAE8kTOQygZ7kew', 'user_token' => '280185832-LiJ78IFzm1SolSZMaFuAkK5yu1XFMs5hhN48cXS1', 'user_secret' => 'vOlhWfm9sCXYPoMPZUCZY5RlqEOJECcz6LtlIb4C2XE'));
    // Make the API call
    $connection->request('POST', $connection->url('1/statuses/update'), array('status' => $tweet_text));
    return $connection->response['code'];
}
Пример #22
0
    /** @see WP_Widget::widget */
    function widget($args, $instance)
    {
        extract($args);
        //these are our widget options
        $title = $instance['title'];
        $login = $instance['login'];
        $count = $instance['count'];
        $consumer_key = $instance['consumer_key'];
        $consumer_secret = $instance['consumer_secret'];
        $access_token = $instance['access_token'];
        $access_token_secret = $instance['access_token_secret'];
        echo $before_widget;
        require_once get_template_directory() . '/libraries/tmhOAuth/tmhOAuth.php';
        require_once get_template_directory() . '/libraries/tmhOAuth/tmhUtilities.php';
        $tmhOAuth = new tmhOAuth(array('consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, 'user_token' => $access_token, 'user_secret' => $access_token_secret));
        $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $login, 'count' => $count, 'include_rts' => 'true'));
        $response = $tmhOAuth->response;
        ?>
		<div class="clearfix">
			<div class="header_left">
				<?php 
        if ($title) {
            echo $before_title . $title . $after_title;
        }
        ?>
			</div>
			<div class="header_right">
				<a href="#" id="latest_tweets_prev" class="scrolling_list_control_left icon_small_arrow left_white"></a>
				<a href="#" id="latest_tweets_next" class="scrolling_list_control_right icon_small_arrow right_white"></a>
			</div>
		</div>
		<div class="scrolling_list_wrapper">
			<ul class="scrolling_list latest_tweets">
				<?php 
        require_once get_template_directory() . "/libraries/lib_autolink.php";
        $tweets = json_decode($response['response']);
        foreach ($tweets as $tweet) {
            echo '<li class="icon_small_arrow right_white"><p>' . autolink($tweet->text, 20, ' target="_blank"') . '<abbr title="' . date('c', strtotime($tweet->created_at)) . '" class="timeago">' . $tweet->created_at . '</abbr></p></li>';
        }
        ?>
			</ul>
		</div>
		<?php 
        echo $after_widget;
    }
Пример #23
0
 public function __construct($config = array())
 {
     $this->config = array_merge(array('consumer_key' => 'YOUR_CONSUMER_KEY', 'consumer_secret' => 'YOUR_CONSUMER_SECRET', 'token' => 'A_USER_TOKEN', 'secret' => 'A_USER_SECRET', 'bearer' => 'YOUR_OAUTH2_TOKEN', 'user_agent' => 'tmhOAuth ' . parent::VERSION . ' Examples 0.1'), $config);
     if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'tmh_myconfig.php')) {
         include __DIR__ . DIRECTORY_SEPARATOR . 'tmh_myconfig.php';
         $this->config = array_merge($this->config, tmh_myconfig());
     }
     parent::__construct($this->config);
 }
Пример #24
0
 /**
  * Checks if the authentication credentials currently stored in hydra.yml are correct or not.
  *
  * @return boolean
  */
 public function isAccessTokenValid()
 {
     if (empty($this->authentication['bearer'])) {
         return false;
     }
     $this->api->apponly_request(array('method' => 'GET', 'url' => $this->api->url('youtube/v3/activities', ''), 'params' => array('part' => 'id', 'mine' => 'true')));
     // HTTP 200 means we were successful
     return $this->api->response['code'] == 200;
 }
Пример #25
0
 public function __construct($config = array())
 {
     $this->config = array_merge(array('consumer_key' => 'ptOjSuaCXjI4zmBMrRzdkKmzH', 'consumer_secret' => '99ytYeHhCfZaxIp1Ca0rdlfe8h1GB11lPwuYihLClsFAOOthXw', 'token' => '3247662382-HKQGaMo9cCds5erYUi5JJIvaGHRfWZEtLO5v4qE', 'secret' => 'hwsmEXRzwLAGz40xMtX5XK7FCZul1CRIOGLiVpu9jHVps', 'bearer' => '3247662382-HKQGaMo9cCds5erYUi5JJIvaGHRfWZEtLO5v4qE', 'user_agent' => 'tmhOAuth ' . parent::VERSION . ' Examples 0.1'), $config);
     if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'tmh_myconfig.php')) {
         include __DIR__ . DIRECTORY_SEPARATOR . 'tmh_myconfig.php';
         $this->config = array_merge($this->config, tmh_myconfig());
     }
     parent::__construct($this->config);
 }
Пример #26
0
 public function __construct($config = array())
 {
     $this->config = array_merge(array('consumer_key' => 'AHbD6KOwFcUp57JJ8ofTw', 'consumer_secret' => 'lxwPpSvedHIEQpevtPChGPuZk4awsVWECx5wUwE3R4', 'token' => 'A_USER_TOKEN', 'secret' => 'A_USER_SECRET', 'bearer' => 'YOUR_OAUTH2_TOKEN', 'user_agent' => 'tmhOAuth ' . parent::VERSION . ' Examples 0.1'), $config);
     if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'tmh_myconfig.php')) {
         include __DIR__ . DIRECTORY_SEPARATOR . 'tmh_myconfig.php';
         $this->config = array_merge($this->config, tmh_myconfig());
     }
     parent::__construct($this->config);
 }
Пример #27
0
 /**
  * Checks if the authentication credentials currently stored in hydra.yml are correct or not.
  *
  * @return boolean
  */
 public function isAccessTokenValid()
 {
     if (empty($this->authentication['accessToken'])) {
         return false;
     }
     $this->api->request('GET', $this->api->url('v1/users/self/feed'), array('access_token' => $this->authentication['accessToken']));
     // HTTP 200 means we were successful
     return $this->api->response['code'] == 200;
 }
Пример #28
0
function nextend_api_auth_flow()
{
    $api_key = NextendRequest::getVar('api_key');
    $api_secret = NextendRequest::getVar('api_secret');
    $redirect_uri = NextendRequest::getVar('redirect_uri');
    if (session_id() == "") {
        @session_start();
    }
    if (!$api_key || !$api_secret || !$redirect_uri) {
        $api_key = isset($_SESSION['api_key']) ? $_SESSION['api_key'] : null;
        $api_secret = isset($_SESSION['api_secret']) ? $_SESSION['api_secret'] : null;
        $redirect_uri = isset($_SESSION['redirect_uri']) ? $_SESSION['redirect_uri'] : null;
    } else {
        $_SESSION['api_key'] = $api_key;
        $_SESSION['api_secret'] = $api_secret;
        $_SESSION['redirect_uri'] = $redirect_uri;
    }
    if ($api_key && $api_secret) {
        require_once dirname(__FILE__) . "/api/tmhOAuth.php";
        $tmhOAuth = new tmhOAuth(array('consumer_key' => $api_key, 'consumer_secret' => $api_secret));
        if (isset($_REQUEST['oauth_verifier'])) {
            $tmhOAuth->config['user_token'] = $_SESSION['t_oauth']['oauth_token'];
            $tmhOAuth->config['user_secret'] = $_SESSION['t_oauth']['oauth_token_secret'];
            $code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/access_token', ''), array('oauth_verifier' => $_REQUEST['oauth_verifier']));
            if ($code == 200) {
                $access_token = $tmhOAuth->extract_params($tmhOAuth->response['response']);
                unset($_SESSION['api_key']);
                unset($_SESSION['api_secret']);
                unset($_SESSION['redirect_uri']);
                unset($_SESSION['t_oauth']);
                echo '<script type="text/javascript">';
                echo 'window.opener.setToken("' . $access_token['oauth_token'] . '", "' . $access_token['oauth_token_secret'] . '");';
                echo '</script>';
            } else {
                echo '<h3>Error</h3><br />';
                echo $tmhOAuth->response['response'];
                exit;
            }
        } else {
            $code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/request_token', ''), array('oauth_callback' => $redirect_uri));
            if ($code == 200) {
                $oauth = $tmhOAuth->extract_params($tmhOAuth->response['response']);
                $_SESSION['t_oauth'] = $oauth;
                $authurl = $tmhOAuth->url("oauth/authenticate", '') . "?oauth_token=" . $oauth['oauth_token'] . "&force_login=1";
                header('Location: ' . $authurl);
                exit;
            } else {
                echo '<h3>Error</h3><br />';
                echo $tmhOAuth->response['response'];
                exit;
            }
        }
    }
}
Пример #29
0
 public function postTweet($msg)
 {
     $msg = clearData($msg);
     $msg = substr($msg, 0, 140);
     session_start();
     define("USER_TOKEN", $_SESSION['USER_TOKEN']);
     define("USER_SECRET", $_SESSION['USER_SECRET']);
     $tmhOAuth = new tmhOAuth(array('consumer_key' => CONSUMER_KEY, 'consumer_secret' => CONSUMER_SECRET, 'user_token' => USER_TOKEN, 'user_secret' => USER_SECRET, 'debug' => true));
     $tmhOAuth->request('POST', $tmhOAuth->url('1/statuses/update'), array('status' => $msg));
     $code = $tmhOAuth->response['code'];
     $datetime = $tmhOAuth->config['timestamp'];
     if ($code == 200) {
         $FieldValuePairs = array('msg' => $msg, 'datetime' => $datetime, 'user_token' => USER_TOKEN, 'user_secret' => USER_SECRET);
         $this->insert($FieldValuePairs);
         return $_SESSION["account"];
     } else {
         echo "There was an error communicating with Twitter. {$tmhOAuth->response['response']}" . PHP_EOL;
     }
 }
Пример #30
0
 private function getTwitterJSON()
 {
     require_once dirname(__FILE__) . '/lib/tmhOAuth.php';
     require_once dirname(__FILE__) . '/lib/tmhUtilities.php';
     $tmhOAuth = new tmhOAuth(array('host' => $_POST['request']['host'], 'consumer_key' => $this->consumer_key, 'consumer_secret' => $this->consumer_secret, 'user_token' => $this->user_token, 'user_secret' => $this->user_secret, 'curl_ssl_verifypeer' => false));
     $url = $_POST['request']['url'];
     $params = $_POST['request']['parameters'];
     $tmhOAuth->request('GET', $tmhOAuth->url($url), $params);
     return $tmhOAuth->response;
 }