ZwiiCMS/module/gallery/gallery.php

441 lines
14 KiB
PHP

<?php
/**
* This file is part of Zwii.
*
* For full copyright and license information, please see the LICENSE
* file that was distributed with this source code.
*
* @author Rémi Jean <remi.jean@outlook.com>
* @copyright Copyright (C) 2008-2018, Rémi Jean
* @license GNU General Public License, version 3
* @link http://zwiicms.com/
* Modifié par @Gilux 2019
*/
class gallery extends common {
public static $actions = [
'config' => self::GROUP_MODERATOR,
'delete' => self::GROUP_MODERATOR,
'dirs' => self::GROUP_MODERATOR,
'edit' => self::GROUP_MODERATOR,
'index' => self::GROUP_VISITOR
];
public static $directories = [];
public static $firstPictures = [];
public static $galleries = [];
public static $pictures = [];
const GALLERY_VERSION = '2.0';
/**
* Configuration
*/
public function config() {
// Liste des galeries
$galleries = $this->getData(['module', $this->getUrl(0)]);
if($galleries) {
ksort($galleries);
foreach($galleries as $galleryId => $gallery) {
// Erreur dossier vide
if(is_dir($gallery['config']['directory'])) {
if(count(scandir($gallery['config']['directory'])) === 2) {
$gallery['config']['directory'] = '<span class="galleryConfigError">' . $gallery['config']['directory'] . ' (dossier vide)</span>';
}
}
// Erreur dossier supprimé
else {
$gallery['config']['directory'] = '<span class="galleryConfigError">' . $gallery['config']['directory'] . ' (dossier introuvable)</span>';
}
// Met en forme le tableau
self::$galleries[] = [
$gallery['config']['name'],
$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')
])
];
}
}
// Soumission du formulaire
if($this->isPost()) {
$galleryId = helper::increment($this->getInput('galleryConfigName', helper::FILTER_ID, true), (array) $this->getData(['module', $this->getUrl(0)]));
$this->setData(['module', $this->getUrl(0), $galleryId, [
'config' => [
'name' => $this->getInput('galleryConfigName'),
'directory' => $this->getInput('galleryConfigDirectory', helper::FILTER_STRING_SHORT, true)
],
'legend' => []
]]);
// Valeurs en sortie
$this->addOutput([
'redirect' => helper::baseUrl() . $this->getUrl(),
'notification' => 'Modifications enregistrées',
'state' => true
]);
}
// Valeurs en sortie
$this->addOutput([
'title' => 'Configuration du module',
'view' => 'config'
]);
}
/**
* Suppression
*/
public function delete() {
// 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' => 'Suppression non autorisée'
]);
}
// Suppression
else {
$this->deleteData(['module', $this->getUrl(0), $this->getUrl(2)]);
// Valeurs en sortie
$this->addOutput([
'redirect' => helper::baseUrl() . $this->getUrl(0) . '/config',
'notification' => 'Galerie supprimée',
'state' => true
]);
}
}
/**
* Liste des dossiers
*/
public function dirs() {
// Valeurs en sortie
$this->addOutput([
'display' => self::DISPLAY_JSON,
'content' => galleriesHelper::scanDir(self::FILE_DIR.'source')
]);
}
/**
* Édition
*/
public function edit() {
// Jeton incorrect
if ($this->getUrl(3) !== $_SESSION['csrf']) {
// Valeurs en sortie
$this->addOutput([
'redirect' => helper::baseUrl() . $this->getUrl(0) . '/config',
'notification' => 'Action non autorisée'
]);
}
// 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 = $this->getInput('galleryEditName', helper::FILTER_ID, true);
if($galleryId !== $this->getUrl(2)) {
// Incrémente le nouvel id de la galerie
$galleryId = helper::increment($galleryId, $this->getData(['module', $this->getUrl(0)]));
// Supprime l'ancienne galerie
$this->deleteData(['module', $this->getUrl(0), $this->getUrl(2)]);
}
$legends = [];
foreach((array) $this->getInput('legend', null) as $file => $legend) {
$file = str_replace('.','',$file);
$legends[$file] = helper::filter($legend, helper::FILTER_STRING_SHORT);
}
$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)
],
'legend' => $legends
]]);
// Valeurs en sortie
$this->addOutput([
'redirect' => helper::baseUrl() . $this->getUrl(0) . '/config',
'notification' => 'Modifications enregistrées',
'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 @getimagesize($fileInfos->getPathname())) {
self::$pictures[$fileInfos->getFilename()] = [
$fileInfos->getFilename(),
template::text('legend[' . $fileInfos->getFilename() . ']', [
'value' => $this->getData(['module', $this->getUrl(0), $this->getUrl(2), 'legend', str_replace('.','',$fileInfos->getFilename())])
])
];
}
}
}
// Valeurs en sortie
$this->addOutput([
'title' => $this->getData(['module', $this->getUrl(0), $this->getUrl(2), 'config', 'name']),
'view' => 'edit'
]);
}
}
/**
* Accueil (deux affichages en un pour éviter une url à rallonge)
*/
public function index() {
// 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 @getimagesize($fileInfos->getPathname())) {
// contrôle et traite éventuellement les images affichées dans la galerie
$imgalerie = str_replace('\\','/',$fileInfos->getPathname());
galleriesHelper::controle($imgalerie);
self::$pictures[$directory . '/' . $fileInfos->getFilename()] = $this->getData(['module', $this->getUrl(0), $this->getUrl(1), 'legend', str_replace('.','',$fileInfos->getFilename())]);
}
}
}
// Affichage du template
if(self::$pictures) {
ksort(self::$pictures);
// Valeurs en sortie
$this->addOutput([
'showBarEditButton' => true,
'title' => $this->getData(['module', $this->getUrl(0), $this->getUrl(1), 'config', 'name']),
'vendor' => ['js'],
'view' => 'gallery'
]);
}
// Pas d'image dans la galerie
else {
// Valeurs en sortie
$this->addOutput([
'access' => false
]);
}
}
}
// Liste des galeries
else {
foreach((array) $this->getData(['module', $this->getUrl(0)]) 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 @getimagesize($fileInfos->getPathname())) {
// contrôle et traite éventuellement les images affichées dans l'index de la galerie
$imgalerie = str_replace('\\','/',$fileInfos->getPathname());
galleriesHelper::controle($imgalerie);
self::$galleries[$galleryId] = $gallery;
self::$firstPictures[$galleryId] = $gallery['config']['directory'] . '/' . $fileInfos->getFilename();
continue(2);
}
}
}
}
// Valeurs en sortie
$this->addOutput([
'showBarEditButton' => true,
'showPageContent' => true,
'vendor' => ['js'],
'view' => 'index'
]);
}
}
}
class galleriesHelper extends helper {
/**
* Scan le contenu d'un dossier et de ses sous-dossiers
* @param string $dir Dossier à scanner
* @return array
*/
public static function scanDir($dir) {
$dirContent = [];
$iterator = new DirectoryIterator($dir);
foreach($iterator as $fileInfos) {
if($fileInfos->isDot() === false AND $fileInfos->isDir()) {
$dirContent[] = $dir . '/' . $fileInfos->getBasename();
$dirContent = array_merge($dirContent, self::scanDir($dir . '/' . $fileInfos->getBasename()));
}
}
return $dirContent;
}
// relevés exif gps des photos
public static function gps_exif($foto) {
if (!preg_match('/(\.jpe?g)$/i', $foto)) {
return null;
}
if (function_exists('exif_read_data')) {
$exif = @exif_read_data($foto, 0, true);
if ($exif && @$exif['GPS']['GPSLongitude'][0]) {
$latitude = self::gps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
$longitude = self::gps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
if (!empty($exif['GPS']['GPSAltitude'])) {
$alt = explode('/',$exif['GPS']['GPSAltitude']);
$altitude = round($alt[0] / $alt[1]);
}
else { $altitude = 0; }
if (!isset($latitude) || !isset($longitude)) {
return null; }
else {
return ($latitude.'¤'.$longitude.'¤'.$altitude);
}
}
}
}
public static function gps($coordinate, $hemisphere) {
if (is_string($coordinate)) {
$coordinate = array_map('trim', explode(',', $coordinate));
}
for ($i = 0; $i < 3; $i++) {
$part = explode('/', $coordinate[$i]);
if (count($part) == 1) {
$coordinate[$i] = $part[0];
} elseif (count($part) == 2) {
$coordinate[$i] = floatval($part[0])/floatval($part[1]);
} else {
$coordinate[$i] = 0;
}
}
list($degrees, $minutes, $seconds) = $coordinate;
$sign = ($hemisphere == 'W' || $hemisphere == 'S') ? -1 : 1;
return $sign * ($degrees + $minutes/60 + $seconds/3600);
}
// formatage light des noms d'images
public static function formate($foto) {
$foto = trim($foto);
$foto = preg_replace('/[^[:alnum:]_.\-\/]/', '', $foto);
return $foto;
}
// reorientation
public static function reorientation($foto) {
$size = getimagesize($foto);
$mime = $size['mime'];
if ((function_exists('exif_read_data')) && ($mime == 'image/jpeg'))
{
$exif = @exif_read_data($foto);
$image = imagecreatefromstring(file_get_contents($foto));
if ($image !== false) {
$orientation = isset($exif['Orientation']) === true ? $exif['Orientation'] : '';
if ( (!empty($orientation)) && ($orientation != 1) )
{
switch($orientation)
{
case 3:
$image = imagerotate($image,180,0);
break;
case 6:
$image = imagerotate($image,-90,0);
break;
case 8:
$image = imagerotate($image,90,0);
break;
}
imagejpeg($image, $foto, 90);
}
}
}
}
// redimension
public static function redimension($foto) {
$max_size = 1280;// dimension du plus petit côté
$infoto = getimagesize($foto);
$large = $infoto[0];
$haut = $infoto[1];
$type = $infoto[2];
// seules les images/jpeg sont redimensionnées
if (($type == 2) && ($large > $max_size) && ($haut > $max_size)) {
$imar = substr(strrchr($foto, '/'), 1);
$urlimar = str_replace($imar,'',$foto);
$backup = $urlimar.'backup';
if(!is_dir($backup)) {
@mkdir($backup);
}
$extension = strrchr($imar,'.');
$namimar = str_replace($extension,'',$imar);
$redimg = $urlimar.$namimar.'_t1280.jpg';
$backimg = $backup.'/'.strtolower(str_replace('.jpeg','.jpg',$imar));
$src = imagecreatefromjpeg($foto);
imageinterlace($src, true);
if ($large > $haut) {
$im = imagecreatetruecolor(round(($max_size/$haut)*$large), $max_size);
imagecopyresampled($im, $src, 0, 0, 0, 0, round(($max_size/$haut)*$large), $max_size, $large, $haut);
} else {
$im = imagecreatetruecolor($max_size, round(($max_size/$large)*$haut));
imagecopyresampled($im, $src, 0, 0, 0, 0, $max_size, round($haut*($max_size/$large)), $large, $haut);
}
imagejpeg($im, $redimg, 80);
imagedestroy($im);
rename($foto,$backimg);
echo '<script>document.location.reload(false);</script>';
exit(0);
}
}
// contrôle des photos
public static function controle($foto) {
$tn_tmp = substr(strrchr($foto, '/'), 1);
$url_picture = str_replace('/'.$tn_tmp,'',$foto);
$minidos = substr(strrchr($url_picture, '/'), 1);
$mini = 'site/file/cache/'.$minidos.'/'.$tn_tmp;
if (!file_exists($mini)) {
$valid = array('-', '_','.');
if (!ctype_alnum(str_replace($valid, '', $tn_tmp))) {
$nommage = self::formate($foto);
$foto = rename($foto,$nommage);
echo '<script>document.location.reload(false);</script>';
exit(0);
} else {
self::reorientation($foto);
self::redimension($foto);
}
}
return $foto;
clearstatcache();
}
}