<?php // Géo Photo Rando v3.4
self::$head_include = 'module/geophoto/include/leaflet-js.txt';
$controluser = ($this->getUser('group') >= self::GROUP_ADMIN && $this->getUser('password') === $this->getInput('DELTA_USER_PASSWORD')) ?? false;
	// Langue de l'interface en, es ou fr
	if ($controluser == true) {
		$langue = $this->getData(['config', 'i18n', 'langAdmin']);
	}
	else {
		if (isset($_SESSION['langFrontEnd']) && isset($_SESSION['translationType']) && $_SESSION['translationType'] === 'site') {
			$langue = $_SESSION['langFrontEnd'];
		}
		else {
			$langue = $this->getData(['config', 'i18n', 'langBase']);
		}
	}
	$param = '';
	if (file_exists('module/geophoto/lang/'. $langue .'/lex_geophoto.php')) {
		include('module/geophoto/lang/'. $langue .'/lex_geophoto.php');
	}
	else {
		include('module/geophoto/lang/'. $this->getData(['config', 'i18n', 'langAdmin']) .'/lex_geophoto.php');
	}

// Gestion des données
    $path = $_SERVER['SCRIPT_FILENAME'];
    $trail = explode('/index.php',$path);
    $root = $trail[0];
    $firstKey = key($module::$pictures);
    $url = dirname(helper::baseUrl(false) . $firstKey);
    $picpath = explode('/source/',$url);
    $picdir = end($picpath);
    $path_files = $root.'/site/file/source';
    $url_thumb = str_replace('source', 'thumb', $url);
    $path_thumb = str_replace('source', 'thumb', $path_files);
    $datas_json = $path_files.'/'.$picdir.'/'.'datas.json';
    $gpx_search = glob($path_files.'/'.$picdir.'/*.gpx',GLOB_NOCHECK);
    $gpx_found = basename($gpx_search[0]);
    $gpx_found_abs_url = $url.'/'.$gpx_found;
    $gpx_found_rel_url = $path_files.'/'.$picdir.'/'.$gpx_found;
    if (file_exists($gpx_found_rel_url)) {
	$valid = array('-', '_','.');
	if (!ctype_alnum(str_replace($valid, '', $gpx_found))) {
		$nommage = geophoto::formate($gpx_found_rel_url);
		$new_gpx_name = rename($gpx_found_rel_url,$nommage);
		echo '<script>document.location.reload(false);</script>';
	}
}
// Création de la base de données
if (!file_exists($datas_json)) {
    $tab  = array();
    $exif_present = false;
	$img_jpeg = ['jp**','JP**'];
    foreach ($img_jpeg as $jpeg) {
		foreach (glob($path_files.'/'.$picdir.'/*.'.$jpeg) as $filename) {
			$size = getimagesize($filename);
			if ($size[0]>$size[1]) { $width = '240'; } else { $width = '135'; }
			if (function_exists('exif_read_data') && mime_content_type($filename) == 'image/jpeg') {
			$exif = @exif_read_data($filename);
			if(isset($exif['GPSLongitude'][0]) && ($exif['GPSLongitude'] != $exif['GPSLatitude'])) {
				$exif_present = true;
				$lon = geophoto::getGps($exif['GPSLongitude'], $exif['GPSLongitudeRef']);
				$lat = geophoto::getGps($exif['GPSLatitude'], $exif['GPSLatitudeRef']);
				$name = basename($filename);
				$tab['file'][] = array('name' => $name, 'width' => $width, 'lon' => $lon, 'lat' => $lat);
			}
		}
	}
}
    if ((count($tab)) > 0) {
		file_put_contents($datas_json, json_encode($tab));
    }
}// !file existe datas-json

