<?

class ImageLoot {
	function get1stGoogleThumbnail($title)
	{
		include_once('simple_html_dom.php');
		$search_keyword=str_replace(' ','+',$title);
		$options = array(
		  'http'=>array(
				'method'=>"GET",
				'header'=>"Accept-language: en\r\n" .
								  "User-Agent: Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1)Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1)\r\n" // IE10
		  )
		);
		$context = stream_context_create($options);
		$url = "http://www.google.co.kr/search?hl=en&tbm=isch&source=hp&q=".$search_keyword;
		$html = file_get_contents($url, false, $context);
		$newhtml = str_get_html($html);
		//echo $newhtml;
		$result_image_source = $newhtml->find('.images_table', 0)->find('img', 0)->src;
		return $result_image_source;
	}

	function http_get_edge($url)
	{
		$options = array(
		  'http'=>array(
				'method'=>"GET",
				'header'=>"Accept-language: en\r\n".
					"User-Agent: ".
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14931".
					"\r\n", // IE10
		  )
		);
		$context = stream_context_create($options);	
		return file_get_contents($url, false, $context);
	}

	function buildGoogleOptoins($options)
	{
		/*
		Large images: tbs=isz:l
		Medium images: tbs=isz:m
		Icon sized images: tba=isz:i
		Image size larger than 400×300: tbs=isz:lt,islt:qsvga
		Image size larger than 640×480: tbs=isz:lt,islt:vga
		Image size larger than 800×600: tbs=isz:lt,islt:svga
		Image size larger than 1024×768: tbs=isz:lt,islt:xga
		Image size larger than 1600×1200: tbs=isz:lt,islt:2mp
		Image size larger than 2272×1704: tbs=isz:lt,islt:4mp
		Image sized exactly 1000×1000: tbs=isz:ex,iszw:1000,iszh:1000
		 Images in full color: tbs=ic:color
		Images in black and white: tbs=ic:gray
		Images that are red: tbs=ic:specific,isc:red [orange, yellow, green, teal, blue, purple, pink, white, gray, black, brown]
		Image type Face: tbs=itp:face
		Image type Photo: tbs=itp:photo
		Image type Clipart: tbs=itp:clipart
		Image type Line drawing: tbs=itp:lineart
		Image type Animated (gif): tbs=itp:animated (thanks Dan)
		Group images by subject: tbs=isg:to
		Show image sizes in search results: tbs=imgo:1
		
		이미지 비율
		square => iar:s 
		tall => iar:t
		wide => iar:w
		panoramc => iaw:xw
		
		파일타입
		ift:png
		
		투명
		ic:trans
		
		*/
		//$tbs = "";
	}

	function searchGoogleImages($title, $tbs, $maxnumber=10)
	{
		include_once('simple_html_dom.php');
		$q=str_replace(' ','+',$title);
		$options = array(
		  'http'=>array(
				'method'=>"GET",
				'header'=>"Accept-language: en\r\n".
					"User-Agent: ".
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14931".
					"\r\n", // IE10
		  )
		);
		$context = stream_context_create($options);
		$url = "https://www.google.com/search?as_st=y&tbm=isch&hl=en&as_q=$q&as_epq=&as_oq=&as_eq=&cr=&as_sitesearch=&safe=images&tbs=$tbs";
		//echo $url."\n";
		//$url = "http://www.google.co.kr/search?hl=en&tbm=isch&source=hp&isz:i&q=$q";
		//$url = "https://www.google.com/search?newwindow=1&biw=1600&bih=795&tbm=isch&sa=1&ei=1pmMXdOoC4H1wAOxnIKYAw&q=mercedes-benz-logo&oq=mercedes-benz-logo&gs_l=img.12...0.0..5629...0.0..0.0.0.......0......gws-wiz-img.G4XhUmfLf1s&ved=0ahUKEwjT6_Gyqu7kAhWBOnAKHTGOADMQ4dUDCAc";
		$html = file_get_contents($url, false, $context);
		$newhtml = str_get_html($html);
		$all = $newhtml->find('.notranslate');//->find('img', 0)->src;
		//echo $all;
		$result = array();
		foreach($all as $t) {
			preg_match('/ou":"(.*)","ow"/', $t->plaintext, $matches);
			if($matches[1]) {
				$t = '"'.$matches[1].'"';
				array_push($result, json_decode($t));
			}
			$maxnumber--;
			if(!$maxnumber)
				break;
		}
		return $result;
	}


