Initial commit: FuZip - Application de fusion interactive de fichiers ZIP
- Backend PHP: architecture MVC avec API REST (upload, merge, preview, extract) - Frontend JavaScript: composants modulaires (arborescence, upload, themes, i18n) - Fonctionnalités: drag&drop, sélection exclusive, détection conflits, persistance état - Sécurité: validation stricte, isolation sessions, sanitization chemins - UI/UX: responsive, thèmes clair/sombre, multi-langue (FR/EN) - Documentation: README complet avec installation et utilisation
This commit is contained in:
190
core/Config.php
Normal file
190
core/Config.php
Normal file
@@ -0,0 +1,190 @@
|
||||
<?php
|
||||
/**
|
||||
* Configuration globale de FuZip
|
||||
*
|
||||
* Ce fichier contient toutes les constantes de configuration
|
||||
* pour l'application de fusion de fichiers ZIP.
|
||||
*/
|
||||
|
||||
class Config {
|
||||
/**
|
||||
* Taille maximale d'un fichier ZIP en octets (500 MB)
|
||||
* Modifié selon les besoins spécifiés dans le plan
|
||||
*/
|
||||
const MAX_FILE_SIZE = 500 * 1024 * 1024; // 500 MB
|
||||
|
||||
/**
|
||||
* Durée de vie d'une session en secondes (24 heures)
|
||||
* Après ce délai, les dossiers de session sont supprimés
|
||||
*/
|
||||
const SESSION_LIFETIME = 24 * 3600; // 24 heures
|
||||
|
||||
/**
|
||||
* Chemin absolu vers le dossier uploads
|
||||
* Utilise DIRECTORY_SEPARATOR pour compatibilité multi-plateforme
|
||||
*/
|
||||
const UPLOAD_DIR = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR;
|
||||
|
||||
/**
|
||||
* Extensions de fichiers interdites dans les ZIP
|
||||
* Pour des raisons de sécurité
|
||||
*/
|
||||
const FORBIDDEN_EXTENSIONS = [
|
||||
'exe', 'bat', 'sh', 'ps1', 'php', 'phtml',
|
||||
'php3', 'php4', 'php5', 'phps', 'cgi'
|
||||
];
|
||||
|
||||
/**
|
||||
* Types MIME autorisés pour les uploads
|
||||
*/
|
||||
const ALLOWED_MIME_TYPES = [
|
||||
'application/zip',
|
||||
'application/x-zip',
|
||||
'application/x-zip-compressed',
|
||||
'application/octet-stream' // Parfois utilisé pour les ZIP
|
||||
];
|
||||
|
||||
/**
|
||||
* Signatures magiques des fichiers ZIP (magic bytes)
|
||||
* Pour vérifier l'authenticité du fichier
|
||||
*/
|
||||
const ZIP_MAGIC_BYTES = [
|
||||
'504B0304', // PK.. (ZIP standard)
|
||||
'504B0506', // PK.. (ZIP vide)
|
||||
'504B0708' // PK.. (ZIP spanned)
|
||||
];
|
||||
|
||||
/**
|
||||
* Nombre maximum de fichiers par ZIP
|
||||
* Pour éviter les problèmes de performance
|
||||
*/
|
||||
const MAX_FILES_PER_ZIP = 10000;
|
||||
|
||||
/**
|
||||
* Profondeur maximale de l'arborescence
|
||||
* Pour éviter les problèmes de récursion
|
||||
*/
|
||||
const MAX_TREE_DEPTH = 50;
|
||||
|
||||
/**
|
||||
* Timeout pour le traitement d'un ZIP (en secondes)
|
||||
*/
|
||||
const PROCESSING_TIMEOUT = 300; // 5 minutes
|
||||
|
||||
/**
|
||||
* Taille du buffer pour le streaming de fichiers
|
||||
*/
|
||||
const STREAM_BUFFER_SIZE = 8192; // 8 KB
|
||||
|
||||
/**
|
||||
* Langues supportées
|
||||
*/
|
||||
const SUPPORTED_LANGUAGES = ['fr', 'en'];
|
||||
|
||||
/**
|
||||
* Langue par défaut
|
||||
*/
|
||||
const DEFAULT_LANGUAGE = 'fr';
|
||||
|
||||
/**
|
||||
* Mode debug (activer les logs détaillés)
|
||||
* À désactiver en production
|
||||
*/
|
||||
const DEBUG_MODE = true;
|
||||
|
||||
/**
|
||||
* Chemin vers le fichier de log
|
||||
*/
|
||||
const LOG_FILE = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'fuzip_debug.log';
|
||||
|
||||
/**
|
||||
* Obtient le chemin complet normalisé du dossier uploads
|
||||
*
|
||||
* @return string Chemin absolu vers uploads/
|
||||
*/
|
||||
public static function getUploadDir(): string {
|
||||
$path = realpath(self::UPLOAD_DIR);
|
||||
if ($path === false) {
|
||||
// Si le dossier n'existe pas encore, le créer
|
||||
if (!file_exists(self::UPLOAD_DIR)) {
|
||||
mkdir(self::UPLOAD_DIR, 0755, true);
|
||||
}
|
||||
$path = realpath(self::UPLOAD_DIR);
|
||||
}
|
||||
return $path . DIRECTORY_SEPARATOR;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si une extension de fichier est interdite
|
||||
*
|
||||
* @param string $filename Nom du fichier
|
||||
* @return bool True si l'extension est interdite
|
||||
*/
|
||||
public static function isForbiddenExtension(string $filename): bool {
|
||||
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
|
||||
return in_array($extension, self::FORBIDDEN_EXTENSIONS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si un type MIME est autorisé
|
||||
*
|
||||
* @param string $mimeType Type MIME à vérifier
|
||||
* @return bool True si le type MIME est autorisé
|
||||
*/
|
||||
public static function isAllowedMimeType(string $mimeType): bool {
|
||||
return in_array($mimeType, self::ALLOWED_MIME_TYPES);
|
||||
}
|
||||
|
||||
/**
|
||||
* Log un message (si DEBUG_MODE activé)
|
||||
*
|
||||
* @param string $message Message à logger
|
||||
* @param string $level Niveau (INFO, WARNING, ERROR)
|
||||
*/
|
||||
public static function log(string $message, string $level = 'INFO'): void {
|
||||
if (!self::DEBUG_MODE) {
|
||||
return;
|
||||
}
|
||||
|
||||
$timestamp = date('Y-m-d H:i:s');
|
||||
$logMessage = "[{$timestamp}] [{$level}] {$message}" . PHP_EOL;
|
||||
|
||||
file_put_contents(self::LOG_FILE, $logMessage, FILE_APPEND);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convertit une taille en octets en format lisible
|
||||
*
|
||||
* @param int $bytes Taille en octets
|
||||
* @return string Taille formatée (ex: "2.5 MB")
|
||||
*/
|
||||
public static function formatBytes(int $bytes): string {
|
||||
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
$bytes = max($bytes, 0);
|
||||
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
|
||||
$pow = min($pow, count($units) - 1);
|
||||
$bytes /= (1 << (10 * $pow));
|
||||
|
||||
return round($bytes, 2) . ' ' . $units[$pow];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize un nom de fichier/dossier
|
||||
* Retire les caractères dangereux et les séquences ..
|
||||
*
|
||||
* @param string $name Nom à sanitizer
|
||||
* @return string Nom nettoyé
|
||||
*/
|
||||
public static function sanitizePath(string $name): string {
|
||||
// Retirer les séquences dangereuses
|
||||
$name = str_replace(['..', '\\', chr(0)], '', $name);
|
||||
|
||||
// Garder seulement les caractères alphanumériques, espaces, tirets, underscores, points et slashes
|
||||
$name = preg_replace('/[^a-zA-Z0-9\s\-_\.\/]/', '', $name);
|
||||
|
||||
// Retirer les slashes multiples
|
||||
$name = preg_replace('#/+#', '/', $name);
|
||||
|
||||
return trim($name);
|
||||
}
|
||||
}
|
||||
408
core/FileTree.php
Normal file
408
core/FileTree.php
Normal file
@@ -0,0 +1,408 @@
|
||||
<?php
|
||||
/**
|
||||
* FileTree - Construction d'arborescence et détection de conflits
|
||||
*
|
||||
* Cette classe gère :
|
||||
* - La conversion d'une liste plate de fichiers en arborescence hiérarchique
|
||||
* - La détection de conflits entre 2 ZIP (fichiers/dossiers identiques)
|
||||
* - La génération de structures JSON pour le frontend
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/Config.php';
|
||||
|
||||
class FileTree {
|
||||
/**
|
||||
* Construit une arborescence hiérarchique à partir d'une liste plate de fichiers
|
||||
*
|
||||
* @param array $filesList Liste plate de fichiers avec 'name', 'size', 'is_dir'
|
||||
* @return array Structure hiérarchique
|
||||
*/
|
||||
public static function buildTree(array $filesList): array {
|
||||
$tree = [
|
||||
'type' => 'folder',
|
||||
'name' => 'root',
|
||||
'path' => '',
|
||||
'children' => []
|
||||
];
|
||||
|
||||
// Trier les fichiers par chemin pour un traitement cohérent
|
||||
usort($filesList, function($a, $b) {
|
||||
return strcmp($a['name'], $b['name']);
|
||||
});
|
||||
|
||||
foreach ($filesList as $file) {
|
||||
$path = $file['name'];
|
||||
$size = $file['size'];
|
||||
$isDir = $file['is_dir'];
|
||||
|
||||
// Découper le chemin en segments
|
||||
$segments = explode('/', trim($path, '/'));
|
||||
|
||||
// Naviguer/créer l'arborescence
|
||||
self::addToTree($tree, $segments, $size, $isDir, $path);
|
||||
}
|
||||
|
||||
Config::log("Arborescence construite : " . self::countNodes($tree) . " nœuds");
|
||||
|
||||
return $tree;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajoute un fichier/dossier à l'arborescence
|
||||
*
|
||||
* @param array &$node Nœud actuel (passé par référence)
|
||||
* @param array $segments Segments du chemin restants
|
||||
* @param int $size Taille du fichier
|
||||
* @param bool $isDir Si c'est un dossier
|
||||
* @param string $fullPath Chemin complet
|
||||
* @param array $processedSegments Segments déjà traités (pour construire le path des dossiers intermédiaires)
|
||||
*/
|
||||
private static function addToTree(array &$node, array $segments, int $size, bool $isDir, string $fullPath, array $processedSegments = []): void {
|
||||
if (empty($segments)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$currentSegment = array_shift($segments);
|
||||
|
||||
// Si c'est vide (cas des chemins se terminant par /), ignorer
|
||||
if ($currentSegment === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ajouter le segment actuel aux segments traités
|
||||
$processedSegments[] = $currentSegment;
|
||||
|
||||
// Chercher si ce segment existe déjà dans les enfants
|
||||
$existingChild = null;
|
||||
$existingIndex = null;
|
||||
|
||||
foreach ($node['children'] as $index => $child) {
|
||||
if ($child['name'] === $currentSegment) {
|
||||
$existingChild = &$node['children'][$index];
|
||||
$existingIndex = $index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Si c'est le dernier segment
|
||||
if (empty($segments)) {
|
||||
// C'est le fichier/dossier final
|
||||
if ($existingChild === null) {
|
||||
$node['children'][] = [
|
||||
'type' => $isDir ? 'folder' : 'file',
|
||||
'name' => $currentSegment,
|
||||
'path' => $fullPath,
|
||||
'size' => $size,
|
||||
'children' => $isDir ? [] : null
|
||||
];
|
||||
} else {
|
||||
// Le nœud existe déjà (cas des dossiers déclarés implicitement)
|
||||
// Mettre à jour avec les vraies infos
|
||||
$node['children'][$existingIndex]['type'] = $isDir ? 'folder' : 'file';
|
||||
$node['children'][$existingIndex]['path'] = $fullPath;
|
||||
$node['children'][$existingIndex]['size'] = $size;
|
||||
if (!$isDir) {
|
||||
$node['children'][$existingIndex]['children'] = null;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Il reste des segments, c'est un dossier intermédiaire
|
||||
if ($existingChild === null) {
|
||||
// Construire le chemin du dossier intermédiaire
|
||||
$intermediatePath = implode('/', $processedSegments) . '/';
|
||||
|
||||
// Créer un dossier intermédiaire
|
||||
$node['children'][] = [
|
||||
'type' => 'folder',
|
||||
'name' => $currentSegment,
|
||||
'path' => $intermediatePath,
|
||||
'size' => 0,
|
||||
'children' => []
|
||||
];
|
||||
// Récursion sur le nouveau nœud
|
||||
self::addToTree($node['children'][count($node['children']) - 1], $segments, $size, $isDir, $fullPath, $processedSegments);
|
||||
} else {
|
||||
// Le dossier existe, continuer la récursion
|
||||
// Mettre à jour le path s'il était vide
|
||||
if ($node['children'][$existingIndex]['path'] === '') {
|
||||
$node['children'][$existingIndex]['path'] = implode('/', $processedSegments) . '/';
|
||||
}
|
||||
self::addToTree($node['children'][$existingIndex], $segments, $size, $isDir, $fullPath, $processedSegments);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compte le nombre total de nœuds dans l'arborescence
|
||||
*
|
||||
* @param array $node Nœud racine
|
||||
* @return int Nombre de nœuds
|
||||
*/
|
||||
private static function countNodes(array $node): int {
|
||||
$count = 1; // Le nœud lui-même
|
||||
|
||||
if (isset($node['children']) && is_array($node['children'])) {
|
||||
foreach ($node['children'] as $child) {
|
||||
$count += self::countNodes($child);
|
||||
}
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Détecte les conflits entre 2 listes de fichiers
|
||||
* Un conflit = même chemin existe dans les 2 listes
|
||||
*
|
||||
* @param array $leftFiles Liste fichiers ZIP gauche
|
||||
* @param array $rightFiles Liste fichiers ZIP droite
|
||||
* @return array Liste des conflits avec détails
|
||||
*/
|
||||
public static function detectConflicts(array $leftFiles, array $rightFiles): array {
|
||||
$conflicts = [];
|
||||
|
||||
// Créer un index des fichiers de droite pour recherche rapide
|
||||
$rightIndex = [];
|
||||
foreach ($rightFiles as $file) {
|
||||
$rightIndex[$file['name']] = $file;
|
||||
}
|
||||
|
||||
// Parcourir les fichiers de gauche
|
||||
foreach ($leftFiles as $leftFile) {
|
||||
$path = $leftFile['name'];
|
||||
|
||||
// Vérifier si ce chemin existe à droite
|
||||
if (isset($rightIndex[$path])) {
|
||||
$rightFile = $rightIndex[$path];
|
||||
|
||||
$conflicts[] = [
|
||||
'path' => $path,
|
||||
'type' => $leftFile['is_dir'] ? 'folder' : 'file',
|
||||
'left_size' => $leftFile['size'],
|
||||
'right_size' => $rightFile['size'],
|
||||
'size_diff' => abs($leftFile['size'] - $rightFile['size']),
|
||||
'same_size' => $leftFile['size'] === $rightFile['size']
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
Config::log("Conflits détectés : " . count($conflicts) . " chemins en doublon");
|
||||
|
||||
return $conflicts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient tous les chemins d'une arborescence (liste plate)
|
||||
*
|
||||
* @param array $tree Arborescence
|
||||
* @return array Liste de chemins
|
||||
*/
|
||||
public static function getAllPaths(array $tree): array {
|
||||
$paths = [];
|
||||
|
||||
if (isset($tree['path']) && $tree['path'] !== '') {
|
||||
$paths[] = $tree['path'];
|
||||
}
|
||||
|
||||
if (isset($tree['children']) && is_array($tree['children'])) {
|
||||
foreach ($tree['children'] as $child) {
|
||||
$paths = array_merge($paths, self::getAllPaths($child));
|
||||
}
|
||||
}
|
||||
|
||||
return $paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filtre l'arborescence selon un pattern de recherche
|
||||
*
|
||||
* @param array $tree Arborescence
|
||||
* @param string $searchTerm Terme de recherche (regex compatible)
|
||||
* @param bool $caseSensitive Sensible à la casse
|
||||
* @return array Arborescence filtrée
|
||||
*/
|
||||
public static function filterTree(array $tree, string $searchTerm, bool $caseSensitive = false): array {
|
||||
// Copier l'arbre
|
||||
$filtered = $tree;
|
||||
|
||||
if (!isset($filtered['children']) || !is_array($filtered['children'])) {
|
||||
return $filtered;
|
||||
}
|
||||
|
||||
$filteredChildren = [];
|
||||
|
||||
foreach ($filtered['children'] as $child) {
|
||||
// Vérifier si le nom matche
|
||||
$name = $child['name'];
|
||||
$matches = $caseSensitive
|
||||
? (stripos($name, $searchTerm) !== false)
|
||||
: (strpos(strtolower($name), strtolower($searchTerm)) !== false);
|
||||
|
||||
if ($matches) {
|
||||
// Ce nœud matche, l'inclure
|
||||
$filteredChildren[] = $child;
|
||||
} elseif (isset($child['children']) && is_array($child['children'])) {
|
||||
// Chercher récursivement dans les enfants
|
||||
$filteredChild = self::filterTree($child, $searchTerm, $caseSensitive);
|
||||
if (!empty($filteredChild['children'])) {
|
||||
// Des enfants matchent, inclure ce dossier
|
||||
$filteredChildren[] = $filteredChild;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$filtered['children'] = $filteredChildren;
|
||||
return $filtered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcule les statistiques d'une arborescence
|
||||
*
|
||||
* @param array $tree Arborescence
|
||||
* @return array Statistiques (total_files, total_folders, total_size, max_depth)
|
||||
*/
|
||||
public static function getTreeStats(array $tree, int $currentDepth = 0): array {
|
||||
$stats = [
|
||||
'total_files' => 0,
|
||||
'total_folders' => 0,
|
||||
'total_size' => 0,
|
||||
'max_depth' => $currentDepth
|
||||
];
|
||||
|
||||
if ($tree['type'] === 'folder') {
|
||||
$stats['total_folders']++;
|
||||
} else {
|
||||
$stats['total_files']++;
|
||||
$stats['total_size'] += $tree['size'] ?? 0;
|
||||
}
|
||||
|
||||
if (isset($tree['children']) && is_array($tree['children'])) {
|
||||
foreach ($tree['children'] as $child) {
|
||||
$childStats = self::getTreeStats($child, $currentDepth + 1);
|
||||
$stats['total_files'] += $childStats['total_files'];
|
||||
$stats['total_folders'] += $childStats['total_folders'];
|
||||
$stats['total_size'] += $childStats['total_size'];
|
||||
$stats['max_depth'] = max($stats['max_depth'], $childStats['max_depth']);
|
||||
}
|
||||
}
|
||||
|
||||
return $stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convertit une arborescence en liste plate de chemins
|
||||
*
|
||||
* @param array $tree Arborescence
|
||||
* @param array $selection Sélection utilisateur (path => 'left'|'right'|null)
|
||||
* @return array Liste de chemins sélectionnés
|
||||
*/
|
||||
public static function treeToPathList(array $tree, array $selection = []): array {
|
||||
$paths = [];
|
||||
|
||||
if (isset($tree['path']) && $tree['path'] !== '') {
|
||||
// Vérifier si ce chemin est sélectionné
|
||||
if (empty($selection) || isset($selection[$tree['path']])) {
|
||||
$paths[] = $tree['path'];
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($tree['children']) && is_array($tree['children'])) {
|
||||
foreach ($tree['children'] as $child) {
|
||||
$childPaths = self::treeToPathList($child, $selection);
|
||||
$paths = array_merge($paths, $childPaths);
|
||||
}
|
||||
}
|
||||
|
||||
return $paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trouve un nœud dans l'arborescence par son chemin
|
||||
*
|
||||
* @param array $tree Arborescence
|
||||
* @param string $path Chemin à rechercher
|
||||
* @return array|null Nœud trouvé ou null
|
||||
*/
|
||||
public static function findNodeByPath(array $tree, string $path): ?array {
|
||||
if (isset($tree['path']) && $tree['path'] === $path) {
|
||||
return $tree;
|
||||
}
|
||||
|
||||
if (isset($tree['children']) && is_array($tree['children'])) {
|
||||
foreach ($tree['children'] as $child) {
|
||||
$found = self::findNodeByPath($child, $path);
|
||||
if ($found !== null) {
|
||||
return $found;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Valide une sélection utilisateur
|
||||
* Vérifie qu'il n'y a pas de conflits (même fichier sélectionné des 2 côtés)
|
||||
*
|
||||
* @param array $selection Map path => 'left'|'right'|null
|
||||
* @return array ['valid' => bool, 'conflicts' => array]
|
||||
*/
|
||||
public static function validateSelection(array $selection): array {
|
||||
$pathsBySide = [
|
||||
'left' => [],
|
||||
'right' => []
|
||||
];
|
||||
|
||||
// Grouper par côté
|
||||
foreach ($selection as $path => $side) {
|
||||
if ($side === 'left' || $side === 'right') {
|
||||
$pathsBySide[$side][] = $path;
|
||||
}
|
||||
}
|
||||
|
||||
// Chercher les doublons (même path des 2 côtés)
|
||||
$conflicts = array_intersect($pathsBySide['left'], $pathsBySide['right']);
|
||||
|
||||
return [
|
||||
'valid' => empty($conflicts),
|
||||
'conflicts' => array_values($conflicts)
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimise une sélection en supprimant les enfants si le parent est sélectionné
|
||||
*
|
||||
* @param array $selection Map path => 'left'|'right'|null
|
||||
* @param array $tree Arborescence (pour connaître la hiérarchie)
|
||||
* @return array Sélection optimisée
|
||||
*/
|
||||
public static function optimizeSelection(array $selection, array $tree): array {
|
||||
$optimized = [];
|
||||
|
||||
foreach ($selection as $path => $side) {
|
||||
if ($side === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Vérifier si un parent de ce chemin est déjà sélectionné du même côté
|
||||
$hasParentSelected = false;
|
||||
|
||||
foreach ($selection as $otherPath => $otherSide) {
|
||||
if ($otherSide === $side && $otherPath !== $path) {
|
||||
// Vérifier si otherPath est un parent de path
|
||||
if (strpos($path, $otherPath . '/') === 0) {
|
||||
$hasParentSelected = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Si aucun parent n'est sélectionné, garder ce chemin
|
||||
if (!$hasParentSelected) {
|
||||
$optimized[$path] = $side;
|
||||
}
|
||||
}
|
||||
|
||||
return $optimized;
|
||||
}
|
||||
}
|
||||
360
core/SessionManager.php
Normal file
360
core/SessionManager.php
Normal file
@@ -0,0 +1,360 @@
|
||||
<?php
|
||||
/**
|
||||
* SessionManager - Gestion des sessions et des dossiers d'upload
|
||||
*
|
||||
* Cette classe gère :
|
||||
* - L'initialisation des sessions PHP
|
||||
* - La création des dossiers d'upload par session
|
||||
* - Le tracking de l'activité (last_access.txt)
|
||||
* - Le nettoyage automatique des sessions expirées (> 24h)
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/Config.php';
|
||||
|
||||
class SessionManager {
|
||||
/**
|
||||
* Nom du fichier pour tracker la dernière activité
|
||||
*/
|
||||
const LAST_ACCESS_FILE = 'last_access.txt';
|
||||
|
||||
/**
|
||||
* Initialise une session PHP et crée le dossier d'upload associé
|
||||
*
|
||||
* @return string L'ID de session
|
||||
* @throws Exception Si la création du dossier échoue
|
||||
*/
|
||||
public static function init(): string {
|
||||
// Démarrer la session si pas déjà démarrée
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
// Vérifier si on est en CLI (pour les tests)
|
||||
if (php_sapi_name() === 'cli') {
|
||||
// En CLI, générer un ID de session unique pour le test
|
||||
$sessionId = 'cli_test_' . bin2hex(random_bytes(16));
|
||||
Config::log("Mode CLI détecté, session ID générée : {$sessionId}");
|
||||
} else {
|
||||
// Mode web normal
|
||||
session_start();
|
||||
$sessionId = session_id();
|
||||
Config::log("Session initialisée : {$sessionId}");
|
||||
}
|
||||
} else {
|
||||
$sessionId = session_id();
|
||||
Config::log("Session existante : {$sessionId}");
|
||||
}
|
||||
|
||||
// Vérifier que le session_id n'est pas vide
|
||||
if (empty($sessionId)) {
|
||||
Config::log("Session ID vide, génération d'un ID unique", 'WARNING');
|
||||
$sessionId = 'fallback_' . bin2hex(random_bytes(16));
|
||||
}
|
||||
|
||||
// Créer le dossier d'upload pour cette session
|
||||
$uploadDir = self::getUploadDir($sessionId);
|
||||
|
||||
if (!file_exists($uploadDir)) {
|
||||
if (!mkdir($uploadDir, 0755, true)) {
|
||||
Config::log("Échec création dossier : {$uploadDir}", 'ERROR');
|
||||
throw new Exception("Impossible de créer le dossier de session");
|
||||
}
|
||||
Config::log("Dossier de session créé : {$uploadDir}");
|
||||
}
|
||||
|
||||
// Mettre à jour le timestamp d'accès
|
||||
self::updateAccess($sessionId);
|
||||
|
||||
// Nettoyer les anciennes sessions (appelé à chaque initialisation)
|
||||
self::cleanOldSessions();
|
||||
|
||||
return $sessionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient le chemin du dossier d'upload pour une session donnée
|
||||
*
|
||||
* @param string $sessionId ID de la session
|
||||
* @return string Chemin absolu vers uploads/{sessionId}/
|
||||
*/
|
||||
public static function getUploadDir(string $sessionId): string {
|
||||
// Sécurité : valider que le session_id ne contient pas de caractères dangereux
|
||||
// Autorise lettres, chiffres et underscores (pour cli_test_ et fallback_)
|
||||
if (!preg_match('/^[a-zA-Z0-9_]{10,150}$/', $sessionId)) {
|
||||
Config::log("Session ID invalide : {$sessionId}", 'WARNING');
|
||||
throw new InvalidArgumentException("Session ID invalide");
|
||||
}
|
||||
|
||||
// Vérifier qu'il n'y a pas de .. ou de chemins relatifs
|
||||
if (strpos($sessionId, '..') !== false || strpos($sessionId, '/') !== false || strpos($sessionId, '\\') !== false) {
|
||||
Config::log("Session ID contient des caractères dangereux : {$sessionId}", 'WARNING');
|
||||
throw new InvalidArgumentException("Session ID invalide");
|
||||
}
|
||||
|
||||
$uploadDir = Config::getUploadDir() . $sessionId . DIRECTORY_SEPARATOR;
|
||||
return $uploadDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour le timestamp de dernière activité pour une session
|
||||
*
|
||||
* @param string $sessionId ID de la session
|
||||
* @return bool True si succès, false sinon
|
||||
*/
|
||||
public static function updateAccess(string $sessionId): bool {
|
||||
try {
|
||||
$uploadDir = self::getUploadDir($sessionId);
|
||||
$lastAccessFile = $uploadDir . self::LAST_ACCESS_FILE;
|
||||
|
||||
$timestamp = time();
|
||||
$result = file_put_contents($lastAccessFile, $timestamp);
|
||||
|
||||
if ($result !== false) {
|
||||
Config::log("Timestamp mis à jour pour session {$sessionId} : {$timestamp}");
|
||||
return true;
|
||||
}
|
||||
|
||||
Config::log("Échec mise à jour timestamp pour session {$sessionId}", 'WARNING');
|
||||
return false;
|
||||
|
||||
} catch (Exception $e) {
|
||||
Config::log("Erreur updateAccess : " . $e->getMessage(), 'ERROR');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient le timestamp de dernière activité d'une session
|
||||
*
|
||||
* @param string $sessionId ID de la session
|
||||
* @return int|null Timestamp ou null si non trouvé
|
||||
*/
|
||||
public static function getLastAccess(string $sessionId): ?int {
|
||||
try {
|
||||
$uploadDir = self::getUploadDir($sessionId);
|
||||
$lastAccessFile = $uploadDir . self::LAST_ACCESS_FILE;
|
||||
|
||||
if (!file_exists($lastAccessFile)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$content = file_get_contents($lastAccessFile);
|
||||
return $content !== false ? (int)$content : null;
|
||||
|
||||
} catch (Exception $e) {
|
||||
Config::log("Erreur getLastAccess : " . $e->getMessage(), 'ERROR');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Nettoie les sessions expirées (> SESSION_LIFETIME)
|
||||
* Supprime récursivement les dossiers et leur contenu
|
||||
*
|
||||
* @return int Nombre de sessions supprimées
|
||||
*/
|
||||
public static function cleanOldSessions(): int {
|
||||
$deletedCount = 0;
|
||||
$uploadBaseDir = Config::getUploadDir();
|
||||
|
||||
Config::log("Début nettoyage sessions expirées");
|
||||
|
||||
try {
|
||||
// Parcourir tous les dossiers dans uploads/
|
||||
if (!is_dir($uploadBaseDir)) {
|
||||
Config::log("Dossier uploads inexistant : {$uploadBaseDir}", 'WARNING');
|
||||
return 0;
|
||||
}
|
||||
|
||||
$sessionDirs = scandir($uploadBaseDir);
|
||||
|
||||
foreach ($sessionDirs as $sessionId) {
|
||||
// Ignorer . et ..
|
||||
if ($sessionId === '.' || $sessionId === '..') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$sessionPath = $uploadBaseDir . $sessionId;
|
||||
|
||||
// Vérifier que c'est un dossier
|
||||
if (!is_dir($sessionPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Récupérer le timestamp de dernière activité
|
||||
$lastAccess = self::getLastAccess($sessionId);
|
||||
|
||||
if ($lastAccess === null) {
|
||||
// Pas de fichier last_access.txt, utiliser mtime du dossier
|
||||
$lastAccess = filemtime($sessionPath);
|
||||
}
|
||||
|
||||
$age = time() - $lastAccess;
|
||||
|
||||
// Si la session a expiré
|
||||
if ($age > Config::SESSION_LIFETIME) {
|
||||
Config::log("Session expirée : {$sessionId} (âge: {$age}s)");
|
||||
|
||||
if (self::deleteDirectory($sessionPath)) {
|
||||
$deletedCount++;
|
||||
Config::log("Session supprimée : {$sessionId}");
|
||||
} else {
|
||||
Config::log("Échec suppression session : {$sessionId}", 'ERROR');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($deletedCount > 0) {
|
||||
Config::log("Nettoyage terminé : {$deletedCount} session(s) supprimée(s)");
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
Config::log("Erreur lors du nettoyage : " . $e->getMessage(), 'ERROR');
|
||||
}
|
||||
|
||||
return $deletedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime récursivement un dossier et son contenu
|
||||
*
|
||||
* @param string $dir Chemin du dossier à supprimer
|
||||
* @return bool True si succès, false sinon
|
||||
*/
|
||||
private static function deleteDirectory(string $dir): bool {
|
||||
if (!file_exists($dir)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!is_dir($dir)) {
|
||||
return unlink($dir);
|
||||
}
|
||||
|
||||
// Parcourir le contenu du dossier
|
||||
$items = scandir($dir);
|
||||
foreach ($items as $item) {
|
||||
if ($item === '.' || $item === '..') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$itemPath = $dir . DIRECTORY_SEPARATOR . $item;
|
||||
|
||||
if (is_dir($itemPath)) {
|
||||
// Récursion pour sous-dossiers
|
||||
if (!self::deleteDirectory($itemPath)) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// Supprimer fichier
|
||||
if (!unlink($itemPath)) {
|
||||
Config::log("Échec suppression fichier : {$itemPath}", 'WARNING');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Supprimer le dossier vide
|
||||
return rmdir($dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime manuellement une session (ex: bouton "Nouveau")
|
||||
*
|
||||
* @param string $sessionId ID de la session à supprimer
|
||||
* @return bool True si succès
|
||||
*/
|
||||
public static function deleteSession(string $sessionId): bool {
|
||||
try {
|
||||
$uploadDir = self::getUploadDir($sessionId);
|
||||
|
||||
if (!file_exists($uploadDir)) {
|
||||
return true; // Déjà supprimé
|
||||
}
|
||||
|
||||
$result = self::deleteDirectory($uploadDir);
|
||||
|
||||
if ($result) {
|
||||
Config::log("Session supprimée manuellement : {$sessionId}");
|
||||
} else {
|
||||
Config::log("Échec suppression manuelle session : {$sessionId}", 'ERROR');
|
||||
}
|
||||
|
||||
return $result;
|
||||
|
||||
} catch (Exception $e) {
|
||||
Config::log("Erreur deleteSession : " . $e->getMessage(), 'ERROR');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si une session existe et est valide
|
||||
*
|
||||
* @param string $sessionId ID de la session
|
||||
* @return bool True si la session existe et n'est pas expirée
|
||||
*/
|
||||
public static function isSessionValid(string $sessionId): bool {
|
||||
try {
|
||||
$uploadDir = self::getUploadDir($sessionId);
|
||||
|
||||
if (!file_exists($uploadDir)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$lastAccess = self::getLastAccess($sessionId);
|
||||
if ($lastAccess === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$age = time() - $lastAccess;
|
||||
return $age <= Config::SESSION_LIFETIME;
|
||||
|
||||
} catch (Exception $e) {
|
||||
Config::log("Erreur isSessionValid : " . $e->getMessage(), 'ERROR');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient les statistiques d'une session
|
||||
*
|
||||
* @param string $sessionId ID de la session
|
||||
* @return array|null Tableau avec infos ou null si erreur
|
||||
*/
|
||||
public static function getSessionStats(string $sessionId): ?array {
|
||||
try {
|
||||
$uploadDir = self::getUploadDir($sessionId);
|
||||
|
||||
if (!file_exists($uploadDir)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$lastAccess = self::getLastAccess($sessionId);
|
||||
$age = $lastAccess ? time() - $lastAccess : null;
|
||||
|
||||
// Compter les fichiers dans le dossier
|
||||
$files = glob($uploadDir . '*');
|
||||
$fileCount = count($files);
|
||||
|
||||
// Calculer la taille totale
|
||||
$totalSize = 0;
|
||||
foreach ($files as $file) {
|
||||
if (is_file($file)) {
|
||||
$totalSize += filesize($file);
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'session_id' => $sessionId,
|
||||
'upload_dir' => $uploadDir,
|
||||
'last_access' => $lastAccess,
|
||||
'age_seconds' => $age,
|
||||
'file_count' => $fileCount,
|
||||
'total_size' => $totalSize,
|
||||
'total_size_formatted' => Config::formatBytes($totalSize),
|
||||
'is_expired' => $age ? $age > Config::SESSION_LIFETIME : false
|
||||
];
|
||||
|
||||
} catch (Exception $e) {
|
||||
Config::log("Erreur getSessionStats : " . $e->getMessage(), 'ERROR');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
454
core/ZipHandler.php
Normal file
454
core/ZipHandler.php
Normal file
@@ -0,0 +1,454 @@
|
||||
<?php
|
||||
/**
|
||||
* ZipHandler - Manipulation des fichiers ZIP
|
||||
*
|
||||
* Cette classe gère :
|
||||
* - L'extraction de la structure d'un ZIP
|
||||
* - La validation des fichiers ZIP
|
||||
* - La fusion de fichiers selon sélection utilisateur
|
||||
* - La création du ZIP final
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/Config.php';
|
||||
|
||||
class ZipHandler {
|
||||
/**
|
||||
* Extraction de la structure complète d'un fichier ZIP
|
||||
*
|
||||
* @param string $zipPath Chemin absolu vers le fichier ZIP
|
||||
* @return array Structure hiérarchique du ZIP
|
||||
* @throws Exception Si le fichier est invalide ou trop volumineux
|
||||
*/
|
||||
public function getStructure(string $zipPath): array {
|
||||
// Vérifier que le fichier existe
|
||||
if (!file_exists($zipPath)) {
|
||||
Config::log("Fichier ZIP introuvable : {$zipPath}", 'ERROR');
|
||||
throw new Exception("Fichier ZIP introuvable");
|
||||
}
|
||||
|
||||
// Vérifier la taille du fichier
|
||||
$fileSize = filesize($zipPath);
|
||||
if ($fileSize > Config::MAX_FILE_SIZE) {
|
||||
$sizeFormatted = Config::formatBytes($fileSize);
|
||||
$maxFormatted = Config::formatBytes(Config::MAX_FILE_SIZE);
|
||||
Config::log("Fichier ZIP trop volumineux : {$sizeFormatted} > {$maxFormatted}", 'ERROR');
|
||||
throw new Exception("Fichier ZIP trop volumineux ({$sizeFormatted}). Maximum : {$maxFormatted}");
|
||||
}
|
||||
|
||||
// Valider que c'est bien un fichier ZIP (magic bytes)
|
||||
if (!$this->isValidZip($zipPath)) {
|
||||
Config::log("Fichier non-ZIP ou corrompu : {$zipPath}", 'ERROR');
|
||||
throw new Exception("Le fichier n'est pas un ZIP valide");
|
||||
}
|
||||
|
||||
// Ouvrir le ZIP
|
||||
$zip = new ZipArchive();
|
||||
$result = $zip->open($zipPath, ZipArchive::RDONLY);
|
||||
|
||||
if ($result !== true) {
|
||||
Config::log("Échec ouverture ZIP : {$zipPath} (code: {$result})", 'ERROR');
|
||||
throw new Exception("Impossible d'ouvrir le fichier ZIP (code erreur: {$result})");
|
||||
}
|
||||
|
||||
Config::log("Extraction structure ZIP : {$zipPath} ({$zip->numFiles} fichiers)");
|
||||
|
||||
// Vérifier le nombre de fichiers
|
||||
if ($zip->numFiles > Config::MAX_FILES_PER_ZIP) {
|
||||
$zip->close();
|
||||
Config::log("Trop de fichiers dans le ZIP : {$zip->numFiles} > " . Config::MAX_FILES_PER_ZIP, 'ERROR');
|
||||
throw new Exception("Le ZIP contient trop de fichiers (" . $zip->numFiles . "). Maximum : " . Config::MAX_FILES_PER_ZIP);
|
||||
}
|
||||
|
||||
// Extraire la liste des fichiers
|
||||
$filesList = [];
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$stat = $zip->statIndex($i);
|
||||
|
||||
if ($stat === false) {
|
||||
Config::log("Impossible de lire l'entrée {$i} du ZIP", 'WARNING');
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = $stat['name'];
|
||||
$size = $stat['size'];
|
||||
$isDir = substr($name, -1) === '/';
|
||||
|
||||
// Sanitize le nom
|
||||
$nameSanitized = Config::sanitizePath($name);
|
||||
|
||||
// Vérifier la profondeur
|
||||
$depth = substr_count($nameSanitized, '/');
|
||||
if ($depth > Config::MAX_TREE_DEPTH) {
|
||||
Config::log("Profondeur excessive ignorée : {$nameSanitized} (depth: {$depth})", 'WARNING');
|
||||
continue;
|
||||
}
|
||||
|
||||
// Vérifier les extensions interdites
|
||||
if (!$isDir && Config::isForbiddenExtension($nameSanitized)) {
|
||||
Config::log("Extension interdite ignorée : {$nameSanitized}", 'WARNING');
|
||||
continue;
|
||||
}
|
||||
|
||||
$filesList[] = [
|
||||
'name' => $nameSanitized,
|
||||
'size' => $size,
|
||||
'is_dir' => $isDir,
|
||||
'index' => $i
|
||||
];
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
|
||||
Config::log("Structure extraite : " . count($filesList) . " éléments valides");
|
||||
|
||||
return [
|
||||
'files' => $filesList,
|
||||
'total_files' => count($filesList),
|
||||
'total_size' => array_sum(array_column($filesList, 'size')),
|
||||
'zip_path' => $zipPath
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si un fichier est un ZIP valide (magic bytes)
|
||||
*
|
||||
* @param string $filePath Chemin vers le fichier
|
||||
* @return bool True si c'est un ZIP valide
|
||||
*/
|
||||
private function isValidZip(string $filePath): bool {
|
||||
$handle = fopen($filePath, 'rb');
|
||||
if (!$handle) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Lire les 4 premiers octets
|
||||
$bytes = fread($handle, 4);
|
||||
fclose($handle);
|
||||
|
||||
if ($bytes === false || strlen($bytes) < 4) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Convertir en hex
|
||||
$hex = bin2hex($bytes);
|
||||
|
||||
// Vérifier contre les signatures ZIP connues
|
||||
foreach (Config::ZIP_MAGIC_BYTES as $magicByte) {
|
||||
if (strcasecmp($hex, $magicByte) === 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fusionne des fichiers de 2 ZIP selon la sélection utilisateur
|
||||
*
|
||||
* @param string $leftZipPath Chemin vers le ZIP de gauche
|
||||
* @param string $rightZipPath Chemin vers le ZIP de droite
|
||||
* @param array $selection Map path => 'left'|'right'|null
|
||||
* @param string $outputPath Chemin de sortie pour le ZIP fusionné
|
||||
* @return string Chemin du ZIP créé
|
||||
* @throws Exception Si erreur lors de la fusion
|
||||
*/
|
||||
public function merge(string $leftZipPath, string $rightZipPath, array $selection, string $outputPath): string {
|
||||
Config::log("Début fusion : left={$leftZipPath}, right={$rightZipPath}, output={$outputPath}");
|
||||
|
||||
// Ouvrir les ZIP sources
|
||||
$leftZip = new ZipArchive();
|
||||
$rightZip = new ZipArchive();
|
||||
$outputZip = new ZipArchive();
|
||||
|
||||
if ($leftZip->open($leftZipPath, ZipArchive::RDONLY) !== true) {
|
||||
throw new Exception("Impossible d'ouvrir le ZIP de gauche");
|
||||
}
|
||||
|
||||
if ($rightZip->open($rightZipPath, ZipArchive::RDONLY) !== true) {
|
||||
$leftZip->close();
|
||||
throw new Exception("Impossible d'ouvrir le ZIP de droite");
|
||||
}
|
||||
|
||||
// Créer le ZIP de sortie
|
||||
if ($outputZip->open($outputPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
|
||||
$leftZip->close();
|
||||
$rightZip->close();
|
||||
throw new Exception("Impossible de créer le ZIP de sortie");
|
||||
}
|
||||
|
||||
$addedCount = 0;
|
||||
$skippedCount = 0;
|
||||
$addedPaths = []; // Pour éviter les doublons
|
||||
|
||||
// Parcourir la sélection
|
||||
foreach ($selection as $path => $side) {
|
||||
if ($side === null) {
|
||||
// Aucun côté sélectionné, ignorer
|
||||
$skippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Déterminer le ZIP source
|
||||
$sourceZip = ($side === 'left') ? $leftZip : $rightZip;
|
||||
|
||||
// Vérifier si c'est un dossier (se termine par /)
|
||||
$isFolder = substr($path, -1) === '/';
|
||||
|
||||
if ($isFolder) {
|
||||
// C'est un dossier : ajouter tous les fichiers qui commencent par ce chemin
|
||||
$folderFileCount = 0;
|
||||
|
||||
for ($i = 0; $i < $sourceZip->numFiles; $i++) {
|
||||
$filename = $sourceZip->getNameIndex($i);
|
||||
|
||||
// Vérifier si ce fichier est dans le dossier
|
||||
if (strpos($filename, $path) === 0) {
|
||||
// Éviter les doublons
|
||||
if (isset($addedPaths[$filename])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Vérifier si c'est un dossier (entrée ZIP vide)
|
||||
$stat = $sourceZip->statIndex($i);
|
||||
if ($stat !== false && substr($stat['name'], -1) === '/') {
|
||||
// C'est un dossier vide, on peut l'ignorer ou l'ajouter
|
||||
// Pour l'instant on l'ignore car on ajoute déjà les fichiers
|
||||
continue;
|
||||
}
|
||||
|
||||
// Récupérer le contenu
|
||||
$content = $sourceZip->getFromIndex($i);
|
||||
|
||||
if ($content === false) {
|
||||
Config::log("Impossible de lire : {$filename}", 'WARNING');
|
||||
$skippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ajouter au ZIP de sortie
|
||||
if ($outputZip->addFromString($filename, $content)) {
|
||||
$addedCount++;
|
||||
$folderFileCount++;
|
||||
$addedPaths[$filename] = true;
|
||||
|
||||
// Flush tous les 50 fichiers pour éviter les timeouts
|
||||
if ($folderFileCount % 50 === 0) {
|
||||
@ob_flush();
|
||||
@flush();
|
||||
}
|
||||
} else {
|
||||
Config::log("Échec ajout : {$filename}", 'WARNING');
|
||||
$skippedCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Config::log("Dossier {$path} : {$folderFileCount} fichiers ajoutés");
|
||||
} else {
|
||||
// C'est un fichier individuel
|
||||
// Éviter les doublons
|
||||
if (isset($addedPaths[$path])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Rechercher l'index du fichier dans le ZIP source
|
||||
$index = $sourceZip->locateName($path);
|
||||
|
||||
if ($index === false) {
|
||||
Config::log("Fichier introuvable : {$path} (côté: {$side})", 'WARNING');
|
||||
$skippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Récupérer le contenu
|
||||
$content = $sourceZip->getFromIndex($index);
|
||||
|
||||
if ($content === false) {
|
||||
Config::log("Impossible de lire : {$path}", 'WARNING');
|
||||
$skippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ajouter au ZIP de sortie
|
||||
if ($outputZip->addFromString($path, $content)) {
|
||||
$addedCount++;
|
||||
$addedPaths[$path] = true;
|
||||
} else {
|
||||
Config::log("Échec ajout : {$path}", 'WARNING');
|
||||
$skippedCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fermer les ZIP
|
||||
$leftZip->close();
|
||||
$rightZip->close();
|
||||
$outputZip->close();
|
||||
|
||||
Config::log("Fusion terminée : {$addedCount} fichiers ajoutés, {$skippedCount} ignorés");
|
||||
|
||||
return $outputPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extrait un fichier spécifique d'un ZIP
|
||||
*
|
||||
* @param string $zipPath Chemin vers le ZIP
|
||||
* @param string $filePath Chemin du fichier dans le ZIP
|
||||
* @param string $outputPath Chemin de sortie
|
||||
* @return bool True si succès
|
||||
*/
|
||||
public function extractFile(string $zipPath, string $filePath, string $outputPath): bool {
|
||||
$zip = new ZipArchive();
|
||||
|
||||
if ($zip->open($zipPath, ZipArchive::RDONLY) !== true) {
|
||||
Config::log("Impossible d'ouvrir le ZIP : {$zipPath}", 'ERROR');
|
||||
return false;
|
||||
}
|
||||
|
||||
$content = $zip->getFromName($filePath);
|
||||
|
||||
if ($content === false) {
|
||||
Config::log("Fichier introuvable dans le ZIP : {$filePath}", 'ERROR');
|
||||
$zip->close();
|
||||
return false;
|
||||
}
|
||||
|
||||
$result = file_put_contents($outputPath, $content);
|
||||
$zip->close();
|
||||
|
||||
if ($result === false) {
|
||||
Config::log("Échec écriture fichier : {$outputPath}", 'ERROR');
|
||||
return false;
|
||||
}
|
||||
|
||||
Config::log("Fichier extrait : {$filePath} -> {$outputPath}");
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prévisualise le contenu d'un fichier texte dans un ZIP
|
||||
*
|
||||
* @param string $zipPath Chemin vers le ZIP
|
||||
* @param string $filePath Chemin du fichier dans le ZIP
|
||||
* @param int $maxLength Longueur maximale à retourner
|
||||
* @return string|null Contenu du fichier ou null si erreur
|
||||
*/
|
||||
public function previewFile(string $zipPath, string $filePath, int $maxLength = 10000): ?string {
|
||||
$zip = new ZipArchive();
|
||||
|
||||
if ($zip->open($zipPath, ZipArchive::RDONLY) !== true) {
|
||||
Config::log("Impossible d'ouvrir le ZIP pour prévisualisation : {$zipPath}", 'ERROR');
|
||||
return null;
|
||||
}
|
||||
|
||||
$content = $zip->getFromName($filePath);
|
||||
$zip->close();
|
||||
|
||||
if ($content === false) {
|
||||
Config::log("Fichier introuvable pour prévisualisation : {$filePath}", 'ERROR');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Limiter la taille
|
||||
if (strlen($content) > $maxLength) {
|
||||
$content = substr($content, 0, $maxLength) . "\n\n... (tronqué)";
|
||||
}
|
||||
|
||||
// Vérifier que c'est du texte (pas du binaire)
|
||||
if (!mb_check_encoding($content, 'UTF-8') && !mb_check_encoding($content, 'ASCII')) {
|
||||
return "[Fichier binaire - prévisualisation impossible]";
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient des informations détaillées sur un ZIP
|
||||
*
|
||||
* @param string $zipPath Chemin vers le ZIP
|
||||
* @return array|null Informations ou null si erreur
|
||||
*/
|
||||
public function getZipInfo(string $zipPath): ?array {
|
||||
if (!file_exists($zipPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$zip = new ZipArchive();
|
||||
if ($zip->open($zipPath, ZipArchive::RDONLY) !== true) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$info = [
|
||||
'file_path' => $zipPath,
|
||||
'file_size' => filesize($zipPath),
|
||||
'file_size_formatted' => Config::formatBytes(filesize($zipPath)),
|
||||
'num_files' => $zip->numFiles,
|
||||
'comment' => $zip->comment,
|
||||
'is_valid' => $this->isValidZip($zipPath)
|
||||
];
|
||||
|
||||
$zip->close();
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Valide un fichier uploadé ZIP
|
||||
*
|
||||
* @param array $uploadedFile Tableau $_FILES['file']
|
||||
* @return array ['valid' => bool, 'error' => string|null]
|
||||
*/
|
||||
public function validateUpload(array $uploadedFile): array {
|
||||
// Vérifier les erreurs d'upload
|
||||
if ($uploadedFile['error'] !== UPLOAD_ERR_OK) {
|
||||
$errorMessages = [
|
||||
UPLOAD_ERR_INI_SIZE => 'Fichier trop volumineux (php.ini)',
|
||||
UPLOAD_ERR_FORM_SIZE => 'Fichier trop volumineux (formulaire)',
|
||||
UPLOAD_ERR_PARTIAL => 'Upload partiel',
|
||||
UPLOAD_ERR_NO_FILE => 'Aucun fichier uploadé',
|
||||
UPLOAD_ERR_NO_TMP_DIR => 'Dossier temporaire manquant',
|
||||
UPLOAD_ERR_CANT_WRITE => 'Échec écriture disque',
|
||||
UPLOAD_ERR_EXTENSION => 'Extension PHP a stoppé l\'upload'
|
||||
];
|
||||
|
||||
$error = $errorMessages[$uploadedFile['error']] ?? 'Erreur inconnue';
|
||||
Config::log("Erreur upload : {$error} (code: {$uploadedFile['error']})", 'ERROR');
|
||||
return ['valid' => false, 'error' => $error];
|
||||
}
|
||||
|
||||
// Vérifier la taille
|
||||
if ($uploadedFile['size'] > Config::MAX_FILE_SIZE) {
|
||||
$sizeFormatted = Config::formatBytes($uploadedFile['size']);
|
||||
$maxFormatted = Config::formatBytes(Config::MAX_FILE_SIZE);
|
||||
return [
|
||||
'valid' => false,
|
||||
'error' => "Fichier trop volumineux ({$sizeFormatted}). Maximum : {$maxFormatted}"
|
||||
];
|
||||
}
|
||||
|
||||
// Vérifier le type MIME
|
||||
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
||||
$mimeType = finfo_file($finfo, $uploadedFile['tmp_name']);
|
||||
finfo_close($finfo);
|
||||
|
||||
if (!Config::isAllowedMimeType($mimeType)) {
|
||||
Config::log("Type MIME non autorisé : {$mimeType}", 'WARNING');
|
||||
return [
|
||||
'valid' => false,
|
||||
'error' => "Type de fichier non autorisé ({$mimeType}). ZIP uniquement."
|
||||
];
|
||||
}
|
||||
|
||||
// Vérifier les magic bytes
|
||||
if (!$this->isValidZip($uploadedFile['tmp_name'])) {
|
||||
Config::log("Magic bytes invalides pour fichier uploadé", 'WARNING');
|
||||
return [
|
||||
'valid' => false,
|
||||
'error' => "Le fichier n'est pas un ZIP valide"
|
||||
];
|
||||
}
|
||||
|
||||
Config::log("Fichier ZIP validé : {$uploadedFile['name']} ({$uploadedFile['size']} octets)");
|
||||
return ['valid' => true, 'error' => null];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user