Saturday, 24 December 2011

How to retrieve contacts from gmail using php classes

After long search i found one solution to grab the gmail contacts using php classes.
This class can be used to grab the contact lists of an Gmail user.It can authenticate in Google with the user name and password of a given account. Then it can retrieve the contact lists from the Gmail user address book.The retrieved contact lists are parsed and returned as arrays.


GrabGmail .class



<?php   class GrabGmail
  
{
     
//To use it in PHP4, please replace each "private" by "var"
     
var $contactListArray = array();
     var 
$contactListTable;
     var 
$requireCaBundle false;
     var 
$caBundleFile;
     var 
$cookiePath;
     var 
$proxyUrl='';
     var 
$userId     ='';
     var 
$password   ='';
     var 
$url        "https://www.google.com/accounts/ServiceLoginAuth";
     var 
$refererUrl "https://www.google.com/accounts/ServiceLogin?service=mail&passive=true&rm=false&continue=http://mail.google.com/mail/?ui=html&zy=f&ltmpl=yj_blanco&ltmplcache=2&hl=en";

     
/**
     * Sets login information of Gmail account
     * @param user id and password
     * @return none
     */
     
function setLoginInfo($userId$password)
     {

        
$this->userId   $userId;
        
$this->password $password;

     }
//EO Method

     /**
     * Sets cookie save path(where cookie will be saved)
     * @param cookie path
     * @return none
     */
     
function setCookiePath($cookiePath)
     {
        
$this->cookiePath $cookiePath;
     }

     
/**
     * Sets proxy information if any
     * @param proxy URL
     * @return none
     */
     
function setProxy($proxyUrl)
     {
        
$this->proxyUrl $proxyUrl;
     }

     
/**
     * Sets Certificate Bundle File (this is necessary in accessing Gmail from localhost)
     * @param user id and password
     * @return none
     */
     
function setCaBundleFile($fileName)
     {
        
$this->requireCaBundle true;
        
$this->caBundleFile    $fileName//provide absolute path
     
}

     
/**
     * Checks whether proxy info is set
     * @param none
     * @return none
     */
     
function isProxy()
     {
        if(
$this->proxyUrl == '')
        {
           return 
false;
        }

        return 
true;

     }
//EO Method

     /**
     * Prepares contact list
     * @param none
     * @return none
     */
     
function prepareContactList()
     {

       if(
$this->userId == "" || $this->password=="")
       {
         die(
"Set Login Info");
       }
       else
       {
         
$this->postRequestToGmail();
       }

     }
//EO Method

     /**
     * Gets contact list in a table
     * @param none
     * @return Contact List Table
     */
     
function getResultTable()
     {
        if(!empty(
$this->contactListTable))
        {
           return 
$this->contactListTable;
        }
        else
        {
           return 
"List is Empty. Check your user id and password.";
        }
     }
//EO Method

     /**
     * Gets contact list in an array
     * @param none
     * @return Contact List Array
     */
     
function getResultArray()
     {
        if(
strlen($this->contactListTable)>33)
        {
           
$strValue $this->contactListTable;
           
$this->convertToArray($strValue);

           return 
$this->contactListArray;

        }
        else
        {
           return 
"List is Empty. Check your user id and password.";
        }
     }
//EO Method

     /**
     /** Modified On 05/25/07
     * Post request to Gmail, gets and parses contact list from Gmail
     * @param none
     * @return none
     */
     
function postRequestToGmail()
     {

        
$requestString  "service=mail&Email=".urlencode($this->userId)."&Passwd=".urlencode(str_replace(' ','+',$this->password))."&null=Sign%20in&continue=http%3A%2F%2Fmail.google.com%2Fmail%3F&rm=false&hl=en";
        
$user_agent     $_SERVER['HTTP_USER_AGENT'];
        
$cookie         1;
        
$cookieFileName md5($this->userId);

        
//setting cookie file. make sure the file has write permission
        
$cookieFileJar  = (isset($this->cookiePath))?($this->cookiePath"/" $cookieFileName) : ($_SERVER['DOCUMENT_ROOT'] . "/temp_dir/" $cookieFileName);

        
$cookieFile     $cookieFileJar;
        
$refererUrl     $this->refererUrl;

        
$c curl_init();
          
curl_setopt($cCURLOPT_URL$this->url);
          
curl_setopt($cCURLOPT_HEADER1);
          
curl_setopt($cCURLOPT_POST,   1);
          
//this referer tells Gmail that request is coming from Gmail
          
curl_setopt($cCURLOPT_REFERER$this->refererUrl);
          
curl_setopt($cCURLOPT_POSTFIELDS$requestString);

          
curl_setopt($cCURLOPT_RETURNTRANSFER1);

          
//Certificate information
        
if($this->requireCaBundle)
        {
          if(isset(
$this->caBundleFile))
          {
             
curl_setopt($cCURLOPT_CAINFO$this->caBundleFile);
          }
          else
          {
             die(
"Provide CA Bundle File");
          }
        }

        if(
$this->isProxy())
        {
           
curl_setopt($cCURLOPT_PROXY$this->proxyUrl);
          }

          
curl_setopt($cCURLOPT_SSL_VERIFYPEERFALSE);

          
curl_setopt($cCURLOPT_FOLLOWLOCATION1);
          
curl_setopt($cCURLOPT_USERAGENT$user_agent);

          
//writting cookie
          
curl_setopt($cCURLOPT_COOKIEJAR$cookieFileJar);
          
curl_setopt($cCURLOPT_COOKIE$cookie);

          
$res curl_exec($c);

          
curl_close($c);

        
$requestString ='http://mail.google.com/mail/h/ggggsdf/?v=cl&pnl=a&ui=html&zy=f';

        
//New curl session
        
$ch curl_init();

          
curl_setopt($chCURLOPT_URL$requestString);
          
curl_setopt($chCURLOPT_HEADER0);

          
curl_setopt($chCURLOPT_REFERER$refererUrl);
          
curl_setopt($chCURLOPT_RETURNTRANSFER1);

          
curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);

          
//Certificate information
        
if($this->requireCaBundle)
        {
          if(isset(
$this->caBundleFile))
          {
             
curl_setopt($chCURLOPT_CAINFO$this->caBundleFile);
          }
          else
          {
             die(
"Provide CA Bundle File");
          }
        }

        if(
$this->isProxy())
        {
           
curl_setopt($chCURLOPT_PROXY$this->proxyUrl);
          }

          
curl_setopt($chCURLOPT_FOLLOWLOCATION1);
           
curl_setopt($chCURLOPT_USERAGENT$user_agent);

           
//reading cookie
           
curl_setopt($chCURLOPT_COOKIEFILE$cookieFile);

           
curl_setopt($chCURLOPT_COOKIE$cookie);

          
$gmailResponse curl_exec($ch);

          
curl_close($ch);

          
$parsedResponse  $this->parseResponse($gmailResponse);

          
$this->contactListTable $parsedResponse;

     }
