<?php
/**
 * Géo Photo Rando
 * @license GNU General Public License, version 3
 * @link https://deltacms.fr/
 * @copyright 2020 © Lionel Croquefer
 */
setlocale (LC_NUMERIC,'English','en_US','en_US.UTF-8');
class geophoto extends common {
	const VERSION = '3.4';
	const REALNAME = 'Géo Photo Rando';
	const DELETE = true;
	const UPDATE = '0.0';
	const DATADIRECTORY = '';
	const MINIATURE = 360;
	const TN_PREFIX = 'gpr-';
	const SORT_ASC = 'SORT_ASC';
	const SORT_DSC = 'SORT_DSC';
	const SORT_HAND = 'SORT_HAND';

	public static $directories = [];
	public static $firstPictures = [];
	public static $galleries = [];
	public static $galleriesId = [];
	public static $pictures = [];
	public static $picturesId = [];
	public static $thumbs = [];
	public static $actions = [
		'config' => self::GROUP_EDITOR,
		'delete' => self::GROUP_MODERATOR,
		'dirs' => self::GROUP_EDITOR,
		'sortGalleries' => self::GROUP_EDITOR,
		'sortPictures' => self::GROUP_EDITOR,
		'edit' => self::GROUP_EDITOR,
		'texts' => self::GROUP_EDITOR,
		'index' => self::GROUP_VISITOR
	];

	/**
	 * Mise à jour du module
	 * Appelée par les fonctions index et config
	*/
	private function update() {
		// Lexique
		$param = '';
		include('./module/geophoto/lang/'. $this->getData(['config', 'i18n', 'langAdmin']) . '/lex_geophoto.php');
		if( null === $this->getData(['module', $this->getUrl(0), 'config', 'versionData']) ) {
			$this->init();
		} else {
			// Version 2.4
			if (version_compare($this->getData(['module', $this->getUrl(0), 'config', 'versionData']), '2.4', '<') ) {
				$this->setData(['module', $this->getUrl(0), 'config', 'texts', 'backButton', $text['geophoto']['init'][0]]);
				$this->setData(['module', $this->getUrl(0), 'config', 'texts', 'showPics', $text['geophoto']['init'][1]]);
				$this->setData(['module', $this->getUrl(0), 'config', 'texts', 'noAlbum', $text['geophoto']['init'][2]]);
				$this->setData(['module', $this->getUrl(0), 'config', 'texts', 'reinitBDD', $text['geophoto']['init'][3]]);
				$this->setData(['module', $this->getUrl(0), 'config', 'versionData','2.4']);
			}
			// Version 2.9
			if (version_compare($this->getData(['module', $this->getUrl(0), 'config', 'versionData']), '2.9', '<') ) {
				$delta_theme = 'module/geophoto/view/gallery/elevation-theme.php';
				if (file_exists($delta_theme)) {
				unlink($delta_theme);
				}
				$oldcss = 'module/geophoto/view/gallery/gallery.css';
				if (file_exists($oldcss)) {
				unlink($oldcss);
				}
			}
			// Mise à jour de la version du module
			if (version_compare($this->getData(['module', $this->getUrl(0), 'config', 'versionData']), self::VERSION, '<') ) {
				$this->setData(['module', $this->getUrl(0), 'config', 'versionData', self::VERSION]);
			}
		}
	}

	/**
	 * Initialisation
	*/
	private function init() {
		// Lexique
		$param = '';
		include('./module/geophoto/lang/'. helper::lexlang($this->getData(['config', 'i18n', 'langBase']) , $this->getData(['config', 'i18n', 'langAdmin'])) . '/lex_geophoto.php');
		$this->setData(['module', $this->getUrl(0), 'config', 'versionData', self::VERSION]);
		$this->setData(['module', $this->getUrl(0), 'config', 'texts', 'backButton', $text['geophoto']['init'][0]]);
		$this->setData(['module', $this->getUrl(0), 'config', 'texts', 'showPics', $text['geophoto']['init'][1]]);
		$this->setData(['module', $this->getUrl(0), 'config', 'texts', 'noAlbum', $text['geophoto']['init'][2]]);
		$this->setData(['module', $this->getUrl(0), 'config', 'texts', 'reinitBDD', $text['geophoto']['init'][3]]);
	}