if (file_exists($datas_json)) {
// lecture des coordonnées
$tab = json_decode(file_get_contents($datas_json), true);
?>
<!-- Affichage -->
<div id="geophoto">
<div id="mapdiv"></div>
<?php if ($gpx_found != '*.gpx') { ?>
<div id="elevation-div"></div>
<div class="row">
	<div class="col4 offset4 divSelecTheme">
		<form method="POST" id="themeselect">
			<label for="selectheme"><?=$text['geophoto_view']['gallery'][20]?></label>
				<select name="selectheme" id="selectheme">
					<option value="delta-theme"><?=$text['geophoto_view']['gallery'][11]?></option>
					<option value="yellow-theme"><?=$text['geophoto_view']['gallery'][15]?></option>
					<option value="lime-theme"><?=$text['geophoto_view']['gallery'][12]?></option>
					<option value="lightblue-theme"><?=$text['geophoto_view']['gallery'][18]?></option>
					<option value="steelblue-theme"><?=$text['geophoto_view']['gallery'][13]?></option>
					<option value="purple-theme"><?=$text['geophoto_view']['gallery'][14]?></option>
					<option value="magenta-theme"><?=$text['geophoto_view']['gallery'][17]?></option>
					<option value="red-theme"><?=$text['geophoto_view']['gallery'][16]?></option>
				</select>
			<input type="submit" value="<?=$text['geophoto_view']['gallery'][19]?>" class="button">
		</form>
	</div>
</div>
<?php
if (isset($_POST['selectheme'])) { $theme = $_POST['selectheme']; }
elseif (isset($_SESSION['theme'])) { $theme = $_SESSION['theme']; }
else { $theme = 'delta-theme'; }
$_SESSION['theme'] = $theme;
?>
<script>
	$('#selectheme').val('<?=$theme?>');
</script>
<?php } ?>
<script>
<?php if ($gpx_found != '*.gpx') { ?>
let opts = {
    elevationControl: {
        url: '<?=$gpx_found_abs_url?>',
        options: {
            theme: '<?=$theme?>',
            collapsed: false,
            detached: true,
            elevationDiv: '#elevation-div',
            followMarker: false,
            imperial: false,
            reverseCoords: false,
            summary: 'line',
        },
    },
    layersControl: {
        options: {
            collapsed: true,
        },
    },
};
<?php } ?>
const mymap = new L.Map('mapdiv', {
	center: [42.7990,-0.5900],
	zoom: 8,
	fullscreenControl: true,
	fullscreenControlOptions: {
	position: 'topleft'
	}
});

let markers = L.markerClusterGroup();
let MyIcon = L.Icon.extend({
    options: {
       iconSize:     [38, 38],
       iconAnchor:   [16, 3],
       popupAnchor:  [6, 0]
    }
});
let PixIcon = new MyIcon({
    iconUrl: 'core/vendor/geolocation/images/appareil-photo.png',
});

const baselayers = {
"OpenHikingMap": L.tileLayer("https://tile.openmaps.fr/opentopomap/{z}/{x}/{y}.png", {
			maxZoom: 19,
			maxNativeZoom: 18,
			attribution: '&copy; <a href="//openmaps.fr/" target="_blank">OpenHikingMap</a> | SRTM (CC-BY-SA)'
		}),
"OpenStreetMap": L.tileLayer("//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
			maxZoom: 20,
			maxNativeZoom: 19,
			attribution: '&copy; <a href="//www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>'
		}),
"MapsRefugesInfo": L.tileLayer("//maps.refuges.info/hiking/{z}/{x}/{y}.png", {
			maxZoom: 19,
			maxNativeZoom: 18,
			attribution: '&copy; <a href="//wiki.openstreetmap.org/wiki/Hiking/mri" target="_blank">sly</a> | <a href="//www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>'
		}),
"CyclOSM" : L.tileLayer("//{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png", {
			maxZoom: 20,
			maxNativeZoom: 19,
			attribution: '<a href="//github.com/cyclosm/cyclosm-cartocss-style/releases" title="CyclOSM - Open Bicycle render" target="_blank">CyclOSM</a> | Map data: &copy; <a href="//www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
		}),
"Satellite Esri" : L.tileLayer("//server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", {
			maxZoom: 19,
			maxNativeZoom: 18,
			attribution: '&copy; <a href="//www.esri.com/fr-fr/" target="_blank">Esri</a> ArcGIS'
		}),
"Plan IGN fr" : L.tileLayer("https://data.geopf.fr/wmts?LAYER=GEOGRAPHICALGRIDSYSTEMS.PLANIGNV2&EXCEPTIONS=text/xml&FORMAT=image/png&SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&STYLE=normal&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}", {
			maxZoom: 19,
			maxNativeZoom: 18,
			attribution: '&copy;IGN <a href="//www.geoportail.gouv.fr/" target="_blank">Geoportail</a> <a href="//www.geoportail.gouv.fr/mentions-legales" target="_blank">Terms of Service</a>'
		}),
"Satellite IGN fr" : L.tileLayer("https://data.geopf.fr/wmts?LAYER=ORTHOIMAGERY.ORTHOPHOTOS&EXCEPTIONS=text/xml&FORMAT=image/jpeg&SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&STYLE=normal&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}", {
			maxZoom: 19,
			maxNativeZoom: 18,
			attribution: '&copy;IGN <a href="//www.geoportail.gouv.fr/" target="_blank">Geoportail</a> <a href="//www.geoportail.gouv.fr/mentions-legales" target="_blank">Terms of Service</a>'
		}),
"Raster IGN es": L.tileLayer("//tms-mapa-raster.ign.es/1.0.0/mapa-raster/{z}/{x}/{-y}.jpeg", {
			maxZoom: 18,
			maxNativeZoom: 17,
			attribution: '&copy; <a href="https://www.ign.es/" target="_blank">CC BY 4.0 ign.es</a>'
		})
};
const HikingTrails = L.tileLayer('//tile.waymarkedtrails.org/{id}/{z}/{x}/{y}.png', {
			id: 'hiking',
			opacity: 0.75,
			attribution: '&copy; <a href="//waymarkedtrails.org" target="_blank">Waymarked Trails</a> (<a href="//creativecommons.org/licenses/by-sa/3.0/" target="_blank">CC-BY-SA</a>)',
		});
