<?php 
/**
 * @author Lukas Goldschmidt / lukas.goldschmidt@googlemail.com 
 * @name Google image search and cache
 * Take a wikipedia page title and return a jsonp wrapped object of thumbnails
 * cache results on the way
 * */
//error_reporting(E_ALL);
//ini_set('display_errors', '1');
 $enable_jsonp = true;
 $Conf["db_server"]="localhost";
 $Conf["db_name"]="image_cache";
 $Conf["db_user"]="image_cache_user";
 $Conf["db_pass"]="user_image_cache";
 
/**
 * our target servers
 */
 $google_servers = array(
	"http://images.google.co.in/",
	"http://images.google.co.uk/",
	"http://images.google.it/",
	"http://images.google.at/",
	"http://images.google.de/",
	"http://images.google.hu/",
	"http://images.google.nl/",
	"http://images.google.fi/",
	"http://images.google.no/",
	"http://images.google.pl/",
	"http://images.google.ru/",
	"http://images.google.es/",
	"http://images.google.fr/",
	"http://images.google.se/",
	"http://images.google.sk/"
);
 
 
 
 
/**
 * make the search url 
 */
function createGoogleUrl($imagesOf,$numberOfImages) {
	global $google_servers;
	$numberOfPages = abs(($numberOfImages/20));
	$j=0;
	for($i=0; $i<$numberOfPages; $i++ ) {
		$thegoogle=$google_servers[rand(0,count($google_servers)-1)];
		$returnArray[] = $thegoogle."images?q=".rawurlencode($imagesOf)."&hl=en&lr=&start=".$j."&sa=N&gbv=1";            
		$j += 20;
	}
	return $returnArray;
}

/**
 * get the page
 */
function getHtml($url){
	$returnStr="";
	$fp=fopen($url, "r");
	if($fp){
		while (!feof($fp)) {
			$returnStr.=fgetc($fp);
		}
		fclose($fp);
	}
	return $returnStr;
}

/**
 * parse results
 */
function parse_gResult($str, $ent_id, $offset,$num){
	global $Conf;
	//echo $str;
	//
	// for each image on the page i want:
	// img_url, w, h, ref_url
	// thmb_url, w, h, 
	// only seven items , so what i write that in 20 min !
	// 
	$img=array();	
	$reg = "/<a href=\"\/imgres([^>]*)>/si";
	preg_match_all($reg, $str, $matches);   
	$ic=$offset+1;
	if(count($matches[0]) < 1 && $offset == 0){

	//	mark_noGoogleImage($ent_id);
	//	return $str;
	}
	foreach ($matches[0] as $value) {

/*
href=/imgres?imgurl=http://img2.timeinc.net/people/i/2008/stylewatch/gallery/milanparis/salma_hayek.jpg

&imgrefurl=http://search.people.com/TIISearch/people/search/search.html%3Fsearch%3Dbreakup
&usg=__3oY4-uFNJMoDMUcfCG7kiXe1zzE=
&h=400&w=300&sz=24&hl=en&start=79
&tbnid=RTeVMtZMbddqnM:
&tbnh=124
&tbnw=93

&prev=/images%3Fq%3Dhayek%2Bactress%26start%3D60%26gbv%3D1%26hl%3Den%26lr%3D%26sa%3DN%26ie%3DUTF-8> 
*/
		$reg = "/\/imgres\?imgurl=([^&]*)&amp;imgrefurl=/si";
		preg_match_all($reg, $value, $matches1);   
		$img["img_url"]=$matches1[1][0];
		$reg = "/&amp;imgrefurl=([^&]*)&amp;usg=__/si";
		preg_match_all($reg, $value, $matches1);   
		$img["ref_url"]=$matches1[1][0];
		$reg = "/&amp;h=([^&]*)&amp;/si";
		preg_match_all($reg, $value, $matches1);   
		$img["img_h"]=$matches1[1][0];
		$reg = "/&amp;w=([^&]*)&amp;/si";
		preg_match_all($reg, $value, $matches1);   
		$img["img_w"]=$matches1[1][0];
		$reg = "/&amp;tbnid=([^&]*)&amp;/si";
		preg_match_all($reg, $value, $matches1);   
		$img["thmb_id"]=$matches1[1][0];
		$reg = "/&amp;tbnh=([^&]*)&amp;/si";
		preg_match_all($reg, $value, $matches1);   
		$img["thmb_h"]=$matches1[1][0];
		$reg = "/&amp;tbnw=([^&]*)&amp;/si";
		preg_match_all($reg, $value, $matches1);   
		$img["thmb_w"]=$matches1[1][0];

// google thumbnailurl looks like this		
// http://tbn2.google.com/images?q=tbn:Wd4OG7eBzgovTM:http://www.topnews.in/light/files/salma-hayek3.jpg		
		$img["thmb_url"]="http://tbn".rand(1,3).".google.com/images?q=tbn:";
		$img["thmb_url"].=$img["thmb_id"].$img["img_url"];
		$ret[]=$img;

$sql = 'INSERT INTO `'.$Conf["db_name"].'`.`image` (
		`id`, 
		`title`, 
		`wpage_id`, 
		`thmb_url`, 
		`thmb_w`, 
		`thmb_h`, 
		`ref_url`, 
		`img_url`, 
		`img_w`, 
		`img_h`, 
		`date`, 
		`404`) VALUES (
		NULL,	NULL, 
		\''.$ent_id.'\', 
		\''.$img['thmb_url'].'\', 
		\''.$img['thmb_w'].'\', 
		\''.$img['thmb_h'].'\', 
		\''.$img['ref_url'].'\', 
		\''.$img['img_url'].'\', 
		\''.$img['img_w'].'\', 
		\''.$img['img_h'].'\', 
		NOW(), 
		\'0\');';		
		$result = mysql_query($sql);
		
	}
	return $ret;
}	