	/**
	 * Tri sans bouton
	 */
	public function sortGalleries () {
		// Autorisation
		$group = $this->getUser('group');
		if ($group === false ) $group = 0;
		if( $group < geophoto::$actions['sortGalleries'] ) {
			// Valeurs en sortie
			$this->addOutput([
				'access' => false
			]);
		} else {
		if($_POST['response']) {
			$data = explode('&',$_POST['response']);
			$data = str_replace('galleryTable%5B%5D=','',$data);
			for($i=0;$i<count($data);$i++) {
				$this->setData(['module', $this->getUrl(0), $data[$i], [
					'config' => [
						'name' => $this->getData(['module',$this->getUrl(0),$data[$i],'config','name']),
						'directory' => $this->getData(['module',$this->getUrl(0),$data[$i],'config','directory']),
						'homePicture' => $this->getData(['module',$this->getUrl(0),$data[$i],'config','homePicture']),
						'sort' => $this->getData(['module',$this->getUrl(0),$data[$i],'config','sort']),
						'position' => $i
					],
					'legend' => $this->getData(['module',$this->getUrl(0),$data[$i],'legend']),
					'order' => $this->getData(['module',$this->getUrl(0),$data[$i],'order'])
				]]);
			}
		}
	}
}

	/**
	 * Tri de la liste des images
	 *
	 */
	public function sortPictures() {
		// Autorisation
		$group = $this->getUser('group');
		if ($group === false ) $group = 0;
		if( $group < geophoto::$actions['sortPictures'] ) {
			// Valeurs en sortie
			$this->addOutput([
				'access' => false
			]);
		} else {
			if($_POST['response']) {
				$galleryName = $_POST['gallery'];
				$data = explode('&',$_POST['response']);
				$data = str_replace('galleryTable%5B%5D=','',$data);
				// Sauvegarder
				$this->setData(['module', $this->getUrl(0), $galleryName, [
					'config' => [
						'name' => $this->getData(['module',$this->getUrl(0),$galleryName,'config','name']),
						'directory' => $this->getData(['module',$this->getUrl(0),$galleryName,'config','directory']),
						'homePicture' => $this->getData(['module',$this->getUrl(0),$galleryName,'config','homePicture']),
						'sort' => $this->getData(['module',$this->getUrl(0),$galleryName,'config','sort']),
						'position' => $this->getData(['module',$this->getUrl(0),$galleryName,'config','position'])

					],
					'legend' => $this->getData(['module',$this->getUrl(0),$galleryName,'legend']),
					'order' => array_flip($data)
				]]);
			}
		}
	}

	/**
	 * Traduction de textes en langue frontend
	 *
	 */
	public function texts() {
		// Autorisation
		$group = $this->getUser('group');
		if ($group === false ) $group = 0;
		if( $group < geophoto::$actions['texts'] ) {
			// Valeurs en sortie
			$this->addOutput([
				'access' => false
			]);
		} else {
			// Lexique
			$param = '';
			include('./module/geophoto/lang/'. $this->getData(['config', 'i18n', 'langAdmin']) . '/lex_geophoto.php');

			// Soumission du formulaire
			if($this->isPost()) {
				$this->setData(['module', $this->getUrl(0), 'config', 'texts',[
					'backButton' => $this->getInput('geophotoTextsBackButton',helper::FILTER_STRING_SHORT),
					'noAlbum' => $this->getInput('geophotoTextsNoAlbum',helper::FILTER_STRING_SHORT),
					'showPics' => $this->getInput('geophotoTextsShowPics',helper::FILTER_STRING_SHORT),
					'reinitBDD' => $this->getInput('geophotoTextsReinitBDD',helper::FILTER_STRING_SHORT)
				]]);

				$this->setData(['module', $this->getUrl(0), 'config', 'versionData', self::VERSION]);

				$this->addOutput([
					'redirect' => helper::baseUrl() . $this->getUrl(0) . '/config',
					'notification' => $text['geophoto']['texts'][0],
					'state' => true
				]);
			}

			$this->addOutput([
				'title' => $text['geophoto']['texts'][1],
				'view' => 'texts',
			]);
		}
	}

