Skip to content

Instantly share code, notes, and snippets.

@erikeldridge
Created April 23, 2010 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikeldridge/376134 to your computer and use it in GitHub Desktop.
Save erikeldridge/376134 to your computer and use it in GitHub Desktop.
A util to do the OAuth dance and make signed requests using the YQL OAuth table
<?php
// Demonstrates how to use the OAuthMonkey by authorizing access to Twitter & Yahoo!, and making a signed request for Twitter secure data.
// usage: put this file in the same directory as OauthMonkey.php and load it in a browser
// license: http://gist.github.com/375593
require 'YqlOauthMonkey.php';
$twitter = new YqlOauthMonkey( array(
//get your key/secret from http://dev.twitter.com/apps
'consumerKey' => 'sdBSJ6gTkRG9cfm554Xg',
'consumerSecret' => 'sUS9RpPVNoeDpyasdrwvE3cj5PBGeexkwWZP2bQ9E',
'requestTokenUri' => 'https://api.twitter.com/oauth/request_token',
'accessTokenUri' => 'https://api.twitter.com/oauth/access_token',
'authorizeUri' => 'https://api.twitter.com/oauth/authorize'
) );
$d = $twitter->makeRequest( array( 'uri' => 'http://api.twitter.com/1/users/show.json?user_id=14092513' ) );
print_r($d);
?>
<?php
// A util to do the OAuth dance and make signed requests using the YQL OAuth table (github.com/yql/yql-tables/raw/master/oauth/oauth.xml)
// usage: create an object above wherever you'll need to make a request, if the user doesn't have an token, it'll do the dance to get one, and store it in a cookie
// example: see the example.php file below
// license: http://gist.github.com/375593
class YqlOauthMonkey {
function __construct ( $params ) {
$this->params = $params;
$requestTokenName = md5( 'oauthMonkeyRequestToken'.$params['consumerKey'] );
$accessTokenName = md5( 'oauthMonkeyAccessToken'.$params['consumerKey'] );
//get input
$filters = array(
'oauth_verifier' => FILTER_SANITIZESTRING,
'oauth_token' => FILTER_SANITIZESTRING,
'oauthMonkeyReset' => FILTER_SANITIZESTRING,
$requestTokenName => FILTER_SANITIZESTRING,
$accessTokenName => FILTER_SANITIZESTRING
);
$input = filter_var_array( $_REQUEST, $filters );
//clear cookies if reset flag passed in
if ($input['oauthMonkeyReset']) {
setcookie( $accessTokenName, "", time() - 3600 );
setcookie( $requestTokenName, "", time() - 3600 );
$uri = $params['callbackUri'] ? $params['callbackUri'] : 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
header( "Location: $uri" );
}
//if access token
if ( $input[ $accessTokenName ] ) {
$this->accessToken = json_decode( stripslashes( $input[ $accessTokenName ] ) );
$time = time();
//if can expire and is expired, refresh it
$expired = isset( $this->accessToken->oauthMonkeyExpireTime )
&& $this->accessToken->oauthMonkeyExpireTime < time();
if ( !$expired ) {
return $this;
}
//kludge: only send necessary params cause yql clams up in the presence of strangers
$results = $this->makeRequest( array(
'uri' => $params['accessTokenUri'],
'sessionHandle' => $this->accessToken->oauth_session_handle
) );
if ( !$results ) {
throw new Exception( 'no access token info returned' );
}
parse_str( $results, $this->accessToken );
$this->accessToken['oauthMonkeyExpireTime'] = $time + $this->accessToken['oauth_expires_in'];
//store access token
setcookie( $accessTokenName, json_encode( $this->accessToken ) );
//printf('<pre>%s</pre>', print_r($this->accessToken, true));
//if stored request token & token in url, we're in redirect after auth
} elseif ( $input['oauth_token'] && $input[ $requestTokenName ] ) {
$token = json_decode( stripslashes( $input[ $requestTokenName ] ) );
$time = time();
//kludge: only send necessary params cause yql clams up in the presence of strangers
$results = $this->makeRequest( array(
'token' => $token->oauth_token,
'tokenSecret' => $token->oauth_token_secret,
'uri' => $params['accessTokenUri'],
'verifier' => $input['oauth_verifier'] ? $input['oauth_verifier'] : ''
) );
if ( !$results ) {
throw new Exception( 'no access token info returned'.print_r($query, true) );
}
parse_str( $results, $this->accessToken );
//calc expiration, if given
if ( isset( $this->accessToken['oauth_expires_in'] ) ) {
$this->accessToken['oauthMonkeyExpireTime'] = $time + $this->accessToken['oauth_expires_in'];
}
//store access token as new cookie so we can test for existence of access token above
setcookie( $accessTokenName, json_encode( $this->accessToken ) );
//delete req token
setcookie( $requestTokenName, "", time() - 3600 );
// if there's no stored req token, get one & redirect to auth
} elseif ( !$input[ $requestTokenName ] ) {
//kludge: only send necessary params cause yql clams up in the presence of strangers
$results = $this->makeRequest( array(
'uri' => $params['requestTokenUri'],
'callbackUri' => $params['callbackUri'] ? $params['callbackUri'] : 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
) );
if ( !$results ) {
throw new Exception( 'no request token info returned' );
}
parse_str( $results, $token );
//store req token
setcookie( $requestTokenName, json_encode( $token ) );
//redirect
header( sprintf( "Location: %s?oauth_token=%s", $params['authorizeUri'], $token['oauth_token'] ) );
exit();
}
return $this;
}
function yql( $query ) {
$params = array(
'q' => $query,
'debug' => 'true',
'diagnostics' => 'true',
'format' => 'json',
'callback' => ''
);
$url = 'https://query.yahooapis.com/v1/public/yql?'.str_replace( '+', '%20', http_build_query( $params ) );
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$json = curl_exec( $ch );
$response = json_decode( $json );
curl_close( $ch );
return $response;
}
function makeRequest ( $params ) {
$params['consumerKey'] = $this->params['consumerKey'];
$params['consumerSecret'] = $this->params['consumerSecret'];
if ($this->accessToken) {
$params['token'] = $this->accessToken->oauth_token;
$params['tokenSecret'] = $this->accessToken->oauth_token_secret;
}
// build query
$query = 'use "http://github.com/yql/yql-tables/raw/master/oauth/oauth.xml" as table; select * from table where ';
foreach( $params as $key => $val ){
$query_params[] = sprintf( '%s="%s"', $key, $val );
}
$query .= implode( ' and ', $query_params );
$results = $this->yql( $query );//printf('<pre>%s</pre>', print_r($params, true));
if ( !$results ) {
throw new Exception( 'nothing returned' );
}
return $results->query->results;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment