Location: PHPKode > scripts > LinkMeIn > linkmein/class.LinkMeIn.php
<?php
/*------------------------------------------------------
 LinkMeIn - LinkedIn Contact List to Array or XML
 
 Version 1.0, Created 04/24/2007
 
 This class is used to fetch LinkedIn Contact List and
 parse it to an XML file

 Copyright (C) 2007 Ehsanul Haque

 License: GPL
------------------------------------------------------*/

/**
 * LinkMeIn - LinkedIn Contact List to XML
 * @package LinkMeIn
 * @license GPL
 * @copyright (C) 2007 Ehsanul Haque
 * @version 1.0
 * @created 04/24/2007
 * @author Ehsanul Haque 
 */
 
class LinkMeIn
{
  /*-------------------------------------------------------
  Public Variables
  -------------------------------------------------------*/
  /**
  * LinkedIn Account Username
  * @public
  * @var string
  */
  var $login              = "";

  /**
  * LinkedIn Account Password
  * @public
  * @var string
  */  
  var $password           = "";

  /**
  * Sets the output format
  * - For Array format : array
  * - For XML format : xml
  * - Default : array
  * @public
  * @var string
  */  
  var $outputFormat       = "array";
  
  /**
  * Abosolute path to save the cookie
  * Default value is DOCUMENT_ROOT
  * @public
  * @var string
  */
  var $cookieJarPath      = "";
  
  /**
  * Abosulte path to the CA Bundle file
  * SSL Certificate required to verify CA cert
  * Usually required when script ran on Localhost
  * Remote servers may not require 
  * Default value is false
  * @public
  * @var string
  */
  var $caBundleFile       = "";

  /**
  * Specifies if Proxy server required as Gateaway
  * Default value is false
  * @public
  * @var boolean
  */  
  var $isUsingProxy       = false;
                          
  /**                     
  * Proxy host name       
  * @public               
  * @var string          
  */                      
  var $proxyHost          = "";
                          
  /**                     
  * Proxy port number     
  * @public               
  * @var int             
  */                      
  var $proxyPort          = 0;

  /*-------------------------------------------------------
  Private Variables
  -------------------------------------------------------*/
  /**
  * URL to Authenticate user on LinkedIn
  * @private
  * @var string
  */
  var $authUrl            = "https://www.linkedin.com/secure/login";

  /**
  * URL for the desired Service
  * @private
  * @var string
  */                          
  var $serviceUrl         = "http://www.linkedin.com/addressBookExport";

  /**
  * User agent (used to trick LinkedIn)
  * @private
  * @var string
  */
  var $userAgent          = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";

  /**
  * Referer URL (used to trick LinkedIn)
  * @private
  * @var string
  */
  var $referer            = "http://www.linkedin.com";

  /**
  * Specifies whether output includes the header
  * @private
  * @var int
  */
  var $showHeader         = 0;

  /**
  * Specifies if cURL should follow the redirected URL
  * @private
  * @var int
  */
  var $follow             = 0;

  /**
  * Specifies if cURL should return the output as string
  * @private
  * @var int
  */
  var $returnTransfer     = 1;

  /**
  * Specifies if cURL should verify peer certificate
  * @private
  * @var int
  */  
  var $sslVerifyPeer      = 0;
  
  /**
  * Specifies number of post fields to pass
  * @private
  * @var int
  */                          
  var $numPostField       = 0;

  /**
  * Specify fields to send via POST method as key=value
  * @private
  * @var string
  */
  var $postFields         = "";

  /**
  * File where output is temporarily saved during authentication
  * @private
  * @var string
  */
  var $authOutputFile     = "";

  /**
  * File where service output is temporarily saved 
  * @private
  * @var string
  */
  var $outputFile         = "";

  /**
  * File where Cookie is temporarily saved 
  * @private
  * @var string
  */                          
  var $cookieFileJar      = "";

  /**
  * Cookie File that is read by service process
  * This carries same value as $cookieFileJar
  * @private
  * @var string
  */
  var $cookieFile         = "";

  /**
  * Specifies if Cookie is to be in header
  * @private
  * @var int
  */
  var $cookie             = 0;

  /**
  * Proxy address as proxy.host:port
  * @private
  * @var string
  */
  var $proxy              = "";

  /**
  * Error Information set by either cURL or Internal process
  * @private
  * @var string
  */
  var $errorInfo          = "";

  /**
  * Output of Contact List
  * @private
  * @var array
  */
  var $list               = array(); 
  
  /**
  * Sets the Cookie Jar File where Cookie is temporarily saved
  * @return void
  */
  function setCookieJar()
  {
    // Sets the encrypted cookie filename using LinkedIn account username
    $this->cookieFilename = MD5($this->login);
    
    // Sets the Cookie Jar filename with an absolute path
    $this->cookieFileJar  = (!empty($this->cookieJarPath)) ? $this->cookieJarPath . "/" . $this->cookieFilename : $_SERVER['DOCUMENT_ROOT'] . "/" . $this->cookieFilename;
    
    fopen($this->cookieFileJar, "w");
  }