	/**
	 * Configuration
	 */
	public function config() {
		// Autorisation
		$group = $this->getUser('group');
		if ($group === false ) $group = 0;
		if( $group < geophoto::$actions['config'] ) {
			// Valeurs en sortie
			$this->addOutput([
				'access' => false
			]);
		} else {
			// Lexique
			$param = '';
			include('./module/geophoto/lang/'. $this->getData(['config', 'i18n', 'langAdmin']) . '/lex_geophoto.php');

		//Affichage de la galerie triée sauf pour la fausse galerie 'config'
		$g = $this->getData(['module', $this->getUrl(0)]);
		unset($g['config']);
		$p = helper::arrayCollumn(helper::arrayCollumn($g,'config'),'position');
		asort($p,SORT_NUMERIC);
		$galleries = [];
		foreach ($p as $positionId => $item) {
			$galleries [$positionId] = $g[$positionId];
		}
		// Traitement de l'affichage
		if($galleries) {
			foreach($galleries as $galleryId => $gallery) {
				// Erreur dossier vide
				if (isset($gallery['config']['directory']) && is_dir($gallery['config']['directory'])) {
					if(count(scandir($gallery['config']['directory'])) === 2) {
						$gallery['config']['directory'] = '<span class="galleryConfigError">' . $gallery['config']['directory'] . $text['gallery']['config'][0].'</span>';
					}
				}
				// Erreur dossier supprimé
				else {
					$gallery['config']['directory'] = '<span class="galleryConfigError">' . $gallery['config']['directory'] . $text['gallery']['config'][1].'</span>';
				}
				// Met en forme le tableau
				self::$galleries[] = [
					template::ico('sort'),
					$gallery['config']['name'],
					str_replace('site/file/source/','',$gallery['config']['directory']),
					template::button('galleryConfigEdit' . $galleryId , [
						'href' => helper::baseUrl() . $this->getUrl(0) . '/edit/' . $galleryId . '/' . $_SESSION['csrf'],
						'value' => template::ico('pencil')
					]),
					template::button('galleryConfigDelete' . $galleryId, [
						'class' => 'galleryConfigDelete buttonRed',
						'href' => helper::baseUrl() . $this->getUrl(0) . '/delete/' . $galleryId . '/' . $_SESSION['csrf'],
						'value' => template::ico('cancel'),
						'disabled' => $this->getUser('group') >= self::GROUP_MODERATOR ? false : true
					])
				];
				// Tableau des id des galleries pour le drag and drop
				self::$galleriesId[] = $galleryId;
			}
		}
		// Soumission du formulaire d'ajout d'une galerie
		if($this->isPost()) {
			if (!$this->getInput('galleryConfigFilterResponse')) {
				$galleryId = helper::increment($this->getInput('galleryConfigName', helper::FILTER_ID, true), (array) $this->getData(['module', $this->getUrl(0)]));
				// définir une vignette par défaut
				$directory = $this->getInput('galleryConfigDirectory', helper::FILTER_STRING_SHORT, true);
				$iterator = new DirectoryIterator($directory);
				foreach($iterator as $fileInfos) {
					if($fileInfos->isDot() === false AND $fileInfos->isFile() AND substr(mime_content_type($fileInfos->getPathname()), 0, 5) == 'image') {
						// Créer la miniature si manquante
						if (!file_exists( str_replace('source','thumb',$fileInfos->getPath()) . '/' . self::TN_PREFIX . strtolower($fileInfos->getFilename()))) {
							$this->makeThumb($fileInfos->getPathname(),
								str_replace('source','thumb',$fileInfos->getPath()) . '/' . self::TN_PREFIX . strtolower($fileInfos->getFilename()),
								self::MINIATURE);
						$exif_data_file = $fileInfos->getPath().'/datas.json';
						if (file_exists($exif_data_file)) {
						unlink($exif_data_file);
						}
						}
						// Miniatures
						$homePicture = strtolower($fileInfos->getFilename());
					break;
					}
				}
				$this->setData(['module', $this->getUrl(0), $galleryId, [
					'config' => [
						'name' => $this->getInput('galleryConfigName'),
						'directory' => $this->getInput('galleryConfigDirectory', helper::FILTER_STRING_SHORT, true),
						'homePicture' => $homePicture,
						'sort' => self::SORT_ASC,
						'position' => $this->getData(['module',$this->getUrl(0)]) !== null ? count($this->getData(['module',$this->getUrl(0)])) + 1 : 0
					],
					'legend' => [],
					'order' => []
				]]);
				// Valeurs en sortie
				$this->addOutput([
					'redirect' => helper::baseUrl() . $this->getUrl(),
					'notification' => $text['gallery']['config'][2],
					'state' => true
				]);
			}
		}
		// Valeurs en sortie
		$this->addOutput([
			'title' => $text['gallery']['config'][3],
			'view' => 'config',
			'vendor' => [
				'tablednd'
			]
		]);
	}
}