	function getImgType($filename) {
		$handle = @fopen($filename, 'r');
		if (!$handle)
			throw new Exception('File Open Error');

		$types = array('jpeg' => "\xFF\xD8\xFF", 'gif' => 'GIF', 'png' => "\x89\x50\x4e\x47\x0d\x0a", 'bmp' => 'BM', 'psd' => '8BPS', 'swf' => 'FWS');
		$bytes = fgets($handle, 8);
		$found = 'png';

		foreach ($types as $type => $header) {
			if (strpos($bytes, $header) === 0) {
				$found = $type;
				break;
			}
		}
		fclose($handle);
		return $found;
	}
	function imgByTitle($a)
	{
		if (!$a[q]) {
			throw new Exception("no search word");
		}
		$dir = "./data/imgcache/$a[tbs]/";
		@mkdir($dir, 0777);
		//$fn = sha1($a[q]).".jpg";	
		
		$fn = "$a[q]-".date("ymj").".jpg";
		$fn = preg_replace('/[\\/]/', "-", $fn);
		//$fn = substr($a[q], 0, 80).".jpg";
		$fullfn = $dir.$fn;
		$cache = glob($dir.$a[q]."-*");
		// print_r($cache);
		//}
		//$cache == null;
		if (count($cache) == 0 || $a[forceupdate]) {
			$all = $this->searchGoogleImages($a[q], $a[tbs]);
			for ($i = 0; $i < count($all); $i++) { 		
				$img = @http_get_edge($all[$i]);
				if($img && substr($img, 0, 5) != "<html")
					break;
			}
			if (!$img)
				throw new Exception("image not found");
			file_put_contents($fullfn, $img);
		} else {
			$all = $cache;
			$fullfn = $all[0];
			//echo $fullfn;
		}
		//die();
		if($a[html]) {
			foreach($all as $i) {
				if (substr("$i", 0, 4) !== "http")
					$i = "/$i";
				echo "<img src='$i' />\n";
				//print_r($a);
				//print_r($all);
			}
			die();
		}
		//die();
		$type = 'image/'.getImgType($fullfn);
		//die($type);
		header('Content-Type:'.$type);
		header('Content-Length: ' . filesize($fullfn));
		readfile($fullfn);
	}
	function urlsByTitle($a)
	{
		if (!$a[q]) {
			throw new Exception("no search word");
		}
		if(!$a[n])
			$a[n] = 300;
		// $all = searchGoogleImages($a[q], $a[tbs], $a[n]);
		
		$dir = "./data/urlcache/$a[tbs]/";
		@mkdir($dir, 0777);
		//$fn = sha1($a[q]).".jpg";	
		
		$fn = "$a[q]-".date("ymj").".json";
		$fn = preg_replace('/[\\/]/', "-", $fn);
		//$fn = substr($a[q], 0, 80).".jpg";
		$fullfn = $dir.$fn;
		$cache = glob($dir.$a[q]."-*");
		// print_r($cache);
		//}
		//$cache == null;
		if (count($cache) == 0 || $a[forceupdate]) {
			$all = $this->searchGoogleImages($a[q], $a[tbs], $a[n]);
			if (count($all) == 0)
				throw new Exception("image not found");
			file_put_contents($fullfn, json_encode($all));
		} else {
			$all = $cache;
			$fullfn = $all[0];
		}
		$urls = file_get_contents($fullfn);	
		//print_r($urls);
		return $urls;	
	}
}

$app->action("img/by-title", function(){
	$a = $_REQUEST;
	$loot = new ImageLoot();
	$loot->imgByTitle($a);
});

$app->action("img/urls-by-title", function(){
	$a = $_REQUEST;
	$loot = new ImageLoot();
	$result = $loot->urlsByTitle($a);
	echo $result;
});



?>