Location: PHPKode > scripts > SEOstats > SEOstats/class.seostats.php
<?php
/*
 ======================================================================
 SEOstats  v1.2.3
  
 Powerful PHP class including 22 functions to get SEO Statistics
 from tracking services by google, majesticseo, yahoo and alexa

 Copyright (C) 2010 Stephan Schmitz, www.php-co.de, hide@address.com

 THANKS TO
 tech163 for contributing with:
 http://fusionswift.com/blog/2010/04/google-pagerank-script-in-php/

 Latest version, features, manual and examples:
 http://seostats.php-co.de/
 
 Live demo:
 http://seostats.php-co.de/preview/
 ----------------------------------------------------------------------
 CHANGELOG
 v1.2.3       18.12.2010    * fixed function PageRank
 v1.2.2       17.12.2010    * improved function AlexaGlobalRank
                              * pure numeric result
                              * no more html in output
                            * improved function AlexaCountryRank
                              * pure numeric result
                              * no more html in output
                            * improved Alexa Stats and Trend functions
                              * no more html wrapped output
                              * returns results as array
 v1.2.1       09.12.2010    * fixed function GoogleLinks
 v1.2         01.12.2010    * added new Google functions
                              * GoogleIndexDetails
                              * GoogleLinkDetails
                              * GoogleMentions
                            * introduced global var $google_tld
                              * used in all google functions
                              * if not defined = com
                            * enhanced function GoogleIndex
                              * No longer requires an API Key
                            * enhanced function GoogleLinks
                              * No longer requires an API Key
 v1.1         29.10.2010    * added Yahoo functions
                              * YahooLinks
                              * YahooLinkDetails
 v1.0.3       19.10.2010    * fixed function AlexaCountryRank
 v1.0.2       19.10.2010    * added function PageRank
 v1.0.1       19.10.2010    * added function cURL
 ----------------------------------------------------------------------
 ======================================================================
*/
/*
 ======================================================================
 LICENSE

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License (GPL)
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.

 To read the license please visit http://www.gnu.org/copyleft/gpl.html
 ======================================================================
*/