/*
 * here the script starts
 * 
 */
$connection = mysql_connect($Conf["db_server"], $Conf["db_user"], $Conf["db_pass"]);
if (!$connection) {   die('Not connected : ' . mysql_error());}
mysql_select_db($Conf["db_name"], $connection);
 
 
 
$wpage = $_GET['wpage'];

if (!$wpage) {
	// Passed url not specified.
	$contents = 'ERROR: url not specified';
	$status = array('http_code' => 'ERROR');
	
} else {
// first lst us see if we know already what we want
	$sql = 'SELECT * FROM `'.$Conf["db_name"].'`.`wpage` w , `'.$Conf["db_name"].'`.`image` i WHERE `w`.`text`=\''.$wpage.'\' AND `i`.`wpage_id`=`w`.`id`;'; 

	$result = mysql_query($sql);
	if (!$result) {  die('Invalid query: ' . mysql_error());}
	if(mysql_num_rows($result) > 0){ 
	while ($row = mysql_fetch_assoc($result)){
		$contents[]=$row;		
	
	}
	$status = array('http_code' => 'OK');
// if so pack it in to the contents
	} else {// else get some data and cache it 
		$sql = 'INSERT INTO `'.$Conf["db_name"].'`.`wpage` (
				`id`,
				`text`, 
				`cachetime` 
		
		) VALUES (
			NULL,
			\''.$wpage.'\',
			NOW()
		
		);';
		$result = mysql_query($sql);
		$id=mysql_insert_id();
		$url=createGoogleUrl($wpage,20);
		$offset=0;
		$ret = parse_gResult(getHtml($url[0]), $id, $offset,20);
		$status = array('http_code' => 'OK');
		$contents = $ret;
	}



}


// Set the JSON data object contents, decoding it from JSON if possible.
$decoded_json = json_decode($contents);
$data['status'] = $status;

$data['contents'] = $decoded_json ? $decoded_json : $contents;

// Generate appropriate content-type header.
$is_xhr = strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
header('Content-type: application/' . ($is_xhr ? 'json' : 'x-javascript'));

// Get JSONP callback.
$jsonp_callback = $enable_jsonp && isset($_GET['callback']) ? $_GET['callback'] : null;

// Generate JSON/JSONP string
$json = json_encode($data);

print $jsonp_callback ? "$jsonp_callback($json)" : $json;



?>