Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

version 0.2.0-beta. includes support for oauth 1.0a and fixes several…

… bugs.
  • Loading branch information...
commit 83e36708d3b5f9fa0b32bff7f3381f919acb2cfc 1 parent bb524c9
@abraham abraham authored
View
40 callback.php
@@ -0,0 +1,40 @@
+<?php
+/**
+ * @file
+ * Take the user when they return from Twitter. Get access tokens.
+ * Verify credentials and redirect to based on response from Twitter.
+ */
+
+/* Start session and load lib */
+session_start();
+require_once('twitteroauth/twitteroauth.php');
+require_once('config.php');
+
+/* If the oauth_token is old redirect to the connect page. */
+if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
+ $_SESSION['oauth_status'] = 'oldtoken';
+ header('Location: ./clearsessions.php');
+}
+
+/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
+$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
+
+/* Request access tokens from twitter */
+$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
+
+/* Save the access tokens. Normally these would be saved in a database for future use. */
+$_SESSION['access_token'] = $access_token;
+
+/* Remove no longer needed request tokens */
+unset($_SESSION['oauth_token']);
+unset($_SESSION['oauth_token_secret']);
+
+/* If HTTP response is 200 continue otherwise send to connect page to retry */
+if (200 == $connection->http_code) {
+ /* The user has been verified and the access tokens can be saved for future use */
+ $_SESSION['status'] = 'verified';
+ header('Location: ./index.php');
+} else {
+ /* Save HTTP status for error dialog on connnect page.*/
+ header('Location: ./clearsessions.php');
+}
View
5 config.php
@@ -5,5 +5,6 @@
* A single location to store configuration.
*/
-define("CONSUMER_KEY", "CONSUMER_KEY_GOES_HERE");
-define("CONSUMER_SECRET", "CONSUMER_SECRET_GOES_HERE");
+define("CONSUMER_KEY", "");
+define("CONSUMER_SECRET", "");
+define("OAUTH_CALLBACK", "");
View
11 connect.php
@@ -0,0 +1,11 @@
+<?php
+
+/**
+ * @file
+ * Get a request token from twitter and present authorization URL to user
+ */
+
+$content = '<a href="./redirect.php"><img src="./images/lighter.png" alt="Sign in with Twitter"/></a>';
+
+/* Include HTML to display on the page */
+include('html.inc');
View
37 html.inc
@@ -0,0 +1,37 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+ <head>
+ <title>Twitter OAuth in PHP</title>
+ <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
+ <style type="text/css">
+ img {border-width: 0}
+ * {font-family:'Lucida Grande', sans-serif;}
+ </style>
+ </head>
+ <body>
+ <div>
+ <h2>Welcome to a Twitter OAuth PHP example.</h2>
+
+ <p>This site is a basic showcase of Twitters OAuth authentication method. If you are having issues try <a href='./clearsessions.php'>clearing your session</a>.</p>
+
+ <p>
+ Links:
+ <a href='http://github.com/abraham/twitteroauth'>Source Code</a> &amp;
+ <a href='http://wiki.github.com/abraham/twitteroauth/documentation'>Documentation</a> |
+ Contact @<a href='http://twitter.com/abraham'>abraham</a>
+ </p>
+ <hr />
+ <?php if (isset($menu)) { ?>
+ <?php echo $menu; ?>
+ <?php } ?>
+ </div>
+ <?php if (isset($status_text)) { ?>
+ <?php echo '<h3>'.$status_text.'</h3>'; ?>
+ <?php } ?>
+ <p>
+ <?php echo $content; ?>
+ </p>
+
+ </body>
+</html>
View
128 index.php
@@ -1,101 +1,33 @@
<?php
-// require twitterOAuth lib
-require_once('twitteroauth/twitterOAuth.php');
-
-/* Sessions are used to keep track of tokens while user authenticates with twitter */
-session_start();
-/* Consumer key from twitter */
-$consumer_key = '';
-/* Consumer Secret from twitter */
-$consumer_secret = '';
-/* Set up placeholder */
-$content = NULL;
-/* Set state if previous session */
-$state = $_SESSION['oauth_state'];
-/* Checks if oauth_token is set from returning from twitter */
-$session_token = $_SESSION['oauth_request_token'];
-/* Checks if oauth_token is set from returning from twitter */
-$oauth_token = $_REQUEST['oauth_token'];
-/* Set section var */
-$section = $_REQUEST['section'];
-
-/* Clear PHP sessions */
-if ($_REQUEST['test'] === 'clear') {/*{{{*/
- session_destroy();
- session_start();
-}/*}}}*/
-
-/* If oauth_token is missing get it */
-if ($_REQUEST['oauth_token'] != NULL && $_SESSION['oauth_state'] === 'start') {/*{{{*/
- $_SESSION['oauth_state'] = $state = 'returned';
-}/*}}}*/
-
-/*
- * Switch based on where in the process you are
- *
- * 'default': Get a request token from twitter for new user
- * 'returned': The user has authorize the app on twitter
+/**
+ * @file
+ * User has successfully authenticated with Twitter. Access tokens saved to session and DB.
*/
-switch ($state) {/*{{{*/
- default:
- /* Create TwitterOAuth object with app key/secret */
- $to = new TwitterOAuth($consumer_key, $consumer_secret);
- /* Request tokens from twitter */
- $tok = $to->getRequestToken();
-
- /* Save tokens for later */
- $_SESSION['oauth_request_token'] = $token = $tok['oauth_token'];
- $_SESSION['oauth_request_token_secret'] = $tok['oauth_token_secret'];
- $_SESSION['oauth_state'] = "start";
-
- /* Build the authorization URL */
- $request_link = $to->getAuthorizeURL($token);
- /* Build link that gets user to twitter to authorize the app */
- $content = 'Click on the link to go to twitter to authorize your account.';
- $content .= '<br /><a href="'.$request_link.'">'.$request_link.'</a>';
- break;
- case 'returned':
- /* If the access tokens are already set skip to the API call */
- if ($_SESSION['oauth_access_token'] === NULL && $_SESSION['oauth_access_token_secret'] === NULL) {
- /* Create TwitterOAuth object with app key/secret and token key/secret from default phase */
- $to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_request_token'], $_SESSION['oauth_request_token_secret']);
- /* Request access tokens from twitter */
- $tok = $to->getAccessToken();
-
- /* Save the access tokens. Normally these would be saved in a database for future use. */
- $_SESSION['oauth_access_token'] = $tok['oauth_token'];
- $_SESSION['oauth_access_token_secret'] = $tok['oauth_token_secret'];
- }
- /* Random copy */
- $content = 'your account should now be registered with twitter. Check here:<br />';
- $content .= '<a href="https://twitter.com/account/connections">https://twitter.com/account/connections</a>';
-
- /* Create TwitterOAuth with app key/secret and user access key/secret */
- $to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_access_token'], $_SESSION['oauth_access_token_secret']);
- /* Run request on twitter API as user. */
- $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');
- //$content = $to->OAuthRequest('https://twitter.com/statuses/update.xml', array('status' => 'Test OAuth update. #testoauth'), 'POST');
- //$content = $to->OAuthRequest('https://twitter.com/statuses/replies.xml', array(), 'POST');
- break;
-}/*}}}*/
-?>
-
-<html>
- <head>
- <title>Twitter OAuth in PHP</title>
- </head>
- <body>
- <h2>Welcome to a Twitter OAuth PHP example.</h2>
- <p>This site is a basic showcase of Twitters new OAuth authentication method. Everything is saved in sessions. If you want to start over <a href='<?php echo $_SERVER['PHP_SELF']; ?>?test=clear'>clear sessions</a>.</p>
-
- <p>
- Get the code powering this at <a href='http://github.com/abraham/twitteroauth'>http://github.com/abraham/twitteroauth</a>
- <br />
- Read the documentation at <a href='https://docs.google.com/View?docID=dcf2dzzs_2339fzbfsf4'>https://docs.google.com/View?docID=dcf2dzzs_2339fzbfsf4</a>
- </p>
-
- <p><pre><?php print_r($content); ?><pre></p>
-
- </body>
-</html>
+/* Load required lib files. */
+session_start();
+require_once('twitteroauth/twitteroauth.php');
+require_once('config.php');
+
+/* Get user access tokens out of the session. */
+$access_token = $_SESSION['access_token'];
+/* If access tokens are not available redirect to connect page. */
+if (empty($access_token['oauth_token']) || empty($access_token['oauth_token_secret'])) {
+ header('Location: '.$home_page.'/clearsessions.php');
+}
+
+/* Create a TwitterOauth object with consumer/user tokens. */
+$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
+
+/* If method is set change API call made. Test is called by default. */
+$content = '<pre>'.$connection->get('account/verify_credentials').'</pre>';
+
+/* Some example calls */
+//$connection->get('users/show', array('screen_name' => 'abraham')));
+//$connection->post('statuses/update', array('status' => date(DATE_RFC822)));
+//$connection->post('statuses/destroy', array('id' => 5437877770));
+//$connection->post('friendships/create', array('id' => 9436992)));
+//$connection->post('friendships/destroy', array('id' => 9436992)));
+
+/* Include HTML to display on the page */
+include('html.inc');
View
28 redirect.php
@@ -0,0 +1,28 @@
+<?php
+
+/* Start session and load lib */
+session_start();
+require_once('twitteroauth/twitteroauth.php');
+require_once('config.php');
+
+/* Create TwitterOAuth object and get request token */
+$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
+
+/* Get request token */
+$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
+
+/* Save request token to session */
+$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
+$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
+
+/* If last connection fails don't display authorization link */
+switch ($connection->http_code) {
+ case 200:
+ /* Build authorize URL */
+ $url = $connection->getAuthorizeURL($token);
+ header('Location: ' . $url);
+ break;
+ default:
+ echo 'Could not connect to Twitter. Refresh the page or try again later.';
+ break;
+}
View
5 twitteroauth/OAuth.php
@@ -11,10 +11,9 @@ class OAuthConsumer {
public $key;
public $secret;
- function __construct($key, $secret, $callback_url=NULL) {
+ function __construct($key, $secret) {
$this->key = $key;
$this->secret = $secret;
- $this->callback_url = $callback_url;
}
function __toString() {
@@ -173,7 +172,7 @@ class OAuthRequest {
private $http_url;
// for debug purposes
public $base_string;
- public static $version = '1.0';
+ public static $version = '1.0a';
public static $POST_INPUT = 'php://input';
function __construct($http_method, $http_url, $parameters=NULL) {
View
130 twitteroauth/twitteroauth.php
@@ -7,7 +7,7 @@
*
* Code based on:
* Fire Eagle code - http://github.com/myelin/fireeagle-php-lib
- * twitterlibphp - http://github.com/poseurtech/twitterlibphp
+ * twitterlibphp - http://github.com/jdp/twitterlibphp
*/
/* Load OAuth lib. You can find it at http://oauth.net */
@@ -18,17 +18,21 @@
*/
class TwitterOAuth {
/* Contains the last HTTP status code returned */
- private $http_code;
+ public $http_code;
/* Contains the last API call */
- private $last_api_call;
+ public $last_api_call;
/* Set up the API root URL */
- public static $host = "https://api.twitter.com/1";
+ public $host = "https://api.twitter.com/1/";
/* Set timeout default */
- public static $timeout = 30;
+ public $timeout = 30;
/* Set connect timeout */
- public static $connecttimeout = 30;
+ public $connecttimeout = 30;
/* Verify SSL Cert */
- public static $ssl_verifypeer = FALSE;
+ public $ssl_verifypeer = FALSE;
+ /* Respons format */
+ public $format = 'json';
+ /* Decode returne json data */
+ public $decode_json = 'TRUE';
@@ -58,7 +62,7 @@ function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oaut
} else {
$this->token = NULL;
}
- }/*}}}*/
+ }
/**
@@ -66,26 +70,15 @@ function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oaut
*
* @returns a key/value array containing oauth_token and oauth_token_secret
*/
- function getRequestToken() {
- $r = $this->oAuthRequest($this->requestTokenURL());
- $token = $this->oAuthParseResponse($r);
+ function getRequestToken($oauth_callback = NULL) {
+ $parameters = array();
+ if (!empty($oauth_callback)) {
+ $parameters['oauth_callback'] = $oauth_callback;
+ }
+ $request = $this->oAuthRequest($this->requestTokenURL(), 'GET', $parameters);
+ $token = OAuthUtil::parse_parameters($request);
$this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
return $token;
- }/*}}}*/
-
- /**
- * Parse a URL-encoded OAuth response
- *
- * @return a key/value array
- */
- function oAuthParseResponse($responseString) {
- $r = array();
- foreach (explode('&', $responseString) as $param) {
- $pair = explode('=', $param, 2);
- if (count($pair) != 2) continue;
- $r[urldecode($pair[0])] = urldecode($pair[1]);
- }
- return $r;
}
/**
@@ -93,10 +86,16 @@ function oAuthParseResponse($responseString) {
*
* @returns a string
*/
- function getAuthorizeURL($token) {
- if (is_array($token)) $token = $token['oauth_token'];
- return $this->authorizeURL() . '?oauth_token=' . $token;
- }/*}}}*/
+ function getAuthorizeURL($token, $sign_in_with_twitter = TRUE) {
+ if (is_array($token)) {
+ $token = $token['oauth_token'];
+ }
+ if (empty($sign_in_with_twitter)) {
+ return $this->authorizeURL() . "?oauth_token={$token}";
+ } else {
+ return $this->authenticateURL() . "?oauth_token={$token}";
+ }
+ }
/**
* Exchange the request token and secret for an access token and
@@ -105,32 +104,65 @@ function getAuthorizeURL($token) {
* @returns array("oauth_token" => the access token,
* "oauth_token_secret" => the access secret)
*/
- function getAccessToken($token = NULL) {
- $r = $this->oAuthRequest($this->accessTokenURL());
- $token = $this->oAuthParseResponse($r);
+ function getAccessToken($oauth_verifier = FALSE) {
+ $parameters = array();
+ if (!empty($oauth_verifier)) {
+ $parameters['oauth_verifier'] = $oauth_verifier;
+ }
+ $request = $this->oAuthRequest($this->accessTokenURL(), 'GET', $parameters);
+ $token = OAuthUtil::parse_parameters($request);
$this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
return $token;
- }/*}}}*/
+ }
+
+ /**
+ * GET wrappwer for oAuthRequest.
+ */
+ function get($url, $parameters = NULL) {
+ return $this->oAuthRequest($url, 'GET', $parameters);
+ }
+
+ /**
+ * POST wreapper for oAuthRequest.
+ */
+ function post($url, $parameters) {
+ return $this->oAuthRequest($url, 'POST', $parameters);
+ }
+
+ /**
+ * DELTE wrapper for oAuthReqeust.
+ */
+ function delete($url, $parameters) {
+ return $this->oAuthRequest($url, 'DELETE', $parameters);
+ }
/**
* Format and sign an OAuth / API request
*/
- function oAuthRequest($url, $args = array(), $method = NULL) {
- if (empty($method)) $method = empty($args) ? "GET" : "POST";
- $req = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $args);
- $req->sign_request($this->sha1_method, $this->consumer, $this->token);
+ function oAuthRequest($url, $method, $parameters = array()) {
+ if (isset($parameters['id'])) {
+ $url = "{$url}/{$parameters['id']}";
+ unset($parameters['id']);
+ }
+ if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) {
+ $url = "{$this->host}{$url}.{$this->format}";
+ }
+ $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters);
+ $request->sign_request($this->sha1_method, $this->consumer, $this->token);
switch ($method) {
- case 'GET': return $this->http($req->to_url());
- case 'POST': return $this->http($req->get_normalized_http_url(), $req->to_postdata());
+ case 'GET':
+ return $this->http($request->to_url(), 'GET');
+ default:
+ return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata());
}
- }/*}}}*/
+ }
/**
* Make an HTTP request
*
* @return API results
*/
- function http($url, $postfields = null) {
+ function http($url, $method, $postfields = NULL) {
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
@@ -138,18 +170,24 @@ function http($url, $postfields = null) {
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
- curl_setopt($ci, CURLOPT_URL, $this->url);
- if (defined("CURL_CA_BUNDLE_PATH")) {
- curl_setopt($ci, CURLOPT_CAINFO, CURL_CA_BUNDLE_PATH);
+ curl_setopt($ci, CURLOPT_URL, $url);
+ switch ($method) {
+ case 'POST':
+ curl_setopt($ci, CURLOPT_POST, TRUE);
+ break;
+ case 'DELETE':
+ curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
if (isset($postfields)) {
- curl_setopt($ci, CURLOPT_POST, 1);
curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
}
$response = curl_exec($ci);
$this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
$this->last_api_call = $url;
curl_close ($ci);
+ //if ($this->format === 'json' && $this->decode_json) {
+ // return json_decode($response);
+ //}
return $response;
}
}
Please sign in to comment.
Something went wrong with that request. Please try again.