const CyclingTrails = L.tileLayer('//tile.waymarkedtrails.org/{id}/{z}/{x}/{y}.png', {
			id: 'cycling',
			opacity: 0.75,
			attribution: '&copy; <a href="//waymarkedtrails.org" target="_blank">Waymarked Trails</a> (<a href="//creativecommons.org/licenses/by-sa/3.0/" target="_blank">CC-BY-SA</a>)',
		});
const MtbTrails = L.tileLayer('//tile.waymarkedtrails.org/{id}/{z}/{x}/{y}.png', {
			id: 'mtb',
			opacity: 0.75,
			attribution: '&copy; <a href="//waymarkedtrails.org" target="_blank">Waymarked Trails</a> (<a href="//creativecommons.org/licenses/by-sa/3.0/" target="_blank">CC-BY-SA</a>)',
		});
const Transportation = L.tileLayer('//server.arcgisonline.com/arcgis/rest/services/Reference/World_Transportation/MapServer/tile/{z}/{y}/{x}', {
			opacity: 1,
			attribution: '&copy; <a href="//www.esri.com/fr-fr/" target="_blank">Esri</a> ArcGIS',
		});
const ignRelief = L.tileLayer('https://data.geopf.fr/wmts?layer=ELEVATION.ELEVATIONGRIDCOVERAGE.SHADOW&style=estompage_grayscale&tilematrixset=PM&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix={z}&TILEROW={y}&TILECOL={x}', {
			attribution: '&copy;IGN <a href="https://www.geoportail.gouv.fr/" target="_blank">Géoportail</a> <a href="https://www.geoportail.gouv.fr/mentions-legales" target="_blank">Terms of Service</a>',
			maxNativeZoom: 18,
			maxZoom: 20,
			opacity: 0.70
		});
const ignPente = L.tileLayer('https://data.geopf.fr/wmts?LAYER=GEOGRAPHICALGRIDSYSTEMS.SLOPES.MOUNTAIN&EXCEPTIONS=text/xml&FORMAT=image/png&SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&STYLE=normal&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}', {
			attribution: '&copy;IGN <a href="https://www.geoportail.gouv.fr/" target="_blank">Géoportail</a> <a href="https://www.geoportail.gouv.fr/mentions-legales" target="_blank">Terms of Service</a>',
			maxNativeZoom: 17,
			maxZoom: 20,
			opacity: 0.70
		});

