Twitter: Read tweets with API 1.0 auth

Twitter has updated their API to version 1.1.

One of the changes in this API has caused many of the pages programmed with Twitter stream had stopped working.
For example in many cases streams programmed with Tweet! (plugin de jQuery).

Currently the connection this plugin does is based in the old Twitter API 1.0, which the connections authenticated weren’t necessary. I had to review page to page in order to adapt them to the new API 1.1.

Fortunately, many people have found the same problem and have already found a solution that allows not start from 0.

In this GitHub repo you can download new php and js files needed to get it working again.

The steps are:

1) The repository uses as API access the address /twitter. In my case, my sites work with CI, so I had to create a controller called Twitter in each one.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class Twitter extends CI_Controller {
	public function index()
	{
		$this->twitteroauth->init();
		$this->twitteroauth->fetch();
	}
}

2) Overwrite file Tweet! jquery.tweet.js or its minified version.

3) Create an app on Twitter. Go in to https://dev.twitter.com/apps and create an application using the form, indicate as Callback URL and Website the address of our website. Once created it generate fields that are the variables we will use in class configuration if you are following ezTweet repository files. The fields are App Consume Key, Consumer Secret App, App Access Token and Access Token Secret.

4) Adapt PHP libraries and index.php file for authentication. Again, in the case of CI, must be adapted. What I have been doing is creating libraries with code that comes in index.php adapted and called from the controller twitter. I mean, I’ve loaded ezTweet class and created a new TwitterOauth that the only thing different about it is that initializes its configuration variables in a init function:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Current TwitterOauth Class
 *
 * @package	Twitter oAuth
 * @subpackage	Libraries
 * @category	Utils Functions
 */
class CI_TwitterOauth {
 
	// Your Twitter App Consumer Key
	private $consumer_key = '';
 
	// Your Twitter App Consumer Secret
	private $consumer_secret = '';
 
	// Your Twitter App Access Token
	private $user_token = '';
 
	// Your Twitter App Access Token Secret
	private $user_secret = '';
 
	// Path to tmhOAuth libraries
	private $lib = '';
 
	// Enable caching
	private $cache_enabled = true;
 
	// Cache interval (minutes)
	private $cache_interval = 15;
 
	// Path to writable cache directory
	private $cache_dir = './';
 
	// Enable debugging
	private $debug = true;
 
	/**************************************************************************************/
 
	public function init() {
 
		$this->CI =& get_instance();
 
		// Initialize paths and etc.
		$this->pathify($this->cache_dir);
		$this->pathify($this->lib);
		$this->message = '';
 
		// Set server-side debug params
		if($this->debug === true) {
			error_reporting(-1);
		} else {
			error_reporting(0);
		}
 
		$this->consumer_key = 'CONSUMER KEY AQUÍ';
		$this->consumer_secret = 'CONSUMER SECRET AQUÍ';
		$this->user_token = 'USER TOKEN AQUÍ';
		$this->user_secret = 'USER SECRET AQUÍ';
		$this->lib = APPPATH. 'libraries/lib/';   // En mi caso tengo los archivos tmhOAuth.php y tmhUtilities.php del repositorio en application/libraries/lib
		$this->cache_enabled = true;
		$this->cache_interval = 15;
		$this->cache_dir = './';
		$this->debug = true;
	}
 
	public function fetch() {
		echo json_encode(
			array(
				'response' => json_decode($this->getJSON(), true),
				'message' => ($this->debug) ? $this->message : false
			)
		);
	}
 
	private function getJSON() {
		if($this->cache_enabled === true) {
			$CFID = $this->generateCFID();
			$cache_file = $this->cache_dir.$CFID;
 
			if(file_exists($cache_file) && (filemtime($cache_file) > (time() - 60 * intval($this->cache_interval)))) {
				return file_get_contents($cache_file, FILE_USE_INCLUDE_PATH);
			} else {
 
				$JSONraw = $this->getTwitterJSON();
				$JSON = $JSONraw['response'];
 
				// Don't write a bad cache file if there was a CURL error
				if($JSONraw['errno'] != 0) {
					$this->consoleDebug($JSONraw['error']);
					return $JSON;
				}
 
				if($this->debug === true) {
					// Check for twitter-side errors
					$pj = json_decode($JSON, true);
					if(isset($pj['errors'])) {
						foreach($pj['errors'] as $error) {
							$message = 'Twitter Error: "'.$error['message'].'", Error Code #'.$error['code'];
							$this->consoleDebug($message);
						}
						return false;
					}
				}
 
				if(is_writable($this->cache_dir) && $JSONraw) {
					if(file_put_contents($cache_file, $JSON, LOCK_EX) === false) {
						$this->consoleDebug("Error writing cache file");
					}
				} else {
					$this->consoleDebug("Cache directory is not writable");
				}
				return $JSON;
			}
		} else {
			$JSONraw = $this->getTwitterJSON();
 
			if($this->debug === true) {
				// Check for CURL errors
				if($JSONraw['errno'] != 0) {
					$this->consoleDebug($JSONraw['error']);
				}
 
				// Check for twitter-side errors
				$pj = json_decode($JSONraw['response'], true);
				if(isset($pj['errors'])) {
					foreach($pj['errors'] as $error) {
						$message = 'Twitter Error: "'.$error['message'].'", Error Code #'.$error['code'];
						$this->consoleDebug($message);
					}
					return false;
				}
			}
			return $JSONraw['response'];
		}
	}
 
	private function getTwitterJSON() {
		require $this->lib.'tmhOAuth.php';
		require $this->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;
	}
 
	private function generateCFID() {
		// The unique cached filename ID
		return md5(serialize($_POST)).'.json';
	}
 
	private function pathify(&$path) {
		// Ensures our user-specified paths are up to snuff
		$path = realpath($path).'/';
	}
 
	private function consoleDebug($message) {
		if($this->debug === true) {
			$this->message .= 'tweet.js: '.$message."\n";
		}
	}
}
This entry was tagged as

Leave a Reply

Your email address will not be published.