	/**
	 * Suppression
	 */
	public function delete() {
		// Autorisation
		$group = $this->getUser('group');
		if ($group === false ) $group = 0;
		if( $group < geophoto::$actions['delete'] ) {
			// Valeurs en sortie
			$this->addOutput([
				'access' => false
			]);
		} else {
			// Lexique
			$param = '';
			include('./module/geophoto/lang/'. $this->getData(['config', 'i18n', 'langAdmin']) . '/lex_geophoto.php');

		// $url prend l'adresse sans le token
		// La galerie n'existe pas
		if($this->getData(['module', $this->getUrl(0), $this->getUrl(2)]) === null) {
			// Valeurs en sortie
			$this->addOutput([
				'access' => false
			]);
		}
		// Jeton incorrect
		if ($this->getUrl(3) !== $_SESSION['csrf']) {
			// Valeurs en sortie
			$this->addOutput([
				'redirect' => helper::baseUrl() . $this->getUrl(0) . '/config',
				'notification' => $text['gallery']['delete'][0]
			]);
		}
		// Suppression
		else {
			$this->deleteData(['module', $this->getUrl(0), $this->getUrl(2)]);
			// Valeurs en sortie
			$this->addOutput([
				'redirect' => helper::baseUrl() . $this->getUrl(0) . '/config',
				'notification' => $text['gallery']['delete'][1],
				'state' => true
			]);
		}
	}
}

	/**
	 * Liste des dossiers
	 */
	public function dirs() {
		// Autorisation
		$group = $this->getUser('group');
		if ($group === false ) $group = 0;
		if( $group < geophoto::$actions['dirs'] ) {
			$this->addOutput([
				'access' => false
			]);
		} else {
		// Valeurs en sortie
		$filter = ['jpg', 'jpeg'];
		$this->addOutput([
			'display' => self::DISPLAY_JSON,
			'content' => helper::scanDir(self::FILE_DIR.'source', $filter, $sort = true)
		]);
	}
}