let layerControl = L.control.layers(baselayers).addTo(mymap);
	layerControl.addOverlay(HikingTrails, "<?=$text['geophoto_view']['gallery'][7]?>");
	layerControl.addOverlay(CyclingTrails, "<?=$text['geophoto_view']['gallery'][8]?>");
	layerControl.addOverlay(MtbTrails, "<?=$text['geophoto_view']['gallery'][9]?>");
	layerControl.addOverlay(Transportation, "<?=$text['geophoto_view']['gallery'][10]?>");
	layerControl.addOverlay(ignRelief, "Ombrage IGN fr");//	à traduire
	layerControl.addOverlay(ignPente, "Pente IGN fr");

	// fond de carte par défaut
	baselayers.OpenStreetMap.addTo(mymap);
	//HikingTrails.addTo(mymap);

	// échelle des cartes
	let scaleOptions = {
	  position: 'bottomleft',
	  metric: true, // meters/kilometers
	  imperial: false // feet/miles
	};
	let scaleControl = L.control.scale(scaleOptions);
	scaleControl.addTo(mymap);

	// detect fullscreen toggling
	mymap.on('enterFullscreen', function(){
		if(window.console) window.console.log('enterFullscreen');
	});
	mymap.on('exitFullscreen', function(){
		if(window.console) window.console.log('exitFullscreen');
	});

<?php
// Création des "markers"
if (isset($tab['file'])) {
    foreach( $tab['file'] as $key => $val ) {
        $img = $val;
        $url_img = file_exists($path_files.'/'.$picdir.'/'.$img['name']) ? $url.'/'.$img['name'] : null;
        $name_thumb = 'gpr-'.strtolower($img['name']);
        $url_mini = $url_thumb.'/'.$name_thumb;
        $path_mini = $path_thumb.'/'.$picdir.'/'.$name_thumb;
        $width = $img['width'];
		$interdits = ['_','-'];
		$autorise = ' ';
		$clean_name = str_replace(strrchr($img['name'],'.'),'',str_replace($interdits,$autorise,$img['name']));
// Gestion de la suppression de photo géotaguée
if (null == $url_img) {
	if (file_exists($datas_json)) {
	unlink($datas_json);
	}
	if (file_exists($path_mini)) {
	unlink($path_mini);
	}
		echo'document.getElementById(\'mapdiv\').innerHTML=\'<div id="missing_pic">'.$text['geophoto_view']['gallery'][2].'</span></div>\';';
	}
        echo "var marker = L.marker([$img[lat],$img[lon]], {icon: PixIcon}).bindPopup('<div style=\"width:".$width."px;\"><a class=\"popimg\" data-lity href=\"".$url_img."\" title=\"".$clean_name."\"><img src=\"".$url_mini."\" alt=\"".$clean_name."\"></a></div>', {maxWidth: ".$width."-5});\n";

        echo "marker.on('mouseover', function (e) {
            this.openPopup();
        });
        markers.addLayer(marker);\n\n";
    }
}
?>
	// ajoute les "markers"
	mymap.addLayer(markers);
<?php
if ($gpx_found != '*.gpx') {
	// détermination de la langue utilisée
	$lang = $this->getData(['config', 'i18n', 'langBase']);
	if( $this->getInput('DELTA_I18N_SITE') !== '' && $this->getInput('DELTA_I18N_SITE') !== null && $this->getInput('DELTA_I18N_SITE') !== 'base') $lang = $this->getInput('DELTA_I18N_SITE');
?>
	// affichage de l'élévation
	let controlElevation = L.control.elevation(opts.elevationControl.options);
	controlElevation.addTo(mymap);
	controlElevation.load(opts.elevationControl.url);

	// localisation
	let mylocale = {
	"Total Length: ": "<?=$text['geophoto_view']['gallery'][3]?>: ",
	"Max Elevation: ": "<?=$text['geophoto_view']['gallery'][4]?>: ",
	"Min Elevation: ": "<?=$text['geophoto_view']['gallery'][5]?>: ",
	"Altitude": "<?=$text['geophoto_view']['gallery'][6]?>"
	};

	L.registerLocale('<?=$lang?>', mylocale);
	L.setLocale('<?=$lang?>');

	// checkbox *.gpx
	mymap.on('eledata_loaded', function(e) {
	layerControl.addOverlay(e.layer, e.name);
	});
<?php } ?>
	mymap.fitBounds(markers.getBounds());
