<?php

/* Fonction month(): convertit le mois (nb) en mois (texte) francais

	photo-du-mois.php
*/

function month($w) {    
    //setlocale(LC_TIME, 'fr_FR');
    $m = date('m', strtotime($w));	// month
    $y = date('Y', strtotime($w));	// year
    //echo $w . "- month: " . $m . "- year: " . $y;
        
    // or any other locales like pl_PL, cs_CZ, fr_FR, zh, zh_Hans, ...
	$locale = 'fr_FR';
	$dateFormatter = new IntlDateFormatter(
    	$locale,
    	IntlDateFormatter::LONG, // date type
    	IntlDateFormatter::NONE  // time type
		);
	$dateFormatter->setPattern('LLLL'); // full month name with NO DECLENSION ;-)
	$months_locale = [];
	for ($month_number = 1; $month_number <= 12; ++$month_number) {
    	$months_locale[] = $dateFormatter->format(
        	// 'n' => month number with no leading zeros
        	DateTime::createFromFormat('n', (string)$month_number)
    		);
		}
	
	array_unshift($months_locale,"");
	unset($months_locale[0]);
	//_pr($months_locale);
	$my = ucfirst($months_locale[(int)$m]) . " " . $y;
	//echo $my;
	return $my;
	}	


/* Fonctions get_gps() et gps2Num(): extrait les coord GPS depuis les exifs

	insert_bdd.php
*/

function gps2Num($coordPart){
	/*
	Array
	(
		[0] => 46/1
		[1] => 408587/10000
		[2] => 0/0
	)
	Array
	(
		[0] => 5/1
		[1] => 562596/10000
		[2] => 0/0
	)
	*/
	
    $parts = explode('/', $coordPart);
	//echo $parts[0].'-'.$parts[1].'<br>';
    if(count($parts) <= 0)
    return 0;
    if(count($parts) == 1)
    return $parts[0];
	if($parts[1] != 0)
    	return floatval($parts[0]) / floatval($parts[1]);
	else return 0;
}

function get_gps($exif) {
	
	if($exif && isset($exif['GPS'])){
		/*
		echo $exif['FILE']['FileName'];
		_pr($exif['GPS']['GPSLatitude']);
		_pr($exif['GPS']['GPSLongitude']);
		*/
		$GPSLatitudeRef = isset($exif['GPS']['GPSLatitudeRef']) ? $exif['GPS']['GPSLatitudeRef'] : '';
		$GPSLatitude = isset($exif['GPS']['GPSLatitude']) ? $exif['GPS']['GPSLatitude'] : '';
		$GPSLongitudeRef = isset($exif['GPS']['GPSLongitudeRef']) ? $exif['GPS']['GPSLongitudeRef'] : '';
		$GPSLongitude = isset($exif['GPS']['GPSLongitude']) ? $exif['GPS']['GPSLongitude'] : '';
		$GPSAltitude = isset($exif['GPS']['GPSAltitude']) ? $exif['GPS']['GPSAltitude'] : '';
    
    	$lat_degrees = count($GPSLatitude) > 0 ? gps2Num($GPSLatitude[0]) : 0;
    	$lat_minutes = count($GPSLatitude) > 1 ? gps2Num($GPSLatitude[1]) : 0;
    	$lat_seconds = count($GPSLatitude) > 2 ? gps2Num($GPSLatitude[2]) : 0;
 
     	$lon_degrees = count($GPSLongitude) > 0 ? gps2Num($GPSLongitude[0]) : 0;
    	$lon_minutes = count($GPSLongitude) > 1 ? gps2Num($GPSLongitude[1]) : 0;
    	$lon_seconds = count($GPSLongitude) > 2 ? gps2Num($GPSLongitude[2]) : 0;
		
    	$lat_direction = ($GPSLatitudeRef == 'W' or $GPSLatitudeRef == 'S') ? -1 : 1;
    	$lon_direction = ($GPSLongitudeRef == 'W' or $GPSLongitudeRef == 'S') ? -1 : 1;
        
    	$latitude = $lat_direction * ($lat_degrees + ($lat_minutes / 60) + ($lat_seconds / (60*60)));
    	$longitude = $lon_direction * ($lon_degrees + ($lon_minutes / 60) + ($lon_seconds / (60*60)));

		$alt      = explode('/', $GPSAltitude);
		$altitude = (isset($alt[1])) ? ($alt[0] / $alt[1]) : $alt[0];
		}
	else {
		$latitude = '';
		$longitude = '';
		$altitude = '';
		}	

		//echo $latitude . " - " . $longitude . " - " . $altitude;

    return array('latitude'=>$latitude, 'longitude'=>$longitude, 'altitude'=>$altitude);
	}


