diff --git a/api.php b/api.php index 4aa1e6e..8e53003 100644 --- a/api.php +++ b/api.php @@ -10,7 +10,10 @@ header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS"); header("Access-Control-Allow-Headers: Content-Type, Authorization"); -if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; } +if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { + http_response_code(200); + exit; +} define('ENCRYPTION_KEY', 'MaCleSecreteSuperRobuste123!'); @@ -23,9 +26,12 @@ try { $pdo->exec("CREATE TABLE IF NOT EXISTS config (key_name VARCHAR(50) PRIMARY KEY, key_value TEXT)"); $pdo->exec("CREATE TABLE IF NOT EXISTS critiques (id BIGINT PRIMARY KEY, title VARCHAR(255), year VARCHAR(10), director VARCHAR(255), poster TEXT, rating DECIMAL(3,1), review TEXT, streaming VARCHAR(255))"); $pdo->exec("CREATE TABLE IF NOT EXISTS videotheque (id BIGINT PRIMARY KEY, title VARCHAR(255), year VARCHAR(10), director VARCHAR(255), poster TEXT, format VARCHAR(50), length VARCHAR(50), publisher VARCHAR(255), ean_isbn13 VARCHAR(50), number_of_discs INT DEFAULT 1, aspect_ratio VARCHAR(50), description TEXT, actors TEXT)"); -} catch (PDOException $e) { die(json_encode(["error" => "Connexion BDD échouée"])); } +} catch (PDOException $e) { + die(json_encode(["error" => "Connexion BDD échouée"])); +} // --- Fonctions Utilitaires --- + function getAuthToken() { if (!empty($_SERVER['HTTP_AUTHORIZATION'])) return $_SERVER['HTTP_AUTHORIZATION']; if (!empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) return $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; @@ -41,7 +47,8 @@ function checkAuth($pdo) { if ($pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() == 0) return true; $token = getAuthToken(); if ($token !== md5(ENCRYPTION_KEY . 'session')) { - http_response_code(403); exit; + http_response_code(403); + exit; } } @@ -69,19 +76,16 @@ function httpGet($url, $timeout = 10, $headers = []) { curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $timeout, - CURLOPT_CONNECTTIMEOUT => 5, // Échoue vite si le serveur est injoignable - CURLOPT_FOLLOWLOCATION => true, // Indispensable : suit les redirections 301/302 - CURLOPT_ENCODING => '', // Gère automatiquement la compression (Gzip/Deflate) - CURLOPT_SSL_VERIFYPEER => false, // À passer à true en production + CURLOPT_CONNECTTIMEOUT => 5, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_ENCODING => '', + CURLOPT_SSL_VERIFYPEER => false, CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0', CURLOPT_HTTPHEADER => $headers ]); - $res = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); - - // On accepte le code 200 (OK), mais aussi 201 ou 202 selon les APIs return ($code >= 200 && $code < 300) ? $res : null; } @@ -93,11 +97,12 @@ function removeAccentsForUrl($str) { return $str; } +// CORRECTION : Ajout du modificateur /u pour une gestion parfaite de l'UTF-8 et des accents function cleanTitle($title) { - $clean = preg_replace('/\s*[\[\(].*?[\]\)]\s*/', '', $title); - $clean = preg_replace('/\s*-\s*(Édition|Edition|Collector|Simple|Spéciale|Digibook|Ultimate|Intégrale|Combo|SteelBook|Boîtier).*$/i', '', $clean); - $clean = preg_replace('/(blu-ray|bluray|dvd|4k|ultra hd|combo|vhs|bdrip).*$/i', '', $clean); - return trim(preg_replace('/\s{2,}/', ' ', $clean)); + $clean = preg_replace('/\s*[\[\(].*?[\]\)]\s*/u', '', $title); + $clean = preg_replace('/\s*-\s*(édition|Edition|Collector|Simple|Spéciale|Digibook|Ultimate|Intégrale|Combo|SteelBook|Boîtier).*$/iu', '', $clean); + $clean = preg_replace('/(blu-ray|bluray|dvd|4k|ultra hd|combo|vhs|bdrip).*$/iu', '', $clean); + return trim(preg_replace('/\s{2,}/u', ' ', $clean)); } function detectFormat($title, $desc = '') { @@ -122,52 +127,25 @@ function emptyPhysicalResult() { ]; } -// ── NOUVELLE FONCTION : SCRAPPING DVDFR.COM ── +// --- SCRAPING DVDFR.COM --- function fetchFromDvdfr($ean) { $empty = emptyPhysicalResult(); $url = "https://www.dvdfr.com/listeliv.php?base=dvd&mots_recherche=" . urlencode($ean); $html = httpGet($url, 15); if (!$html) return $empty; - - // Recherche du premier produit trouvé dans la liste if (preg_match('/
  • \s*
    .*?.*?]*src="([^"]+)"[^>]*alt="([^"]+)".*?<\/a>.*?

    .*?]*>([^<]+)<\/a>.*?<\/h2>.*?

    .*?]*>([^<]+)<\/a>.*?<\/h2>.*?
  • .*?]*>([^<]+)<\/span>.*?<\/li>.*?.*?]*>([^<]+)<\/a>.*?.*?]*>([^<]+)<\/a>/is', $html, $m)) { - $empty['title'] = trim($m[1]); - } - - if (preg_match('/

    .*?]*>([^<]+)<\/a>/is', $html, $m)) { - $empty['director'] = trim($m[1]); - } - - if (preg_match('/
  • .*?]*>([^<]+)<\/span>/is', $html, $m)) { - $empty['publisher'] = trim($m[1]); - } - + if (preg_match('/

    .*?]*>([^<]+)<\/a>/is', $html, $m)) $empty['title'] = trim($m[1]); + if (preg_match('/

    .*?]*>([^<]+)<\/a>/is', $html, $m)) $empty['director'] = trim($m[1]); + if (preg_match('/
  • .*?]*>([^<]+)<\/span>/is', $html, $m)) $empty['publisher'] = trim($m[1]); if (preg_match('/]*id="img' . preg_quote($ean, '/') . '"[^>]*src="([^"]+)"/i', $html, $m)) { $imageUrl = trim($m[1]); $imageUrl = str_replace('_v.jpg', '_1.jpg', $imageUrl); @@ -177,43 +155,33 @@ function fetchFromDvdfr($ean) { $imageUrl = str_replace('_v.jpg', '_1.jpg', $imageUrl); $empty['poster'] = $imageUrl; } - if (preg_match('/.*?]*>([^<]+)<\/a>/is', $html, $m)) { $format = trim($m[1]); $empty['format'] = detectFormat($format); } } - - // Nettoyage du titre if (!empty($empty['title'])) { $empty['title'] = html_entity_decode($empty['title'], ENT_QUOTES | ENT_HTML5, 'UTF-8'); $empty['title'] = cleanTitle($empty['title']); $empty['title'] = trim($empty['title']); } - return $empty; } -// ── NOUVELLE FONCTION : SCRAPPING UPCINDEX.COM (MODIFIÉE AVEC MÉTADONNÉES) ── +// --- SCRAPING UPCINDEX.COM --- function fetchFromUpcIndex($ean) { $empty = emptyPhysicalResult(); $url = "https://www.upcindex.com/" . urlencode($ean); $html = httpGet($url, 15); if (!$html) return $empty; - - // Recherche du titre if (preg_match('/]*class="text-center"[^>]*>.*?]*itemprop="name"[^>]*>([^<]+)<\/span>/is', $html, $m)) { $empty['title'] = trim(strip_tags($m[1])); } elseif (preg_match('/]*>([^<]+)<\/title>/i', $html, $m)) { $title = trim($m[1]); - $title = preg_replace('/\s*[-–]\s*UPCindex.*$/i', '', $title); + $title = preg_replace('/\s*[- ]\s*UPCindex.*$/i', '', $title); $empty['title'] = $title; } - - // ✅ RÉCUPÉRATION DE L'IMAGE DEPUIS UPCINDEX (première image produit) - // Chercher la première image de produit (après le barcode) if (preg_match_all('/]*itemprop="http:\/\/schema\.org\/image"[^>]*src="([^"]+)"/i', $html, $matches)) { - // Prendre la première image de produit (pas le barcode) foreach ($matches[1] as $imgSrc) { if (strpos($imgSrc, 'barcode.png') === false && strpos($imgSrc, 'upcindex.com') !== false) { $empty['poster'] = 'https:' . $imgSrc; @@ -221,121 +189,58 @@ function fetchFromUpcIndex($ean) { } } } - - // ✅ RÉCUPÉRATION DES MÉTADONNÉES PHYSIQUES - // Directeur - if (preg_match('/]*>director<\/dt>\s*]*>([^<]+)<\/dd>/is', $html, $m)) { - $empty['director'] = trim($m[1]); - } - - // Acteurs - if (preg_match_all('/]*>actor<\/dt>\s*]*>([^<]+)<\/dd>/is', $html, $actorsMatches)) { - $empty['actors'] = implode(', ', array_map('trim', $actorsMatches[1])); - } - - // Format + if (preg_match('/]*>director<\/dt>\s*]*>([^<]+)<\/dd>/is', $html, $m)) $empty['director'] = trim($m[1]); + if (preg_match_all('/]*>actor<\/dt>\s*]*>([^<]+)<\/dd>/is', $html, $actorsMatches)) $empty['actors'] = implode(', ', array_map('trim', $actorsMatches[1])); if (preg_match('/]*>format<\/dt>\s*]*>([^<]+)<\/dd>/is', $html, $m)) { $format = trim($m[1]); if (stripos($format, 'DVD') !== false) $empty['format'] = 'DVD'; elseif (stripos($format, 'Blu-ray') !== false) $empty['format'] = 'Blu-ray'; elseif (stripos($format, '4K') !== false) $empty['format'] = '4K Ultra HD'; } - - // Aspect ratio - if (preg_match('/]*>aspect ratio<\/dt>\s*]*>([^<]+)<\/dd>/is', $html, $m)) { - $empty['aspect_ratio'] = trim($m[1]); - } - - // Nombre de disques - if (preg_match('/]*>number of discs<\/dt>\s*]*>(\d+)<\/dd>/is', $html, $m)) { - $empty['number_of_discs'] = (int)$m[1]; - } - - // Brand/Publisher - if (preg_match('/]*>brand<\/dt>\s*]*>([^<]+)<\/dd>/is', $html, $m)) { - $empty['publisher'] = trim($m[1]); - } - - // Region code - if (preg_match('/]*>region code<\/dt>\s*]*>([^<]+)<\/dd>/is', $html, $m)) { - $empty['description'] = 'Region ' . trim($m[1]); - } - - // Nettoyage du titre + if (preg_match('/]*>aspect ratio<\/dt>\s*]*>([^<]+)<\/dd>/is', $html, $m)) $empty['aspect_ratio'] = trim($m[1]); + if (preg_match('/]*>number of discs<\/dt>\s*]*>(\d+)<\/dd>/is', $html, $m)) $empty['number_of_discs'] = (int)$m[1]; + if (preg_match('/]*>brand<\/dt>\s*]*>([^<]+)<\/dd>/is', $html, $m)) $empty['publisher'] = trim($m[1]); + if (preg_match('/]*>region code<\/dt>\s*]*>([^<]+)<\/dd>/is', $html, $m)) $empty['description'] = 'Region ' . trim($m[1]); if (!empty($empty['title'])) { $empty['title'] = html_entity_decode($empty['title'], ENT_QUOTES | ENT_HTML5, 'UTF-8'); $empty['title'] = trim($empty['title']); - } - - if (!empty($empty['title'])) { $empty['format'] = detectFormat($empty['title']); } - return $empty; } -// ── SCRAPPING FNAC ── +// --- SCRAPING FNAC --- function fetchFromFnac($ean) { $empty = emptyPhysicalResult(); $url = "https://www.fnac.com/SearchResult/ResultList.aspx?Search=" . urlencode($ean); $html = httpGet($url, 15); if (!$html) return $empty; - - // GARDE-FOU : si l'EAN recherché n'apparaît nulle part dans le HTML $eanDigits = preg_replace('/[^0-9]/', '', (string)$ean); - if ($eanDigits && strpos($html, $eanDigits) === false) { - error_log("fetchFromFnac: EAN $eanDigits absent du HTML retourné — page rejetée."); - return $empty; - } - - // Chercher un lien avec un titre - if (preg_match('/]*href="\/(?:[^"]*\/)?(?:tp\d+|A\d+|[^"]*-s\d+\.html)"[^>]*>([^<]+)<\/a>/i', $html, $m)) { - $empty['title'] = trim(strip_tags($m[1])); - } - elseif (preg_match('/]*href="\/(?:[^"]*\/)?(?:tp\d+|A\d+|[^"]*-s\d+\.html)"[^>]*title="([^"]+)"[^>]*>/i', $html, $m)) { - $empty['title'] = trim($m[1]); - } - elseif (preg_match('/]*class="[^"]*f-product__name[^"]*"[^>]*>([^<]+)<\/h2>/i', $html, $m)) { - $empty['title'] = trim(strip_tags($m[1])); - } - elseif (preg_match('/]*class="[^"]*js-ProductTitle[^"]*"[^>]*>([^<]+)<\/a>/i', $html, $m)) { - $empty['title'] = trim(strip_tags($m[1])); - } - + if ($eanDigits && strpos($html, $eanDigits) === false) return $empty; + if (preg_match('/]*href="\/(?:[^"]*\/)?(?:tp\d+|A\d+|[^"]*-s\d+\.html)"[^>]*>([^<]+)<\/a>/i', $html, $m)) $empty['title'] = trim(strip_tags($m[1])); + elseif (preg_match('/]*href="\/(?:[^"]*\/)?(?:tp\d+|A\d+|[^"]*-s\d+\.html)"[^>]*title="([^"]+)"[^>]*>/i', $html, $m)) $empty['title'] = trim($m[1]); + elseif (preg_match('/]*class="[^"]*f-product__name[^"]*"[^>]*>([^<]+)<\/h2>/i', $html, $m)) $empty['title'] = trim(strip_tags($m[1])); + elseif (preg_match('/]*class="[^"]*js-ProductTitle[^"]*"[^>]*>([^<]+)<\/a>/i', $html, $m)) $empty['title'] = trim(strip_tags($m[1])); if (!empty($empty['title'])) { $empty['title'] = html_entity_decode($empty['title'], ENT_QUOTES | ENT_HTML5, 'UTF-8'); $empty['title'] = preg_replace('/\s*\|\s*Fnac.*$/i', '', $empty['title']); $empty['title'] = trim($empty['title']); } - - if (preg_match('/]*property="og:image"[^>]*content="([^"]+)"/i', $html, $m)) { - $empty['poster'] = trim($m[1]); - } elseif (preg_match('/]*class="[^"]*js-ProductImage[^"]*"[^>]*src="([^"]+)"/i', $html, $m)) { - $empty['poster'] = trim($m[1]); - } - - if (!empty($empty['title'])) { - $empty['format'] = detectFormat($empty['title']); - } - + if (preg_match('/]*property="og:image"[^>]*content="([^"]+)"/i', $html, $m)) $empty['poster'] = trim($m[1]); + elseif (preg_match('/]*class="[^"]*js-ProductImage[^"]*"[^>]*src="([^"]+)"/i', $html, $m)) $empty['poster'] = trim($m[1]); + if (!empty($empty['title'])) $empty['format'] = detectFormat($empty['title']); return $empty; } -// ── SCRAPPING BLU-RAY.COM (PAR TITRE) ── function fetchFromBlurayComByTitle($title) { static $lastRequest = 0; $empty = emptyPhysicalResult(); if (empty($title)) return $empty; - $now = microtime(true); - if ($lastRequest > 0 && ($now - $lastRequest) < 3) { - usleep((int)((3 - ($now - $lastRequest)) * 1000000)); - } + if ($lastRequest > 0 && ($now - $lastRequest) < 3) usleep((int)((3 - ($now - $lastRequest)) * 1000000)); $lastRequest = microtime(true); - $cleanTitle = cleanTitle($title); $searchUrl = "https://www.blu-ray.com/movies/search.php?keyword=" . urlencode($cleanTitle) . "&action=search"; - $ch = curl_init($searchUrl); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_CONNECTTIMEOUT => 5, @@ -346,16 +251,9 @@ function fetchFromBlurayComByTitle($title) { $searchHtml = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); - - if (!$searchHtml || $httpCode !== 200) return $empty; - - if (!preg_match('/href="(https:\/\/www\.blu-ray\.com\/movies\/[^"]+\/(\d+)\/)"/i', $searchHtml, $matches)) { - return $empty; - } - + if (!$searchHtml || $httpCode !== 200 || !preg_match('/href="(https:\/\/www\.blu-ray\.com\/movies\/[^"]+\/(\d+)\/)"/i', $searchHtml, $matches)) return $empty; $movieUrl = $matches[1]; sleep(2); - $ch2 = curl_init($movieUrl); curl_setopt_array($ch2, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_CONNECTTIMEOUT => 5, @@ -365,47 +263,33 @@ function fetchFromBlurayComByTitle($title) { ]); $movieHtml = curl_exec($ch2); curl_close($ch2); - if (!$movieHtml) return $empty; - if (preg_match('/]*>([^<]+)<\/h3>\s*(?: )?\((\d{4})\)/i', $movieHtml, $m)) $empty['year'] = $m[2]; if (preg_match('/href="[^"]*studioid=\d+[^"]*"[^>]*>([^<]+)<\/a>/i', $movieHtml, $m)) $empty['publisher'] = trim($m[1]); if (preg_match('/(\d+)\s*min<\/span>/i', $movieHtml, $m)) $empty['length'] = $m[1] . ' min'; if (preg_match('/Aspect[\s-]*ratio:\s*([\d\.]+:[\d\.]+)/i', $movieHtml, $m)) $empty['aspect_ratio'] = trim($m[1]); - if (preg_match('/(\w+)-disc\s+set/i', $movieHtml, $m)) { $wordToNum = ['single' => 1, 'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5, 'six' => 6]; $empty['number_of_discs'] = $wordToNum[strtolower($m[1])] ?? 1; } elseif (preg_match('/(\d+)-disc\s+set/i', $movieHtml, $m)) { $empty['number_of_discs'] = (int)$m[1]; } - if (strpos($movieUrl, '/4k/') !== false || stripos($movieHtml, '4K Ultra HD') !== false) $empty['format'] = '4K Ultra HD'; elseif (strpos($movieUrl, '/3d/') !== false) $empty['format'] = '3D Blu-ray'; else $empty['format'] = 'Blu-ray'; - - if (preg_match('/src="(https:\/\/images\.static-bluray\.com\/movies\/covers\/\d+_front\.jpg[^"]*)"/i', $movieHtml, $m)) { - $empty['poster'] = $m[1]; - } elseif (preg_match('/]*class="coverfront"[^>]*src="([^"]+)"/i', $movieHtml, $m)) { - $empty['poster'] = preg_replace('/_large\.jpg/', '_front.jpg', $m[1]); - } - + if (preg_match('/src="(https:\/\/images\.static-bluray\.com\/movies\/covers\/\d+_front\.jpg[^"]*)"/i', $movieHtml, $m)) $empty['poster'] = $m[1]; + elseif (preg_match('/]*class="coverfront"[^>]*src="([^"]+)"/i', $movieHtml, $m)) $empty['poster'] = preg_replace('/_large\.jpg/', '_front.jpg', $m[1]); return $empty; } -// ── SCRAPPING BLU-RAY.COM (PAR EAN - FALLBACK) ── function fetchFromBlurayComByEan($ean) { static $lastRequest = 0; $empty = emptyPhysicalResult(); $ean = preg_replace('/[^0-9]/', '', (string)$ean); if (strlen($ean) < 8) return $empty; - $now = microtime(true); - if ($lastRequest > 0 && ($now - $lastRequest) < 3) { - usleep((int)((3 - ($now - $lastRequest)) * 1000000)); - } + if ($lastRequest > 0 && ($now - $lastRequest) < 3) usleep((int)((3 - ($now - $lastRequest)) * 1000000)); $lastRequest = microtime(true); - $searchUrl = "https://www.blu-ray.com/movies/search.php?ean=" . urlencode($ean) . "&action=search"; $ch = curl_init($searchUrl); curl_setopt_array($ch, [ @@ -417,14 +301,9 @@ function fetchFromBlurayComByEan($ean) { $searchHtml = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); - - if (!$searchHtml || $httpCode !== 200 || !preg_match('/href="(https:\/\/www\.blu-ray\.com\/movies\/[^"]+\/(\d+)\/)"/i', $searchHtml, $matches)) { - return $empty; - } - + if (!$searchHtml || $httpCode !== 200 || !preg_match('/href="(https:\/\/www\.blu-ray\.com\/movies\/[^"]+\/(\d+)\/)"/i', $searchHtml, $matches)) return $empty; $movieUrl = $matches[1]; sleep(2); - $ch2 = curl_init($movieUrl); curl_setopt_array($ch2, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_CONNECTTIMEOUT => 5, @@ -434,40 +313,46 @@ function fetchFromBlurayComByEan($ean) { ]); $movieHtml = curl_exec($ch2); curl_close($ch2); - if (!$movieHtml) return $empty; - - if (preg_match('/]*id="movie_info"[^>]*>.*?

    ([^<]+)<\/h3>/is', $movieHtml, $m)) { - $empty['title'] = trim($m[1]); - } elseif (preg_match('/]*>([^<]+)<\/h1>/i', $movieHtml, $m)) { - $empty['title'] = trim(preg_replace('/\s*(Blu-ray|4K|3D|DVD|UHD).*$/i', '', trim(strip_tags($m[1])))); - } - + if (preg_match('/]*id="movie_info"[^>]*>.*?

    ([^<]+)<\/h3>/is', $movieHtml, $m)) $empty['title'] = trim($m[1]); + elseif (preg_match('/]*>([^<]+)<\/h1>/i', $movieHtml, $m)) $empty['title'] = trim(preg_replace('/\s*(Blu-ray|4K|3D|DVD|UHD).*$/i', '', trim(strip_tags($m[1])))); if (preg_match('/]*>([^<]+)<\/h3>\s*(?: )?\((\d{4})\)/i', $movieHtml, $m)) $empty['year'] = $m[2]; if (preg_match('/href="[^"]*studioid=\d+[^"]*"[^>]*>([^<]+)<\/a>/i', $movieHtml, $m)) $empty['publisher'] = trim($m[1]); if (preg_match('/(\d+)\s*min<\/span>/i', $movieHtml, $m)) $empty['length'] = $m[1] . ' min'; if (preg_match('/Aspect[\s-]*ratio:\s*([\d\.]+:[\d\.]+)/i', $movieHtml, $m)) $empty['aspect_ratio'] = trim($m[1]); - if (preg_match('/(\w+)-disc\s+set/i', $movieHtml, $m)) { $wordToNum = ['single' => 1, 'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5, 'six' => 6]; $empty['number_of_discs'] = $wordToNum[strtolower($m[1])] ?? 1; } elseif (preg_match('/(\d+)-disc\s+set/i', $movieHtml, $m)) { $empty['number_of_discs'] = (int)$m[1]; } - if (strpos($movieUrl, '/4k/') !== false || stripos($movieHtml, '4K Ultra HD') !== false) $empty['format'] = '4K Ultra HD'; elseif (strpos($movieUrl, '/3d/') !== false) $empty['format'] = '3D Blu-ray'; else $empty['format'] = 'Blu-ray'; - - if (preg_match('/src="(https:\/\/images\.static-bluray\.com\/movies\/covers\/\d+_front\.jpg[^"]*)"/i', $movieHtml, $m)) { - $empty['poster'] = $m[1]; - } elseif (preg_match('/]*class="coverfront"[^>]*src="([^"]+)"/i', $movieHtml, $m)) { - $empty['poster'] = preg_replace('/_large\.jpg/', '_front.jpg', $m[1]); - } - + if (preg_match('/src="(https:\/\/images\.static-bluray\.com\/movies\/covers\/\d+_front\.jpg[^"]*)"/i', $movieHtml, $m)) $empty['poster'] = $m[1]; + elseif (preg_match('/]*class="coverfront"[^>]*src="([^"]+)"/i', $movieHtml, $m)) $empty['poster'] = preg_replace('/_large\.jpg/', '_front.jpg', $m[1]); return $empty; } +// CORRECTION : Fonction helper pour trouver le film le plus populaire disposant d'un poster valide +function findBestTmdbMovie($results) { + if (empty($results) || !is_array($results)) return null; + $bestWithPoster = null; + $maxPopularity = -1; + + foreach ($results as $m) { + if (!empty($m['poster_path'])) { + $pop = (float)($m['popularity'] ?? 0); + if ($pop > $maxPopularity) { + $maxPopularity = $pop; + $bestWithPoster = $m; + } + } + } + return $bestWithPoster !== null ? $bestWithPoster : $results[0]; +} + +// CORRECTION MAJEURE : Recherche TMDB intelligente en 4 étapes pour garantir une affiche function fetchTmdbPosterAndSynopsis($title, $year = '', $pdo = null) { $default = ['poster'=>'assets/img/default_physical_media.jpg','title'=>'','description'=>'','director'=>'','actors'=>'','length'=>'','year'=>'']; if (empty($title)) return $default; @@ -475,10 +360,10 @@ function fetchTmdbPosterAndSynopsis($title, $year = '', $pdo = null) { $tmdbKey = getTmdbApiKey($pdo); if (!$tmdbKey) return $default; - // Nettoyage et encodage correct pour l'URL $clean = cleanTitle($title); $queryUrl = urlencode($clean); + // 1. Recherche principale en français avec l'année $searchUrl = "https://api.themoviedb.org/3/search/movie?api_key={$tmdbKey}&query={$queryUrl}&language=fr-FR"; if (!empty($year)) { $searchUrl .= "&year={$year}"; @@ -486,16 +371,49 @@ function fetchTmdbPosterAndSynopsis($title, $year = '', $pdo = null) { $res = httpGet($searchUrl, 8); $data = $res ? json_decode($res, true) : []; + $movie = !empty($data['results']) ? findBestTmdbMovie($data['results']) : null; - // Fallback : Si l'année exacte ne donne rien, on cherche le titre seul immédiatement - if (empty($data['results']) && !empty($year)) { - $res = httpGet("https://api.themoviedb.org/3/search/movie?api_key={$tmdbKey}&query={$queryUrl}&language=fr-FR", 8); - $data = $res ? json_decode($res, true) : []; + // 2. Fallback en français SANS l'année (si aucun poster valide trouvé) + if ((empty($movie) || empty($movie['poster_path'])) && !empty($year)) { + $resFallback = httpGet("https://api.themoviedb.org/3/search/movie?api_key={$tmdbKey}&query={$queryUrl}&language=fr-FR", 8); + $dataFallback = $resFallback ? json_decode($resFallback, true) : []; + if (!empty($dataFallback['results'])) { + $candidate = findBestTmdbMovie($dataFallback['results']); + if (!empty($candidate['poster_path']) || empty($movie)) { + $movie = $candidate; + } + } + } + + // 3. Fallback SANS restriction de langue (titre original/VO) + if (empty($movie) || empty($movie['poster_path'])) { + $resGlobal = httpGet("https://api.themoviedb.org/3/search/movie?api_key={$tmdbKey}&query={$queryUrl}", 8); + $dataGlobal = $resGlobal ? json_decode($resGlobal, true) : []; + if (!empty($dataGlobal['results'])) { + $candidate = findBestTmdbMovie($dataGlobal['results']); + if (!empty($candidate['poster_path']) || empty($movie)) { + $movie = $candidate; + } + } } - if (empty($data['results'])) return $default; + // 4. Fallback SANS accents si le titre accentué n'a rien donné + if (empty($movie) || empty($movie['poster_path'])) { + $noAccentUrl = urlencode(removeAccentsForUrl($clean)); + if ($noAccentUrl !== $queryUrl && !empty($noAccentUrl)) { + $resNoAccent = httpGet("https://api.themoviedb.org/3/search/movie?api_key={$tmdbKey}&query={$noAccentUrl}", 8); + $dataNoAccent = $resNoAccent ? json_decode($resNoAccent, true) : []; + if (!empty($dataNoAccent['results'])) { + $candidate = findBestTmdbMovie($dataNoAccent['results']); + if (!empty($candidate['poster_path']) || empty($movie)) { + $movie = $candidate; + } + } + } + } + + if (empty($movie)) return $default; - $movie = $data['results'][0]; $movieId = $movie['id']; $default['poster'] = !empty($movie['poster_path']) ? "https://image.tmdb.org/t/p/w500{$movie['poster_path']}" : $default['poster']; $default['year'] = !empty($movie['release_date']) ? substr($movie['release_date'], 0, 4) : $year; @@ -519,27 +437,18 @@ function fetchTmdbPosterAndSynopsis($title, $year = '', $pdo = null) { return $default; } -// ── MOVIECOVERS (Jaquettes HD FR) ── function fetchFromMovieCovers($title, $year = '') { $empty = ['title' => '', 'year' => '', 'director' => '', 'actors' => '', 'poster' => '', 'description' => '', 'length' => '', 'publisher' => '', 'format' => 'DVD', 'number_of_discs' => 1, 'aspect_ratio' => '']; if (empty($title)) return $empty; - $cleanTitle = removeAccentsForUrl($title); $urlTitle = strtoupper(str_replace(' ', '+', $cleanTitle)); $url = "https://moviecovers.com/film/titre_{$urlTitle}.html"; - $html = httpGet($url, 10); if (!$html) return $empty; - if (preg_match('/([^<]+)<\/TITLE>/i', $html, $m)) $empty['title'] = trim($m[1]); - $idmc = ''; - if (preg_match('/IDMC.*?<PRE>([^<]+)<\/PRE>/is', $html, $m)) { - $idmc = trim($m[1]); - } elseif (preg_match('/<meta property="og:image" content="[^"]*\/getjpg\.html\/([^"\']+)\.jpg"/i', $html, $m)) { - $idmc = urldecode($m[1]); - } - + if (preg_match('/IDMC.*?<PRE>([^<]+)<\/PRE>/is', $html, $m)) $idmc = trim($m[1]); + elseif (preg_match('/<meta property="og:image" content="[^"]*\/getjpg\.html\/([^"\']+)\.jpg"/i', $html, $m)) $idmc = urldecode($m[1]); if ($idmc) { $idmc_encoded = urlencode($idmc); $hd_urls = ["https://moviecovers.com/DATA/zipcache/{$idmc_encoded}.jpg", "https://moviecovers.com/getjpg.html/{$idmc_encoded}.jpg"]; @@ -551,89 +460,55 @@ function fetchFromMovieCovers($title, $year = '') { } } } - if (empty($empty['poster'])) { if (preg_match('/<img[^>]*title="Recto[^"]*"[^>]*src="([^"]+)"/i', $html, $m)) $empty['poster'] = $m[1]; elseif (preg_match('/<meta[^>]*property="og:image"[^>]*content="([^"]+)"/i', $html, $m)) $empty['poster'] = $m[1]; } - if (preg_match('/Réalisateur<\/TH>\s*<TD[^>]*>.*?<a[^>]*>([^<]+)<\/a>/is', $html, $m)) $empty['director'] = trim($m[1]); if (preg_match('/Année<\/TH>\s*<TD[^>]*>.*?<a[^>]*>(\d{4})<\/a>/is', $html, $m)) $empty['year'] = $m[1]; if (preg_match('/Durée<\/TH>\s*<TD[^>]*>([\dH]+[\dmin]*)/is', $html, $m)) $empty['length'] = trim($m[1]); if (preg_match_all('/<a href="\/multicrit\.html\?acteur=[^"]*">([^<]+)<\/a>/i', $html, $matches)) $empty['actors'] = implode(', ', array_slice($matches[1], 0, 5)); if (preg_match('/<meta[^>]*property="og:description"[^>]*content="([^"]+)"/i', $html, $m)) $empty['description'] = html_entity_decode($m[1]); - return $empty; } -// ── AGGREGATEUR PHYSIQUE (VERSION MODIFIÉE AVEC DVDFR) ── function fetchPhysicalByEan($ean, $pdo = null) { error_log("=== DEBUT fetchPhysicalByEan EAN=$ean ==="); - $res = emptyPhysicalResult(); $title = ''; - - // 1. DVDFR.COM (Priorité 1 - pour titre, image et métadonnées) $dvdfrData = fetchFromDvdfr($ean); - error_log("DVDFR -> title='" . ($dvdfrData['title'] ?? '') . "' poster='" . ($dvdfrData['poster'] ?? '') . "' director='" . ($dvdfrData['director'] ?? '') . "'"); - if (!empty($dvdfrData['title'])) { $title = $dvdfrData['title']; $res = $dvdfrData; } - - // 2. UPCINDEX.COM (Priorité 2 - pour métadonnées physiques détaillées) $upcIndexData = fetchFromUpcIndex($ean); - error_log("UPCINDEX -> title='" . ($upcIndexData['title'] ?? '') . "' director='" . ($upcIndexData['director'] ?? '') . "'"); - - if (!empty($upcIndexData['title']) && empty($title)) { - $title = $upcIndexData['title']; - } - - // Fusionner les données UPCINDEX (métadonnées physiques) + if (!empty($upcIndexData['title']) && empty($title)) $title = $upcIndexData['title']; if (!empty($upcIndexData)) { - if (!empty($upcIndexData['director']) && empty($res['director'])) { - $res['director'] = $upcIndexData['director']; - } + if (!empty($upcIndexData['director']) && empty($res['director'])) $res['director'] = $upcIndexData['director']; if (!empty($upcIndexData['actors'])) $res['actors'] = $upcIndexData['actors']; - if (!empty($upcIndexData['format']) && empty($res['format'])) { - $res['format'] = $upcIndexData['format']; - } + if (!empty($upcIndexData['format']) && empty($res['format'])) $res['format'] = $upcIndexData['format']; if (!empty($upcIndexData['aspect_ratio'])) $res['aspect_ratio'] = $upcIndexData['aspect_ratio']; if (!empty($upcIndexData['number_of_discs'])) $res['number_of_discs'] = $upcIndexData['number_of_discs']; - if (!empty($upcIndexData['publisher']) && empty($res['publisher'])) { - $res['publisher'] = $upcIndexData['publisher']; - } + if (!empty($upcIndexData['publisher']) && empty($res['publisher'])) $res['publisher'] = $upcIndexData['publisher']; if (!empty($upcIndexData['description'])) $res['description'] = $upcIndexData['description']; if (!empty($upcIndexData['year'])) $res['year'] = $upcIndexData['year']; - // Garder l'image de DVD.fr en priorité - if (empty($res['poster']) && !empty($upcIndexData['poster'])) { - $res['poster'] = $upcIndexData['poster']; - } + if (empty($res['poster']) && !empty($upcIndexData['poster'])) $res['poster'] = $upcIndexData['poster']; } - - // 3. FNAC (Fallback si pas de titre) if (empty($title)) { $fnacData = fetchFromFnac($ean); - error_log("FNAC -> title='" . ($fnacData['title'] ?? '') . "'"); if (!empty($fnacData['title'])) { $title = $fnacData['title']; if (empty($res['title'])) $res = $fnacData; } } - - // 4. MovieCovers (pour jaquette HD FR si pas d'image) if (!empty($title) && empty($res['poster'])) { $mc = fetchFromMovieCovers($title, $res['year'] ?? ''); - error_log("MOVIECOVERS -> poster='" . ($mc['poster'] ?? '') . "'"); if (!empty($mc['poster'])) $res['poster'] = $mc['poster']; } - - error_log("=== FIN fetchPhysicalByEan -> title FINAL='" . ($res['title'] ?? '') . "' poster='" . ($res['poster'] ?? '') . "' ==="); return $res; } -// ── ROUTEUR PRINCIPAL ── +// --- ROUTEUR PRINCIPAL --- $action = $_GET['action'] ?? ''; $data = json_decode(file_get_contents('php://input'), true) ?? []; @@ -641,30 +516,36 @@ switch ($action) { case 'check_security_status': echo json_encode(["is_blank" => ($pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() == 0)]); break; - + case 'login': if ($pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() == 0) { echo json_encode(["success" => true, "token" => md5(ENCRYPTION_KEY . 'session'), "blank" => true]); } else { $stmt = $pdo->prepare("SELECT password_hash FROM users WHERE username = 'admin'"); - $stmt->execute(); $user = $stmt->fetch(); + $stmt->execute(); + $user = $stmt->fetch(); if ($user && password_verify($data['password'] ?? '', $user['password_hash'])) { echo json_encode(["success" => true, "token" => md5(ENCRYPTION_KEY . 'session'), "blank" => false]); - } else { http_response_code(401); echo json_encode(["error" => "Mot de passe incorrect."]); } + } else { + http_response_code(401); + echo json_encode(["error" => "Mot de passe incorrect."]); + } } break; - - case 'setup_admin': case 'update_password': + + case 'setup_admin': + case 'update_password': checkAuth($pdo); $pwd = $data['password'] ?? $data['new_password'] ?? ''; $stmt = $pdo->prepare("REPLACE INTO users (id, username, password_hash) VALUES (1, 'admin', :pass)"); $stmt->execute([':pass' => password_hash($pwd, PASSWORD_BCRYPT)]); echo json_encode(["success" => true]); break; - + case 'get_config_keys': $stmt = $pdo->prepare("SELECT key_value FROM config WHERE key_name = 'tmdb_api_key'"); - $stmt->execute(); $row = $stmt->fetch(); + $stmt->execute(); + $row = $stmt->fetch(); echo json_encode(['tmdb_api_key' => $row ? decryptData($row['key_value']) : '']); break; @@ -672,15 +553,19 @@ switch ($action) { checkAuth($pdo); $name = $data['key_name'] ?? ''; $val = trim($data['key_value'] ?? ''); - if ($name !== 'tmdb_api_key' || empty($val)) { http_response_code(400); echo json_encode(["error" => "Clé invalide."]); break; } + if ($name !== 'tmdb_api_key' || empty($val)) { + http_response_code(400); + echo json_encode(["error" => "Clé invalide."]); + break; + } $stmt = $pdo->prepare("REPLACE INTO config (key_name, key_value) VALUES (?, ?)"); $stmt->execute([$name, encryptData($val)]); echo json_encode(["success" => true]); break; - + case 'get_films': $critiques = $pdo->query("SELECT id, title, year, director, poster, rating, review, NULL AS description, streaming, 'critique' AS type, NULL AS format FROM critiques ORDER BY id DESC")->fetchAll(); - foreach ($critiques as $row) { + foreach ($critiques as &$row) { if ($row['rating'] !== null) { $ratingVal = (float)$row['rating']; $row['rating'] = ($ratingVal == floor($ratingVal)) ? (int)$ratingVal : $ratingVal; @@ -690,12 +575,11 @@ switch ($action) { $videotheque = $pdo->query("SELECT id, title, year, director, poster, NULL AS rating, NULL AS review, description, NULL AS streaming, 'videotheque' AS type, format FROM videotheque ORDER BY id DESC")->fetchAll(); echo json_encode(['critique' => $critiques, 'videotheque' => $videotheque]); break; - + case 'save_film': checkAuth($pdo); $type = $data['type'] ?? 'critique'; $id = !empty($data['id']) ? $data['id'] : makeStableId($type, $data['title'] ?? '', $data['year'] ?? '0000'); - if ($type === 'critique') { if (empty($data['director']) || empty($data['poster'])) { $tmdbData = fetchTmdbPosterAndSynopsis($data['title'] ?? '', $data['year'] ?? '', $pdo); @@ -722,118 +606,110 @@ switch ($action) { } echo json_encode(["success" => true]); break; - + case 'delete_film': checkAuth($pdo); - $type = $_GET['type'] ?? 'critique'; $table = ($type === 'videotheque') ? 'videotheque' : 'critiques'; + $type = $_GET['type'] ?? 'critique'; + $table = ($type === 'videotheque') ? 'videotheque' : 'critiques'; $id = $_GET['id'] ?? null; if (!$id) { http_response_code(400); echo json_encode(["error" => "ID manquant."]); break; } - $stmt = $pdo->prepare("DELETE FROM $table WHERE id = ?"); $stmt->execute([$id]); + $stmt = $pdo->prepare("DELETE FROM $table WHERE id = ?"); + $stmt->execute([$id]); echo json_encode(["success" => true]); break; - + case 'bulk_delete': checkAuth($pdo); - $ids = $data['ids'] ?? []; $type = $data['type'] ?? 'critique'; $table = ($type === 'videotheque') ? 'videotheque' : 'critiques'; - if (!empty($ids)) { $placeholders = implode(',', array_fill(0, count($ids), '?')); $stmt = $pdo->prepare("DELETE FROM $table WHERE id IN ($placeholders)"); $stmt->execute($ids); echo json_encode(["success" => true]); } - else { http_response_code(400); echo json_encode(["success" => false, "error" => "Aucun élément sélectionné."]); } + $ids = $data['ids'] ?? []; + $type = $data['type'] ?? 'critique'; + $table = ($type === 'videotheque') ? 'videotheque' : 'critiques'; + if (!empty($ids)) { + $placeholders = implode(',', array_fill(0, count($ids), '?')); + $stmt = $pdo->prepare("DELETE FROM $table WHERE id IN ($placeholders)"); + $stmt->execute($ids); + echo json_encode(["success" => true]); + } else { + http_response_code(400); + echo json_encode(["success" => false, "error" => "Aucun élément sélectionné."]); + } break; - -case 'add_item_by_ean': - $ean = preg_replace('/[^0-9]/', '', $data['ean'] ?? ''); - if (strlen($ean) < 8) { echo json_encode(["success" => false, "error" => "EAN invalide"]); exit; } - - $physicalData = fetchPhysicalByEan($ean, $pdo); - $rawTitle = $physicalData['title'] ?? ''; - - $tmdbData = fetchTmdbPosterAndSynopsis($rawTitle, $physicalData['year'] ?? '', $pdo); - - $finalTitle = !empty($tmdbData['title']) ? $tmdbData['title'] : $rawTitle; - - // ✅ PRIORITÉ ABSOLUE À L'IMAGE DE GO-UPC/PHYSICAL - $poster = !empty($physicalData['poster']) ? $physicalData['poster'] : - (($tmdbData['poster'] !== 'assets/img/default_physical_media.jpg') ? $tmdbData['poster'] : 'assets/img/default_physical_media.jpg'); - - $year = $tmdbData['year'] ?? $physicalData['year'] ?? ''; - $id = makeStableId('videotheque', $finalTitle, $year); - - $stmt = $pdo->prepare("INSERT INTO videotheque (id, title, year, poster, description, director, actors, ean_isbn13, format, length, publisher, number_of_discs, aspect_ratio) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title=VALUES(title), year=VALUES(year), poster=IF(VALUES(poster)!='', VALUES(poster), poster), description=IF(VALUES(description)!='', VALUES(description), description), director=IF(VALUES(director)!='', VALUES(director), director), actors=IF(VALUES(actors)!='', VALUES(actors), actors)"); - $stmt->execute([ - $id, $finalTitle, $year, $poster, - $tmdbData['description'] ?? $physicalData['description'] ?? '', - $physicalData['director'] ?: $tmdbData['director'], // ✅ Priorité aux données physiques - $physicalData['actors'] ?: $tmdbData['actors'], // ✅ Priorité aux données physiques - $ean, $physicalData['format'] ?? detectFormat($rawTitle), - $tmdbData['length'] ?: ($physicalData['length'] ?? ''), - $physicalData['publisher'] ?? '', $physicalData['number_of_discs'] ?? 1, $physicalData['aspect_ratio'] ?? '' - ]); - - echo json_encode(["success" => true, "title" => $finalTitle, "director" => $physicalData['director'] ?: $tmdbData['director'], "year" => $year]); - break; - -case 'import_batch': - checkAuth($pdo); - $type = $data['type'] ?? ''; - $items = $data['items'] ?? []; - $pdo->beginTransaction(); - $imported = 0; $skipped = 0; - - try { - if ($type === 'videotheque') { - $stmt = $pdo->prepare("INSERT INTO videotheque (id, title, year, format, poster, ean_isbn13, description, length, number_of_discs, aspect_ratio, actors, publisher, director) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE title=VALUES(title), year=VALUES(year), format=VALUES(format), poster=IF(VALUES(poster)!='assets/img/default_physical_media.jpg', VALUES(poster), poster), ean_isbn13=IF(VALUES(ean_isbn13)!='', VALUES(ean_isbn13), ean_isbn13), description=IF(VALUES(description)!='', VALUES(description), description), length=IF(VALUES(length)!='', VALUES(length), length), number_of_discs=IF(VALUES(number_of_discs)!=1, VALUES(number_of_discs), number_of_discs), aspect_ratio=IF(VALUES(aspect_ratio)!='', VALUES(aspect_ratio), aspect_ratio), actors=IF(VALUES(actors)!='', VALUES(actors), actors), publisher=IF(VALUES(publisher)!='', VALUES(publisher), publisher), director=IF(VALUES(director)!='', VALUES(director), director)"); - - foreach ($items as $item) { - $ean = preg_replace('/[^0-9]/', '', (string)($item['ean'] ?? '')); - if (strlen($ean) < 8) { $skipped++; continue; } - - $physicalData = fetchPhysicalByEan($ean, $pdo); - $title = $physicalData['title'] ?? ''; - $year = $physicalData['year'] ?? ''; - $format = $physicalData['format'] ?: detectFormat($title); - $publisher = $physicalData['publisher'] ?? ''; - $discs = $physicalData['number_of_discs'] ?: 1; - $aspect = $physicalData['aspect_ratio'] ?? ''; - $length = $physicalData['length'] ?? ''; - - // ✅ PRIORITÉ À L'IMAGE DE GO-UPC - $poster = !empty($physicalData['poster']) ? $physicalData['poster'] : 'assets/img/default_physical_media.jpg'; - - $desc = $physicalData['description'] ?? ''; - $director = $physicalData['director'] ?? ''; - $actors = $physicalData['actors'] ?? ''; - - if (empty($poster) || empty($director) || empty($actors) || empty($desc) || empty($title)) { - $tmdb = fetchTmdbPosterAndSynopsis($title, $year, $pdo); - if (empty($title)) $title = $tmdb['title'] ?? "EAN: $ean"; - // ⚠️ NE PAS ÉCRASER L'IMAGE DE GO-UPC - if (empty($poster) && $tmdb['poster'] !== 'assets/img/default_physical_media.jpg') { - $poster = $tmdb['poster']; + + case 'add_item_by_ean': + $ean = preg_replace('/[^0-9]/', '', $data['ean'] ?? ''); + if (strlen($ean) < 8) { echo json_encode(["success" => false, "error" => "EAN invalide"]); exit; } + $physicalData = fetchPhysicalByEan($ean, $pdo); + $rawTitle = $physicalData['title'] ?? ''; + $tmdbData = fetchTmdbPosterAndSynopsis($rawTitle, $physicalData['year'] ?? '', $pdo); + $finalTitle = !empty($tmdbData['title']) ? $tmdbData['title'] : $rawTitle; + $poster = !empty($physicalData['poster']) ? $physicalData['poster'] : (($tmdbData['poster'] !== 'assets/img/default_physical_media.jpg') ? $tmdbData['poster'] : 'assets/img/default_physical_media.jpg'); + $year = $tmdbData['year'] ?? $physicalData['year'] ?? ''; + $id = makeStableId('videotheque', $finalTitle, $year); + $stmt = $pdo->prepare("INSERT INTO videotheque (id, title, year, poster, description, director, actors, ean_isbn13, format, length, publisher, number_of_discs, aspect_ratio) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title=VALUES(title), year=VALUES(year), poster=IF(VALUES(poster)!='', VALUES(poster), poster), description=IF(VALUES(description)!='', VALUES(description), description), director=IF(VALUES(director)!='', VALUES(director), director), actors=IF(VALUES(actors)!='', VALUES(actors), actors)"); + $stmt->execute([ + $id, $finalTitle, $year, $poster, + $tmdbData['description'] ?? $physicalData['description'] ?? '', + $physicalData['director'] ?: $tmdbData['director'], + $physicalData['actors'] ?: $tmdbData['actors'], + $ean, $physicalData['format'] ?? detectFormat($rawTitle), + $tmdbData['length'] ?: ($physicalData['length'] ?? ''), + $physicalData['publisher'] ?? '', $physicalData['number_of_discs'] ?? 1, $physicalData['aspect_ratio'] ?? '' + ]); + echo json_encode(["success" => true, "title" => $finalTitle, "director" => $physicalData['director'] ?: $tmdbData['director'], "year" => $year]); + break; + + case 'import_batch': + checkAuth($pdo); + $type = $data['type'] ?? ''; + $items = $data['items'] ?? []; + $pdo->beginTransaction(); + $imported = 0; $skipped = 0; + + try { + if ($type === 'videotheque') { + $stmt = $pdo->prepare("INSERT INTO videotheque (id, title, year, format, poster, ean_isbn13, description, length, number_of_discs, aspect_ratio, actors, publisher, director) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE title=VALUES(title), year=VALUES(year), format=VALUES(format), poster=IF(VALUES(poster)!='assets/img/default_physical_media.jpg', VALUES(poster), poster), ean_isbn13=IF(VALUES(ean_isbn13)!='', VALUES(ean_isbn13), ean_isbn13), description=IF(VALUES(description)!='', VALUES(description), description), length=IF(VALUES(length)!='', VALUES(length), length), number_of_discs=IF(VALUES(number_of_discs)!=1, VALUES(number_of_discs), number_of_discs), aspect_ratio=IF(VALUES(aspect_ratio)!='', VALUES(aspect_ratio), aspect_ratio), actors=IF(VALUES(actors)!='', VALUES(actors), actors), publisher=IF(VALUES(publisher)!='', VALUES(publisher), publisher), director=IF(VALUES(director)!='', VALUES(director), director)"); + foreach ($items as $item) { + $ean = preg_replace('/[^0-9]/', '', (string)($item['ean'] ?? '')); + if (strlen($ean) < 8) { $skipped++; continue; } + $physicalData = fetchPhysicalByEan($ean, $pdo); + $title = $physicalData['title'] ?? ''; + $year = $physicalData['year'] ?? ''; + $format = $physicalData['format'] ?: detectFormat($title); + $publisher = $physicalData['publisher'] ?? ''; + $discs = $physicalData['number_of_discs'] ?: 1; + $aspect = $physicalData['aspect_ratio'] ?? ''; + $length = $physicalData['length'] ?? ''; + $poster = !empty($physicalData['poster']) ? $physicalData['poster'] : 'assets/img/default_physical_media.jpg'; + $desc = $physicalData['description'] ?? ''; + $director = $physicalData['director'] ?? ''; + $actors = $physicalData['actors'] ?? ''; + if (empty($poster) || empty($director) || empty($actors) || empty($desc) || empty($title)) { + $tmdb = fetchTmdbPosterAndSynopsis($title, $year, $pdo); + if (empty($title)) $title = $tmdb['title'] ?? "EAN: $ean"; + if (empty($poster) && $tmdb['poster'] !== 'assets/img/default_physical_media.jpg') { + $poster = $tmdb['poster']; + } + if (empty($director)) $director = $tmdb['director'] ?? ''; + if (empty($actors)) $actors = $tmdb['actors'] ?? ''; + if (empty($desc)) $desc = $tmdb['description'] ?? ''; + if (empty($length) && !empty($tmdb['length'])) $length = $tmdb['length']; + if (empty($year) && !empty($tmdb['year'])) $year = $tmdb['year']; } - if (empty($director)) $director = $tmdb['director'] ?? ''; - if (empty($actors)) $actors = $tmdb['actors'] ?? ''; - if (empty($desc)) $desc = $tmdb['description'] ?? ''; - if (empty($length) && !empty($tmdb['length'])) $length = $tmdb['length']; - if (empty($year) && !empty($tmdb['year'])) $year = $tmdb['year']; + if (empty($title)) { $skipped++; continue; } + $id = makeStableId('videotheque', $title, $year); + $stmt->execute([$id, $title, $year, $format, $poster, $ean, $desc, $length, $discs, $aspect, $actors, $publisher, $director]); + $imported++; } - - if (empty($title)) { $skipped++; continue; } - $id = makeStableId('videotheque', $title, $year); - $stmt->execute([$id, $title, $year, $format, $poster, $ean, $desc, $length, $discs, $aspect, $actors, $publisher, $director]); - $imported++; - } } else { $stmtCritiques = $pdo->prepare("INSERT INTO critiques (id, title, year, director, poster, rating, review, streaming) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title=VALUES(title), year=VALUES(year), director=VALUES(director), poster=VALUES(poster), rating=VALUES(rating), review=VALUES(review), streaming=VALUES(streaming)"); foreach ($items as $rowData) { - // Supporte "Name" (Letterboxd standard) ou "Title" $title = $rowData['Title'] ?? $rowData['title'] ?? $rowData['Name'] ?? ''; if (empty($title)) continue; - // PRIORITY FIX : On cherche la vraie année du film, on ignore publish_date pour la recherche TMDB $year = $rowData['Year'] ?? $rowData['year'] ?? ''; if (empty($year) && !empty($rowData['Release Date'])) { $year = substr($rowData['Release Date'], 0, 4); } - + $id = makeStableId('critique', $title, $year); $ratingRaw = $rowData['Rating'] ?? $rowData['rating'] ?? ''; $rating = ($ratingRaw !== '' && $ratingRaw !== null) ? (float)$ratingRaw : null; @@ -842,7 +718,7 @@ case 'import_batch': $poster = 'assets/img/default_physical_media.jpg'; $streaming = 'Support physique / Cinéma'; - // Appel TMDB + // Appel TMDB intelligent $tmdbData = fetchTmdbPosterAndSynopsis($title, $year, $pdo); if ($tmdbData) { if (!empty($tmdbData['director'])) $director = $tmdbData['director']; @@ -852,7 +728,7 @@ case 'import_batch': $stmtCritiques->execute([$id, $title, $year, $director, $poster, $rating, $review, $streaming]); - // PAUSE ANTI-BLOCAGE : 250 millisecondes entre chaque film pour respecter le quota TMDB + // PAUSE ANTI-BLOCAGE : 250 ms usleep(250000); $imported++; }