Friday, October 1, 2010

Using Oauth-php to retrieve email addresses from Google contacts (Gmail) in Symfony

The below code is a modification of the example code from the Oauth-php project. The example is for getting the 3 legged OAuth access to Google Docs.

Here the code was modified to get email addresses from Google contacts. That are basically all the email address that are used in Gmail.

The code was integrated in the Symfony framework. To get it running on a single PHP page only use the stuff in the action.class.php.

Of oauth-php project only the files in the library folder where used and copied into the symfony-project-base/lib/oauth.

For the rest a module gmail in symfony-project-base/apps/frontend/modules was created.

Symfony version 1.4.8 and oauth-php version 155.

in the action.class.php

public function executeStart(){

include_once sfConfig::get('sf_lib_dir')."/oauth/OAuthStore.php";
include_once sfConfig::get('sf_lib_dir')."/oauth/OAuthRequester.php";

define("GOOGLE_CONSUMER_KEY", sfConfig::get("app_google_consumer_key", "myDomain.com")); //
define("GOOGLE_CONSUMER_SECRET", sfConfig::get("app_google_consumer_secret", "myConsumerKey")); //

define("GOOGLE_OAUTH_HOST", "https://www.google.com");
define("GOOGLE_REQUEST_TOKEN_URL", GOOGLE_OAUTH_HOST . "/accounts/OAuthGetRequestToken");
define("GOOGLE_AUTHORIZE_URL", GOOGLE_OAUTH_HOST . "/accounts/OAuthAuthorizeToken");
define("GOOGLE_ACCESS_TOKEN_URL", GOOGLE_OAUTH_HOST . "/accounts/OAuthGetAccessToken");

define('OAUTH_TMP_DIR', function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : realpath($_ENV["TMP"]));

//  Init the OAuthStore
$options = array(
'consumer_key' => GOOGLE_CONSUMER_KEY,
'consumer_secret' => GOOGLE_CONSUMER_SECRET,
'server_uri' => GOOGLE_OAUTH_HOST,
'request_token_uri' => GOOGLE_REQUEST_TOKEN_URL,
'authorize_uri' => GOOGLE_AUTHORIZE_URL,
'access_token_uri' => GOOGLE_ACCESS_TOKEN_URL
);


// Note: do not use "Session" storage in production. Prefer a database
// storage, such as MySQL.
OAuthStore::instance("Session", $options);

try
{
//  STEP 1:  If we do not have an OAuth token yet, go get one
if (empty($_GET["oauth_token"]))
{
$getAuthTokenParams = array('scope' =>
'http://www.google.com/m8/feeds/contacts/default/base',
'xoauth_displayname' => 'Oauth test',
'oauth_callback' => 'http://myDomain.com/gmail/start');

// get a request token
$tokenResultParams = OAuthRequester::requestRequestToken(GOOGLE_CONSUMER_KEY, 0, $getAuthTokenParams);

$this->redirect(GOOGLE_AUTHORIZE_URL . "?btmpl=mobile&oauth_token=" . $tokenResultParams['token']);
}
else {
//  STEP 2:  Get an access token
$oauthToken = $_GET["oauth_token"];

$tokenResultParams = $_GET;

try {
OAuthRequester::requestAccessToken(GOOGLE_CONSUMER_KEY, $oauthToken, 0, 'POST', $_GET);

}
catch (OAuthException2 $e)
{
var_dump($e);
// Something wrong with the oauth_token.
// Could be:
// 1. Was already ok
// 2. We were not authorized
return;
}
}
// STEP 3: make the contacts request. Default is 25 contacts per request, the max that worked for me is 32.
$nextUrl = "http://www.google.com/m8/feeds/contacts/default/base?max-results=32";
$emailList = "";
while($nextUrl != ""){
$request = new OAuthRequester($nextUrl, 'GET', $tokenResultParams);
$result = $request->doRequest(0);
if ($result['code'] == 200) {
$oXML = new SimpleXMLElement($result['body']);

$nextUrl = "";
//parse for next url
foreach($oXML->link as $link){
$linkAttributes = $link->attributes();
$nextFlag = $linkAttributes["rel"];
if($nextFlag == "next"){
$nextUrl = $linkAttributes["href"];
//                                    echo "nextUrl: ".$nextUrl."
";
//replace user id with default, because otherwise the next call fails
$endOfFirstPart = strrpos($nextUrl,"feeds/contacts/");
$startOfSecondPart = strrpos($nextUrl,"/base?");

$urlFirstPart = substr($nextUrl,0,$endOfFirstPart+15);
$urlSecondPart = substr($nextUrl,$startOfSecondPart,strlen($nextUrl));
$nextUrl = $urlFirstPart."default".$urlSecondPart;
//                                    echo "nextUrl: ".$nextUrl."
";
break;
}
}

//parse for email entries 
foreach($oXML->entry as $oEntry){
$gd = $oEntry->children("http://schemas.google.com/g/2005");
foreach($gd->email as $emailNode){
$attributeArray = $emailNode->attributes();
$emailList = $emailList.$attributeArray["address"].",\n";
}
}
}
else {
echo 'Error';
}
}
$this->resultList = $emailList;
}
catch(OAuthException2 $e) {
echo "OAuthException:  " . $e->getMessage();
var_dump($e);
}
return sfView::SUCCESS;
}

in the template startSuccess.php

Show Gmail contacts

<?php echo $resultList; ?>

in the routing.yml

gmailStart:
url:    /gmail/start/*.
param:  { module: gmail, action: start }

0 comments:

Post a Comment