<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Insert photos in Sqlite base</title>
    
	<link rel="stylesheet" href="css/sls.css" /> 
	<link rel='stylesheet' href='css/lc_lightbox.min.css' />
	<link rel='stylesheet' href='css/open_close_fx.css' />
	<link rel='stylesheet' href='css/minimal.css' />

	<?php include 'functions.php'; ?>
	<script src='https://code.jquery.com/jquery-3.2.1.min.js' type='text/javascript'></script>

</head>
	
<body>

<?php
$base = 'db_photo.sqlite3';

// Taille des vignettes
$th_w = 300;
$th_h = 300;

//Get a list of file paths using the glob function.
$fileList = glob('photos/img/*');

echo '<h3>Creation de la base <i>' . $base . '</i> et de la table <i>photo</i> (si nécessaire)...</h3>';

// Création de la base et de la table photos
$conn = new PDO("sqlite:db_photo.sqlite3");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "CREATE TABLE IF NOT EXISTS photos (
	id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
	filename TEXT NOT NULL, 
	date TEXT,
	lens TEXT,
	exposure INTEGER,
	iso INTEGER,
	width INTEGER,
	height INTEGER,
	html TEXT,
	aperture TEXT,
	model TEXT,
	lat REAL,
	long REAL,
	alt REAL,
	legende TEXT, 
	copyright TEXT, 
	titre TEXT, 
	createur TEXTr, 
	keywords TEXT,
	UNIQUE(filename)
	)";
$conn->exec($query);

echo '<h3>Lecture des fichiers images dans le dossier <i>photos/img/</i>...</h3>';

$i = 1;

// Ajout de données dans la table
foreach($fileList as $file){

	$x = in_bdd($file);
		
	if ($x == false) {	//false

		if ($exif = @exif_read_data($file, 0, true )) {

			//_pr($exif);
			# YYYY-MM-DD HH:MM:SS.SSS - 2019:10:01 14:03:12
			$da = isset($exif['EXIF']['DateTimeOriginal']) ? $exif['EXIF']['DateTimeOriginal'] : '';
			$obj = isset($exif['EXIF']['UndefinedTag:0xA434']) ? $exif['EXIF']['UndefinedTag:0xA434'] : '';
			$ex = isset($exif['EXIF']['ExposureTime']) ? $exif['EXIF']['ExposureTime'] : '';
			$iso = isset($exif['EXIF']['ISOSpeedRatings']) ? $exif['EXIF']['ISOSpeedRatings'] : '';

			$wi = isset($exif['COMPUTED']['Width']) ? $exif['COMPUTED']['Width'] : '';
			$he = isset($exif['COMPUTED']['Height']) ? $exif['COMPUTED']['Height'] : '';
			$ht = isset($exif['COMPUTED']['html']) ? $exif['COMPUTED']['html'] : '';
			$ap = isset($exif['COMPUTED']['ApertureFNumber']) ? $exif['COMPUTED']['ApertureFNumber'] : '';

			$mod = isset($exif['IFD0']['Model']) ? $exif['IFD0']['Model'] : '';
			
			$gps = get_gps($exif);
			
			$photos[$i] = array(
	    	    'filename' => $file,
	    	    
    	    	'date' => $da,
	    	    'lens' => $obj,
		        'exposure' => $ex,
    		    'iso' => $iso,
	    	    
    	    	'width' => $wi,
	        	'height' => $he,      
		        'html' => $ht,
    		    'aperture' => $ap,
    		    
        		'model' => $mod,
    		    
    		    'lat' => $gps['latitude'],
    		    'long' => $gps['longitude'],
    		    'alt' => $gps['altitude']
    		    
			   	);			   	
			}
			
		if ($iptc = getimagesize($file, $info)) {
			if (isset($info["APP13"])) {
				$mots = "";
   				$iptc = iptcparse ($info["APP13"]);
   				$legende = (isset($iptc["2#120"][0])) ? $iptc["2#120"][0] : '';
      			$copyright = (isset($iptc["2#116"][0])) ? $iptc["2#116"][0] : '';
 				$titre = (isset($iptc["2#105"][0])) ? $iptc["2#105"][0] : '';
  				$createur = (isset($iptc["2#080"][0])) ? $iptc["2#080"][0] : '';
  				$mots_cles = (isset($iptc["2#025"])) ? $iptc["2#025"] : '';
				if (!empty($mots_cles)) {
					foreach ($mots_cles as $key => $val) {
						$mots .= $val . ",";
						}
 					$mots = substr($mots, 0, -1);
					}
 				
 				$photos[$i]['legende'] = $legende;
 				$photos[$i]['copyright'] = $copyright;
 				$photos[$i]['titre'] = $titre;
 				$photos[$i]['createur'] = $createur;
 				$photos[$i]['mots_cles'] = $mots;
				}
			}	
		}
		
		$i++;
	}