	/**
	 * Édition
	 */
	public function edit() {
		// Autorisation
		$group = $this->getUser('group');
		if ($group === false ) $group = 0;
		if( $group < geophoto::$actions['edit'] ) {
			// Valeurs en sortie
			$this->addOutput([
				'access' => false
			]);
		} else {
			// Lexique
			$param = '';
			include('./module/geophoto/lang/'. $this->getData(['config', 'i18n', 'langAdmin']) . '/lex_geophoto.php');

		// Jeton incorrect
		if ($this->getUrl(3) !== $_SESSION['csrf']) {
			// Valeurs en sortie
			$this->addOutput([
				'redirect' => helper::baseUrl() . $this->getUrl(0) . '/config',
				'notification' => $text['gallery']['edit'][0]
			]);
		}
		// La galerie n'existe pas
		if($this->getData(['module', $this->getUrl(0), $this->getUrl(2)]) === null) {
			// Valeurs en sortie
			$this->addOutput([
				'access' => false
			]);
		}
		// La galerie existe
		else {
			// Soumission du formulaire
			if($this->isPost()) {
				// Si l'id a changée
				$galleryId = !empty($this->getInput('galleryEditName')) ? $this->getInput('galleryEditName', helper::FILTER_ID, true) : $this->getUrl(2);
				if($galleryId !== $this->getUrl(2)) {
					// Incrémente le nouvel id de la galerie
					$galleryId = helper::increment($galleryId, $this->getData(['module', $this->getUrl(0)]));
					// Transférer la position des images
					$oldorder = $this->getData(['module',$this->getUrl(0), $this->getUrl(2),'order']);
					// Supprime l'ancienne galerie
					$this->deleteData(['module', $this->getUrl(0), $this->getUrl(2)]);
				}
				// légendes
				$legends = [];
				foreach((array) $this->getInput('legend', null) as $file => $legend) {
					// Image de couverture par défaut si non définie
					$homePicture = $file;
					$file = str_replace('.','',$file);
					$legends[$file] = helper::filter($legend, helper::FILTER_STRING_SHORT);
				}
				// Photo de la page de garde de l'album définie dans form
				if (is_array($this->getInput('homePicture', null)) ) {
					$d = array_keys($this->getInput('homePicture', null));
					$homePicture = $d[0];
				}
				// Sauvegarder
					if ($this->getInput('galleryEditName')) {
				$this->setData(['module', $this->getUrl(0), $galleryId, [
					'config' => [
						'name' => $this->getInput('galleryEditName', helper::FILTER_STRING_SHORT, true),
						'directory' => $this->getInput('galleryEditDirectory', helper::FILTER_STRING_SHORT, true),
						'homePicture' => $homePicture,
						// pas d'ordre, on active le tri alpha
						'sort' => $this->getInput('galleryEditSort'),
						'position' => $this->getData(['module', $this->getUrl(0), $galleryId,'config','position'])

					],
					'legend' => $legends,
					'order' => empty($oldorder) ? $this->getData(['module', $this->getUrl(0), $galleryId, 'order']) : $oldorder
				]]);
				}
				// Valeurs en sortie
				$this->addOutput([
					'redirect' => helper::baseUrl() . $this->getUrl(0) . '/edit/' . $galleryId . '/' . $_SESSION['csrf'] ,
					'notification' => $text['gallery']['edit'][1],
					'state' => true
				]);
			}

			// Met en forme le tableau
			$directory = $this->getData(['module', $this->getUrl(0), $this->getUrl(2), 'config', 'directory']);
			if(is_dir($directory)) {
				$iterator = new DirectoryIterator($directory);

				foreach($iterator as $fileInfos) {
					if($fileInfos->isDot() === false AND $fileInfos->isFile() AND substr(mime_content_type($fileInfos->getPathname()), 0, 5) == 'image') {
						// Créer la miniature RFM si manquante
						if (!file_exists( str_replace('source','thumb',$fileInfos->getPath()) . '/' . strtolower($fileInfos->getFilename()))) {
							$this->makeThumb($fileInfos->getPathname(),
								str_replace('source','thumb',$fileInfos->getPath()) . '/' . strtolower($fileInfos->getFilename()),
								122);
						}
						self::$pictures[str_replace('.','',$fileInfos->getFilename())] = [
							template::ico('sort'),
							$fileInfos->getFilename(),
							template::checkbox( 'homePicture[' . $fileInfos->getFilename() . ']', true, '', [
								'checked' => $this->getData(['module', $this->getUrl(0), $this->getUrl(2),'config', 'homePicture']) === $fileInfos->getFilename() ? true : false,
								'class' => 'homePicture'
							]),
							template::text('legend[' . $fileInfos->getFilename() . ']', [
								'value' => $this->getData(['module', $this->getUrl(0), $this->getUrl(2), 'legend', str_replace('.','',$fileInfos->getFilename())])
							]),
							'<a href="' . str_replace('source','thumb',$directory) . '/' . self::TN_PREFIX . $fileInfos->getFilename() .'" rel="data-lity" data-lity=""><img src="'. str_replace('source','thumb',$directory) . '/' . strtolower($fileInfos->getFilename()) . '"></a>'
						];
						self::$picturesId [] = str_replace('.','',$fileInfos->getFilename());
					}
				}
				// Tri des images
				switch ($this->getData(['module', $this->getUrl(0), $this->getUrl(2), 'config', 'sort'])) {
					case self::SORT_HAND:
						$order = $this->getData(['module',$this->getUrl(0), $this->getUrl(2),'order']);
						if ($order) {
							foreach ($order as $key => $value) {
								if (array_key_exists($key,self::$pictures)) {
									$tempPictures[$key] = self::$pictures[$key];
									$tempPicturesId [] = $key;
								}
							}
							// Images ayant été ajoutées dans le dossier mais non triées
							foreach (self::$pictures as $key => $value) {
								if (!array_key_exists($key,$tempPictures)) {
									$tempPictures[$key] = self::$pictures[$key];
									$tempPicturesId [] = $key;
								}
							}
							self::$pictures = $tempPictures;
							self::$picturesId = $tempPicturesId;
						}
						break;
					case self::SORT_ASC:
						ksort(self::$pictures,SORT_NATURAL);
						sort(self::$picturesId,SORT_NATURAL);
						break;
					case self::SORT_DSC:
						krsort(self::$pictures,SORT_NATURAL);
						rsort(self::$picturesId,SORT_NATURAL);
						break;
				}
			}
			// Valeurs en sortie
			$this->addOutput([
				'title' => $this->getData(['module', $this->getUrl(0), $this->getUrl(2), 'config', 'name']),
				'view' => 'edit',
				'vendor' => [
					'tablednd'
				]
			]);
		}
	}
}

