public function sendMessage($toUserID, $strSubject, $strMessage) { $arrNotificationSettings = $this->pdh->get('user', 'notification_settings', array($toUserID)); $twitterAccount = str_replace("@", "", $arrNotificationSettings['ntfy_twitter_user']); if ($twitterAccount == "") { return false; } include_once $this->root_path . 'libraries/twitter/codebird.class.php'; Codebird::setConsumerKey($this->config->get('twitter_consumer_key'), $this->config->get('twitter_consumer_secret')); // static, see 'Using multiple Codebird instances' $cb = Codebird::getInstance(); $cb->setToken($this->config->get('twitter_access_token'), $this->config->get('twitter_access_token_secret')); $strMessage = strip_tags($strMessage); //$strMessage = substr($strMessage, 0, 160); $params = array('screen_name' => $twitterAccount, 'text' => $strMessage); $reply = $cb->directMessages_new($params); return true; }
/** * Initialise Codebird class * * @return \Codebird\Codebird The Codebird class */ protected function getCB() { Codebird::setConsumerKey('123', '456'); $cb = new CodebirdM(); $cb->setToken('234', '567'); return $cb; }
private function get_static_tweets() { require_once APPPATH . 'third_party/codebird.php'; try { Codebird::setConsumerKey($this->settings->info->twitter_consumer_key, $this->settings->info->twitter_consumer_secret); $cb = Codebird::getInstance(); $cb->setToken($this->settings->info->twitter_access_token, $this->settings->info->twitter_access_secret); $tweets = $cb->statuses_userTimeline('screen_name=' . $this->settings->info->twitter_name . '&count=' . $this->settings->info->twitter_display_limit . '&exclude_replies=true&include_rts=1'); } catch (Exception $e) { $this->template->errori("Exception: " . $e); } // Store tweets in database $this->content_model->delete_tweets(); $new_tweets = array(); $t = null; foreach ($tweets as $tweet) { if (is_object($tweet)) { $t = new stdClass(); $t->username = $tweet->user->name; $t->name = $tweet->user->screen_name; $t->tweet = $tweet->text; $t->timestamp = $tweet->created_at; $new_tweets[] = $t; $this->content_model->add_tweet($tweet->user->name, $tweet->user->screen_name, $tweet->text, $tweet->created_at); } } return $new_tweets; }
/** * Tests _getBearerAuthorization * @expectedException \Exception * @expectedExceptionMessage To make an app-only auth API request, consumer key or bearer token must be set. */ public function testGetBearerAuthorization1() { $cb = $this->getCB(); Codebird::setConsumerKey(null, null); $cb->setBearerToken(null); $cb->call('_getBearerAuthorization', []); }
function tweets() { if (!class_exists('Codebird')) { include_once 'codebird.php'; } $cb = new Codebird(); $method = sh_set($_POST, 'method'); $theme_options = get_option(SH_NAME . '_theme_options'); //printr($theme_options); $api = sh_set($theme_options, 'twitter_api'); $api_secret = sh_set($theme_options, 'twitter_api_secret'); $token = sh_set($theme_options, 'twitter_token'); $token_secret = sh_set($theme_options, 'twitter_token_Secret'); if (!$api && $api_secret) { _e('Please provide tiwtter api information to fetch feed', SH_NAME); exit; } $cb->setConsumerKey($api, $api_secret); $cb->setToken($token, $token_secret); $reply = (array) $cb->statuses_userTimeline(array('count' => sh_set($_POST, 'number'), 'screen_name' => sh_set($_POST, 'screen_name'))); if (isset($reply['httpstatus'])) { unset($reply['httpstatus']); } foreach ($reply as $k => $v) { //if( $k == 'httpstatus' ) continue; //$time = human_time_diff( strtotime( sh_set( $v, 'created_at') ), current_time('timestamp') ) . __(' ago', SH_NAME); $text = preg_replace('@(https?://([-\\w\\.]+[-\\w])+(:\\d+)?(/([\\w/_\\.#-]*(\\?\\S+)?[^\\.\\s])?)?)@', '<a href="$1" target="_blank">$1</a>', sh_set($v, 'text')); echo '<li>' . $text . '</li>'; } }
function tweets() { if (!class_exists('Codebird')) { include_once 'codebird.php'; } $cb = new Codebird(); $method = sh_set($_GET, 'method'); $theme_options = _WSH()->option(); //printr($theme_options); $api = sh_set($theme_options, 'twitter_api'); $api_secret = sh_set($theme_options, 'twitter_api_secret'); $token = sh_set($theme_options, 'twitter_token'); $token_secret = sh_set($theme_options, 'twitter_token_secret'); if (!$api && $api_secret) { _e('Please provide tiwtter api information to fetch feed', SH_NAME); exit; } $cb->setConsumerKey($api, $api_secret); $cb->setToken($token, $token_secret); $resp = array(); $reply = (array) $cb->statuses_userTimeline(array('count' => sh_set($_GET, 'number'), 'screen_name' => sh_set($_GET, 'screen_name'))); if (isset($reply['httpstatus'])) { unset($reply['httpstatus']); } foreach ($reply as $k => $v) { //if( $k == 'httpstatus' ) continue; $time = human_time_diff(strtotime(sh_set($v, 'created_at')), current_time('timestamp')) . __(' ago', SH_NAME); $text = preg_replace('@(https?://([-\\w\\.]+[-\\w])+(:\\d+)?(/([\\w/_\\.#-]*(\\?\\S+)?[^\\.\\s])?)?)@', '<a href="$1" target="_blank">$1</a>', sh_set($v, 'text')); if (sh_set($_POST, 'template') === 'lead') { echo '<i class="fa fa-twitter"></i>' . $text . ' <a href="#"> ' . $time . '</a>'; } else { $res[$k]['date'] = $time; //array('date'=>$time, 'tweet'=>$text); $res[$k]['tweet'] = $text; //echo //'<li><span></span><p>'.$text.' <a href="#">'.__(' about ', SH_NAME).$time.'</a></p></li>'; } } //printr($res); echo json_encode($res); }
protected function really_simple_twitter_messages($options) { // CHECK OPTIONS if ($options['username'] == '') { return __('Twitter username is not configured', 'vibe'); } if (!is_numeric($options['num']) or $options['num'] <= 0) { return __('Number of tweets is not valid', 'vibe'); } if ($options['consumer_key'] == '' or $options['consumer_secret'] == '' or $options['access_token'] == '' or $options['access_token_secret'] == '') { return __('Twitter Authentication data is incomplete', 'vibe'); } if (!class_exists('Codebird')) { require 'twitter_class.php'; } Codebird::setConsumerKey($options['consumer_key'], $options['consumer_secret']); $this->cb = Codebird::getInstance(); $this->cb->setToken($options['access_token'], $options['access_token_secret']); // From Codebird documentation: For API methods returning multiple data (like statuses/home_timeline), you should cast the reply to array $this->cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY); // SET THE NUMBER OF ITEMS TO RETRIEVE - IF "SKIP TEXT" IS ACTIVE, GET MORE ITEMS $max_items_to_retrieve = $options['num']; if (isset($options['skip_text']) && $options['skip_text'] != '' || isset($options['skip_replies']) && $options['skip_replies'] || isset($options['skip_retweets'])) { $max_items_to_retrieve *= 3; } // TWITTER API GIVES MAX 200 TWEETS PER REQUEST if ($max_items_to_retrieve > 200) { $max_items_to_retrieve = 200; } if (isset($options['skip_text'])) { $transient_name = 'twitter_data_' . $options['username'] . $options['skip_text'] . '_' . $options['num']; } else { $transient_name = 'twitter_data_' . $options['username'] . '_' . $options['num']; } if (isset($options['erase_cached_data']) && $options['erase_cached_data']) { $this->debug($options, '<!-- ' . __('Fetching data from Twitter') . '... -->'); $this->debug($options, '<!-- ' . __('Erase cached data option enabled') . '... -->'); delete_transient($transient_name); delete_transient($transient_name . '_status'); delete_option($transient_name . '_valid'); try { $twitter_data = $this->cb->statuses_userTimeline(array('screen_name' => $options['username'], 'count' => $max_items_to_retrieve, 'exclude_replies' => $options['skip_replies'], 'include_rts' => !$options['skip_retweets'])); } catch (Exception $e) { return __('Error retrieving tweets', 'vibe'); } if (isset($twitter_data['errors'])) { $this->debug($options, __('Twitter data error:', 'vibe') . ' ' . $twitter_data['errors'][0]['message'] . '<br />'); } } else { // USE TRANSIENT DATA, TO MINIMIZE REQUESTS TO THE TWITTER FEED $timeout = 10 * 60; //10m $error_timeout = 5 * 60; //5m $twitter_data = get_transient($transient_name); $twitter_status = get_transient($transient_name . '_status'); // Twitter Status if (!$twitter_status || !$twitter_data) { try { $twitter_status = $this->cb->application_rateLimitStatus(); set_transient($transient_name . "_status", $twitter_status, $error_timeout); } catch (Exception $e) { $this->debug($options, __('Error retrieving twitter rate limit', 'vibe') . '<br />'); } } // Tweets if (empty($twitter_data) or count($twitter_data) < 1 or isset($twitter_data['errors'])) { $calls_limit = (int) $twitter_status['resources']['statuses']['/statuses/user_timeline']['limit']; $remaining = (int) $twitter_status['resources']['statuses']['/statuses/user_timeline']['remaining']; $reset_seconds = (int) $twitter_status['resources']['statuses']['/statuses/user_timeline']['reset'] - time(); $this->debug($options, '<!-- ' . __('Fetching data from Twitter') . '... -->'); $this->debug($options, '<!-- ' . __('Requested items') . ' : ' . $max_items_to_retrieve . ' -->'); $this->debug($options, '<!-- ' . __('API calls left') . ' : ' . $remaining . ' of ' . $calls_limit . ' -->'); $this->debug($options, '<!-- ' . __('Seconds until reset') . ' : ' . $reset_seconds . ' -->'); if ($remaining <= 7 and $reset_seconds > 0) { $timeout = $reset_seconds; $error_timeout = $reset_seconds; } try { $twitter_data = $this->cb->statuses_userTimeline(array('screen_name' => $options['username'], 'count' => $max_items_to_retrieve, 'exclude_replies' => 1, 'include_rts' => 0)); } catch (Exception $e) { return __('Error retrieving tweets', 'vibe'); } if (!isset($twitter_data['errors']) and count($twitter_data) >= 1) { set_transient($transient_name, $twitter_data, $timeout); update_option($transient_name . "_valid", $twitter_data); } else { set_transient($transient_name, $twitter_data, $error_timeout); // Wait 5 minutes before retry if (isset($twitter_data['errors'])) { $this->debug($options, __('Twitter data error:', 'vibe') . ' ' . $twitter_data['errors'][0]['message'] . '<br />'); } } } else { $this->debug($options, '<!-- ' . __('Using cached Twitter data') . '... -->'); if (isset($twitter_data['errors'])) { $this->debug($options, __('Twitter cache error:', 'vibe') . ' ' . $twitter_data['errors'][0]['message'] . '<br />'); } } if (empty($twitter_data) and false === ($twitter_data = get_option($transient_name . "_valid"))) { return __('No public tweets', 'vibe'); } if (isset($twitter_data['errors'])) { // STORE ERROR FOR DISPLAY $twitter_error = $twitter_data['errors']; if (false === ($twitter_data = get_option($transient_name . "_valid"))) { $debug = $options['debug'] ? '<br /><i>Debug info:</i> [' . $twitter_error[0]['code'] . '] ' . $twitter_error[0]['message'] . ' - username: "******"' : ''; return __('Unable to get tweets', 'vibe') . $debug; } } } if (empty($twitter_data) or count($twitter_data) < 1) { return __('No public tweets', 'vibe'); } $link_target = $options['link_target_blank'] ? ' target="_blank" ' : ''; $image = '<div class="author"><i class="icon-twitter"></i>'; if ($options['style'] == 'horizontal') { $out = '<div class="tweets"><div class="tweet_icon">' . $image . '</div><div class="twitter_carousel flexslider light loading"> <ul class="slides">'; } else { $out = '<div class="twitter_carousel flexslider light loading"> <ul class="slides">'; } $i = 0; foreach ($twitter_data as $message) { // CHECK THE NUMBER OF ITEMS SHOWN if ($i >= $options['num']) { break; } $msg = $message['text']; if ($msg == '') { continue; } if (isset($options['skip_text']) && $options['skip_text'] != '' && strpos($msg, $options['skip_text']) !== false) { continue; } if (isset($options['encode_utf8']) && $options['encode_utf8']) { $msg = utf8_encode($msg); } if ($options['style'] == 'horizontal') { $out .= '<li><div class="tweet"><p>'; } else { $out .= '<li><div class="twitter_item clearfix"><p>'; } // TODO: LINK if (isset($options['thumbnail']) && $options['thumbnail'] && $message['user']['profile_image_url_https'] != '') { $out .= '<img src="' . $message['user']['profile_image_url_https'] . '" />'; } if (isset($options['hyperlinks']) && $options['hyperlinks']) { if (isset($options['replace_link_text']) && $options['replace_link_text'] != '') { // match protocol://address/path/file.extension?some=variable&another=asf% $msg = preg_replace('/\\b([a-zA-Z]+:\\/\\/[\\w_.\\-]+\\.[a-zA-Z]{2,6}[\\/\\w\\-~.?=&%#+$*!]*)\\b/i', "<a href=\"\$1\" class=\"twitter-link\" " . $link_target . " title=\"\$1\">" . $options['replace_link_text'] . "</a>", $msg); // match www.something.domain/path/file.extension?some=variable&another=asf% $msg = preg_replace('/\\b(?<!:\\/\\/)(www\\.[\\w_.\\-]+\\.[a-zA-Z]{2,6}[\\/\\w\\-~.?=&%#+$*!]*)\\b/i', "<a href=\"http://\$1\" class=\"twitter-link\" " . $link_target . " title=\"\$1\">" . $options['replace_link_text'] . "</a>", $msg); } else { // match protocol://address/path/file.extension?some=variable&another=asf% $msg = preg_replace('/\\b([a-zA-Z]+:\\/\\/[\\w_.\\-]+\\.[a-zA-Z]{2,6}[\\/\\w\\-~.?=&%#+$*!]*)\\b/i', "<a href=\"\$1\" class=\"twitter-link\" " . $link_target . ">\$1</a>", $msg); // match www.something.domain/path/file.extension?some=variable&another=asf% $msg = preg_replace('/\\b(?<!:\\/\\/)(www\\.[\\w_.\\-]+\\.[a-zA-Z]{2,6}[\\/\\w\\-~.?=&%#+$*!]*)\\b/i', "<a href=\"http://\$1\" class=\"twitter-link\" " . $link_target . ">\$1</a>", $msg); } // match name@address $msg = preg_replace('/\\b([a-zA-Z][a-zA-Z0-9\\_\\.\\-]*[a-zA-Z]*\\@[a-zA-Z][a-zA-Z0-9\\_\\.\\-]*[a-zA-Z]{2,6})\\b/i', "<a href=\"mailto://\$1\" class=\"twitter-link\" " . $link_target . ">\$1</a>", $msg); //NEW mach #trendingtopics //$msg = preg_replace('/#([\w\pL-.,:>]+)/iu', '<a href="http://twitter.com/#!/search/\1" class="twitter-link">#\1</a>', $msg); //NEWER mach #trendingtopics $msg = preg_replace('/(^|\\s)#(\\w*[a-zA-Z_]+\\w*)/', '\\1<a href="http://twitter.com/#!/search/%23\\2" class="twitter-link" ' . $link_target . '>#\\2</a>', $msg); } if ($options['twitter_users']) { $msg = preg_replace('/([\\.|\\,|\\:|\\¡|\\¿|\\>|\\{|\\(]?)@{1}(\\w*)([\\.|\\,|\\:|\\!|\\?|\\>|\\}|\\)]?)\\s/i', "\$1<a href=\"http://twitter.com/\$2\" class=\"twitter-user\" " . $link_target . ">@\$2</a>\$3 ", $msg); } $link = 'http://twitter.com/#!/' . $options['username'] . '/status/' . $message['id_str']; if (isset($options['linked']) && $options['linked'] == 'all') { $msg = '<a href="' . $link . '" class="twitter-link" ' . $link_target . '>' . $msg . '</a>'; // Puts a link to the status of each tweet } else { if (isset($options['linked']) && $options['linked'] != '') { $msg = $msg . ' <a href="' . $link . '" class="twitter-link" ' . $link_target . '>' . $options['linked'] . '</a>'; // Puts a link to the status of each tweet } } $out .= $msg; if ($options['update']) { $time = strtotime($message['created_at']); $h_time = abs(time() - $time) < 86400 ? sprintf(__('%s ago', 'vibe'), human_time_diff($time)) : date(__('M d', 'vibe'), $time); $out .= '<span>,</span> <span class="twitter-timestamp" title="' . date(__('Y/m/d H:i', 'vibe'), $time) . '">' . $h_time . '</span>'; } $out .= '</p>'; if ($options['style'] != 'horizontal') { $out .= $image; } $out .= '</div></li>'; $i++; } $out .= '</ul></div>'; if ($options['style'] == 'horizontal') { $out .= '</div>'; } return $out; }
private function cb_object() { if (!class_exists('Codebird') || !isset($this->consumer_key) || !isset($this->consumer_secret)) { return false; } Codebird::setConsumerKey($this->consumer_key, $this->consumer_secret); return Codebird::getInstance(); }
protected function initializeAPIs() { $this->amazonAPI = new AmazonProductAPI(); $this->bestBuyRemix = new BestBuy_Service_Remix(myInfo::MY_BESTBUY_PUBLIC_KEY); //New API which may become more useful $this->facebook = new facebookLib(array('appId' => myInfo::MY_FACEBOOK_PUBLIC_KEY, 'secret' => myInfo::MY_FACEBOOK_PRIVATE_KEY, 'cookie' => true)); facebookLib::$CURL_OPTS[CURLOPT_CAINFO] = './ca-bundle.crt'; facebookLib::$CURL_OPTS[CURLOPT_FRESH_CONNECT] = 1; facebookLib::$CURL_OPTS[CURLOPT_PORT] = 443; $this->facebookAccessToken = $this->facebook->getAccessToken(); $this->flickrAPI = new phpFlickr(myInfo::MY_FLICKR_PUBLIC_KEY, myInfo::MY_FLICKR_PRIVATE_KEY); $this->flickrAPI->enableCache("fs", "./" . myInfo::CACHING_DIRECTORY . "/Flickr"); // This class came with it's own caching system, now I'm using at least three. Last.fm PHP API has one too but it requires a database. // Twitter's API now requires Oauth, GData wants you to use this too, but currently it is still possible to search Google (YouTube) without Oauth Codebird::setConsumerKey(myInfo::MY_TWITTER_PUBLIC_KEY, myInfo::MY_TWITTER_PRIVATE_KEY); $this->codeBird = Codebird::getInstance(); $this->codeBird->setToken(myInfo::MY_TWITTER_ACCESS_TOKEN, myInfo::MY_TWITTER_ACCESS_TOKEN_SECRET); }
public function ajax_twitterfeed() { $data = $this->pdc->get('core.twitterfeed_data'); if ($data != null) { //there is cached data $rsstwitter_out = $this->xmltools->prepareLoad($data); } else { //expired or not available, update from Server include_once $this->root_path . 'libraries/twitter/codebird.class.php'; Codebird::setConsumerKey(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET); // static, see 'Using multiple Codebird instances' $cb = Codebird::getInstance(); $cb->setToken(TWITTER_OAUTH_TOKEN, TWITTER_OAUTH_SECRET); $params = array('screen_name' => EQDKP_TWITTER_SCREENNAME); $objJSON = $cb->statuses_userTimeline($params); if ($objJSON) { require_once $this->root_path . 'core/feed.class.php'; $feed = registry::register('feed'); $feed->title = "EQdkp Plus Twitter"; $feed->description = "EQdkp Plus Twitter"; $feed->published = time(); $feed->language = 'EN-EN'; if ($objJSON) { foreach ($objJSON as $key => $objEntry) { if ($objEntry->in_reply_to_user_id_str != "") { continue; } if (strpos($objEntry->text, '@') === 0) { continue; } //print_r($objEntry->text); $truncated = $objEntry->text; if (strlen($objEntry->text) > 40) { $truncated = substr($objEntry->text, 0, strpos($objEntry->text, ' ', 40)); if ($truncated != '') { $truncated = $truncated . '...'; } } $rssitem = registry::register('feeditems', array($key)); $rssitem->title = $truncated; $rssitem->description = $objEntry->text; $rssitem->published = $objEntry->created_at; $rssitem->author = 'EQdkp Plus'; $rssitem->link = "https://twitter.com/EQdkpPlus/status/" . $objEntry->id_str; $feed->addItem($rssitem); } } $rsstwitter_out = $feed->show(); $this->pdc->put('core.twitterfeed_data', $this->xmltools->prepareSave($rsstwitter_out), $this->rsscachetime * 3600); } else { $expiredData = $this->pdc->get('core.twitterfeed_data', false, false, true); $this->pdc->put('core.twitterfeed_data', $expiredData != null ? $expiredData : "", 6 * 3600); $rsstwitter_out = $expiredData != null ? $this->xmltools->prepareLoad($expiredData) : ""; } } header('content-type: text/html; charset=UTF-8'); print $rsstwitter_out; exit; }
/** * Initialise Codebird class * * @return \Codebird\Codebird The Codebird class */ protected function getCB() { Codebird::setConsumerKey('123', '456'); $cb = new CodebirdM(); return $cb; }
$instance['showProfilePicTF'] = true; break; case "none": break; } if ($new_instance['showTweetTimeTF'] == "1") { $instance['showTweetTimeTF'] = true; } else { $instance['showTweetTimeTF'] = false; } if ($new_instance['includeRepliesTF'] == "1") { $instance['includeRepliesTF'] = true; } else { $instance['includeRepliesTF'] = false; } return $instance; } function widget($args, $instance) { extract($args, EXTR_SKIP); $query_arg['count'] = $instance['count'] ? $instance['count'] : 3; $query_arg['exclude_replies'] = !$instance['includeRepliesTF']; $query_arg['include_rts'] = false; $query_arg['screen_name'] = $instance['user']; $title = $instance['widgetTitle']; if (!class_exists('Codebird')) { require_once get_template_directory() . '/widgets/latest_twitter/codebird.php'; } Codebird::setConsumerKey('Cz2crWMRSc62Nlp1yagt9w', 'UOwKXRriyG2l4oL8NKuqsEwr0pXEkPNEkhrxrftI4lE'); $codebird_instance = Codebird::getInstance(); $codebird_instance->setToken('764237641-JLC4OqK2WNkpWlNgc3pHWN68bmjl0s9669nldZ5I', '8Lo97YIwwLJn78FlFwZ80lw2iOHEyZ8wwcJ9xCTVv8'); $codebird_instance->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY); try { $latest_tweet = $codebird_instance->statuses_userTimeline($query_arg); } catch (Exception $e) { echo 'Error retrieving tweets';
public function run() { register('pm'); $arrFeeds = $this->pdh->get('feedposter_feeds', 'id_list', array()); foreach ($arrFeeds as $intFeedID) { $arrData = $this->pdh->get('feedposter_feeds', 'data', array($intFeedID)); if (!$arrData['enabled']) { continue; } //Check Interval Time if ($arrData['lastUpdated'] + $arrData['interval'] > $this->time->time) { continue; } //Twitter $arrTwitterOut = array(); if (preg_match("/http(s?):\\/\\/twitter.com\\/(.*)/i", $arrData['url'], $arrTwitterOut)) { $strScreename = $arrTwitterOut[2]; if ($strScreename == "" || !$strScreename) { continue; } include_once $this->root_path . 'libraries/twitter/codebird.class.php'; Codebird::setConsumerKey(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET); // static, see 'Using multiple Codebird instances' $cb = Codebird::getInstance(); $cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY); $cb->setToken(TWITTER_OAUTH_TOKEN, TWITTER_OAUTH_SECRET); $params = array('screen_name' => $strScreename); $objJSON = $cb->statuses_userTimeline($params); if (is_array($objJSON)) { $i = 0; foreach ($objJSON as $itemData) { //No Replies or Retweets if (strlen($itemData['in_reply_to_user_id'])) { continue; } if (isset($itemData['retweeted_status'])) { continue; } $hash = sha1($itemData['id_str']); $time = strtotime($itemData['created_at']); $arrTags = array(); if (isset($itemData['entities']['hashtags'])) { foreach ($itemData['entities']['hashtags'] as $val) { $arrTags[] = $val['text']; } } // get data $data[$hash] = array('title' => $arrData['name'] . ': ' . cut_text($itemData['text'], 40, true), 'link' => 'https://twitter.com/' . $strScreename . '/status/' . $itemData['id_str'], 'description' => $this->twitterify($itemData['text']), 'time' => $time, 'hash' => $hash, 'tags' => $arrTags); // check max results $i++; if ($arrData['maxPosts'] && $i == $arrData['maxPosts']) { break; } } if (empty($data)) { continue; } //Build Hash-Array of Feed $arrHashList = $this->pdh->get('feedposter_log', 'hash_list', array($intFeedID)); $intLastUpdate = $arrData['lastUpdated']; foreach ($data as $key => $val) { if ($val['time'] > $intLastUpdate && !in_array($val['hash'], $arrHashList)) { $strTitle = $val['title']; $strText = $val['description']; $strText = nl2br($strText); if ($arrData['maxTextLength']) { if (strlen($strText) > $arrData['maxTextLength']) { $strText = cut_text($strText, $arrData['maxTextLength'], true); } } $strFeedType = 'twitter'; $strText = '<div class="feedposter feedid_' . $intFeedID . ' feedtype_' . $strFeedType . '"><blockquote>' . strip_tags($strText, '<img><a>') . '</blockquote>' . $this->user->lang('fp_source') . ': <a href="' . sanitize(strip_tags($val['link'])) . '">' . sanitize(strip_tags($val['link'])) . '</a></div>'; $strPreviewimage = ""; $strAlias = $strTitle; $intPublished = 1; $intFeatured = 0; $intCategory = $arrData['categoryID']; $intUserID = $arrData['userID']; $intComments = $arrData['allowComments']; $intVotes = 0; $intHideHeader = 0; $arrFeedTags = unserialize($arrData['tags']); if (!is_array($arrFeedTags)) { $arrFeedTags = array(); } $arrFeedTags = $arrFeedTags[0] != "" ? array_merge($arrFeedTags, $val['tags']) : $val['tags']; $arrTags = $arrFeedTags; $intDate = $val['time']; $strShowFrom = $strShowTo = ""; $blnResult = $this->pdh->put('articles', 'add', array($strTitle, $strText, $arrTags, $strPreviewimage, $strAlias, $intPublished, $intFeatured, $intCategory, $intUserID, $intComments, $intVotes, $intDate, $strShowFrom, $strShowTo, $intHideHeader)); //Write Log $this->pdh->put('feedposter_log', 'add', array($intFeedID, $val['hash'], $this->time->time)); //Prevent double input $arrHashList[] = $val['hash']; } } //Set Last Updated $this->pdh->put('feedposter_feeds', 'set_last_update', array($intFeedID, $this->time->time)); $this->pdh->process_hook_queue(); } else { //Update Error $this->pdh->put('feedposter_feeds', 'set_error', array($intFeedID, 'Invalid Json')); $this->pdh->process_hook_queue(); } } else { //Normal RSS/ATOM Feed $strContent = register('urlfetcher')->fetch($arrData['url']); if ($strContent) { try { $document = new \DOMDocument('1.0', 'UTF-8'); $document->preserveWhiteSpace = false; $document->loadXML($strContent); $xpath = new \DOMXPath($document); if ($document->documentElement !== null && $document->documentElement !== false && is_object($document->documentElement)) { $namespace = $document->documentElement->getAttribute('xmlns'); $xpath->registerNamespace('ns', $namespace); } else { //Update Error $this->pdh->put('feedposter_feeds', 'set_error', array($intFeedID)); $this->pdh->process_hook_queue(); continue; } $rootNode = $xpath->query('/*')->item(0); if ($rootNode === null) { //Update Error $this->pdh->put('feedposter_feeds', 'set_error', array($intFeedID)); $this->pdh->process_hook_queue(); continue; } if ($rootNode->nodeName == 'feed') { $data = $this->readAtomFeed($xpath, $arrData); $strFeedType = 'rss'; } else { if ($rootNode->nodeName == 'rss') { $data = $this->readRssFeed($xpath, $arrData); $strFeedType = 'rss'; } else { if ($rootNode->nodeName == 'response') { $data = $this->readEQdkpFeed($xpath, $arrData); $strFeedType = 'eqdkp'; } else { //Update Error $this->pdh->put('feedposter_feeds', 'set_error', array($intFeedID)); $this->pdh->process_hook_queue(); continue; } } } if (empty($data)) { continue; } //Build Hash-Array of Feed $arrHashList = $this->pdh->get('feedposter_log', 'hash_list', array($intFeedID)); $intLastUpdate = $arrData['lastUpdated']; foreach ($data as $key => $val) { if ($val['time'] > $intLastUpdate && !in_array($val['hash'], $arrHashList)) { $strTitle = $val['title']; $strText = $val['description']; $strText = nl2br($strText); if ($arrData['maxTextLength']) { if (strlen($strText) > $arrData['maxTextLength']) { $strText = cut_text($strText, $arrData['maxTextLength'], true); } } if ($strFeedType == 'eqdkp') { $strText = '<div class="feedposter feedid_' . $intFeedID . ' feedtype_' . $strFeedType . ' feedsource_category_' . $val['category_id'] . '">' . $strText . '</div>'; } else { $strText = preg_replace("'<style[^>]*>.*</style>'siU", '', $strText); $strText = '<div class="feedposter feedid_' . $intFeedID . ' feedtype_' . $strFeedType . '"><blockquote>' . strip_tags($strText, '<img>') . '</blockquote>' . $this->user->lang('fp_source') . ': <a href="' . sanitize(strip_tags($val['link'])) . '">' . sanitize(strip_tags($val['link'])) . '</a></div>'; } $strPreviewimage = ""; $strAlias = $strTitle; $intPublished = 1; $intFeatured = $arrData['featured']; $intCategory = $arrData['categoryID']; $intUserID = $arrData['userID']; $intComments = $arrData['allowComments']; $intVotes = 0; $intHideHeader = 0; $arrTags = unserialize($arrData['tags']); $intDate = $val['time']; $strShowFrom = $strShowTo = ""; if ($arrData['showForDays'] > 0) { $strShowTo = $intDate + $arrData['showForDays'] * 86400; } $blnResult = $this->pdh->put('articles', 'add', array($strTitle, $strText, $arrTags, $strPreviewimage, $strAlias, $intPublished, $intFeatured, $intCategory, $intUserID, $intComments, $intVotes, $intDate, $strShowFrom, $strShowTo, $intHideHeader)); //Write Log $this->pdh->put('feedposter_log', 'add', array($intFeedID, $val['hash'], $this->time->time)); //Prevent double input $arrHashList[] = $val['hash']; } } //Set Last Updated $this->pdh->put('feedposter_feeds', 'set_last_update', array($intFeedID, $this->time->time)); } catch (Exception $e) { //Update Error $this->pdh->put('feedposter_feeds', 'set_error', array($intFeedID, 'Parsing error')); $this->pdh->process_hook_queue(); } $this->pdh->process_hook_queue(); } else { //Update Error $this->pdh->put('feedposter_feeds', 'set_error', array($intFeedID, 'Fetching error')); $this->pdh->process_hook_queue(); } } } }
public function updateRSS() { include_once $this->root_path . 'libraries/twitter/codebird.class.php'; Codebird::setConsumerKey(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET); // static, see 'Using multiple Codebird instances' $cb = Codebird::getInstance(); $cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY); $cb->setToken(TWITTER_OAUTH_TOKEN, TWITTER_OAUTH_SECRET); $params = array('screen_name' => $this->twitter_screenname); $objJSON = $cb->statuses_userTimeline($params); $rss_string = serialize($objJSON); if (strlen($rss_string) > 1) { $this->pdc->del('portal.module.twitter.id' . $this->module_id); $sql = "DELETE FROM __module_twitter WHERE id=?"; $this->db->prepare($sql)->execute($this->module_id); $this->db->prepare("INSERT INTO __module_twitter :p")->set(array('updated' => time(), 'rss' => $rss_string, 'id' => $this->module_id))->execute(); $this->pdc->put('portal.module.twitter.id' . $this->module_id, $rss_string, $this->cachetime - 5, false, true); } }
function bsh_twitter_api() { global $cb; $consumer_key = get_theme_mod('twitter_consumer_key'); $consumer_key = empty($consumer_key) ? BSH_TWITTER_CONSUMER_KEY : $consumer_key; $consumer_secret = get_theme_mod('twitter_consumer_secret'); $consumer_secret = empty($consumer_secret) ? BSH_TWITTER_CONSUMER_SECRET : $consumer_secret; $access_token = get_theme_mod('twitter_access_token'); $access_token = empty($access_token) ? BSH_TWITTER_ACCESS_TOKEN : $access_token; $access_secret = get_theme_mod('twitter_access_secret'); $access_secret = empty($access_secret) ? BSH_TWITTER_ACCESS_SECRET : $access_secret; require_once 'framework/external/Codebird/Codebird.class.php'; Codebird::setConsumerKey($consumer_key, $consumer_secret); $cb = Codebird::getInstance(); $cb->setToken($access_token, $access_secret); }
function multi_twitter($widget) { if (!class_exists('Codebird')) { require 'lib/codebird.php'; } // Initialize Codebird with our keys. We'll wait and // pass the token when we make an actual request Codebird::setConsumerKey($widget['consumer_key'], $widget['consumer_secret']); $cb = Codebird::getInstance(); $output = ''; // Get our root upload directory and create cache if necessary $upload = wp_upload_dir(); $upload_dir = $upload['basedir'] . "/cache"; if (!file_exists($upload_dir)) { if (!mkdir($upload_dir)) { $output .= '<span style="color: red;">' . sprintf(__('Could not create dir "%s"; please create this directory.', 'multi-twitter-widget'), $upload_dir) . '</span>'; return $output; } } // split the accounts and search terms specified in the widget $accounts = explode(" ", $widget['users']); $terms = explode(", ", $widget['terms']); $output .= '<ul class="multi-twitter">'; // Parse the accounts and CRUD cache $feeds = null; foreach ($accounts as $account) { if ($account != "") { $cache = false; // Assume the cache is empty $cFile = "{$upload_dir}/users_{$account}.txt"; if (file_exists($cFile)) { $modtime = filemtime($cFile); $timeago = time() - 1800; // 30 minutes ago // Check if length is less than new limit $str = file_get_contents($cFile); $content = unserialize($str); $length = count($content); if ($modtime < $timeago or $length != $widget['user_limit']) { // Set to false just in case as the cache needs to be renewed $cache = false; } else { // The cache is not too old so the cache can be used. $cache = true; } } // begin if ($cache === false) { $cb->setToken($widget['access_token'], $widget['access_token_secret']); $params = array('screen_name' => $account, 'count' => $widget['user_limit']); // let Codebird make an authenticated request Result is json $reply = $cb->statuses_userTimeline($params); // turn the json into an array $json = json_decode($reply, true); $length = count($json); for ($i = 0; $i < $length; $i++) { // add it to the feeds array $feeds[] = $json[$i]; // prepare it for caching $content[] = $json[$i]; } // Let's save our data into uploads/cache/ $fp = fopen($cFile, 'w'); if (!$fp) { $output .= '<li style="color: red;">' . sprintf(__('Permission to write cache dir to <em>%s</em> not granted.', 'multi-twitter-widget'), $cFile) . '</li>'; } else { $str = serialize($content); fwrite($fp, $str); } fclose($fp); $content = null; } else { //cache is true let's load the data from the cached file $str = file_get_contents($cFile); $content = unserialize($str); $length = count($content); // echo $length; for ($i = 0; $i < $length; $i++) { // add it to the feeds array $feeds[] = $content[$i]; } } } // end account empty check } // end accounts foreach // Parse the terms and CRUD cache foreach ($terms as $term) { if ($term != "") { $cache = false; // Assume the cache is empty $cFile = "{$upload_dir}/term_{$term}.txt"; if (file_exists($cFile)) { $modtime = filemtime($cFile); $timeago = time() - 1800; // 30 minutes ago // Check if length is less than new limit $str = file_get_contents($cFile); $content = unserialize($str); $length = count($content); if ($modtime < $timeago or $length != $widget['term_limit']) { // Set to false just in case as the cache needs to be renewed $cache = false; } else { // The cache is not too old so the cache can be used. $cache = true; } } if ($cache === false) { $cb->setToken($widget['access_token'], $widget['access_token_secret']); $search_params = array('q' => $term, 'count' => $widget['term_limit']); $reply = $cb->search_tweets($search_params); $json = json_decode($reply, true); $length = count($json['statuses']); for ($i = 0; $i < $length; $i++) { // add it to the feeds array $feeds[] = $json['statuses'][$i]; // prepare it for caching $content[] = $json['statuses'][$i]; } if ($content === false) { // Content couldn't be retrieved... Do something.. $output .= '<li>' . __('Content could not be retrieved; Twitter API failed.', 'multi-twitter-widget') . '</li>'; } else { // Let's save our data into uploads/cache/ $fp = fopen($cFile, 'w'); if (!$fp) { $output .= '<li style="color: red;">' . sprintf(__('Permission to write cache dir to <em>%s</em> not granted.', 'multi-twitter-widget'), $cFile) . '</li>'; } else { fwrite($fp, serialize($content)); } fclose($fp); $content = null; } } else { //cache is true let's load the data from the cached file $str = file_get_contents($cFile); $content = unserialize($str); $length = count($content); for ($i = 0; $i < $length; $i++) { // add it to the feeds array $feeds[] = $content[$i]; } } } // end terms empty check } // end terms foreach // Sort our $feeds array if ($widget['sort_by_date']) { usort($feeds, "feed_sort"); } // Split array and output results $i = 1; // format the tweet for display foreach ($feeds as $feed) { if (!empty($feed)) { $output .= '<li class="tweet clearfix" style="margin-bottom:8px;">' . '<a href="http://twitter.com/' . $feed['user']['screen_name'] . '">' . '<img class="twitter-avatar" src="' . $feed['user']['profile_image_url'] . '" width="40" height="40" alt="' . $feed['user']['screen_name'] . '" />' . '</a>'; $output .= '<span class="tweet-userName">' . $feed['user']['name'] . '</span>'; if ($widget['date']) { $output .= '<span class="tweet-time">' . human_time(strtotime($feed['created_at'])) . '</span>'; } $output .= '<span class="tweet-message">' . format_tweet($feed['text'], $widget) . '</span>'; $output .= '</li>'; } } $output .= '</ul>'; if ($widget['credits'] === true) { $output .= '<hr /><strong>' . __('Development by', 'multi-twitter-widget') . '</strong> ' . '<a href="http://twitter.com/thinkclay" target="_blank">Clay McIlrath</a>, ' . '<a href="http://twitter.com/roger_hamilton" target="_blank">Roger Hamilton</a>, ' . '<a href="http://twitter.com/wrought/" target="_blank">Matt Senate</a>, and ' . '<a href="http://twitter.com/cviebrock/" target="_blank">Colin Viebrock</a>.'; } if ($widget['styles'] === true) { $output .= '<style type="text/css">' . '.twitter-avatar { clear: both; float: left; padding: 6px 12px 2px 0; }' . '.twitter{background:none;}' . '.tweet{min-height:48px;margin:0!important;}' . '.tweet a{text-decoration:underline;}' . '.tweet-userName{padding-top:7px;font-size:12px;line-height:0;color:#454545;font-family:Arial,sans-serif;font-weight:700;margin-bottom:10px;margin-left:8px;float:left;min-width:50px;}' . '.twitter-avatar{width:48px;height:48px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;padding:0!important;}' . '.tweet-time{color:#8A8A8A;float:left;margin-top:-3px;font-size:11px!important;}' . '.tweet-message{font-size:11px;line-height:14px;color:#333;font-family:Arial,sans-serif;word-wrap:break-word;margin-top:-30px!important;width:200px;margin-left:58px;}' . '</style>'; } echo $output; }
function widget($args, $instance) { extract($args, EXTR_SKIP); $query_arg['count'] = $instance['count'] ? $instance['count'] : 3; $query_arg['exclude_replies'] = !$instance['includeRepliesTF']; $query_arg['include_rts'] = false; $query_arg['screen_name'] = $instance['user']; $title = $instance['widgetTitle']; if (!class_exists('Codebird')) { require_once get_template_directory() . '/widgets/latest_twitter/codebird.php'; } if (strlen($instance['api']) < 5) { $instance['api'] = "Cz2crWMRSc62Nlp1yagt9w"; } if (strlen($instance['apisecret']) < 10) { $instance['apisecret'] = "UOwKXRriyG2l4oL8NKuqsEwr0pXEkPNEkhrxrftI4lE"; } if (strlen($instance['token']) < 10) { $instance['token'] = "764237641-JLC4OqK2WNkpWlNgc3pHWN68bmjl0s9669nldZ5I"; } if (strlen($instance['tokensecret']) < 10) { $instance['tokensecret'] = "8Lo97YIwwLJn78FlFwZ80lw2iOHEyZ8wwcJ9xCTVv8"; } Codebird::setConsumerKey($instance["api"], $instance["apisecret"]); $codebird_instance = Codebird::getInstance(); $codebird_instance->setToken($instance["token"], $instance["tokensecret"]); $codebird_instance->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY); try { $latest_tweet = $codebird_instance->statuses_userTimeline($query_arg); } catch (Exception $e) { echo 'Error retrieving tweets'; } echo $before_widget; echo $before_title . $title . $after_title; if (isset($latest_tweet['errors'][0])) { //error handling here plz echo "Error code " . $latest_tweet['errors'][0]['code'] . ": " . $latest_tweet['errors'][0]['message']; } else { foreach ($latest_tweet as $single_tweet) { $tweet_text = $single_tweet['text']; $tweet_text = preg_replace("/[^^](http:\\/\\/+[\\S]*)/", '<a href="$0">$0</a>', $tweet_text); $screen_name = $single_tweet['user']['screen_name']; $user_permalink = 'http://twitter.com/#!/' . $screen_name; $tweet_permalink = 'http://twitter.com/#!/' . $screen_name . '/status/' . $single_tweet['id_str']; if ($tweet_text) { echo '<div class="latest-twitter-tweet"><i class="icon-twitter"></i> "' . $tweet_text . '"</div>'; } } } $username = $instance['user']; echo '<div id="latest-twitter-follow-link"><a href="http://twitter.com/' . $username . '">'; _e('follow ', 'orizon'); echo @$username; _e(' on twitter', 'orizon'); echo '</a></div>'; echo $after_widget; }
public function really_simple_twitter_codebird_set($options) { if (!class_exists('Codebird')) { require 'lib/codebird.php'; } Codebird::setConsumerKey($options['consumer_key'], $options['consumer_secret']); $this->cb = Codebird::getInstance(); $this->cb->setToken($options['access_token'], $options['access_token_secret']); // From Codebird documentation: For API methods returning multiple data (like statuses/home_timeline), you should cast the reply to array $this->cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY); }
function astrum_twitter_api() { global $cb; $consumer_key = ot_get_option('pp_twitter_ck'); $consumer_secret = ot_get_option('pp_twitter_cs'); $access_token = ot_get_option('pp_twitter_at'); $access_secret = ot_get_option('pp_twitter_ts'); require_once 'codebird.php'; Codebird::setConsumerKey($consumer_key, $consumer_secret); $cb = Codebird::getInstance(); $cb->setToken($access_token, $access_secret); }
<?php //We use already made Twitter OAuth library //https://github.com/mynetx/codebird-php require_once 'codebird.php'; //Twitter OAuth Settings, enter your settings here: $CONSUMER_KEY = 'NmlAuK76cw6riIJSHGwT2gAQs'; $CONSUMER_SECRET = 'u75d10LP3z29UYfwnJanfpFLEYPGf1G57sJ4u8GoFBb5SY2cpj'; $ACCESS_TOKEN = '4845733430-92pzC0h78LUw5ufefpPKSlxOyCs4L5r2CIDw5MC'; $ACCESS_TOKEN_SECRET = 'Lu1ZqSf9Xb7l99VMF68Ut5QuI3PkOO48zrv005KOlESlB'; //Get authenticated Codebird::setConsumerKey($CONSUMER_KEY, $CONSUMER_SECRET); $cb = Codebird::getInstance(); $cb->setToken($ACCESS_TOKEN, $ACCESS_TOKEN_SECRET); //retrieve posts $q = $_POST['q']; $count = $_POST['count']; $api = $_POST['api']; //https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline //https://dev.twitter.com/docs/api/1.1/get/search/tweets $params = array('screen_name' => $q, 'q' => $q, 'count' => $count); //Make the REST call $data = (array) $cb->{$api}($params); //Output result in JSON, getting it ready for jQuery to process echo json_encode($data);
<?php $consumer = '0ckhWwE8MAQzM2IjRH3seg'; $consumer_secret = 'G642Iu5fPoCSruaUlhsXcHZLkuv4N41ai9jKRbRc'; require_once 'codebird.php'; Codebird::setConsumerKey($consumer, $consumer_secret); $cb = Codebird::getInstance(); //$cb = new Codebird; //$cb->setConsumerKey($consumer,$consumer_secret); $reply = $cb->oauth_requestToken(array('oauth_callback' => 'http://shot.dogmap.jp/')); var_dump($reply); var_dump($cb);