$query5 = "SELECT MAX(id) FROM photos";
//$conn->$stmt->execute($query5);
$stmt = $conn->prepare($query5);
$stmt->execute();
//$resultat = $stmt->fetchAll(PDO::FETCH_ASSOC);
/*
Array
	(
		[0] => Array
			(
				[MAX(id)] => 5
			)
	
	)
*/
$resultat = $stmt->fetch(PDO::FETCH_ASSOC);
/*
Array
	(
		[MAX(id)] => 5
	)
*/
//_pr($resultat);
$nb_avant = $resultat['MAX(id)'];


echo '<h3>Création des vignettes dans le dossier <i>photos/thumb/</i> et insertion dans la base...</h3>';

// Insertion des photos dans la base
// Création des vignettes
try {
	$query2 = "INSERT OR IGNORE INTO photos (filename, date, lens, exposure, iso, width, height, html, aperture, model, lat, long, alt, legende, copyright, titre, createur, keywords) VALUES (:filename, :date, :lens, :exposure, :iso, :width, :height, :html, :aperture, :model, :lat, :long, :alt, :legende, :copyright, :titre, :createur, :keywords)";

	$stmt = $conn->prepare($query2);
	$stmt->bindParam(':filename', $file);
	$stmt->bindParam(':date', $da);
	$stmt->bindParam(':lens', $obj);
	$stmt->bindParam(':exposure', $ex);
	$stmt->bindParam(':iso', $iso);
	$stmt->bindParam(':width', $wi);
	$stmt->bindParam(':height', $he);
	$stmt->bindParam(':html', $ht);
	$stmt->bindParam(':aperture', $ap);
	$stmt->bindParam(':model', $mod);
 	$stmt->bindParam(':lat', $gps['latitude']);
	$stmt->bindParam(':long', $gps['longitude']);
	$stmt->bindParam(':alt', $gps['altitude']);
	
	$stmt->bindParam(':legende', $leg);
	$stmt->bindParam(':copyright', $cop);
 	$stmt->bindParam(':titre', $tit);
	$stmt->bindParam(':createur', $crea);
	$stmt->bindParam(':keywords', $mot);	

 	if (isset($photos)) {
 		foreach ($photos as $item) {	 		
 			$file = $item['filename'];
 			$da = $item['date'];
	 		$obj = $item['lens'];
	  		$ex = $item['exposure'];
 			$iso = $item['iso'];
 			$wi = $item['width'];
 			$he = $item['height'];
	 		$ht = $item['html'];
 			$ap = $item['aperture'];
 			$mod = $item['model'];
	 		$gps['latitude'] = $item['lat'];
 			$gps['longitude'] = $item['long'];
 			$gps['altitude'] = $item['alt'];

 			$leg = $item['legende'];
 			$cop = $item['copyright'];
 			$tit = $item['titre'];
 			$crea = $item['createur'];
 			$mot =	$item['mots_cles'];
 			
 			create_thumb($th_w, $th_h, $file);
 								
			$stmt->execute();
			}
		}
    }
    catch(PDOException $e) {
        echo $e->getMessage();
        }


