28 November, 2010

Codeigniter Library for getting Gmail Contact List

Today i needed to get the gmail contact list for a project that i am doing in codeigniter. For this is thought of making a library, so that it can be used easily. So, here in the complete library class fr getting gmail contact list.

if (!defined('BASEPATH')) exit('No direct script access allowed');

class GmailContacts_lib {

var $FEED_URL = "http://www.google.com/m8/feeds/contacts/default/full";
var $LOGIN_URL = "https://www.google.com/accounts/ClientLogin";
var $username;
var $passwd;
var $postData = array();

function GmailContacts_lib($gUsername, $gPassword) {
//constructor function
$this->username = $gUsername;
$this->passwd = $gPassword;
}

function get_gmail_contacts() {
$emailLists = array();
//create an array for post data
$this->postData = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => $this->username,
"Passwd" => $this->passwd,
"service" => "cp",
"source" => "anything"
);
//initialize the curl object
$curl = curl_init($this->LOGIN_URL);
//set the curl options
$this->set_curl_options($curl, CURLOPT_POST, true);
$this->set_curl_options($curl, CURLOPT_POSTFIELDS, $this->postData);
$this->set_curl_options($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
$this->set_curl_options($curl, CURLOPT_SSL_VERIFYPEER, false);
$this->set_curl_options($curl, CURLOPT_RETURNTRANSFER, 1);

//following variable contains the responses
$response = curl_exec($curl);

//check if the user has logged in sucessfully
//and save auth key if logged in
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
if( !empty($auth)) {
$headers = array("Authorization: GoogleLogin auth=".$auth);

//make the request to google contacts feed with the auth key maximum contacts is 10000
$curl1 = curl_init($this->FEED_URL);

//passing the headers of auth key
$this->set_curl_options($curl1, CURLOPT_HTTPHEADER, $headers);
//return the result in a variable
$this->set_curl_options($curl1, CURLOPT_RETURNTRANSFER, 1);

//results response
$feed = curl_exec($curl1);
//parse the feed and return email list array
$emailLists = $this->parse_response($feed);
}
else {
$emailLists = array("Invalid Username/Password");
}
return $emailLists;
}

//function to set curl options
function set_curl_options($ch, $option, $value) {
//make the post TRUE
return curl_setopt($ch, $option, $value);
}

//function to parse response
public function parse_response($feed) {
$contacts = array();
$doc = new DOMDocument();

//load the XML response
$doc->loadXML($feed);
//check the entry tag
$nodeList = $doc->getElementsByTagName( 'entry' );

foreach($nodeList as $node) {
//children of each entry tag
$entry_nodes = $node->childNodes;
$tempArray = array();

foreach($entry_nodes as $child) {
//get the tagname of the child
$domNodesName = $child->nodeName;
switch($domNodesName) {
case "title":
{ $tempArray['fullName'] = $child->nodeValue; }
break;
case "gd:email":
{
if (strpos($child->getAttribute('rel'),'home')!==false)
$tempArray['email_1']=$child->getAttribute('address');
elseif(strpos($child->getAttribute('rel'),'work')!=false)
$tempArray['email_2']=$child->getAttribute('address');
elseif(strpos($child->getAttribute('rel'),'other')!==false)
$tempArray['email_3']=$child->getAttribute('address');
}
break;
} //end of switch for nodeNames
} //end of foreach for entry_nodes child nodes
if( !empty($tempArray['email_1'])) $contacts[$tempArray['email_1']] = $tempArray;
if( !empty($tempArray['email_2'])) $contacts[$tempArray['email_2']] = $tempArray;
if( !empty($tempArray['email_3'])) $contacts[$tempArray['email_3']] = $tempArray;
}
return $contacts;
}
}

And thats it. Hope this helps someone like me.

18 comments:

Kamoor said...

Nice work..But it is returning only 25 contacts ..You know why

Sudhir Bastakoti said...

Hi,
I'm getting all of my contacts list using the code, and it should work as defined in google contacts api. Replace the feed URL by https://www.google.com/m8/feeds/contacts/your_gmail_address/full, and check once, if it works or not.

Kamoor said...

It worked for me..there is a query string you can pass max-results=xxx which will limit the max contacts
Thanks for your help

Friends World said...

Hi,
Nice Work.....But it is returning only 25 contacts

but i use feed URL https://www.google.com/m8/feeds/contacts/your_gmail_address/full i have getting an error like

A PHP Error was encountered