	/**
	 * Accueil (deux affichages en un pour éviter une url à rallonge)
	 */
	public function index() {
		// Mise à jour des données de module
		if ( null===$this->getData(['module', $this->getUrl(0), 'config', 'versionData']) || version_compare($this->getData(['module', $this->getUrl(0), 'config', 'versionData']), self::VERSION, '<') ) $this->update();
		// Images d'une galerie
		if($this->getUrl(1)) {
			// La galerie n'existe pas
			if($this->getData(['module', $this->getUrl(0), $this->getUrl(1)]) === null) {
				// Valeurs en sortie
				$this->addOutput([
					'access' => false
				]);
			}
			// La galerie existe
			else {
				// Images de la galerie
				$directory = $this->getData(['module', $this->getUrl(0), $this->getUrl(1), 'config', 'directory']);
				if(is_dir($directory)) {
					$iterator = new DirectoryIterator($directory);
					foreach($iterator as $fileInfos) {
						if($fileInfos->isDot() === false AND $fileInfos->isFile() AND substr(mime_content_type($fileInfos->getPathname()), 0, 5) == 'image') {
							self::$pictures[$directory . '/' . $fileInfos->getFilename()] = $this->getData(['module', $this->getUrl(0), $this->getUrl(1), 'legend', str_replace('.','',$fileInfos->getFilename())]);
							$picturesSort[$directory . '/' . $fileInfos->getFilename()] = $this->getData(['module', $this->getUrl(0), $this->getUrl(1), 'order', str_replace('.','',$fileInfos->getFilename())]);
							// Créer la miniature si manquante
							if (!file_exists( str_replace('source','thumb',$fileInfos->getPath()) . '/' . self::TN_PREFIX . strtolower($fileInfos->getFilename()))) {
								$this->makeThumb($fileInfos->getPathname(),
									str_replace('source','thumb',$fileInfos->getPath()) . '/' . self::TN_PREFIX . strtolower($fileInfos->getFilename()),
									self::MINIATURE);
						$exif_data_file = $fileInfos->getPath().'/datas.json';
						if (file_exists($exif_data_file)) {
						unlink($exif_data_file);
						}
							}
							// Définir la Miniature
							self::$thumbs[$directory . '/' . $fileInfos->getFilename()] = file_exists( str_replace('source','thumb',$directory) . '/' . self::TN_PREFIX . strtolower($fileInfos->getFilename()))
								? str_replace('source','thumb',$directory) . '/' . self::TN_PREFIX . strtolower($fileInfos->getFilename())
								: str_replace('source','thumb',$directory) . '/' . strtolower($fileInfos->getFilename());
						}
					}
					// Tri des images par ordre alphabétique
					switch ($this->getData(['module', $this->getUrl(0), $this->getUrl(1), 'config', 'sort'])) {
						case self::SORT_HAND:
							asort($picturesSort);
							if ($picturesSort) {
								foreach ($picturesSort as $name => $position) {
									$temp[$name] = self::$pictures[$name];
								}
								self::$pictures = $temp;
								break;
							}
						case self::SORT_DSC:
							krsort(self::$pictures,SORT_NATURAL);
							break;
						case self::SORT_ASC:
						default:
							ksort(self::$pictures,SORT_NATURAL);
							break;
					}
				}
				// Affichage du template
				if(self::$pictures) {
					// Valeurs en sortie
					$this->addOutput([
						'showBarEditButton' => true,
						'title' => $this->getData(['module', $this->getUrl(0), $this->getUrl(1), 'config', 'name']),
						'view' => 'gallery'
					]);
				}
				// Pas d'image dans la galerie
				else {
					// Valeurs en sortie
					$this->addOutput([
						'access' => false
					]);
				}
			}
		}
		// Liste des galeries
		else {
			// Tri des galeries suivant l'ordre défini sauf pour la fausse galerie 'config'
			$g = $this->getData(['module', $this->getUrl(0)]);
			unset($g['config']);
			$p = helper::arrayCollumn(helper::arrayCollumn($g,'config'),'position');
			asort($p,SORT_NUMERIC);
			$galleries = [];
			foreach ($p as $positionId => $item) {
				$galleries [$positionId] = $g[$positionId];
			}
			// Construire le tableau
			foreach((array) $galleries as $galleryId => $gallery) {
				if(is_dir($gallery['config']['directory'])) {
					$iterator = new DirectoryIterator($gallery['config']['directory']);
					foreach($iterator as $fileInfos) {
						if($fileInfos->isDot() === false AND $fileInfos->isFile() AND substr(mime_content_type($fileInfos->getPathname()), 0, 5) == 'image') {
							self::$galleries[$galleryId] = $gallery;
							// L'image de couverture est-elle supprimée ?
							if (file_exists( $gallery['config']['directory'] . '/' . $gallery['config']['homePicture'])) {
							// Créer la miniature si manquante
							if (!file_exists( str_replace('source','thumb',$gallery['config']['directory']) . '/' . self::TN_PREFIX . strtolower($gallery['config']['homePicture']))) {
								$this->makeThumb($gallery['config']['directory'] . '/' . str_replace(self::TN_PREFIX ,'',$gallery['config']['homePicture']),
									str_replace('source','thumb',$gallery['config']['directory']) . '/' . self::TN_PREFIX . strtolower($gallery['config']['homePicture']),
									self::MINIATURE);
						$exif_data_file = $fileInfos->getPath().'/datas.json';
						if (file_exists($exif_data_file)) {
						unlink($exif_data_file);
						}
								}
							// Définir l'image de couverture
							self::$firstPictures[$galleryId] = file_exists( str_replace('source','thumb',$gallery['config']['directory']) . '/' . self::TN_PREFIX . strtolower($gallery['config']['homePicture']))
								? str_replace('source','thumb',$gallery['config']['directory']) . '/' . self::TN_PREFIX . strtolower($gallery['config']['homePicture'])
								: str_replace('source','thumb',$gallery['config']['directory']) . '/' . strtolower($gallery['config']['homePicture']);
							} else {
								// homePicture contient une image invalide, supprimée ou déplacée
								// Définir l'image de couverture, première image disponible
								$this->makeThumb($fileInfos->getPath() . '/' . $fileInfos->getFilename(),
									str_replace('source','thumb',$fileInfos->getPath()) . '/' . self::TN_PREFIX . strtolower($fileInfos->getFilename()),
									self::MINIATURE);
						/*$exif_data_file = $fileInfos->getPath().'/datas.json';
						if (file_exists($exif_data_file)) {
						unlink($exif_data_file);
						}*/
							self::$firstPictures[$galleryId] = file_exists( str_replace('source','thumb',$fileInfos->getPath()) . '/' . self::TN_PREFIX . strtolower($fileInfos->getFilename()))
								? str_replace('source','thumb',$fileInfos->getPath()) . '/' . self::TN_PREFIX . strtolower($fileInfos->getFilename())
								: str_replace('source','thumb',$fileInfos->getPath()) . '/' . strtolower($fileInfos->getFilename());
							}
						}
						continue(1);
					}
				}
			}
			// Valeurs en sortie
			$this->addOutput([
				'showBarEditButton' => true,
				'showPageContent' => true,
				'view' => 'index'
			]);
		}
	}

// exif gps
	public static function gps2Num($coordPart) {
		if ($coordPart != 0) :
		$parts = explode('/', $coordPart);
		if (count($parts) <= 0) return 0;
		if (count($parts) == 1) return $parts[0];
		return floatval($parts[0]) / floatval($parts[1]);
		else : return false;
		endif;
		}
	public static function getGps($exifCoord, $hemi) {
		$degrees = count($exifCoord) > 0 ? geophoto::gps2Num($exifCoord[0]) : 0;
		$minutes = count($exifCoord) > 1 ? geophoto::gps2Num($exifCoord[1]) : 0;
		$seconds = count($exifCoord) > 2 ? geophoto::gps2Num($exifCoord[2]) : 0;
		$flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1;
		return $flip * ($degrees + $minutes / 60 + $seconds / 3600);
	}
// formatage light des noms des fichiers .gpx
	public static function formate($gpx) {
		return preg_replace('/[^[:alnum:]_.\-\/]/', '', trim($gpx));
		}

}