/* Fonction create_thumb(): Création des vignettes 

	insert_bdd.php
*/

function create_thumb($thumb_w, $thumb_h, $image) {

	list($origin_w, $origin_h) = getimagesize($image);
	$origin_ratio = round($origin_w / $origin_h, 1);
	$outFile = str_replace("photos/img", "photos/thumb", $image);

	if ($origin_w != null && $origin_h != null) {
		if ($thumb_w / $thumb_h > $origin_ratio) {
    		$thumb_w = $thumb_h * $origin_ratio;
			} else {
    		$thumb_h = $thumb_w / $origin_ratio;
			}

		if ($origin_w >= 400 && $origin_h >= 400) {
			$image = new Imagick($image);				// !!!
			$image->thumbnailImage($thumb_w, $thumb_h);
			$image->writeImage($outFile);
			$image->destroy();
			}
		}
	}

	
/* Fonction in_bdd(): test si la photo est déjà dans la bdd 

	insert_bdd.php
*/

function in_bdd($image) {
	try {
		$conn3 = new PDO('sqlite:db_photo.sqlite3');
		#$query3 = "SELECT filename FROM photos WHERE instr(filename, '". $file . "') > 0;";
		$query3 = "SELECT filename FROM photos WHERE filename = :filename";
		$stmt = $conn3->prepare($query3);
		$stmt->bindParam(':filename', $image, PDO::PARAM_STR);

		$stmt->execute();
		$result3 = $stmt->fetchAll(PDO::FETCH_ASSOC);
		if (count($result3) > 0) {
			return true;
			} else {
			return false;
			}
		$conn3 = null;	
   		}
    catch(PDOException $e) {
        echo $e->getMessage();
        }
	}


//

function _pr($d) {
    echo "<div style='border: 1px solid#ccc; padding: 10px;'>";
    echo '<strong>' . debug_backtrace()[0]['file'] . ' ' . debug_backtrace()[0]['line'] . '</strong>';
    echo "</div>";
    echo '<pre>';
    if(is_array($d)) {
    	print_r($d);
    	} else if(is_object($d)) {
    	var_dump($d);
    	}
    echo '</pre>';
	}



/* return geo exif in a nice form

*/

function geo_frac2dec($str) {
	@list( $n, $d ) = explode( '/', $str );
	if ( !empty($d) )
		return $n / $d;
	return $str;
}


/*
33° 52.37′ 0″ S 151° 9.06′ 0″ E
*/


function geo_pretty_fracs2dec($fracs) {
	return	geo_frac2dec($fracs[0]) . '&deg; ' .
		geo_frac2dec($fracs[1]) . '&prime; ' .
		geo_frac2dec($fracs[2]) . '&Prime; ';
}


/* 
to GoogleMaps 
*/

function geo_single_fracs2dec($fracs) {
	return	geo_frac2dec($fracs[0]) +
		geo_frac2dec($fracs[1]) / 60 +
		geo_frac2dec($fracs[2]) / 3600;
}

