<!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 
	//if ($_SERVER['SERVER_NAME'] == 'airbook.local')
	$root = $_SERVER['DOCUMENT_ROOT'];
	//$root = dirname($_SERVER['SCRIPT_FILENAME']); // /Users/bruno/Sites/sls
	include($root.'/lib2/localize.php');
	$dir_locales = $root . '/Locale';
	
	$liste_locale = list_dir($dir_locales);
	if ((!isset($_POST['lang'])) and (!isset($_GET['lang']))) $langue = locale_language_from_browser($myLanguages);
	else $langue = $_REQUEST['lang'];
	
	$domain = 'sentier';
	putenv('LC_ALL=' . $langue);
	$loc = setlocale(LC_ALL, $langue);
	
	bindtextdomain($domain, $root . '/Locale/');
	bind_textdomain_codeset($domain, 'UTF-8');
	textdomain($domain);
	
	$nation = array('fr_FR' => gettext('French'), 'en_US' => gettext('English') , 'de_DE' => gettext('German'), 'es_ES' => gettext('Spanish') );
	
	include 'functions.php';
    ?>
	<script   src="https://code.jquery.com/jquery-3.6.0.min.js"   integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="   crossorigin="anonymous"></script>

</head>
	
<body>

<?php

$base = 'db_photo.sqlite3';

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

$dir = (new AdvancedFilesystemIterator('photos/img/'))->match('/heic|HEIC|jpg|jpeg|JPG|JPEG|webp|WEBP$/');

echo '<h3>' . count($dir) . gettext(' images found in folder') . ' <i>photos/img/</i> ...</h3>';

echo '<h3>' . gettext("Creation of the database") . ' <i>' . $base . '</i> ' . gettext("and the table") . ' <i>photo</i> (' . gettext("if necessary") . ')...</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,
	speed TEXT,
	iso INTEGER,
	width INTEGER,
	height INTEGER,
	html TEXT,
	aperture TEXT,
	model TEXT,
	lat REAL,
	long REAL,
	alt REAL,
	legende TEXT, 
	copyright TEXT, 
	title TEXT, 
	creator TEXTr, 
	keywords TEXT,
	metering TEXT,
	flash TEXT,
	focal TEXT,
	wb TEXT,
	program TEXT,
	UNIQUE(filename)
	)";
$conn->exec($query);

echo '<h3>' . gettext('Read image files in the folder') . ' <i>photos/img/</i>...</h3>';

$i = 1;
$photos = array();

