<?php
/*
    Proof of concept for "Sign in with Twitter" (see https://dev.twitter.com/docs/auth/sign-twitter).

    Requires PHP 5 with the PECL OAuth extension (see http://www.php.net/manual/en/book.oauth.php).

    Feel free to copy and modify. No guarantees, things may break, use at your own risk.

    tim@strehle.de
    http://www.strehle.de/tim/
*/

/* 
    The file included below contains the consumer key and secret for the app I registered with Twitter.
    Register your own at: https://dev.twitter.com/apps
    
    It looks like this:

    <?php
    define('TWITTER_CONSUMER_KEY', 'my_key');
    define('TWITTER_CONSUMER_SECRET', 'my_secret');
    ?>
*/

require_once('../twitter_auth_demo_secrets.inc.php');

session_name('twitter_auth_demo');
session_start();

if (! isset(
$_SESSION'twitter_request_token_info' ]))
    
$_SESSION'twitter_request_token_info' ] = array();

/* API URLs */
define('TWITTER_REQUEST_TOKEN_URL''https://api.twitter.com/oauth/request_token');
define('TWITTER_AUTHORIZE_URL''https://api.twitter.com/oauth/authorize');
define('TWITTER_ACCESS_TOKEN_URL''https://api.twitter.com/oauth/access_token');

if (empty(
$_REQUEST'step' ]))
{
    
// First step: Redirect to Twitter
    
    
try 
    {            
        
$oauth = new OAuth
        
(
            
TWITTER_CONSUMER_KEY,
            
TWITTER_CONSUMER_SECRET,
            
OAUTH_SIG_METHOD_HMACSHA1,
            
OAUTH_AUTH_TYPE_URI
        
);
    
        
$callback_url 'http://www.strehle.de/twitter_auth_demo.php?step=callback';

        
$request_token_info $oauth->getRequestToken
        
(
            
TWITTER_REQUEST_TOKEN_URL,
            
$callback_url
        
);

        
$_SESSION'twitter_request_token_info' ] = $request_token_info;
    
        
$url sprintf
        
(
            
'%s?oauth_token=%s',
            
TWITTER_AUTHORIZE_URL
            
urlencode($request_token_info'oauth_token' ])
        );
        
        
header('Location: ' $url);
        exit;        
    }
    catch (
OAuthException $E
    {
        
htmlOut('<p>An exception occurred: ' htmlspecialchars($E->getMessage()) . '</p>');
    }
}
elseif (
$_REQUEST'step' ] === 'callback')
{
    
// Second step: Twitter redirected to us, validate and login here
    
    /*

        array(3) {
      ["step"]=>
      string(8) "callback"
      ["oauth_token"]=>
      string(42) "QVzp0eX9ifZ6zVtWhl6TDoBoe3beIV2TUq92ueeUBI"
      ["oauth_verifier"]=>
      string(43) "8mPkqLpXRhxseHbbzg5WhCleZYdt1wsJ0PWFvHGftXA"
    }
          
        OR 
        
         array(2) {
      ["step"]=>
      string(8) "callback"
      ["denied"]=>
      string(42) "QVzp0eX9ifZ6zVtWhl6TDoBoe3beIV2TUq92ueeUBI"
    }
    
    */
    
    
if ((! empty($_REQUEST'oauth_token' ])) && (! empty($_REQUEST'oauth_verifier' ])))
    {
        try 
        {
            
$oauth = new OAuth
            
(
                
TWITTER_CONSUMER_KEY,
                
TWITTER_CONSUMER_SECRET,
                
OAUTH_SIG_METHOD_HMACSHA1,
                
OAUTH_AUTH_TYPE_URI
            
);
        
            
$oauth->setToken
            
(
                
$_REQUEST'oauth_token' ],
                
$_SESSION'twitter_request_token_info' ][ 'oauth_token_secret' ]
            );
            
            
$access_token_info $oauth->getAccessToken(TWITTER_ACCESS_TOKEN_URL);
            
            
/*            
            [02-Jan-2012 15:39:11] Array
            (
                [oauth_token] => 39279413-jNPO4eWvx7OMnO7dG26IzZERu6uakWwTiIqBDE4NN
                [oauth_token_secret] => 2ZGG1MCWKZ96Cv6NbLro6UwuEwcb4K1sptAXd1Q8zh8
                [user_id] => 39279413
                [screen_name] => tistre
            )
            */

            // Now you could go on, register or load your user account etc.

            
$html =
                
'<p>This is all the information Twitter sends to my site (don\'t worry, I won\'t track or use any of it):</p>'
                
'<pre>' htmlspecialchars(print_r($access_token_infotrue)) . '</pre>';

            
htmlOut($html);
        }
        catch (
OAuthException $E
        {
            
htmlOut('<p>An exception occurred: ' htmlspecialchars($E->getMessage()) . '</p>');
        }
    }
}


function 
htmlOut($html)
{
    
header('Content-Type: text/html; charset=UTF-8');

    
?>
    <html><head><title>Tim Strehle's "Sign in with Twitter" PHP OAuth Demo</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    </head><body><h3>Tim Strehle's "Sign in with Twitter" PHP OAuth Demo</h3>
    <?php echo $html?>
    <a href="twitter_auth_demo.phps">PHP source code for this demo</a>
    <br /><a href="auth_demo.html">"Sign in with ..." start page</a><br /><a href="/tim/">Home</a>
    <br /><a href="https://dev.twitter.com/docs/auth/sign-twitter">Twitter developer documentation</a>
   </body></html>

   <?php
}

?>