<?php
function echoPre($array){
	echo '<pre>';
	print_r($array);
	echo '</pre>';
}

function get_web_page( $url)
{
	$user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';

	$options = array(

		CURLOPT_CUSTOMREQUEST  =>"GET",        //set request type post or get
		CURLOPT_POST           =>false,        //set to GET
		CURLOPT_USERAGENT      => $user_agent, //set user agent
		CURLOPT_COOKIEFILE     =>"cookie.txt", //set cookie file
		CURLOPT_COOKIEJAR      =>"cookie.txt", //set cookie jar
		CURLOPT_RETURNTRANSFER => true,     // return web page
		CURLOPT_HEADER         => false,    // don't return headers
		CURLOPT_FOLLOWLOCATION => true,     // follow redirects
		CURLOPT_ENCODING       => "",       // handle all encodings
		CURLOPT_AUTOREFERER    => true,     // set referer on redirect
		CURLOPT_CONNECTTIMEOUT => 360,      // timeout on connect
		CURLOPT_TIMEOUT        => 360,      // timeout on response
		CURLOPT_MAXREDIRS      => 10      // stop after 10 redirects

	);
	
	$ch      = curl_init( $url );

	curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");
	curl_setopt_array( $ch, $options );
	$content = curl_exec( $ch );
	$err     = curl_errno( $ch );
	$errmsg  = curl_error( $ch );
	$header  = curl_getinfo( $ch );
	curl_close( $ch );

	$header['errno']   = $err;
	$header['errmsg']  = $errmsg;
	$header['content'] = $content;
	return $header;
}


function saveJPG($occurence,$name){
	if (!is_dir('temp'))
		mkdir('temp');
	if (!is_dir($name))
		mkdir($name);
	if (substr($occurence,0,7)!='http://'&&substr($occurence,0,8)!='https://')
		return;
	echo "<h2>$occurence</h2>";
	$url='https://api.gbif.org/v1/image/unsafe/fit-in/2000x/'.urlencode($occurence);
	echo "<h2>$url</h2>";
	
	$data=get_web_page($url);
	if ($data['errmsg'])
		die($data['errmsg']);
	$data=$data['content'];
	$md5_file=md5($data);
	//verify duplicates
	if (!is_file($name.'/md5.txt'))
		file_put_contents($name.'/md5.txt','');
	$txt=explode("\n",file_get_contents($name.'/md5.txt'));
	foreach($txt as $md5)
		if ($md5==$md5_file)
			return;
	file_put_contents('temp/temp',$data);
	//because some URL don't have extension
	if (exif_imagetype('temp/temp')==2)//JPG
		copy('temp/temp',$name.'/'.uniqid().'.jpg');
	if (exif_imagetype('temp/temp')==3)//PNG
		copy('temp/temp',$name.'/'.uniqid().'.png');
	
	$txt[]=$md5_file;
	file_put_contents($name.'/md5.txt',implode("\n",$txt));
	echo "<h1>$occurence</h1>";
}


$url = 'https://api.gbif.org/v1/occurrence/download/request';
$username="sylvain.ard@gmail.com";
$password="XXX";
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// add more options if you wish
$response = curl_exec($ch);
   
if(curl_exec($ch) === false)
{
    echo 'Erreur Curl : ' . curl_error($ch).'<br>';
}
else
{
    echo 'L\'opération s\'est terminée sans aucune erreur<br>';
}
/*$pdo = new PDO('mysql:host=localhost;dbname=taxref15', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt= $pdo->prepare("SELECT DISTINCT LB_NOM FROM taxref15 WHERE CD_SUP IN (SELECT CD_REF FROM taxref15 WHERE LB_NOM='Taraxacum') AND RANG='ES' and FR='P'");
$stmt->execute([]);*/
//while($row=$stmt->fetch())
{ 
	//$name=$row['LB_NOM'];
	
	$name='Taraxacum acutangulum';
	
	echo "<b>$name</b><br>";
	
	
	$url='https://api.gbif.org/v1/species?name='.urlencode($name).'&limit=2000';
	echo $url.'<br />';
	$especes=json_decode(file_get_contents($url),true);
	echoPre($especes);
	$keys=array();
	foreach($especes['results'] as $espece){
		if (isset($espece['nubKey']))
			$keys[]=$espece['nubKey'];
	}
	$keys=array_unique($keys);
	foreach($keys as $key){
		$url='https://api.gbif.org/v1/occurrence/search?taxonKey='.$key.'&limit=2000';
		echo "$url<br />";
		$occurences=json_decode(file_get_contents($url),true);
		$count=$occurences['count'];
		$n=ceil($count/300);
		for ($i=0;$i<$n;$i++){
			$url='https://api.gbif.org/v1/occurrence/search?taxonKey='.$key.'&limit=2000&offset='.($i*300);
			echo "$url<br />";
			$occurences=json_decode(file_get_contents($url),true);
			echoPre($occurences);
			foreach($occurences['results'] as $occurence){
				echoPre($occurence);
				if (is_array($occurence)){
					foreach($occurence as $occ){
						if (is_array($occ)){
							foreach($occ as $occ2){
								if (is_array($occ2)){
									foreach($occ2 as $occ3){
										if (is_array($occ3)){
											foreach($occ3 as $occ4){
												if (is_array($occ4)){
													foreach($occ4 as $occ5){
														
															saveJPG($occ5,$name);
													}
												}
												else
													
														saveJPG($occ4,$name);
											}
										}
										else
											
												saveJPG($occ3,$name);
									}
								}
								else
									
										saveJPG($occ2,$name);
									
								}
							}
								else
								
									saveJPG($occ,$name);
							}
						}
						else
							
								saveJPG($occurrence,$name);
					}
				}
			}
}
curl_close($ch);

?>