/**/
function host() {
	$pv_sslport=443;
	//$pv_serverport=80; 
	//$pv_servername="sur-le-sentier.fr";
		
	$pv_URIprotocol = isset($_SERVER["HTTPS"]) ? (($_SERVER["HTTPS"]==="on" || $_SERVER["HTTPS"]===1 || $_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://") :  (($_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://");
	if ($_SERVER['HTTP_HOST'] == "sur-le-sentier.fr") {
		$host = $pv_URIprotocol . $_SERVER['HTTP_HOST'] . "/";
		}
	elseif ($_SERVER['HTTP_HOST'] == "airbook.local") {
		$host = $pv_URIprotocol . $_SERVER['HTTP_HOST'] . "/sls/";
		}
	return $host;
	}


class AdvancedFilesystemIterator extends ArrayIterator
	{
		public function __construct(string $path, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS)
		{
			parent::__construct(iterator_to_array(new FilesystemIterator($path, $flags)));
		}
	
		public function __call(string $name, array $arguments)
		{
			if (preg_match('/^sortBy(.*)/', $name, $m)) return $this->sort('get' . $m[1]);
			throw new MemberAccessException('Method ' . $methodName . ' not exists');
		}
	
		public function sort($method)
		{
			if (!method_exists('SplFileInfo', $method)) throw new InvalidArgumentException(sprintf('Method "%s" does not exist in SplFileInfo', $method));
	
			$this->uasort(function(SplFileInfo $a, SplFileInfo $b) use ($method) { return (is_string($a->$method()) ? strnatcmp($a->$method(), $b->$method()) : $b->$method() - $a->$method()); });
	
			return $this;
		}
	
		public function limit(int $offset = 0, int $limit = -1)
		{
			return parent::__construct(iterator_to_array(new LimitIterator($this, $offset, $limit))) ?? $this;
		}
	
		public function match(string $regex, int $mode = RegexIterator::MATCH, int $flags = 0, int $preg_flags = 0)
		{
			return parent::__construct(iterator_to_array(new RegexIterator($this, $regex, $mode, $flags, $preg_flags))) ?? $this;
		}
	}

/* 
Suppress keywords like _vert_, _violet_...
*/
function clean_keywords($keywords) {
	$v = preg_replace( "/_\w+_/", "", $keywords );
	$v = str_replace(",,", ",", $v);
	//$v= (substr($v, strlen($v)-1) == ",") ? substr($v, 0, -1) : $v;
	$v= rtrim($v, ",");
	$v= ltrim($v, ",");
	return $v;
}

function data_for_lightbox($data) {
	
	$filename = $data['filename'];
	$title_thumb = pathinfo($filename, PATHINFO_FILENAME);
	
	$aperture = $data['aperture'];
	$model = $data['model'];
	$objectif = $data['lens'];
	$speed = $data['speed'];
	$iso = $data['iso'];
	$exif = $model . " \u{30FB} " .  $objectif . " \u{30FB} " .  $speed . " \u{30FB} " .  $aperture . " \u{30FB} " .  $iso . "ISO";
	
	
	$title = $data['title'];
	$legende = $data['legende'];
	$file = basename($filename);
	if (!empty($title)) {
		$x = $title;
		$y = ($legende != "") ? $legende : "";
		}
	elseif (!empty($legende)) {
		$x= $legende;
		$y = "";
		}
	else {
		$x = $file;
		$y = "";
		}
	
	$creator = $data['creator']; 
		
	$big = host() . $data['filename'];
	$thumb = host() . str_replace("photos/img", "photos/thumb", $data['filename']);
	
	$keywords = str_replace(',', " \u{30FB} ", clean_keywords($data['keywords']));
	
	$lightbox = array();
	$lightbox['title_thumb'] = $title_thumb;
	$lightbox['exif'] = $exif;
	$lightbox['title'] = $x;
	$lightbox['legende'] = $y;
	$lightbox['thumb'] = $thumb;
	$lightbox['big'] = $big;
	$lightbox['keywords'] = $keywords;
	$lightbox['creator'] = $creator;
	
	return $lightbox;
}

/* ----------------------------------------------------

	Localization:
		
		-list_dir($dir) : liste le dossier des locales (Locale)
		-locale_language_from_browser($languages) : Identify language from the Accept-language HTTP header
		-localize() : fonction à ajouter sur chaque page
	
-----------------------------------------------------*/

function list_dir($dir) {
	if ($handle = opendir($dir)) {
		$files = array();
		while(false!==($file = readdir($handle))) {
			if (is_dir($dir . '/' . $file)) {
				$files[] = $file;
				}
			}
		closedir($handle);
		sort($files);
		$i = 0;
		global $myLanguages;
		$myLanguages = array();
		foreach($files as $f) {
			if (strstr($f,'.') == false) {
				$myLanguages[$i] = $f;
				$i++;
				}
			//$myLanguages[] = $f;
			}
		}
	else {
		echo 'error: missing language files';
		exit;
		}
	//print_r($myLanguages);
	return $myLanguages;
}

function locale_language_from_browser($languages) {
	  if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
		return FALSE;
	  }
	
	  // The Accept-Language header contains information about the language
	  // preferences configured in the user's browser / operating system.
	  // RFC 2616 (section 14.4) defines the Accept-Language header as follows:
	  //   Accept-Language = "Accept-Language" ":"
	  //                  1#( language-range [ ";" "q" "=" qvalue ] )
	  //   language-range  = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
	  // Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5"
	  $browser_langcodes = array();
	  if (preg_match_all('@(?<=[, ]|^)([a-zA-Z-]+|\\*)(?:;q=([0-9.]+))?(?:$|\\s*,\\s*)@', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']), $matches, PREG_SET_ORDER)) {
		foreach ($matches as $match) {
	
		  // We can safely use strtolower() here, tags are ASCII.
		  // RFC2616 mandates that the decimal part is no more than three digits,
		  // so we multiply the qvalue by 1000 to avoid floating point comparisons.
		  $langcode = strtolower($match[1]);
		  $qvalue = isset($match[2]) ? (double) $match[2] : 1;
		  $browser_langcodes[$langcode] = (int) ($qvalue * 1000);
		}
	  }
	
	  // We should take pristine values from the HTTP headers, but Internet Explorer
	  // from version 7 sends only specific language tags (eg. fr-CA) without the
	  // corresponding generic tag (fr) unless explicitly configured. In that case,
	  // we assume that the lowest value of the specific tags is the value of the
	  // generic language to be as close to the HTTP 1.1 spec as possible.
	  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 and
	  // http://blogs.msdn.com/b/ie/archive/2006/10/17/accept-language-header-for-internet-explorer-7.aspx
	  asort($browser_langcodes);
	  foreach ($browser_langcodes as $langcode => $qvalue) {
		$generic_tag = strtok($langcode, '-');
		if (!isset($browser_langcodes[$generic_tag])) {
		  $browser_langcodes[$generic_tag] = $qvalue;
		}
	  }
	
	  // Find the enabled language with the greatest qvalue, following the rules
	  // of RFC 2616 (section 14.4). If several languages have the same qvalue,
	  // prefer the one with the greatest weight.
	  $best_match_langcode = FALSE;
	  $max_qvalue = 0;
	  foreach ($languages as $langcode => $language) {
	
		// Language tags are case insensitive (RFC2616, sec 3.10).
		$langcode = strtolower($langcode);
	
		// If nothing matches below, the default qvalue is the one of the wildcard
		// language, if set, or is 0 (which will never match).
		$qvalue = isset($browser_langcodes['*']) ? $browser_langcodes['*'] : 0;
	
		// Find the longest possible prefix of the browser-supplied language
		// ('the language-range') that matches this site language ('the language tag').
		$prefix = $langcode;
		do {
		  if (isset($browser_langcodes[$prefix])) {
			$qvalue = $browser_langcodes[$prefix];
			break;
		  }
		} while ($prefix = substr($prefix, 0, strrpos($prefix, '-')));
	
		// Find the best match.
		if ($qvalue > $max_qvalue) {
		  $best_match_langcode = $language->language;
		  $max_qvalue = $qvalue;
		}
	  }
	return $best_match_langcode;
}

function localize($domain) {
	//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($liste_locale);
	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') );
}

?>