Commits

Iván Flores  committed d3d18d6

Now using 'twitter-api-php' by James Mallison..
Table 'rm_twitter_feed_custom' -> 'rm_twitter_feed_parameters'
Ajax function now have nonce and die()
Update README credits.

  • Participants
  • Parent commits 0ba465d
  • Tags 0.2

Comments (0)

Files changed (3)

-# RM Plugin for WordPress: Twitter Feed API 1.1
+# RM Plugin for WordPress: Twitter Feed 
 
 ### Setup Instrucctions:
 
 
 ### Credits
 
-This plugin is based on [this code](https://gist.github.com/MikeRogers0/5033286) by Mike Rogers
+This plugin use [twitter-api-php](https://github.com/J7mbo/twitter-api-php) by James Mallison
 
 This plugin use [urlize.js](https://github.com/ljosa/urlize.js) by Vebjorn Ljosa

File TwitterAPIExchange.php

+<?php
+
+/**
+ * Twitter-API-PHP : Simple PHP wrapper for the v1.1 API
+ * 
+ * PHP version 5.3.10
+ * 
+ * @category Awesomeness
+ * @package  Twitter-API-PHP
+ * @author   James Mallison <me@j7mbo.co.uk>
+ * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
+ * @link     http://github.com/j7mbo/twitter-api-php
+ */
+class TwitterAPIExchange
+{
+    private $oauth_access_token;
+    private $oauth_access_token_secret;
+    private $consumer_key;
+    private $consumer_secret;
+    private $postfields;
+    private $getfield;
+    protected $oauth;
+    public $url;
+
+    /**
+     * Create the API access object. Requires an array of settings::
+     * oauth access token, oauth access token secret, consumer key, consumer secret
+     * These are all available by creating your own application on dev.twitter.com
+     * Requires the cURL library
+     * 
+     * @param array $settings
+     */
+    public function __construct(array $settings)
+    {
+        if (!in_array('curl', get_loaded_extensions())) 
+        {
+            throw new Exception('You need to install cURL, see: http://curl.haxx.se/docs/install.html');
+        }
+        
+        if (!isset($settings['oauth_access_token'])
+            || !isset($settings['oauth_access_token_secret'])
+            || !isset($settings['consumer_key'])
+            || !isset($settings['consumer_secret']))
+        {
+            throw new Exception('Make sure you are passing in the correct parameters');
+        }
+
+        $this->oauth_access_token = $settings['oauth_access_token'];
+        $this->oauth_access_token_secret = $settings['oauth_access_token_secret'];
+        $this->consumer_key = $settings['consumer_key'];
+        $this->consumer_secret = $settings['consumer_secret'];
+    }
+    
+    /**
+     * Set postfields array, example: array('screen_name' => 'J7mbo')
+     * 
+     * @param array $array Array of parameters to send to API
+     * 
+     * @return TwitterAPIExchange Instance of self for method chaining
+     */
+    public function setPostfields(array $array)
+    {
+        if (!is_null($this->getGetfield())) 
+        { 
+            throw new Exception('You can only choose get OR post fields.'); 
+        }
+        
+        if (isset($array['status']) && substr($array['status'], 0, 1) === '@')
+        {
+            $array['status'] = sprintf("\0%s", $array['status']);
+        }
+        
+        $this->postfields = $array;
+        
+        return $this;
+    }
+    
+    /**
+     * Set getfield string, example: '?screen_name=J7mbo'
+     * 
+     * @param string $string Get key and value pairs as string
+     * 
+     * @return \TwitterAPIExchange Instance of self for method chaining
+     */
+    public function setGetfield($string)
+    {
+        if (!is_null($this->getPostfields())) 
+        { 
+            throw new Exception('You can only choose get OR post fields.'); 
+        }
+        
+        $search = array('#', ',', '+', ':');
+        $replace = array('%23', '%2C', '%2B', '%3A');
+        $string = str_replace($search, $replace, $string);  
+        
+        $this->getfield = $string;
+        
+        return $this;
+    }
+    
+    /**
+     * Get getfield string (simple getter)
+     * 
+     * @return string $this->getfields
+     */
+    public function getGetfield()
+    {
+        return $this->getfield;
+    }
+    
+    /**
+     * Get postfields array (simple getter)
+     * 
+     * @return array $this->postfields
+     */
+    public function getPostfields()
+    {
+        return $this->postfields;
+    }
+    
+    /**
+     * Build the Oauth object using params set in construct and additionals
+     * passed to this method. For v1.1, see: https://dev.twitter.com/docs/api/1.1
+     * 
+     * @param string $url The API url to use. Example: https://api.twitter.com/1.1/search/tweets.json
+     * @param string $requestMethod Either POST or GET
+     * @return \TwitterAPIExchange Instance of self for method chaining
+     */
+    public function buildOauth($url, $requestMethod)
+    {
+        if (!in_array(strtolower($requestMethod), array('post', 'get')))
+        {
+            throw new Exception('Request method must be either POST or GET');
+        }
+        
+        $consumer_key = $this->consumer_key;
+        $consumer_secret = $this->consumer_secret;
+        $oauth_access_token = $this->oauth_access_token;
+        $oauth_access_token_secret = $this->oauth_access_token_secret;
+        
+        $oauth = array( 
+            'oauth_consumer_key' => $consumer_key,
+            'oauth_nonce' => time(),
+            'oauth_signature_method' => 'HMAC-SHA1',
+            'oauth_token' => $oauth_access_token,
+            'oauth_timestamp' => time(),
+            'oauth_version' => '1.0'
+        );
+        
+        $getfield = $this->getGetfield();
+        
+        if (!is_null($getfield))
+        {
+            $getfields = str_replace('?', '', explode('&', $getfield));
+            foreach ($getfields as $g)
+            {
+                $split = explode('=', $g);
+                $oauth[$split[0]] = $split[1];
+            }
+        }
+        
+        $base_info = $this->buildBaseString($url, $requestMethod, $oauth);
+        $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
+        $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
+        $oauth['oauth_signature'] = $oauth_signature;
+        
+        $this->url = $url;
+        $this->oauth = $oauth;
+        
+        return $this;
+    }
+    
+    /**
+     * Perform the acual data retrieval from the API
+     * 
+     * @param boolean $return If true, returns data.
+     * 
+     * @return json If $return param is true, returns json data.
+     */
+    public function performRequest($return = true)
+    {
+        if (!is_bool($return)) 
+        { 
+            throw new Exception('performRequest parameter must be true or false'); 
+        }
+        
+        $header = array($this->buildAuthorizationHeader($this->oauth), 'Expect:');
+        
+        $getfield = $this->getGetfield();
+        $postfields = $this->getPostfields();
+
+        $options = array( 
+            CURLOPT_HTTPHEADER => $header,
+            CURLOPT_HEADER => false,
+            CURLOPT_URL => $this->url,
+            CURLOPT_RETURNTRANSFER => true
+        );
+
+        if (!is_null($postfields))
+        {
+            $options[CURLOPT_POSTFIELDS] = $postfields;
+        }
+        else
+        {
+            if ($getfield !== '')
+            {
+                $options[CURLOPT_URL] .= $getfield;
+            }
+        }
+
+        $feed = curl_init();
+        curl_setopt_array($feed, $options);
+        $json = curl_exec($feed);
+        curl_close($feed);
+
+        if ($return) { return $json; }
+    }
+    
+    /**
+     * Private method to generate the base string used by cURL
+     * 
+     * @param string $baseURI
+     * @param string $method
+     * @param string $params
+     * 
+     * @return string Built base string
+     */
+    private function buildBaseString($baseURI, $method, $params) 
+    {
+        $return = array();
+        ksort($params);
+        
+        foreach($params as $key=>$value)
+        {
+            $return[] = "$key=" . $value;
+        }
+        
+        return $method . "&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $return)); 
+    }
+    
+    /**
+     * Private method to generate authorization header used by cURL
+     * 
+     * @param array $oauth Array of oauth data generated by buildOauth()
+     * 
+     * @return string $return Header used by cURL for request
+     */    
+    private function buildAuthorizationHeader($oauth) 
+    {
+        $return = 'Authorization: OAuth ';
+        $values = array();
+        
+        foreach($oauth as $key => $value)
+        {
+            $values[] = "$key=\"" . rawurlencode($value) . "\"";
+        }
+        
+        $return .= implode(', ', $values);
+        return $return;
+    }
+
+}

File rm-twitter-feed.php

     Plugin URI: http://restatemedia.com
     Description: Plugin for displaying tweets using Twitter API 1.1 
     Author: Iván Flores
-    Version: 1.0 
+    Version: 0.2 
     Author URI: http://restatemedia.com
 */ 
 
 	       	<tr valign="top">
 	        <th scope="row">Parameters:</th>
 	        <td>
-	        	<input type="text" style="width: 400px" name="rm_twitter_feed_custom" value="<?php echo get_option('rm_twitter_feed_custom'); ?>" />
+	        	<input type="text" style="width: 400px" name="rm_twitter_feed_parameters" value="<?php echo get_option('rm_twitter_feed_parameters'); ?>" />
 	        	<p class="description"><a href="https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline" target="_blank">List of Parameters</a> you can use.<br> Ex: <code>screen_name=RestateMedia&count=5</code></p>
 	        </td>
 	        </tr>
 add_action( 'admin_init', 'rm_twitter_feed_register_fields' );
 function rm_twitter_feed_register_fields() {
 
-	register_setting( 'rm_twitter_feed_options_fields', 'rm_twitter_feed_custom');
+	register_setting( 'rm_twitter_feed_options_fields', 'rm_twitter_feed_parameters');
 	register_setting( 'rm_twitter_feed_options_fields', 'rm_twitter_feed_oauth_access_token', 'sanitize_text_field');
 	register_setting( 'rm_twitter_feed_options_fields', 'rm_twitter_feed_oauth_access_token_secret', 'sanitize_text_field');
 	register_setting( 'rm_twitter_feed_options_fields', 'rm_twitter_feed_consumer_key', 'sanitize_text_field');
 	<script type="text/javascript">
 	jQuery(document).ready( function() {
 
-		var myquery = 'statuses/user_timeline.json?<?php echo get_option('rm_twitter_feed_custom'); ?>';
+		var myquery = 'statuses/user_timeline.json?<?php echo get_option('rm_twitter_feed_parameters'); ?>',
+			nonce = '<?php echo wp_create_nonce("rm_getTweets") ?>';
 
 
 		jQuery.ajax({
-	         type : "get",
+	         type : "post",
 	         dataType : "json",
 	         url : tweetsAjax.ajaxurl,
-	         data : {action: "rm_getTweets", myquery: myquery },
+	         data : {action: "rm_getTweets", nonce: nonce},
 	         success: function(d) {
 	    	   
+	    	  	console.log('success!');
+	         	console.log(d);
+
 	    	    jQuery.each(d, function(i, object) {
 					appendTweets(object);
 
-				}); 
+				});
 
 	         },
 	         error: function(a, b, c) {
 add_action("wp_ajax_nopriv_rm_getTweets", "rm_getTweets");
 function rm_getTweets() {
 
-	/**
-	 *  Usage:
-	 *  Send the url you want to access url encoded in the url paramater, for example (This is with JS): 
-	 *  /twitter-proxy.php?url='+encodeURIComponent('statuses/user_timeline.json?screen_name=MikeRogers0&count=2')
-	*/
-
-	// The tokens, keys and secrets from the app you created at https://dev.twitter.com/apps
-	$config = array(
-		'oauth_access_token' => get_option('rm_twitter_feed_oauth_access_token'),
-		'oauth_access_token_secret' => get_option('rm_twitter_feed_oauth_access_token_secret'),
-		'consumer_key' => get_option('rm_twitter_feed_consumer_key'),
-		'consumer_secret' => get_option('rm_twitter_feed_consumer_secret'),
-		'use_whitelist' => true, // If you want to only allow some requests to use this script.
-		'base_url' => 'http://api.twitter.com/1.1/',
-		'whitelist' => get_option('rm_twitter_feed_custom')
-	);
+	if ( !wp_verify_nonce( $_REQUEST['nonce'], "rm_getTweets")) {
+      exit("No naughty business please");
+   }  
 
-	// Only allow certain requests to twitter. Stop randoms using your server as a proxy.
-	$whitelist = array(
-		'statuses/user_timeline.json?' . get_option('rm_twitter_feed_custom') => true
-	);
+	require_once('TwitterAPIExchange.php');
 
-	/*
-	* Ok, no more config should really be needed. Yay!
-	*/
-
-	// We'll get the URL from $_GET[]. Make sure the url is url encoded, for example encodeURIComponent('statuses/user_timeline.json?screen_name=MikeRogers0&count=10&include_rts=false&exclude_replies=true')
-	if(!isset($_GET['myquery'])){
-		die('No URL set');
-	}
-
-	$url = $_GET['myquery'];
-
-
-	if($config['use_whitelist'] && !isset($whitelist[$url])){
-		die('URL is not authorised');
-	}
-
-	// Figure out the URL parmaters
-	$url_parts = parse_url($url);
-	parse_str($url_parts['query'], $url_arguments);
-
-	$full_url = $config['base_url'].$url; // Url with the query on it.
-	$base_url = $config['base_url'].$url_parts['path']; // Url without the query.
-
-	/**
-	* Code below from http://stackoverflow.com/questions/12916539/simplest-php-example-retrieving-user-timeline-with-twitter-api-version-1-1 by Rivers 
-	* with a few modfications by Mike Rogers to support variables in the URL nicely
-	*/
-
-	function buildBaseString($baseURI, $method, $params) {
-		$r = array();
-		ksort($params);
-		foreach($params as $key=>$value){
-		$r[] = "$key=" . rawurlencode($value);
-		}
-		return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
-	}
-
-	function buildAuthorizationHeader($oauth) {
-		$r = 'Authorization: OAuth ';
-		$values = array();
-		foreach($oauth as $key=>$value)
-		$values[] = "$key=\"" . rawurlencode($value) . "\"";
-		$r .= implode(', ', $values);
-		return $r;
-	}
-
-	// Set up the oauth Authorization array
-	$oauth = array(
-		'oauth_consumer_key' => $config['consumer_key'],
-		'oauth_nonce' => time(),
-		'oauth_signature_method' => 'HMAC-SHA1',
-		'oauth_token' => $config['oauth_access_token'],
-		'oauth_timestamp' => time(),
-		'oauth_version' => '1.0'
-	);
-		
-	$base_info = buildBaseString($base_url, 'GET', array_merge($oauth, $url_arguments));
-	$composite_key = rawurlencode($config['consumer_secret']) . '&' . rawurlencode($config['oauth_access_token_secret']);
-	$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
-	$oauth['oauth_signature'] = $oauth_signature;
-
-	// Make Requests
-	$header = array(
-		buildAuthorizationHeader($oauth), 
-		'Expect:'
-	);
-	$options = array(
-		CURLOPT_HTTPHEADER => $header,
-		//CURLOPT_POSTFIELDS => $postfields,
-		CURLOPT_HEADER => false,
-		CURLOPT_URL => $full_url,
-		CURLOPT_RETURNTRANSFER => true,
-		CURLOPT_SSL_VERIFYPEER => false
+	$settings = array(
+    'oauth_access_token' => get_option('rm_twitter_feed_oauth_access_token'),
+    'oauth_access_token_secret' => get_option('rm_twitter_feed_oauth_access_token_secret'),
+    'consumer_key' => get_option('rm_twitter_feed_consumer_key'),
+    'consumer_secret' => get_option('rm_twitter_feed_consumer_secret')
 	);
 
-	$feed = curl_init();
-	curl_setopt_array($feed, $options);
-	$result = curl_exec($feed);
-	$info = curl_getinfo($feed);
-	curl_close($feed);
+	$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
+	$getfield = '?'.get_option('rm_twitter_feed_parameters');
+	$requestMethod = 'GET';
+
+	$twitter = new TwitterAPIExchange($settings);
+	$response = $twitter->setGetfield($getfield)
+	                    ->buildOauth($url, $requestMethod)
+	                    ->performRequest(); 
 
-	//Send suitable headers to the end user.
-	if(isset($info['content_type']) && isset($info['size_download'])){
-		header('Content-Type: '.$info['content_type']);
-		header('Content-Length: '.$info['size_download']);
+	echo $response;
 
-	}
+	die();
 
-	echo $result;
 }
 
 ?>