  /**
  * Initializes cURL session
  * @return void
  */  
  function initCurl()
  {
    $this->curlSession    = curl_init();
  }

  /**
  * Sets cURL options
  * @return boolean
  */  
  function setCurlOption() 
  {
    // Sets the User Agent  
    curl_setopt($this->curlSession, CURLOPT_USERAGENT, $this->userAgent);
    
    // Sets the HTTP Referer
    curl_setopt($this->curlSession, CURLOPT_REFERER, $this->referer);
    
    // Sets the URL that PHP will fetch using cURL
    curl_setopt($this->curlSession, CURLOPT_URL, $this->url);
    
    // Sets the number of fields to be passed via HTTP POST
    curl_setopt($this->curlSession, CURLOPT_POST, $this->numPostField);
    
    // Sets the fields to be sent via HTTP POST as key=value
    curl_setopt($this->curlSession, CURLOPT_POSTFIELDS, $this->postFields);
    
    // Sets the filename where cookie information will be saved
    curl_setopt($this->curlSession, CURLOPT_COOKIEJAR, $this->cookieFileJar);
    
    // Sets the filename where cookie information will be looked up
    curl_setopt($this->curlSession, CURLOPT_COOKIEFILE, $this->cookieFile);
    
    // Sets the option to set Cookie into HTTP header
    curl_setopt($this->curlSession, CURLOPT_COOKIE, $this->cookie);

    // Checks if the user needs proxy (to be set by user)
    if ($this->isUsingProxy) 
    { 
      // Checks if the proxy host and port is specified
      if ((empty($this->proxyHost)) || (empty($this->proxyPort)))
      { 
        $this->setError("proxy_required");
        $this->unlinkFile($this->cookieFileJar);
        return false;
      }
     
      // Sets the proxy address as proxy.host:port
      $this->proxy          = $this->proxyHost . ":" . $this->proxyPort;
    }
        
    // Sets the proxy server as proxy.host:port
    curl_setopt($this->curlSession, CURLOPT_PROXY, $this->proxy);
    
    // Sets the filename where output will be temporarily saved
    curl_setopt($this->curlSession, CURLOPT_RETURNTRANSFER, $this->returnTransfer);
    
    // Sets to false if the authentication URL is a secured server address
    curl_setopt($this->curlSession, CURLOPT_SSL_VERIFYPEER, $this->sslVerifyPeer);
    
    curl_setopt($this->curlSession, CURLOPT_FOLLOWLOCATION, $this->follow);
    
    return true;
  }

  /**
  * Executes the Service
  * @param string $login Username of user's LinkedIn Account
  * @param string $password Password of the user's LinkedIn Account
  * @return array|false
  */  
  function execService($login, $password)
  {
    $login      = trim($login);
    $password   = trim($password);
    
    if (empty($login)) 
    {
      $this->setError("provide_login");
      return false;
    }
    
    if (empty($password)) 
    {
      $this->setError("provide_pass");
      return false;
    }
    
    $this->login      = $login;
    $this->password   = $password;
    
    //$this->setServiceUrl();
    
    // Instructs to authenticate user on LinkedIn
    $this->auth       = $this->doAuthentication();
    
    if ($this->auth)
    {
      // Instructs to fetch output if Authenticated
      $this->getServiceOutput();
      
      return $this->serviceOutput;
    }
  }

  /**
  * Authenticates user on LinkedIn
  * @return boolean
  */
  function doAuthentication()
  {
    // Instructs to initialize cURL session
    $this->initCurl();
    
    // Sets the URL for authentication purpose
    $this->url              = $this->authUrl;
    
    // Sets the number of fields to send via HTTP POST
    $this->numPostField     = 4;
    
    // Sets the fields to be sent via HTTP POST as key=value
    $this->postFields       = "session_key=$this->login&session_password=$this->password&session_login=&session_rikey=invalid key";
    
    // Instructs to set Cookie Jar
    $this->setCookieJar();
          
    // Checks if the cURL options are all set properly
    if ($this->setCurlOption())
    {
      // Instructs to execute cURL session
      $this->execCurl();

      // Checks if any cURL error is generated
      if ($this->getCurlError())
      {
        $this->unlinkFile($this->cookieFileJar);
        $this->setError("curl_error");
        return false;
      }

      // Checks if the authentication failed, either invalid login or username is not registered
      if ((preg_match("/invalid/i", $this->outputContent)) || (preg_match("/not yet taken/i", $this->outputContent)))
      {
        // Instructs to close cURL session
        $this->closeCurl();
        
        // Unlinks the cookie file
        $this->unlinkFile($this->cookieFileJar);
        
        $this->setError("invalid_login");
        return false;
      }
      
      $this->closeCurl();
    }

    unset($this->outputContent);
    
    return true;
  }

  /**
  * Sets the Service Output
  * @return void
  */  
  function getServiceOutput()
  {  
    $this->showHeader     = 0;
    $this->follow         = 1;
    $this->serviceOutput  = $this->processContactList(); 
    
    $this->unlinkFile($this->cookieFileJar);
  }