foreach($dir as $file){
	/*
	$file->getFilename()
	pathName()
	*/
    $file = $file->getpathName();
 
	$x = in_bdd($file);
		
	if ($x == false) {	//false

		if ($exif = @exif_read_data($file, 0, true )) {
			//_pr($exif);
			//if (($file == 'photos/img/12_2007.jpg') || ($file == 'photos/img/11_2007.jpg') || ($file == 'photos/img/10_2020.jpg')) {
			if (($file == 'photos/img/4_2008.jpg') || ($file == 'photos/img/10_2020.jpg')) {
				_pr($exif);
			}
			$mod = isset($exif['IFD0']['Model']) ? $exif['IFD0']['Model'] : '';
						
			//_pr($exif);
			# YYYY-MM-DD HH:MM:SS.SSS - 2019:10:01 14:03:12
			$da = isset($exif['EXIF']['DateTimeOriginal']) ? $exif['EXIF']['DateTimeOriginal'] : '';

			if (isset($exif['EXIF']['UndefinedTag:0xA434'])) {
				$w = $exif['EXIF']['UndefinedTag:0xA434'];
				
				$arr = array("100.0 mm" => "EF100mm f/2.8 Macro USM", "100.0-400.0 mm" => "EF100-400mm f/4.5-5.6L IS USM", "140.0-560.0 mm" => "EF100-400mm f/4.5-5.6L IS USM +1.4x II", "17.0-40.0 mm" => "EF17-40mm f/4L USM", "24-70mm" => "SIGMA 24-70mm F2.8 EX DG", "70.0-200.0 mm" => "EF70-200mm f/4L USM", "10.0-22.0 mm" => "EF-S10-22mm f/3.5-4.5 USM", "500.0 mm" => "Sigma 500mm f/4.5 EX HSM ", "500mm" => "Sigma 500mm f/4.5 EX HSM ");
				
				if (array_key_exists($w, $arr)) $obj= $arr[$w];
				else $obj = $w;
				
			} else {
				$obj = '';
			}
			
			if (isset($exif['EXIF']['ExposureTime'])) {
				$q = explode('/', $exif['EXIF']['ExposureTime']);
				$sp = ($q[0] > 1) ? ($q[0] / $q[1]) . "s" : $exif['EXIF']['ExposureTime'];
			} else {
				$sp = '';
			}

			$iso = isset($exif['EXIF']['ISOSpeedRatings']) ? $exif['EXIF']['ISOSpeedRatings'] : '';

			if (isset($exif['EXIF']['MeteringMode'])) {
				$mm = $exif['EXIF']['MeteringMode'];
				
				switch ($mm) {
					case 1: $mm = gettext("Average");
						break;
					case 2: $mm = gettext("Center-weighted average");	// Moy. à pred. centrale
						break;
					case 3: $mm = gettext("Spot");
						break;
					case 4: $mm = gettext("Multi-Spot");
						break;
					case 5: $mm = gettext("Pattern");	// Mesure évaluative
						break;
					case 6: $mm = gettext("Partial");	// Mesure sélective
						break;
					default: $mm = gettext("Unknown") . ': ' . $mm;
					// Evaluative					Mesure évaluative
					// Centre-weighted Average		Moy. à pred. centrale
					// Partial						Mesure sélective
					// Spot							Spot
					
					// Pattern						=Mesure évaluative (30D)
					// Average						Mesure évaluative
				}

			} else {
				$mm = '';
			}

			if (isset($exif['EXIF']['Flash'])) {
				$fla = $exif['EXIF']['Flash'];

				switch ($fla) {
					case 0: $fla = gettext("Off");
						break;
					case 1: $fla = gettext("Auto");
						break;
					case 2: $fla = gettext("On");
						break;
					case 3: $fla = gettext("Red Eye Reduction");
						break;
					case 4: $fla = gettext("Slow Synchro");
						break;
					case 5: $fla = gettext("Auto + Red Eye Reduction");
						break;
					case 6: $fla = gettext("On + Red Eye Reduction");
						break;
					case 16: $fla = gettext("External Flash");
						break;
					default: $fla = gettext("Unknown");
				}
				
			} else {
				$fla = '';
			}

			if (isset($exif['EXIF']['FocalLength'])) {
				$k = explode('/', $exif['EXIF']['FocalLength']);
				$fl = $k[0] . " mm";
			} else {
				$fl = '';
			}

			/*
			if (isset($exif['EXIF']['ExposureMode'])) {
				$em = $exif['EXIF']['ExposureMode'];
				echo $em;
				$em = hexdec(intel2Moto($exif['EXIF']['ExposureMode']));
				echo $em;
				
				switch ($em) {
					case 0: $em = gettext("EasyShoot");
						break;
					case 1: $em = gettext("Program");
						break;
					case 2: $em = gettext("Tv");
						break;
					case 3: $em = gettext("Av");
						break;
					case 4: $em = gettext("Manual");
						break;
					case 5: $em = gettext("Auto-DEP");
						break;
					default: $em = gettext("Unknown");
				}

			} else {
				$em = '';
			}
			*/

			if (isset($exif['EXIF']['WhiteBalance'])) {
				$wb = $exif['EXIF']['WhiteBalance'];
				
				switch ($wb) {
					case 0: $wb = gettext("Auto");
						break;
					case 1: $wb = gettext("Daylight");
						break;
					case 2: $wb = gettext("Cloudy");
						break;
					case 3: $wb = gettext("Tungsten");
						break;
					case 4: $wb = gettext("Fluorescent");
						break;
					case 5: $wb = gettext("Flash");
						break;
					case 6: $wb = gettext("Custom");
						break;
					case 7: $wb = gettext("Black & White");
						break;
					case 8: $wb = gettext("Shade");
						break;
					case 9: $wb = gettext("Manual Temperature (Kelvin)");
						break;
					default: $wb = gettext("Unknown");
				}

			} else {
				$wb = '';
			}
			if (isset($exif['EXIF']['ExposureProgram'])) {
				$ep = $exif['EXIF']['ExposureProgram'];
				
				switch ($ep) {
					case 1: $ep = gettext('Manual');
						break;
					case 2: $ep = gettext('Program');
						break;
					case 3: $ep = gettext('Aperture Priority');
						break;
					case 4: $ep = gettext('Shutter Priority');
						break;
					case 5: $ep = gettext('Program Creative');
						break;
					case 6: $ep = gettext('Program Action');
						break;
					case 7: $ep = gettext('Portrait');
						break;
					case 8: $ep = gettext('Landscape');
						break;
					default: $ep = gettext('Unknown') . ': ' . $data;
						break;
				}

			} else {
				$ep = '';
			}
			
			///echo "File: " . basename($file) . " - Objectif: " . $obj . " - Model: " . $mod . " - Metering: " . $mm . " - Flash: " . $fla. " - Focal: " . $fl. " - Exposure: " . " - Balance: " . $wb. " - Program: " . $ep . "<br>";

			$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'] : '';

			$gps = get_gps($exif);
			
			$photos[$i] = array(
	    	    'filename' => $file,
	    	    
    	    	'date' => $da,
	    	    'lens' => $obj,
		        'speed' => $sp,
    		    'iso' => $iso,
	    	    
    	    	'width' => $wi,
	        	'height' => $he,      
		        'html' => $ht,
    		    'aperture' => $ap,
    		    
        		'model' => $mod,
    		    
    		    'lat' => $gps['latitude'],
    		    'long' => $gps['longitude'],
    		    'alt' => $gps['altitude'],
    		    
				'metering' => $mm,
				'flash' => $fla,
				'focal' => $fl,
				'wb' => $wb,
				'program' => $ep
				
			   	);			   	
			}
			
		//$qq = getimagesize($file, $info);
		//_pr($qq);
		
		if ($iptc = @getimagesize($file, $info)) {
			//_pr($iptc);
			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] : '';
 				$title = (isset($iptc["2#105"][0])) ? $iptc["2#105"][0] : '';
  				$creator = (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]['title'] = $title;
 				$photos[$i]['creator'] = $creator;
 				$photos[$i]['mots_cles'] = $mots;
				}
			else {
				$photos[$i]['legende'] = '';
				$photos[$i]['copyright'] = '';
			    $photos[$i]['title'] = '';
			    $photos[$i]['creator'] = '';
			    $photos[$i]['mots_cles'] = '';	 
			    }
			}	
		}
		
		$i++;
	}

