<?php

class GoogleService
{

    private $site;
    private $_source;
    private $pageStatistic = false;
    private $googleData = [
        'google_pagerank'          => -1,
        'google_index_count'       => -1,
        'google_backlink_count'    => -1,
        'google_image_index_count' => -1,
        'google_page_speed_score'  => -1,
        'google_adsense_id'        => '',
        'google_analytics_id'      => '',
        'google_is_banned'         => -1,
    ];

    public function __construct($site, $source)
    {
        $this->site = $site;
        $this->_source = $source;
    }

    public function get()
    {
        $this->getIndexCount();
        $this->getBacklinkCount();
        $this->getImageCount();
        $this->getPageStatistic('score');
        $this->getAdsenseId();
        $this->getAnalyticsId();
        $this->isBanned();
        $this->getPageRank();

        return $this->googleData;
    }

    public function isBanned()
    {

        $apiResponse = file_get_contents_curl('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=info:' . $this->site);

        if (!$apiResponse) {
            return false;
        }

        $apiResponse = json_decode($apiResponse);

        if (!$apiResponse) {
            return false;
        }

        if ($apiResponse->responseStatus != 200) {
            return false;
        }

        if (!isset($apiResponse->responseData->cursor->estimatedResultCount)) {
            $this->googleData['google_is_banned'] = 1;
        }else{
            $this->googleData['google_is_banned'] = 0;
        }

        return true;
    }

    public function getIndexCount()
    {

        $apiResponse = file_get_contents_curl('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site:' . $this->site);

        if (!$apiResponse) {
            return false;
        }

        $apiResponse = json_decode($apiResponse);

        if (!$apiResponse) {
            return false;
        }

        if ($apiResponse->responseStatus != 200) {
            return false;
        }

        if (isset($apiResponse->responseData->cursor->estimatedResultCount)) {
            $this->googleData['google_index_count'] = $apiResponse->responseData->cursor->estimatedResultCount;

        }else{
            $this->googleData['google_index_count'] = 0;
        }

        return true;
    }

    public function getImageCount()
    {

        $apiResponse = file_get_contents_curl('http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=site:' . $this->site);

        if (!$apiResponse) {
            return false;
        }

        $apiResponse = json_decode($apiResponse);

        if (!$apiResponse) {
            return false;
        }

        if ($apiResponse->responseStatus != 200) {
            return false;
        }

        if (isset($apiResponse->responseData->cursor->estimatedResultCount)) {
            $this->googleData['google_image_index_count'] = $apiResponse->responseData->cursor->estimatedResultCount;
        }else{
            $this->googleData['google_image_index_count'] = 0;
        }

        return true;
    }

    public function getBacklinkCount()
    {

        $apiResponse = file_get_contents_curl('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=link:' . $this->site);

        if (!$apiResponse) {
            return false;
        }

        $apiResponse = json_decode($apiResponse);

        if (!$apiResponse) {
            return false;
        }

        if ($apiResponse->responseStatus != 200) {
            return false;
        }

        if (isset($apiResponse->responseData->cursor->estimatedResultCount)) {
            $this->googleData['google_backlink_count'] = $apiResponse->responseData->cursor->estimatedResultCount;
        }else{
            $this->googleData['google_backlink_count'] = 0;
        }

        return true;
    }

    public function getPageStatistic($val = 'score')
    {

        if (!$this->pageStatistic) {

            $data = file_get_contents_curl('https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=http://' . $this->site);

            if(! $data){
                return false;
            }
            $this->pageStatistic = json_decode($data);
        }

        if (!isset($this->pageStatistic->$val) && !isset($this->pageStatistic->pageStats->$val)) {
            return false;
        }

        if ($val == 'score') {
            $this->googleData['google_page_speed_score'] = $this->pageStatistic->score;
            return true;
        }

        return $this->pageStatistic->pageStats->$val;
    }

    public function getAdsenseId()
    {
        preg_match('/\"ca-pub-(.*?)\"/mis', $this->_source, $match);

        if (!$match) {
            preg_match('/\"pub-(.*?)\"/mis', $this->_source, $match);
        }

        if ($match) {
            $this->googleData['google_adsense_id'] = str_replace('"', '', $match[0]);
        }

        return true;
    }

    public function getAnalyticsId()
    {
        preg_match("/\'UA-(.*?)\'/mis", $this->_source, $match);

        if (!$match) {
            preg_match('/\"UA-(.*?)\"/mis', $this->_source, $match);
        }

        if ($match) {
            $this->googleData['google_analytics_id'] = str_replace(['"', "'"], ['', ''], $match[0]);
        }

        return true;
    }

    public function getPageRank()
    {

        $f_str_to_num = create_function('$str, $check, $magic', '
		$int_32_unit = 4294967296;
		$length = strlen($str);

		for($i = 0; $i < $length; $i++) {
			$check *= $magic;

			if($check >= $int_32_unit) {
				$check = ($check - $int_32_unit * (int) ($check / $int_32_unit));
				$check = ($check < -2147483648) ? ($check + $int_32_unit) : $check;
			}

			$check += ord($str{$i});
		}

		return $check;
	');

        $f_hash_url = create_function('$str', '
		$f_str_to_num = "' . $f_str_to_num . '";
		$check1 = $f_str_to_num($str, 0x1505, 0x21);
		$check2 = $f_str_to_num($str, 0, 0x1003F);

		$check1 >>= 2;
		$check1 = (($check1 >> 4) & 0x3FFFFC0 ) | ($check1 & 0x3F);
		$check1 = (($check1 >> 4) & 0x3FFC00 ) | ($check1 & 0x3FF);
		$check1 = (($check1 >> 4) & 0x3C000 ) | ($check1 & 0x3FFF);
		$t1 = (((($check1 & 0x3C0) << 4) | ($check1 & 0x3C)) <<2 ) | ($check2 & 0xF0F );
		$t2 = (((($check1 & 0xFFFFC000) << 4) | ($check1 & 0x3C00)) << 0xA) | ($check2 & 0xF0F0000 );

		return ($t1 | $t2);
	');

        $f_check_hash = create_function('$hashNum', '
		$check_byte = 0;
		$flag = 0;
		$hash_str = sprintf("%u", $hashNum);
		$length = strlen($hash_str);

		for($i = $length - 1; $i >= 0; $i--) {
			$re = $hash_str{$i};

			if(1 === ($flag % 2)) {
				$re += $re;
				$re = (int)($re / 10) + ($re % 10);
			}

			$check_byte += $re;
			$flag ++;
		}

		$check_byte %= 10;

		if(0 !== $check_byte) {
			$check_byte = 10 - $check_byte;

			if(1 === ($flag % 2) ) {
				if(1 === ($check_byte % 2))
					$check_byte += 9;

				$check_byte >>= 1;
			}
		}

		return "7".$check_byte.$hash_str;
	');

        $checksum = $f_check_hash($f_hash_url($this->site));

        // Request the page PageRank
        $request_url = sprintf(
            'http://%s/tbr?client=navclient-auto&ch=%s&ie=UTF-8&oe=UTF-8&features=Rank&q=info:%s',
            'toolbarqueries.google.com',
            $checksum,
            urlencode($this->site)
        );

        if (($c = file_get_contents_curl($request_url)) === false)
            return false;
        else if (empty($c))
            return false;
        else
            $this->googleData['google_pagerank'] = intval(substr($c, strrpos($c, ':') + 1));

        return true;
    }


} 