<?php
class GoogleRank {
  
  private $_phrase;
  private $_url;
  private $_localization;
  private $_results;
  private $_num;
  private $_start;
  private $_i;
  
  function __construct( $_phrase, $_url, $_localization, $_num = 10, $_start = 0, $_i ) 
  {
    $this -> _phrase            = $_phrase;
    $this -> _url               = $_url;
    $this -> _localization      = $_localization;
    $this -> _num               = $_num;
    $this -> _start             = $_start;
    $this -> _i                 = $_i;
  }
  
  public static function uule( $city ) 
  {
    $secretkey = array_merge(range('A','Z'), range('a','z'), range('0','9'), array('-', '_'));
    return trim('w+CAIQICI'.$secretkey[strlen($city)%count($secretkey)].base64_encode($city), '=');
  }

  public function getRankProxy()
  {
    global $db, $mdb, $mdb_2;
    
    $headers    = [
                    'Accept-Language: pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7',
                    'Pragma: no-cache',
                    'Cache-control: no-cache',
                    'Upgrade-insecure-requests: 1',
                    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
                  ];
    
    $results = $mdb_2 -> query( 'SELECT '
                                    . 'id, proxy, bg '
                                  . 'FROM '
                                    . 'pro_proxy_servers '
                                  . 'WHERE '
                                      . 'enabled = 1 '
                                    . 'AND '
                                      . '( bgd < NOW() OR bgd IS NULL ) '
                                  . 'ORDER BY '
                                    . 'used ASC '
                                  . 'LIMIT 1' ) -> fetchAll();
    if ( is_array( $results ) and !empty( $results ) )
    {
      foreach ( $results as $row )
      {
        $google = 'phrase=' . trim( $this -> _phrase ) . '&num=' . $this -> _num . '&start=' . $this -> _start;
        
        $curl = curl_init();
        curl_setopt( $curl, CURLOPT_URL, $row['proxy'] );
        curl_setopt( $curl, CURLOPT_POST, true );
        curl_setopt( $curl, CURLOPT_POSTFIELDS, 'action=check_rank&' . $google . '&localization=' . trim( $this -> _localization ) );
        curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0' );
        curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 10 );
        curl_setopt( $curl, CURLOPT_TIMEOUT, 10 );
        curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt( $curl, CURLOPT_ENCODING, "gzip,deflate" );
        $result   = curl_exec( $curl );
        $speed    = curl_getinfo( $curl, CURLINFO_TOTAL_TIME );
        $retcode  = curl_getinfo( $curl, CURLINFO_HTTP_CODE ); 
        curl_close( $curl );
        if ( !$result or $retcode == 404 )
        {
          $mdb_2 -> query( 'UPDATE pro_proxy_servers SET used = NOW(), bg = ' . ( $row['bg'] + 1 ) . ', bgd = DATE_ADD( NOW(), INTERVAL ( bg + 1 ) * 15 MINUTE ) WHERE id = ' . $row['id'] );
          return -1;
        }

        if ( 
                strpos( $result, 'Google' ) == false 
              or
                strpos( $result, 'Our systems have detected unusual traffic' ) !== false
              or 
                strpos( $result, 'Forbidden' ) !== false
              or
                strpos( $result, 'Aby kontynuowa' ) !== false
              or
                strpos( $result, 'Our systems have detected unusual traffic' ) !== false
              or
                strpos( $result, 'sending automated queries' ) !== false
              or
                strpos( $result, 'Thatâ€™s an error' ) !== false
              or
                strpos( $result, 'Nasze systemy wykryĹ‚y nietypowy ruch pochodzÄ…cy z Twojej siec' ) !== false
            )
        {
          $mdb_2 -> query( 'UPDATE pro_proxy_servers SET used = NOW(), bg = ' . ( $row['bg'] + 1 ) . ', bgd = DATE_ADD( NOW(), INTERVAL ( bg + 1 ) * 15 MINUTE ), speed = \'' . $speed . '\'  WHERE id = ' . $row['id'] );
          return -1;
        }
        
        $mdb_2 -> query( 'UPDATE pro_proxy_servers SET used = NOW(), bg = 0, speed = \'' . $speed . '\'  WHERE id = ' . $row['id'] );
      }
    }
    else
    {
      $results2 = $mdb -> query( 'SELECT '
                                    . 'id, proxy, userpasswd '
                                  . 'FROM '
                                    . 'pro_proxy '
                                  . 'WHERE '
                                      . 'is_banned = 0 '
                                  . 'ORDER BY '
                                    . 'last_used ASC '
                                  . 'LIMIT 1' ) -> fetchAll();
      if ( is_array( $results2 ) and !empty( $results2 ) ) {
        foreach ( $results2 as $row ) {
          
          $google = 'phrase=' . trim( $this -> _phrase ) . '&num=' . $this -> _num . '&start=' . $this -> _start;

          $curl = curl_init();
          curl_setopt( $curl, CURLOPT_URL, 'http://www.rank24.pl/monitoring.php' );
          curl_setopt( $curl, CURLOPT_POST, true );
          curl_setopt( $curl, CURLOPT_POSTFIELDS, 'action=check_rank&' . $google . '&localization=' . trim( $this -> _localization ) . '&proxy=' . $row['proxy'] . '&userpasswd=' . $row['userpasswd'] );
          curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
          curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0' );
          curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 10 );
          curl_setopt( $curl, CURLOPT_TIMEOUT, 10 );
          curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
          curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );  
          curl_setopt( $curl, CURLOPT_ENCODING, "gzip,deflate" ); 
          $result   = curl_exec( $curl );
          $speed    = curl_getinfo( $curl, CURLINFO_TOTAL_TIME );
          $retcode  = curl_getinfo( $curl, CURLINFO_HTTP_CODE ); 
          curl_close( $curl );
          if ( !$result or $retcode == 404 )
          {
            $mdb -> query( 'UPDATE pro_proxy SET last_used = NOW(), is_banned = 1, banned_count = ' . ( $row['banned_count'] + 1 ) . ', banned_date = DATE_ADD( NOW(), INTERVAL ( banned_count + 1 ) * 15 MINUTE ) WHERE id = ' . $row['id'] );
            return -1;
          }

          if ( 
                  strpos( $result, 'Google' ) == false 
                or
                  strpos( $result, 'Our systems have detected unusual traffic' ) !== false
                or 
                  strpos( $result, 'Forbidden' ) !== false
                or
                  strpos( $result, 'Aby kontynuowa' ) !== false
                or
                  strpos( $result, 'Our systems have detected unusual traffic' ) !== false
                or
                  strpos( $result, 'sending automated queries' ) !== false
                or
                  strpos( $result, 'Thatâ€™s an error' ) !== false
                or
                  strpos( $result, 'Nasze systemy wykryĹ‚y nietypowy ruch pochodzÄ…cy z Twojej siec' ) !== false
              )
          {
            $mdb -> query( 'UPDATE pro_proxy SET last_used = NOW(), is_banned = 1, banned_count = ' . ( $row['banned_count'] + 1 ) . ', banned_date = DATE_ADD( NOW(), INTERVAL ( banned_count + 1 ) * 15 MINUTE ) WHERE id = ' . $row['id'] );
            return -1;
          }

          $mdb -> query( 'UPDATE pro_proxy SET last_used = NOW(), is_banned = 0  WHERE id = ' . $row['id'] );
        }
      } else
        return -1;
    }
    
    $this -> _results = self::parse_urls( $result );
    $site_details = $this -> searchUrl();
    return $site_details;
  }
  
  public static function parse_urls( $result, $zennoposter = false )
  {
    $results = array();
    
    $doc = new DOMDocument();
    $doc -> loadHTML( $result );

    $div  = $doc -> getElementById( 'res' );
    
    /* do sprawdzenia */
    if ( $div == null )
    {
      file_put_contents( 'google-rank.txt', $result );
      return false;
    }
    
    $div_g_array = $div -> getElementsByTagName( 'div' );
    foreach ( $div_g_array as $div_a  )
    {
      if ( $div_a -> getAttribute( 'class' ) == 'g' or $div_a -> getAttribute( 'class' ) == '_gt' or $div_a -> getAttribute( 'class' ) == 'g mnr-c g-blk' or strpos( $div_a -> getAttribute( 'class' ), 'uMdZh' ) !== false )
      {
        if ( $div_a -> getAttribute( 'class' ) == 'g' or $div_a -> getAttribute( 'class' ) == 'g mnr-c g-blk' )
        {
          $div2_a = $div_a -> getElementsByTagName( 'div' );
          foreach ( $div2_a as $div2 )
          {
            if ( $div2 -> getAttribute( 'class' ) == 'r' )
            {
              $a_a = $div2 -> getElementsByTagName( 'a' );
              foreach ( $a_a as $a )
              {
                if ( $a -> getAttribute( 'class' ) == '' )
                {
                  unset( $row );

                  $row['type'] = 'organic';
                  $row['href'] = $a -> getAttribute( 'href' );

                  $results[] = $row;
                }
              }
            }
          }
        }
        else if ( $div_a -> getAttribute( 'class' ) == '_gt' )
        {
          $a_a = $div_a -> getElementsByTagName( 'a' );
          foreach ( $a_a as $a )
          {
            if ( strpos( $a -> getAttribute( 'class' ), '_Jrh' ) !== false )
            {
              unset( $row );

              $row['type'] = 'map';
              $row['href'] = $a -> getAttribute( 'href' );

              $results[] = $row;
            }
          }
        }
        
        if ( strpos( $div_a -> getAttribute( 'class' ), 'uMdZh' ) !== false )
        {
          $a_a = $div_a -> getElementsByTagName( 'a' );
          foreach ( $a_a as $a )
          {
            if ( strpos( $a -> getAttribute( 'class' ), 'L48Cpd' ) !== false )
            {
              unset( $row );

              $row['type'] = 'map';
              $row['href'] = $a -> getAttribute( 'href' );

              $results[] = $row;
            }
          }
        }
      }
    }
//    \S::pre( $results ); exit;
    return $results;
  }
  
  function searchUrl()
  {
    $site_details = array();    
    $i            = $this -> _i;
    
    if ( is_array( $this -> _results ) ) foreach ( $this -> _results as $res )
    {
      if ( self::getHost( $res['href'] ) == self::getHost( 'http://' . $this -> _url ) && !$site_details['position'] )
      {
        $site_details['url'] = $res['href'];
        
        if ( $res['type'] == 'map' )
          $site_details['map']  = true;
        else
          $site_details['map']  = false;
        
        $site_details['position'] = $i;
      }
      $i++;
    }
    
    if ( !$site_details['map'] )
    {
      $i = $this -> _i;
      $site_details['position'] = 0;
      
      if ( is_array( $this -> _results ) ) foreach ( $this -> _results as $res )
      {
        if ( self::getHost( $res['href'] ) == self::getHost( 'http://' . $this -> _url ) && !$site_details['position'] )
        {
          $site_details['href']     = $res['href'];
          $site_details['map']      = false;
          $site_details['position'] = $i;
        }
        
        if ( $res['type'] != 'map' )
          $i++;
      }
    }
    
    return $site_details;
  }
  
  function deleteMapFromResults()
  {
    if ( is_array( $this -> _results ) ) foreach ( $this -> _results as $res )
    {
      if ( $res['type'] == 'organic' )
        $results_tmp[] = $res;
    }
    $this -> _results = $results_tmp;
  }
  
  function getHost( $page ) 
	{
    $page = parse_url( $page, PHP_URL_HOST );
    $page = str_replace( "www.", "", $page );
    return $page;
	}
}
?>