//_pr($photos);
$z = count($photos);
if ($z == 0) {
	echo '<h3>' . gettext('No new image files to add') . '...</h3>';
	die();
	}

$query5 = "SELECT MAX(id) FROM photos";
$stmt = $conn->prepare($query5);
$stmt->execute();
$resultat = $stmt->fetch(PDO::FETCH_ASSOC);
$avant = $resultat['MAX(id)'];

$nb_avant = (isset($avant)) ? $avant : 0;


echo '<h3>' . gettext('Creation of thumbnails') . ' ('. $th_w . 'px x ' . $th_h . 'px) ' . gettext('in the folder') . ' <i>photos/thumb/</i>.</h3>';
//$b = ($z > 1) ? 'nouvelles images' : 'nouvelle image';
$b = ($z > 1) ? gettext('new images') : gettext('new image');
echo '<h3>' . gettext('Insertion of ') . $z . ' ' . $b . gettext(' in database') . '...</h3>';

// Insertion des photos dans la base
// Création des vignettes
try {
	$query2 = "INSERT OR IGNORE INTO photos (filename, date, lens, speed, iso, width, height, html, aperture, model, lat, long, alt, legende, copyright, title, creator, keywords, metering, flash, focal, wb, program) VALUES (:filename, :date, :lens, :speed, :iso, :width, :height, :html, :aperture, :model, :lat, :long, :alt, :legende, :copyright, :title, :creator, :keywords, :metering, :flash, :focal, :wb, :program)";

	$stmt = $conn->prepare($query2);
	$stmt->bindParam(':filename', $file);
	$stmt->bindParam(':date', $da);
	$stmt->bindParam(':lens', $obj);
	$stmt->bindParam(':speed', $sp);
	$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(':title', $tit);
	$stmt->bindParam(':creator', $crea);
	$stmt->bindParam(':keywords', $mot);	

	$stmt->bindParam(':metering', $mm);
	$stmt->bindParam(':flash', $fla);
	$stmt->bindParam(':focal', $fl);
	$stmt->bindParam(':wb', $wb);
	$stmt->bindParam(':program', $ep);

	//echo count($photos);
	//_pr($photos);
	
 	if (isset($photos)) {
 		foreach ($photos as $item) {	 		
 			$file = $item['filename'];
 			$da = $item['date'];
	 		$obj = $item['lens'];
	  		$sp = $item['speed'];
 			$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['title'];
 			$crea = $item['creator'];
 			$mot =	$item['mots_cles'];
 
 			$mm = $item['metering'];
  		   	$fla = $item['flash'];
  			$fl = $item['focal'];
  			$wb = $item['wb'];
  			$ep = $item['program'];
			
 			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, speed, iso, width, height, html, aperture, model, lat, long, alt, legende, copyright, title, creator, keywords, metering, flash, focal, wb, program FROM photos WHERE id > ? ORDER BY date DESC";
	//$query4 = "SELECT filename, date, lens, speed, iso, width, height, html, aperture, model, lat, long, alt, legende, copyright, title, creator, 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>' . gettext('Thumb') . '</th><th>' . gettext('Filename') . '</th><th>' . gettext('Date') . '</th><th>' . gettext('Lens') . '</th><th>' . gettext('Speed') . '</th><th>' . gettext('Iso') . '</th><th>' . gettext('Width') . '</th><th>' . gettext('Height') . '</th><th>' . gettext('Html') . '</th>';
	echo '<th>' . gettext('Aperture') . '</th><th>' . gettext('Model') . '</th><th>' . gettext('Latitude') . '</th><th>' . gettext('Longitude') . '</th><th>' . gettext('Alttitude') . '</th><th>' . gettext('Legende') . '</th><th>' . gettext('Copyright') . '</th><th>' . gettext('Title') . '</th>';
	echo '<th>' . gettext('Creator') . '</th><th>' . gettext('Keywords') . '</th><th>' . gettext('Metering') . '</th><th>' . gettext('Flash') . '</th><th>' . gettext('Focal') . '</th><th>' . gettext('Wb') . '</th><th>' . gettext('Program') . '</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 '<tr><td>' . '<a href="' . $full . '"><img src="'.$thumbnail.'" /></a>' . '</td><td>' . $row['filename'] . '</td><td>' . $row['date'] . '</td><td>' . $row['lens'] . '</td><td>' . $row['speed'] . '</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['title'] . '</td><td>' . $row['creator'] . '</td><td>' . $row['keywords'] . '</td><td>' . $row['metering'] . '</td><td>' . $row['flash'] . '</td><td>' . $row['focal'] . '</td><td>' . $row['wb'] . '</td><td>' . $row['program'] . '</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>

	<h4><a href="photo-du-mois.php" title="<?php echo gettext("Picture of the month"); ?>"><?php echo gettext("Picture of the month"); ?></a></h4>
	
	<script src='js/lc_lightbox.min.js' type='text/javascript'></script>
	<script src='js/alloy_finger.min.js' type='text/javascript'></script>

</body>
		
</html>