class SEOstats {
// -------------------------------------------------------------------
// CLASS VARS
// -------------------------------------------------------------------
    var $domain;              // Domain to check
    var $google_tld = 'com';  // Google TLD (for Google functions)
    var $period  = '1';       // Date Range in months (for alexa stats & graph)
    var $type  = '1';         // Graph type (for alexa graph)
    var $w = '660';           // Width of graph (for alexa graph)
    var $h = '330';           // Height of Graph (for alexa graph)
// -------------------------------------------------------------------
// PRIVATE FUNCTIONS
// -------------------------------------------------------------------
    // -------------------------------------------------------------------
    // Private Function cURL
    // -------------------------------------------------------------------
    private function cURL($target){
      // -------------------------------------------------------------------
      // Save result page to string using curl
      // -------------------------------------------------------------------
      $ch = curl_init();
      curl_setopt($ch,CURLOPT_URL,$target);
      curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
      curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
      $str = curl_exec($ch);
      curl_close($ch);
      return $str;   
    } // End of private cURL
    // -------------------------------------------------------------------
    // Private Function to return result page as string
    // -------------------------------------------------------------------
    private function google($exec){
      // -------------------------------------------------------------------
      // Extract data
      // -------------------------------------------------------------------
      $url = 'http://www.google.'.$this->google_tld.'/custom?num=1&q='.$exec.':'.urlencode($this->domain);
      $str = $this->cURL($url);
      $tmp1 = explode('<td align=right nowrap>',$str);
      $tmp2 = explode('<b>',$tmp1[1]);
      $tmp3 = explode('</b>',$tmp2[3]);
      // -------------------------------------------------------------------
      // Return string
      // -------------------------------------------------------------------
      return $tmp3[0];
    } // End of private function google
    // -------------------------------------------------------------------
    // Private Function to return detailed results from Google SERP's
    // -------------------------------------------------------------------
    private function googleDetails($q){
      // -------------------------------------------------------------------
      // External classes
      // -------------------------------------------------------------------
      include_once("ext/snoopy.class.php");
      include_once("ext/htmlsql.class.php");
      // -------------------------------------------------------------------
      // Scrape Google SERP's
      // -------------------------------------------------------------------
      $results = array ();
      $pages = 2;
      for($start=1;$start<=$pages;$start++){
        $url = 'http://www.google.'.$this->google_tld.'/custom?q='.$q.'&num=100'.(($start == 1) ? '' : '&start='.$start.'00');
        $wsql = new htmlsql();
        $wsql->connect('url', $url);
        $wsql->query('SELECT * FROM a WHERE $class == "l"');
        $row = $wsql->fetch_array();
        $wsql2 = new htmlsql();
        $wsql2->connect('url', $url);
        $wsql2->query('SELECT * FROM table WHERE $border == "0"');
        $row2 = $wsql2->fetch_array();
        // -------------------------------------------------------------------
        // Write results array
        // -------------------------------------------------------------------
        for($i=0;$i<sizeof($row);$i++){
          $x = $i+3;
          $str = explode('<br>',$row2[$x]['text']);
          $desc = strip_tags($str[0]);
          $results[] = array('url' => $row[$i]['href'],
                             'title' => strip_tags(utf8_encode($row[$i]['text'])),
                             'description' => utf8_encode($desc));
        }
        // -------------------------------------------------------------------
        // Check if there's a next page. If so, the for-loop will restart
        // -------------------------------------------------------------------
        $str = $this->cURL($url);
        if (preg_match('/<div id=nn><\/div>/i', $str)){
          $next = 1;
        } else{ $next = 0; }
        $pages = (($next == 1) ? $pages+1 : $pages-1);
      }
      // -------------------------------------------------------------------
      // Return array
      // -------------------------------------------------------------------
      return $results;
    } // End of private function googleDetails
    // -------------------------------------------------------------------
    // Private Function to return result page as string
    // -------------------------------------------------------------------
    private function yahooBL(){
      // -------------------------------------------------------------------
      // Save yahoo result page to string using curl
      // -------------------------------------------------------------------
      $str = $this->cURL('http://search.yahooapis.com/SiteExplorerService/V1/inlinkData?appid=oVFwwjnV34GEEZTLB3K_WW1YC9_VysYbCYQ4szoXTAHZscrDvMazUpFR7TR0wchmlA--&results=1&output=json&query=http://'.urlencode($this->domain));
      // -------------------------------------------------------------------
      // Decode JSON response
      // -------------------------------------------------------------------
      $data = json_decode($str);
      // -------------------------------------------------------------------
      // Return int
      // -------------------------------------------------------------------
      return intval($data->ResultSet->totalResultsAvailable);   
    } // End of private function yahooBL
    // -------------------------------------------------------------------
    // Private Function to return detailed backlink data from yahoo
    // -------------------------------------------------------------------
    private function yahooLl(){
      // -------------------------------------------------------------------
      // Save yahoo result page to string using curl
      // -------------------------------------------------------------------
      $str = $this->cURL('http://search.yahooapis.com/SiteExplorerService/V1/inlinkData?appid=oVFwwjnV34GEEZTLB3K_WW1YC9_VysYbCYQ4szoXTAHZscrDvMazUpFR7TR0wchmlA--&results=100&output=json&query=http://'.urlencode($this->domain));
      // -------------------------------------------------------------------
      // Decode JSON response
      // -------------------------------------------------------------------
      $data = json_decode($str);
      // -------------------------------------------------------------------
      // Write results array
      // -------------------------------------------------------------------
      $result = array();
      for ($i=0;$i<sizeof($data->ResultSet->Result);$i++){
        $result []= array(
                    'URL' => $data->ResultSet->Result[$i]->Url,
                    'Anchortext' => $data->ResultSet->Result[$i]->Title
        );
      }
      // -------------------------------------------------------------------
      // Return array
      // -------------------------------------------------------------------
      return $result;   
    } // End of private function yahooLl
    // -------------------------------------------------------------------
    // Private Function to return result page as string
    // -------------------------------------------------------------------
    private function alexa(){
      // -------------------------------------------------------------------
      // Save alexa result page to string using curl
      // -------------------------------------------------------------------
      $str = $this->cURL('http://www.alexa.com/siteinfo/'.$this->domain);
      // -------------------------------------------------------------------
      // Correct image paths
      // -------------------------------------------------------------------
      $str = str_replace('/images/', 'http://www.alexa.com/images/', $str);
      // -------------------------------------------------------------------
      // Return string
      // -------------------------------------------------------------------
      return $str;    
    } // End of private function alexa
    // -------------------------------------------------------------------
    // Private Function to return result page as string
    // -------------------------------------------------------------------
    private function majestic(){
      // -------------------------------------------------------------------
      // Save Majestic SEO result page to string using curl
      // -------------------------------------------------------------------
      $str = $this->cURL('http://www.majesticseo.com/reports/search?folder=&q='.$this->domain);
      // -------------------------------------------------------------------
      // Return string
      // -------------------------------------------------------------------
      return $str;    
    } // End of private function alexa
    // -------------------------------------------------------------------
    // Private Function to extract data using htmlsql and snoopy class
    // -------------------------------------------------------------------
    private function extractSingle($tag,$atr,$id,$site,$val){
      // -------------------------------------------------------------------
      // External classes
      // -------------------------------------------------------------------
      include_once("ext/snoopy.class.php");
      include_once("ext/htmlsql.class.php");
      // -------------------------------------------------------------------
      // Extract information
      // -------------------------------------------------------------------
      $wsql = new htmlsql();
      if (!$wsql->connect('string', $this->$site())){
        print 'Error while connecting: ' . $wsql->error;
        exit;
      }
      if (!$wsql->query('SELECT * FROM '.$tag.' WHERE $'.$atr.' == "'.$id.'"')){
        print "Query error: " . $wsql->error; 
        exit;
      }
      $row = $wsql->fetch_array();      
      // -------------------------------------------------------------------
      // Return string
      // -------------------------------------------------------------------
      return $row[$val]['text'];
    } // End of private function extractSingle
    // -------------------------------------------------------------------
    // Private Function to extract data using htmlsql and snoopy class
    // -------------------------------------------------------------------
    private function extractMulti($tag,$atr,$id,$site){
      // -------------------------------------------------------------------
      // External classes
      // -------------------------------------------------------------------
      include_once("ext/snoopy.class.php");
      include_once("ext/htmlsql.class.php");
      // -------------------------------------------------------------------
      // Extract information
      // -------------------------------------------------------------------
      $wsql = new htmlsql();
      if (!$wsql->connect('string', $this->$site())){
        print 'Error while connecting: ' . $wsql->error;
        exit;
      }
      if (!$wsql->query('SELECT * FROM '.$tag.' WHERE $'.$atr.' == "'.$id.'"')){
        print "Query error: " . $wsql->error; 
        exit;
      }     
      $r = array ();   
      foreach($wsql->fetch_array() as $row){
        array_push($r, $row['text']);
      }
      // -------------------------------------------------------------------
      // Return Array
      // -------------------------------------------------------------------
      return $r;
    } // End of private function extractMulti
    // -------------------------------------------------------------------
    // Private Function to build array output off of alexa html return
    // -------------------------------------------------------------------
    private function alextract($tmp){
      $tmpArr = explode('</td>',$tmp);
      $value1 = trim(str_replace('1 month','',strip_tags($tmpArr[3])));
      $change1 = trim(strip_tags($tmpArr[4]));
      $value3 = trim(str_replace('3 month','',strip_tags($tmpArr[6])));
      $change3 = trim(strip_tags($tmpArr[7]));
      $month1 = array('value' => $value1, 'change' => $change1);
      $month3 = array('value' => $value3, 'change' => $change3);
      $return = array('1 Month' => $month1,'3 Months' => $month3);
      return $return;
    } // End of private function alextract
    // -------------------------------------------------------------------
    // Private Function to generate the hash off of an URL
    // -------------------------------------------------------------------
    private function genhash ($url){
      $hash = 'Mining PageRank is AGAINST GOOGLE\'S TERMS OF SERVICE. Yes, I\'m talking to you, scammer.';
      $c = 16909125;
      $length = strlen($url);
      $hashpieces = str_split($hash);
      $urlpieces = str_split($url);
      for ($d = 0; $d < $length; $d++){
        $c = $c ^ (ord($hashpieces[$d]) ^ ord($urlpieces[$d]));
        $c = $this->zerofill($c, 23) | $c << 9;
      }
      return '8' . $this->hexencode($c);
    } // End of private function genhash
    // -------------------------------------------------------------------
    // Private Function zerofill
    // -------------------------------------------------------------------
    private function zerofill($a, $b){
      $z = hexdec(80000000);
      if ($z & $a){
        $a = ($a>>1);
        $a &= (~$z);
        $a |= 0x40000000;
        $a = ($a>>($b-1));
      } else{
        $a = ($a>>$b);
      }
      return $a;
    } // End of private function zerofill
    // -------------------------------------------------------------------
    // Private Function hexencode
    // -------------------------------------------------------------------
    private function hexencode($str){
      $out  = $this->hex8($this->zerofill($str, 24));
      $out .= $this->hex8($this->zerofill($str, 16) & 255);
      $out .= $this->hex8($this->zerofill($str, 8 ) & 255);
      $out .= $this->hex8($str & 255);
      return $out;
    } // End of private function hexencode
    // -------------------------------------------------------------------
    // Private Function hex8
    // -------------------------------------------------------------------
    private function hex8 ($str) {
      $str = dechex($str);
      (strlen($str) == 1 ? $str = '0' . $str: null);
      return $str;
    } // End of private function hex8
    // -------------------------------------------------------------------
    // Private Function to get the google page rank
    // -------------------------------------------------------------------
    private function PR(){
      $googleurl = 'http://toolbarqueries.google.com/search?features=Rank&sourceid=navclient-ff&client=navclient-auto-ff&googleip=O;66.249.81.104;104&ch='.$this->genhash($this->domain).'&q=info:'.urlencode($this->domain);
      $out = $this->cURL($googleurl);
      return substr($out, 9);
    } // End of private function PR
// -------------------------------------------------------------------
// PUBLIC FUNCTIONS
// -------------------------------------------------------------------
    // -------------------------------------------------------------------
    // Public Function to get indexed sites at google
    // -------------------------------------------------------------------
    public function PageRank(){
      return $this->PR();
    } // End of function GoogleIndex
    // -------------------------------------------------------------------
    // Public Function to get indexed sites at google
    // -------------------------------------------------------------------
    public function GoogleIndex(){    
      return $this->google('site');      
    } // End of function GoogleIndex
    // -------------------------------------------------------------------
    // Public Function to get Details about indexed sites at google
    // -------------------------------------------------------------------
    public function GoogleIndexDetails(){
      $q = urlencode('site:'.$this->domain);
      return $this->googleDetails($q);
    } // End of function GoogleIndexDetails
    // -------------------------------------------------------------------
    // Public Function to get indexed backlinks at google
    // -------------------------------------------------------------------
    public function GoogleLinks(){    
      return $this->google('link');      
    } // End of function GoogleLinks
    // -------------------------------------------------------------------
    // Public Function to get Details about indexed backlinks at google
    // -------------------------------------------------------------------
    public function GoogleLinkDetails(){
      $q = urlencode('link:'.$this->domain);
      return $this->googleDetails($q);
    } // End of function GoogleLinkDetails
    // -------------------------------------------------------------------
    // Public Function to get Details about indexed backlinks at google
    // -------------------------------------------------------------------
    public function GoogleMentions(){
      $q = urlencode('"'.$this->domain.'"');
      return $this->googleDetails($q);
    } // End of function GoogleMentions
    // -------------------------------------------------------------------
    // Public Function to get indexed backlinks from yahoo
    // -------------------------------------------------------------------
    public function YahooLinks(){    
      return $this->yahooBL();      
    } // End of function YahooLinks
    // -------------------------------------------------------------------
    // Public Function to get detailed backlink data from yahoo
    // -------------------------------------------------------------------
    public function YahooLinkDetails(){    
      return $this->yahooLl();      
    } // End of function YahooLinkDetails
    // -------------------------------------------------------------------
    // Public Function to get the indexed URL's (from majesticseo.com)
    // -------------------------------------------------------------------
    public function IndexedURLs(){
      $array = $this->extractMulti('td','align','right','majestic');    
      return trim($array[1]);      
    } // End of function IndexedURLs
    // -------------------------------------------------------------------
    // Public Function to get the backlinks (from majesticseo.com)
    // -------------------------------------------------------------------
    public function Backlinks(){
      $array = $this->extractMulti('td','align','right','majestic');
      $return = explode('<br>',$array[2]);  
      return $return[0];      
    } // End of function Backlinks
    // -------------------------------------------------------------------
    // Public Function to get the backlinks (from majesticseo.com)
    // -------------------------------------------------------------------
    public function BacklinkDomains(){
      $array = $this->extractMulti('td','align','right','majestic');
      $return = explode('<br>',$array[3]);  
      return $return[0];      
    } // End of function BacklinkDomains
    // -------------------------------------------------------------------
    // Public Function to get the backlinks (from majesticseo.com)
    // -------------------------------------------------------------------
    public function BacklinkIPs(){
      $array = $this->extractMulti('td','align','right','majestic');
      $return = explode('<br>',$array[4]);  
      return $return[0];      
    } // End of function BacklinkIPs
    // -------------------------------------------------------------------
    // Public Function to get the global Alexa traffic rank
    // -------------------------------------------------------------------
    public function AlexaGlobalRank(){    
      $tmp = $this->extractSingle('div','class','data up','alexa','0');
      $return = strip_tags($tmp);
      return $return;
    } // End of function AlexaGlobalRank
    // -------------------------------------------------------------------
    // Public Function to get the global Alexa traffic rank
    // -------------------------------------------------------------------
    public function AlexaCountryRank(){
      $tmp = $this->extractSingle('div','class','data','alexa','1');
      $return = strip_tags($tmp);
      return $return;
    } // End of function AlexaCountryRank
    // -------------------------------------------------------------------
    // Public Function to get the daily traffic rank trend stats
    // -------------------------------------------------------------------
    public function TrafficRankTrend(){
      $tmp = $this->extractSingle('div','id','rank','alexa','0');
      $return = $this->alextract($tmp);
      return $return;
    } // End of function DailyTrafficRankTrend
    // -------------------------------------------------------------------
    // Public Function to get the daily pageviews stats
    // -------------------------------------------------------------------
    public function Pageviews(){
      $tmp = $this->extractSingle('div','id','pageviews','alexa','0');
      $return = $this->alextract($tmp);
      return $return;
    } // End of function DailyPageviews    
    // -------------------------------------------------------------------
    // Public Function to get the daily pageviews per user stats
    // -------------------------------------------------------------------
    public function PageviewsPerUser(){
      $tmp = $this->extractSingle('div','id','pageviews_per_user','alexa','0');
      $return = $this->alextract($tmp);
      return $return;
    } // End of function DailyPageviewsPerUser
    // -------------------------------------------------------------------
    // Public Function to get the reach stats
    // -------------------------------------------------------------------
    public function Reach(){
      $tmp = $this->extractSingle('div','id','reach','alexa','0');
      $return = $this->alextract($tmp);
      return $return;
    } // End of function Reach
    // -------------------------------------------------------------------
    // Public Function to get the bounce rate stats
    // -------------------------------------------------------------------
    public function BounceRate(){
      $tmp = $this->extractSingle('div','id','bounce','alexa','0');
      $return = $this->alextract($tmp);
      return $return;
    } // End of function BounceRate
    // -------------------------------------------------------------------
    // Public Function to get the time on site stats
    // -------------------------------------------------------------------
    public function TimeOnSite(){
      $tmp = $this->extractSingle('div','id','time_on_site','alexa','0');
      $return = $this->alextract($tmp);
      return $return;
    } // End of function TimeOnSite
    // -------------------------------------------------------------------
    // Public Function to get the search visit stats
    // -------------------------------------------------------------------
    public function SearchVisits(){
      $tmp = $this->extractSingle('div','id','search','alexa','0');
      $return = $this->alextract($tmp);
      return $return;
    } // End of function SearchVisits
    // -------------------------------------------------------------------
    // Public Function to write statistics as graph -> returns html string
    // -------------------------------------------------------------------
    public function writeGraph(){
      // -------------------------------------------------------------------
      // Define graph type
      // -------------------------------------------------------------------  
      switch($this->type) {
                                case 1:
          $type = 't'; // Daily traffic rank trend                              
                                        break;
                                case 2:
          $type = 'p'; // Daily pageviews (percent)                                     
                                        break;
                                case 3:
          $type = 'u'; // Daily pageviews per user                                      
                                        break;
                                case 4:
          $type = 's'; // Time on site (minutes)                                        
                                        break;
                                case 5:
          $type = 'b'; // Bounce rate (percent)                                 
                                        break;
                                case 6:
          $type = 'q'; // Search visits (percent)                                       
                                        break;
                                default:break;
      }
      // -------------------------------------------------------------------
      // Build html output
      // -------------------------------------------------------------------    
      $graph = '<img src="http://traffic.alexa.com/graph?&w='.$this->w.'&h='.$this->h.'&o=f&c=1&y='.$type.'&b=ffffff&n=666666&r='.$this->period.'m&u='.$this->domain.'" />';
      return $graph;
    } // End of function writeGraph
} // End of class SEOStats v1.2.3 by Stephan Schmitz @ http://seostats.php-co.de/
?>
Return current item: SEOstats