  /**
  * Processes LinkedIn Contact List
  * @return array|xml|false
  */
  function processContactList()
  {
    $this->initCurl();
    $this->url              = $this->serviceUrl;
    $this->numPostField     = 1;
    $this->postFields       = "outputType=microsoft_outlook&exportNetwork=";
    $this->cookieFile       = $this->cookieFileJar;
    $this->outputFile       = "addressBook." . md5($this->login) . ".txt";
    $this->fileHandler      = fopen($this->outputFile, "w");
    
    if ($this->setCurlOption())
    {
      $this->execCurl();
      fwrite($this->fileHandler, $this->outputContent);      
      unset($this->outputContent);
      $this->closeCurl();
      fclose($this->fileHandler);
      
      // Sets the service output as an array
      $fileContentArr       = file($this->outputFile);
      
      // Sets the contact list column headings
      $abColumnHeadLine     = trim($fileContentArr[0]);
      $abColumnHeadLine     = str_replace("\"", "", $abColumnHeadLine);
      
      // Sets the contact list column headings into an array
      $abColumnHeadArr      = explode(",", $abColumnHeadLine);
      
      // Unsets the heading line from the file content array
      unset($fileContentArr[0]);
      
      foreach ($fileContentArr as $key => $value)
      {
        // Sets the contact list list individually
        $listColumnLine     = trim($value);
        
        // Sets the individual list into an array
        $listColumnArr      = explode("\",\"", $listColumnLine);
        
        // Iterates through each item of individual address in the list
        foreach ($listColumnArr as $listColumnKey => $listColumnValue)
        {
          // Sets the column heading as key
          $listKey          = $abColumnHeadArr[$listColumnKey];
          $listColumnValue = str_replace("\"", "", trim($listColumnValue));
          
          if ($listKey && $listColumnValue)
          {
            // Sets the value for the key respectively
            $list_[$listKey]  = htmlentities($listColumnValue);
          }
        }
        
        // Sets the contact list list in an array
        $this->list[]             = $list_;
      }
      
      $this->unlinkFile($this->outputFile);

      if ($this->outputFormat == "xml")
      {
        return $this->getXML();
      }
      else
      {      
        return $this->list;      
      }
    }    
  }

  /**
  * Processes XML
  * @return xml
  */
  function getXML()
  {
    header("Content-type: text/xml; charset=UTF-8");
    
    echo '<?xml version="1.0" encoding="UTF-8" ?>';
    echo "
      <rss version=\"2.0\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">
        <channel>
        <title>My LinkedIn Contact List</title>
        <language>en-us</language>    
    ";
    
    if ($this->list)
    {
      foreach ($this->list as $key => $value)
      {
        echo "<address id=\"$key\">\n";
        
        foreach ($value as $dataKey => $dataValue)
        {
          $thisTag      = str_replace("'", "", str_replace(" ", "_", strtolower($dataKey)));
          echo "<" . $thisTag . ">" . $dataValue . "</" . $thisTag . ">\n";  
        }
        
        echo "</address>\n";
      }  
    }
    
    echo "
        </channel>
      </rss>        
    ";      
  }
  
  /**
  * Executes cURL Session
  * @return void
  */  
  function execCurl()
  {
    $this->outputContent    = curl_exec($this->curlSession);  
  }

  /**
  * Closes cURL session
  * @return void
  */  
  function closeCurl()
  {
    curl_close($this->curlSession); 
    unset($this->curlSession); 
  }

  /**
  * Unlinks any given file
  * @return void
  */  
  function unlinkFile($fileToUnlink)
  {
    if (file_exists($fileToUnlink))
    {
      unlink($fileToUnlink);
    }
  }

  /**
  * Sets any cURL error generated
  * @return boolean
  */  
  function getCurlError()
  {
    $this->curlError    = curl_error($this->curlSession);
    
    return (!empty($this->curlError)) ? true : false;
  }
  
  /**
  * Sets Error Information
  * @return void
  */  
  function setError($error) 
  {
    $msg  = (!empty($error)) ? $this->getErrorInfo($error) : null;
    $this->errorCount++;
    $this->errorInfo = $msg;
  }

  /**
  * Provides the Error message
  * @param string $error Error code for which error message is generated
  * @return string
  */  
  function getErrorInfo($error) 
  {
    switch ($error) 
    {
      case 'provide_service'    : $msg  = "Must specify a Service"; break;
      
      case 'provide_login'      : $msg  = "Must provide Login name"; break;
                                
      case 'provide_pass'       : $msg  = "Must provide Password"; break;
                                
      case 'provide_ca'         : $msg  = "Must provide a SSL Certificate to verfiy CA cert"; break;
                                
      case 'proxy_required'     : $msg  = "Must provide both Proxy host and port"; break;
                                
      case 'invalid_login'      : $msg  = "Login information incorrect"; break;
                                
      case 'curl_error'         : $msg  = $this->curlError; break;
    }
    
    return $msg;
  }
}
?>
Return current item: LinkMeIn