</script>
</div>
<!-- *************************** Galerie *************************** -->
<div id="galerie" style="display: none;">
<?php
// réinitialisation de la bdd
if (isset($_POST['initbdd'])) {
	unlink($datas_json);
	echo '<script>document.location.href = "';
	echo helper::baseUrl() . $this->getUrl(0);
	echo '";</script>';
	}
} else { ?>
<div id="galerie">
<?php }
 $i = 1;
 $picturesNb = count($module::$pictures);
 foreach($module::$pictures as $picture => $legend):
	 if($i % 6 === 1): ?>
		<div class="row">
	 <?php endif; ?>
		<div class="col2 gallery">
			<a href="<?=$picture?>"<?php if ( $picture === $this->getData(['module',$this->getUrl(0),$this->getUrl(1),'config','homePicture']) )  { echo ' id="homePicture"'; }	?> class="geophotoGalleryPicture" style="background-image:url('<?=$module::$thumbs[$picture]?>')" data-caption="<?=$legend?>" title="<?=str_replace(strrchr($picture,'.'),'',basename(str_replace('_',' ',$picture)))?>">
			<?php if (!empty($legend)):
			echo '<div class="geophotoGalleryName">';
				$shortenedLegend = helper::subword($legend, 0, 20);
				if ( strlen($shortenedLegend) < strlen($legend) ) $legend = $shortenedLegend.'...';
				echo $legend;
			echo '</div>';
			endif; ?></a>
			</div>
	<?php if($i % 6 === 0 OR $i === $picturesNb): ?>
		</div>
	<?php endif;
	$i++;
	endforeach; ?>
</div><!-- /galerie -->
<div id="infos">
<?php
$descriptif = 'infos-'.$langue;
	// texte informatif
	$infos = $path_files.'/'.$picdir.'/'.$descriptif;
	$infos_txt = $infos.'.txt';//v 2.2
	$infos_htm = $infos.'.htm';

if (file_exists($infos_htm)) {
	readfile($infos_htm);
}
// v 2.5, conversion des fichiers.txt en fichiers.htm
elseif (file_exists($infos_txt)) {
	$oldext = explode('.', basename($infos_txt));
	$changethisext = $oldext[1];
	$renommage = str_replace($changethisext,'htm',$infos_txt);
	$new_infos_ext = rename($infos_txt, $renommage);
    }
?>
</div>
<div class="row back">
	<div class="col2">
		<?php echo template::button('geophotoGalleryBack', [
			'class' => 'buttonGrey backbutt',
			'href' => helper::baseUrl() . $this->getUrl(0),
			'ico' => 'left',
			'value' => $this->getData(['module', $this->getUrl(0), 'config', 'texts', 'backButton'])
		]); ?>
	</div>
	<div class="col4 offset2">
        <?php if (file_exists($datas_json)) : echo template::button('geophotoGalleryShowpics', [
            'class' => 'buttonShowpics buttonGrey',
            'href' => helper::baseUrl() . $this->getUrl(0).'/'.$this->getUrl(1).'#galerie',
            'value' => $this->getData(['module', $this->getUrl(0), 'config', 'texts', 'showPics'])
        ]); endif; ?>
	</div>
	<div class="col2 offset2">
		<?php if (($this->getUser('group') >= self::GROUP_EDITOR) AND file_exists($datas_json)) : ?>
			<form method="post">
			<input type="submit" value="<?=$this->getData(['module', $this->getUrl(0), 'config', 'texts', 'reinitBDD'])?>" name="initbdd" class="button reinit" title="<?=$text['geophoto_view']['gallery'][0]?>" Onclick="this.value='<?=$text['geophoto_view']['gallery'][1]?>'">
			</form>
	<?php endif; ?>
	</div>
</div>