Severity: Warning

Message: DOMDocument::loadXML() [function.DOMDocument-loadXML]: Empty string supplied as input

Filename: libraries/GmailContacts_lib.php

Line Number: 77

but i use this feed url
http://www.google.com/m8/feeds/contacts/your_gmail_address/full

i have getting only 25 contacts

you know why?

Thanks for ur help

Friends World said...

Nice work..But it is returning only 25 contacts

but i have use feed url like

https://www.google.com/m8/feeds/contacts/your_gmail_address/full

i have getting an error like

A PHP Error was encountered

Severity: Warning

Message: DOMDocument::loadXML() [function.DOMDocument-loadXML]: Empty string supplied as input

Filename: libraries/GmailContacts_lib.php

Line Number: 77


but i have use feed url like

http://www.google.com/m8/feeds/contacts/your_gmail_address/full

i have getting only 25 contacts

you know why?

Thanks for ur help

Sudhir Bastakoti said...

Hi, by default to google contact feed shows less results, if you want to get all your contacts then you can add a parameter max-results to some maximim number ,
like,
http://www.google.com/m8/feeds/contacts/your_gmail_address/full?max-results=99999

daniel said...

Hello! How can I use this library? Is it possible to use it to import contacts and to send to them some invitations? I tried to use but it throws some errors like..
Severity: Warning

Message: Missing argument 2 for GmailContacts_lib::GmailContacts_lib(), called in /xxx/libraries/Loader.php on line 928 and defined

Filename: libraries/GmailContacts_lib.php

Line Number: 11

and
Severity: Notice

Message: Undefined variable: gPassword

Filename: libraries/GmailContacts_lib.php

Line Number: 14

Sudhir Bastakoti said...

Hi Daniel,
Thanks for your comment. Well you load the GmailContacts library providing your gmail username and password as parameter.
It will return with array of your gmail contacts list.

For now this library can only be used to get all your contact lists from gmail. You will have to write more code to send invitations for the contacts lists fetched using this library.
Thanks

Unknown said...

Hi Sudhir,

I am quite new with PHP, please could you post an simple example on how I can use your GmailContacts_lib Class?

Thank you very much,

Sergio.

Sergio Cutrera said...

Hi Sudhir,

I am quite new with PHP, please could you post a simple PHP code on how to your your GmailContacts_lib Class?

Thank you very much,

Sergio.

Sergio Cutrera said...

Hi Sudhir,

Please, could you post a simple PHP code on how to your your GmailContacts_lib Class?

Thank you very much,

Sergio

Sergio Cutrera said...

Hi Sudhir,

Just FYI, I tried the following code:
username";

$oResult = array();

$oResult = $oGmailContacts->get_gmail_contacts();

$oContacts = array();

$oContacts = $oGmailContacts->parse_response($oResult);

print "oContacts: $oContacts";

?>

But I got the following error:

start new oGmailContacts created : cuthbertlincoln
Warning: DOMDocument::loadXML() expects parameter 1 to be string, array given in C:\xampp\htdocs\CRMOD2\GmailContactsClass.php on line 78
oContacts: Array

Thanks, Sergio.

Sudhir Bastakoti said...

Hi Sergio,
Sorry for late response. You can use this library as follows:
In a function in your controller do:

$config = array("your_gmail_username", "your_gmail_password");
$this->load->library('GmailContacts', $config);
$gmailContactsList = $this->gmailcontacts->get_gmail_contacts();

print_r($gmailContactsList);

joylifeclue said...

hi Sudhir,

i am getting error like this, how do i fix it. please help me. thanks

A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: libraries/GmailContacts_lib.php
Line Number: 39
Array ( [0] => Invalid Username/Password )

Sudhir Bastakoti said...

That's most probably because you might have provided wrong email/password for your gmail account. As i tested the code and its working fine for me.

Unknown said...

Hi,
am getting the following error

Fatal error: Call to undefined function curl_init() in D:\xampp\htdocs\ukulima.net\application\libraries\GmailContacts.php on line 29

Thenks

Sudhir Bastakoti said...

@alex::
that means your cURL extension does not seem to be enabled. In order to enable it, Go to your php.ini file and remove the semicolon (;) mark from the beginning of the line: ;extension=php_curl.dll
and be sure to restart your Apache after you make this change. Hope that helps

Anonymous said...

When I tried to import contact, some times its showing correct records for some gmail id. But for some ids its showing invalid in a popup.