/* Affichage depuis la bdd des dernières images ajoutées */
/* */
try {
	$query4 = "SELECT filename, date, lens, exposure, iso, width, height, html, aperture, model, lat, long, alt, legende, copyright, titre, createur, keywords FROM photos WHERE id > ? ORDER BY date DESC";
	//$query4 = "SELECT filename, date, lens, exposure, iso, width, height, html, aperture, model, lat, long, alt, legende, copyright, titre, createur, keywords FROM photos WHERE lat != '' OR long != '' ORDER BY date DESC";
	
	$stmt = $conn->prepare($query4);
	$stmt->bindValue(1, $nb_avant, SQLITE3_INTEGER);	// (1,3...) 1=1ere valeur	3=valeur
	# id 1 -> 3
	//$stmt->execute(array(1, 3));	// WHERE id >= ? AND id <= ? ORDER BY date DESC";
	$stmt->execute();
	
	//$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
	//_pr($result);

	echo '<h3>Lecture des photos ajoutées:</h3>';
	echo '<div id="add_to_bdd">';
	echo '<table class="styled-table">';
	echo '<thead>';
	echo '<th>Thumb</th><th>Filename</th><th>Date</th><th>Lens</th><th>Exposure</th><th>Iso</th><th>Width</th><th>Height</th><th>Html</th><th>Aperture</th><th>Model</th><th>Lat</th><th>Long</th><th>Alt</th><th>Legende</th><th>Copyright</th><th>Titre</th><th>Createur</th><th>Keywords</th>';
	echo '</thead>';
	echo '<tbody>';
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$thumbnail = host() . str_replace("photos/img", "photos/thumb", $row['filename']);
		$full = host() . $row['filename'];
		//echo ' | ' . $row['filename'] . ' | ' . $row['date'] . ' | ' . $row['lens'] . ' | ' . $row['exposure'] . ' | ' . $row['iso'] . ' | ' . $row['width'] . ' | ' . $row['height'] . ' | ' . $row['html'] . ' | ' . $row['aperture'] . ' | ' . $row['model'] . ' | ' . $row['lat'] . ' | ' . $row['long'] . ' | ' . $row['alt'] . ' | ' . $row['legende'] . ' | ' . $row['copyright'] . ' | ' . $row['titre'] . ' | ' . $row['createur'] . " |\r\n";
		echo '<tr><td>' . '<a href="' . $full . '"><img src="'.$thumbnail.'" /></a>' . '</td><td>' . $row['filename'] . '</td><td>' . $row['date'] . '</td><td>' . $row['lens'] . '</td><td>' . $row['exposure'] . '</td><td>' . $row['iso'] . '</td><td>' . $row['width'] . '</td><td>' . $row['height'] . '</td><td>' . $row['html'] . '</td><td>' . $row['aperture'] . '</td><td>' . $row['model'] . '</td><td>' . $row['lat'] . '</td><td>' . $row['long'] . '</td><td>' . $row['alt'] . '</td><td>' . $row['legende'] . '</td><td>' . $row['copyright'] . '</td><td>' . $row['titre'] . '</td><td>' . $row['createur'] . '</td><td>' . $row['keywords'] . '</td></tr>';
	}
	echo '</tbody></table>';
	echo '</div>';
	
	$conn = null;
    }
    catch(PDOException $e) {
        echo $e->getMessage();
        }
?>

	<script type='text/javascript'>
		$(document).ready(function() {

			var $obj = lc_lightbox('#add_to_bdd a', {
				open_close_time : 200,
				ol_time_diff : 100,
				wrap_class : 'lcl_zoomin_oc',
				skin : 'minimal',
				txt_hidden : true,
				fullscreen : false,
				fs_img_behavior : 'smart',
				browser_fs_mode : true,
				rclick_prevent : true,
				});
	
		});
	</script>


	<script src='js/lc_lightbox.min.js' type='text/javascript'></script>
	<script src='js/alloy_finger.min.js' type='text/javascript'></script>

</body>
		
</html>