//EO Method

     /** Modified On 05/25/07
     * Converts table data to array data
     * @param Table of Contact List
     * @return Contact List Array
     */
     
function convertToArray($strValue)
     {
        
$strVal str_replace("&nbsp;","",$strValue);
        
$output = array();
        
$strVal nl2br($strVal);
        
$strVal str_replace("<br />",'',$strVal);

        
## added on 01/23/07
        
$strVal preg_replace("/<span[^>]*?>.*?<\/span>/si",""$strVal);
        
$matches1 preg_match_all("/<b>([^<]+)<\/b>/si",$strVal,$outputPREG_PATTERN_ORDER);
        
$offset = array();
        
$matches2 preg_match_all("/<td[^>]*>([a-zA-Z0-9_\.]+@[a-zA-Z0-9_\.]+)?([^<]*)<\/td>/si",$strVal,$offsetPREG_PATTERN_ORDER);

        
//putting values into associative array
        
for($i=0;$i<sizeof($offset[2]); $i++)
        {
             
$email trim($offset[2][$i]);
             
$name  $output[1][$i];
           
$this->contactListArray[$email] =$name;
        }

     }
//EO Method

     /**
     * Parses Gmail Response String
     * @param Gmail Response
     * @return Parsed Response
     */
     
function parseResponse($str)
     {
        
$str nl2br($str);
        
$str str_replace("<br />","",$str);
        
$str preg_replace("/<script[^>]*?>.*?<\/script>/si",""$str);
        
$off = array();
        
$matches preg_match_all("/<table[^>]*?>.*?<\/table>/si"$str$off,PREG_PATTERN_ORDER);
        
$strVal $off[0][6];

        return 
$strVal;

     }
//EO Method

     /**
     * Debugs dump/data
     * @param $dump
     * @return none
     */
     
function dBug($dump)
     {

        echo 
"<PRE>";
        
print_r($dump);
        echo 
"</PRE>";

     }
//EO Method

  
}//EO Class
?>
How to use it:

just call this class by using object and pass gmail username and password as arguments


<?php   require_once("GrabGmail.class.php");
  
  
$login 'yourgmailid';//without "@gmail.com"
  
$password 'yourgmailpassword';
  
$cookiePath '/path/to/cookie/dir';  

  
$obj = new GrabGmail();
  
$obj->setLoginInfo($login$password);
  
$obj->setCookiePath($cookiePath);
  
$obj->setProxy("proxy.proxydomain.com:port");
  
$obj->prepareContactList();
  
$obj->dBug("========== All Contacts of <b>$login@gmail.com</b> ==============");
  
$obj->dBug('---- Contacts in Table ------');
  
$resultTable $obj->getResultTable();
  
$obj->dBug($resultTable);
  
$obj->dBug('---- Contacts in Array ------');
  
$resultArray $obj->getResultArray();
  
$obj->dBug($resultArray);     ?>

No comments:

Post a Comment