Actualiser api.php

This commit is contained in:
2026-06-22 10:52:51 +02:00
parent 107138ee7c
commit 0c6bebc0ed
+168 -219
View File
@@ -30,6 +30,7 @@ try {
)"); )");
} catch (\PDOException $e) { echo json_encode(["error" => "Erreur BDD : " . $e->getMessage()]); exit; } } catch (\PDOException $e) { echo json_encode(["error" => "Erreur BDD : " . $e->getMessage()]); exit; }
// ── FONCTIONS UTILITAIRES ──
function makeStableId($title, $year) { function makeStableId($title, $year) {
return (abs(crc32(strtolower(trim($title ?? '')) . '|' . trim($year ?? ''))) % 2000000000) + 100000000; return (abs(crc32(strtolower(trim($title ?? '')) . '|' . trim($year ?? ''))) % 2000000000) + 100000000;
} }
@@ -64,101 +65,18 @@ function getTmdbApiKey($pdo) {
return $row ? decryptData($row['key_value']) : null; return $row ? decryptData($row['key_value']) : null;
} }
function getConfigValue($pdo, $keyName) {
try {
$stmt = $pdo->prepare("SELECT key_value FROM config WHERE key_name = ?");
$stmt->execute([$keyName]);
$row = $stmt->fetch();
return $row ? decryptData($row['key_value']) : null;
} catch (\Exception $e) { return null; }
}
function fetchPosterByEAN($ean, $pdo) {
if (empty($ean) || strlen($ean) < 8) return null;
// Vérification du cache
$cacheKey = 'ean_poster_' . md5($ean);
$cached = getCache($pdo, $cacheKey);
if ($cached && !empty($cached['poster'])) return $cached['poster'];
// 1. UPCitemDB (Toujours présent comme base gratuite, sans clé)
$upcData = fetchUPCitemdb($ean, $pdo);
if ($upcData && !empty($upcData['poster'])) {
setCache($pdo, $cacheKey, ['poster' => $upcData['poster']], 'upc');
return $upcData['poster'];
}
// 2. eBay Developers Program (Finding API)
$ebayKey = getConfigValue($pdo, 'ebay_api_key');
if ($ebayKey) {
$url = "https://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&SECURITY-APPNAME={$ebayKey}&RESPONSE-DATA-FORMAT=JSON&REST-PAYLOAD&keywords={$ean}";
$res = httpGet($url, 5);
if ($res) {
$data = json_decode($res, true);
// On récupère l'image du premier résultat trouvé correspondant au code barre
if (!empty($data['findItemsByKeywordsResponse'][0]['searchResult'][0]['item'][0]['galleryURL'][0])) {
$img = $data['findItemsByKeywordsResponse'][0]['searchResult'][0]['item'][0]['galleryURL'][0];
// eBay retourne parfois une image par défaut si non trouvée
if (strpos($img, 'default') === false) {
setCache($pdo, $cacheKey, ['poster' => $img], 'ebay');
return $img;
}
}
}
}
// 3. WorldCat APIs (xID / Search API)
$worldcatKey = getConfigValue($pdo, 'worldcat_api_key');
if ($worldcatKey) {
// WorldCat est principalement pour les livres (ISBN), utile pour les Digibooks ou éditions spéciales
$url = "https://worldcat.org/webservices/catalog/content/isbn/{$ean}?wskey={$worldcatKey}";
$res = httpGet($url, 5);
if ($res) {
// Logique de parsing XML à implémenter selon la structure de réponse WorldCat
// Si une couverture est trouvée :
// setCache($pdo, $cacheKey, ['poster' => $img], 'worldcat');
// return $img;
}
}
// 4. Amazon Product Advertising API (PA-API 5.0)
$amazonKey = getConfigValue($pdo, 'amazon_api_key');
if ($amazonKey) {
// Note: L'API Amazon requiert une signature AWS V4 (clé d'accès + clé secrète).
// Voici la structure cible de l'appel pour rechercher par EAN (Keywords)
$url = "https://webservices.amazon.fr/paapi5/searchitems";
// Pseudo-requête de démonstration
// Il faudrait utiliser un SDK AWS ou une fonction de signature HMAC-SHA256 ici
$payload = json_encode([
"Keywords" => $ean,
"Resources" => ["Images.Primary.Large"],
"PartnerTag" => "moncinema-21",
"PartnerType" => "Associates",
"Marketplace" => "www.amazon.fr"
]);
// Simulation d'une réponse valide
// if ($response && !empty($data['SearchResult']['Items'][0]['Images']['Primary']['Large']['URL'])) { ... }
}
return null;
}
// ─ HTTP avec cURL (timeout court pour vitesse) ──
function httpGet($url, $timeout = 5) { function httpGet($url, $timeout = 5) {
if (!function_exists('curl_init')) { if (!function_exists('curl_init')) {
$ctx = stream_context_create(['http' => ['timeout' => $timeout, 'user_agent' => 'MonCinema/4.0']]); $ctx = stream_context_create(['http' => ['timeout' => $timeout, 'user_agent' => 'MonCinema/5.0']]);
return @file_get_contents($url, false, $ctx); return @file_get_contents($url, false, $ctx);
} }
$ch = curl_init($url); $ch = curl_init($url);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $timeout, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_USERAGENT => 'MonCinema/4.0', CURLOPT_FOLLOWLOCATION => true]); curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $timeout, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_USERAGENT => 'MonCinema/5.0', CURLOPT_FOLLOWLOCATION => true]);
$res = curl_exec($ch); $res = curl_exec($ch);
curl_close($ch); curl_close($ch);
return $res ?: null; return $res ?: null;
} }
// ── Cache BDD ──
function getCache($pdo, $key) { function getCache($pdo, $key) {
try { try {
$stmt = $pdo->prepare("SELECT data FROM cache_api WHERE cache_key = ? AND created_at > ?"); $stmt = $pdo->prepare("SELECT data FROM cache_api WHERE cache_key = ? AND created_at > ?");
@@ -175,57 +93,60 @@ function setCache($pdo, $key, $data, $source) {
} catch (\Exception $e) { /* ignore */ } } catch (\Exception $e) { /* ignore */ }
} }
// ── NETTOYAGE TITRE pour TMDB ──
function cleanTitle($title) { function cleanTitle($title) {
$clean = preg_replace('/\s*[\[\(].*?[\]\)]\s*/', '', $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('/\s*-\s*(Édition|Edition|Collector|Simple|Spéciale|Digibook|Ultimate|Intégrale|Combo|SteelBook|Boîtier).*$/i', '', $clean);
$clean = preg_replace('/\s*(Blu-ray|DVD|4K|UHD|VHS|BDRip)\s*$/i', '', $clean); // Coupe radicale si on rencontre des mots clés liés aux supports physiques
$clean = preg_replace('/\s*-\s*Édition\s+\d+\s*DVD\s*$/i', '', $clean); $clean = preg_replace('/(blu-ray|bluray|dvd|4k|ultra hd|combo|vhs|bdrip).*$/i', '', $clean);
return trim(preg_replace('/\s{2,}/', ' ', $clean)); return trim(preg_replace('/\s{2,}/', ' ', $clean));
} }
// ── 1. MOVIEPOSTERDB (spécialisé jaquettes DVD/Blu-ray) ── function detectFormat($title, $desc = '') {
function fetchMoviePosterDB($title, $year, $pdo) { $t = strtoupper($title . ' ' . $desc);
$cacheKey = 'mpdb_' . md5(strtolower(cleanTitle($title)) . '|' . $year); if (strpos($t, '4K') !== false || strpos($t, 'UHD') !== false) return '4K Ultra HD';
$cached = getCache($pdo, $cacheKey); if (strpos($t, 'BLU-RAY') !== false || strpos($t, 'BLURAY') !== false) return 'Blu-ray';
if ($cached) return $cached; if (strpos($t, 'DVD') !== false) return 'DVD';
if (strpos($t, 'VHS') !== false) return 'VHS';
$url = "https://api.movieposterdb.com/v1/search?apikey=free&q=" . urlencode(cleanTitle($title)) . "&year=" . $year; if (strpos($t, 'COFFRET') !== false || strpos($t, 'TRILOGIE') !== false) return 'Coffret';
$res = httpGet($url, 4); return 'Blu-ray'; // Format par défaut moderne
if (!$res) return null;
$data = json_decode($res, true);
if (empty($data['results'][0]['poster'])) return null;
$poster = $data['results'][0]['poster'];
setCache($pdo, $cacheKey, ['poster' => $poster], 'mpdb');
return ['poster' => $poster];
} }
// ── 2. UPCitemdb (spécialisé codes-barres DVD/Blu-ray) ── function extractYear($dateStr) {
if (preg_match('/(\d{4})/', $dateStr, $m)) return $m[1];
return '';
}
// ── 1. API UPCitemDB ──
function fetchUPCitemdb($ean, $pdo) { function fetchUPCitemdb($ean, $pdo) {
if (empty($ean) || strlen($ean) < 10) return null; if (empty($ean) || strlen($ean) < 8) return null;
$cacheKey = 'upc_' . $ean; $cacheKey = 'upc_full_' . md5($ean);
$cached = getCache($pdo, $cacheKey); $cached = getCache($pdo, $cacheKey);
if ($cached) return $cached; if ($cached) return $cached;
$url = "https://api.upcitemdb.com/prod/trial/lookup?upc={$ean}"; $url = "https://api.upcitemdb.com/prod/trial/lookup?upc=" . urlencode($ean);
$res = httpGet($url, 4); $res = httpGet($url, 5);
if (!$res) return null; if (!$res) return null;
$data = json_decode($res, true); $data = json_decode($res, true);
if (empty($data['items'][0]['images'][0])) return null; if (isset($data['code']) && $data['code'] === 'OK' && !empty($data['items'])) {
$item = $data['items'][0];
$poster = $data['items'][0]['images'][0]; $result = [
setCache($pdo, $cacheKey, ['poster' => $poster], 'upc'); 'title' => $item['title'] ?? '',
return ['poster' => $poster]; 'poster' => $item['images'][0] ?? '',
'publisher' => $item['brand'] ?? $item['publisher'] ?? '',
'format' => detectFormat($item['title'] ?? '', $item['description'] ?? '')
];
setCache($pdo, $cacheKey, $result, 'upc');
return $result;
}
return null;
} }
// ── 3. TMDB (fallback avec curl_multi) ── // ── 2. API TMDB (Full Extract) ──
function fetchTMDB($title, $year, $apiKey, $pdo) { function fetchTMDBFull($title, $year, $apiKey, $pdo) {
if (empty($apiKey) || empty($title)) return null; if (empty($apiKey) || empty($title)) return null;
$cleanTitle = cleanTitle($title); $cleanTitle = cleanTitle($title);
$cacheKey = 'tmdb_' . md5(strtolower($cleanTitle) . '|' . $year); $cacheKey = 'tmdb_full_' . md5(strtolower($cleanTitle) . '|' . $year);
$cached = getCache($pdo, $cacheKey); $cached = getCache($pdo, $cacheKey);
if ($cached) return $cached; if ($cached) return $cached;
@@ -245,74 +166,48 @@ function fetchTMDB($title, $year, $apiKey, $pdo) {
} }
if (empty($searchData['results'])) return null; if (empty($searchData['results'])) return null;
$movie = $searchData['results'][0]; $movieId = $searchData['results'][0]['id'];
$movieId = $movie['id'];
$poster = !empty($movie['poster_path']) ? "https://image.tmdb.org/t/p/w500" . $movie['poster_path'] : '';
// Appels parallèles avec curl_multi // Appel TMDB complet pour avoir le Réalisateur, la Durée (Runtime) et le Streaming
$detailsUrl = "https://api.themoviedb.org/3/movie/{$movieId}?api_key={$apiKey}&append_to_response=credits,watch/providers&language=fr-FR";
$detailsRes = httpGet($detailsUrl, 5);
if (!$detailsRes) return null;
$details = json_decode($detailsRes, true);
// Extraction Réalisateur
$director = ''; $director = '';
$streaming = ''; if (!empty($details['credits']['crew'])) {
foreach ($details['credits']['crew'] as $crew) {
if (function_exists('curl_multi_init')) { if ($crew['job'] === 'Director') { $director = $crew['name']; break; }
$mh = curl_multi_init();
$ch1 = curl_init("https://api.themoviedb.org/3/movie/{$movieId}/credits?api_key={$apiKey}&language=fr-FR");
$ch2 = curl_init("https://api.themoviedb.org/3/movie/{$movieId}/watch/providers?api_key={$apiKey}");
curl_setopt_array($ch1, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 4, CURLOPT_SSL_VERIFYPEER => false]);
curl_setopt_array($ch2, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 4, CURLOPT_SSL_VERIFYPEER => false]);
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);
$running = 0;
do { curl_multi_exec($mh, $running); curl_multi_select($mh); } while ($running > 0);
$creditsRes = curl_multi_getcontent($ch1);
$watchRes = curl_multi_getcontent($ch2);
curl_multi_remove_handle($mh, $ch1); curl_close($ch1);
curl_multi_remove_handle($mh, $ch2); curl_close($ch2);
curl_multi_close($mh);
if ($creditsRes) {
$creditsData = json_decode($creditsRes, true);
if (!empty($creditsData['crew'])) {
foreach ($creditsData['crew'] as $crew) {
if ($crew['job'] === 'Director') { $director = $crew['name']; break; }
}
}
}
if ($watchRes) {
$watchData = json_decode($watchRes, true);
$frProviders = $watchData['results']['FR'] ?? [];
$platforms = [];
if (!empty($frProviders['flatrate'])) { foreach ($frProviders['flatrate'] as $p) $platforms[] = $p['provider_name']; }
if (empty($platforms)) {
if (!empty($frProviders['rent'])) { foreach ($frProviders['rent'] as $p) $platforms[] = $p['provider_name'] . ' (loc.)'; }
if (!empty($frProviders['buy'])) { foreach ($frProviders['buy'] as $p) $platforms[] = $p['provider_name'] . ' (achat)'; }
}
if (!empty($platforms)) $streaming = implode(', ', array_unique($platforms));
} }
} }
$result = ['director' => $director, 'poster' => $poster, 'streaming' => $streaming]; // Extraction Streaming
$streaming = '';
$frProviders = $details['watch/providers']['results']['FR'] ?? [];
$platforms = [];
if (!empty($frProviders['flatrate'])) { foreach ($frProviders['flatrate'] as $p) $platforms[] = $p['provider_name']; }
if (empty($platforms)) {
if (!empty($frProviders['rent'])) { foreach ($frProviders['rent'] as $p) $platforms[] = $p['provider_name'] . ' (loc.)'; }
if (!empty($frProviders['buy'])) { foreach ($frProviders['buy'] as $p) $platforms[] = $p['provider_name'] . ' (achat)'; }
}
if (!empty($platforms)) $streaming = implode(', ', array_unique($platforms));
$result = [
'title' => $details['title'] ?? '',
'year' => !empty($details['release_date']) ? substr($details['release_date'], 0, 4) : '',
'director' => $director,
'poster' => !empty($details['poster_path']) ? "https://image.tmdb.org/t/p/w500" . $details['poster_path'] : '',
'length' => !empty($details['runtime']) ? $details['runtime'] . ' min' : '',
'streaming' => $streaming
];
setCache($pdo, $cacheKey, $result, 'tmdb'); setCache($pdo, $cacheKey, $result, 'tmdb');
return $result; return $result;
} }
function detectFormat($title, $desc = '') { // ── ROUTEUR PRINCIPAL ──
$t = strtoupper($title . ' ' . $desc);
if (strpos($t, '4K') !== false || strpos($t, 'UHD') !== false) return 'Blu-ray 4K';
if (strpos($t, 'BLU-RAY') !== false || strpos($t, 'BLURAY') !== false) return 'Blu-ray';
if (strpos($t, 'DVD') !== false) return 'DVD';
if (strpos($t, 'VHS') !== false) return 'VHS';
if (strpos($t, 'COFFRET') !== false || strpos($t, 'TRILOGIE') !== false) return 'Coffret';
return 'DVD';
}
function extractYear($dateStr) {
if (preg_match('/(\d{4})/', $dateStr, $m)) return $m[1];
return '';
}
// ── ROUTEUR ──
$action = $_GET['action'] ?? ''; $action = $_GET['action'] ?? '';
$data = json_decode(file_get_contents('php://input'), true) ?? []; $data = json_decode(file_get_contents('php://input'), true) ?? [];
@@ -343,11 +238,13 @@ switch ($action) {
case 'get_config_keys': case 'get_config_keys':
checkAuth($pdo); checkAuth($pdo);
$keys = ['tmdb_api_key', 'ean_search_key', 'barcode_lookup_key']; $keys = ['tmdb_api_key']; // Les autres APIs ont été supprimées
$result = []; $result = [];
foreach ($keys as $k) { foreach ($keys as $k) {
$val = getConfigValue($pdo, $k); $stmt = $pdo->prepare("SELECT key_value FROM config WHERE key_name = ?");
$result[$k] = $val ? '••••••••' : ''; // Masqué pour sécurité $stmt->execute([$k]);
$row = $stmt->fetch();
$result[$k] = $row ? '••••••••' : '';
} }
echo json_encode($result); echo json_encode($result);
break; break;
@@ -356,7 +253,7 @@ switch ($action) {
checkAuth($pdo); checkAuth($pdo);
$keyName = $data['key_name'] ?? ''; $keyName = $data['key_name'] ?? '';
$keyValue = $data['key_value'] ?? ''; $keyValue = $data['key_value'] ?? '';
$allowedKeys = ['tmdb_api_key', 'ean_search_key', 'barcode_lookup_key']; $allowedKeys = ['tmdb_api_key']; // Les autres APIs ont été supprimées
if (in_array($keyName, $allowedKeys) && !empty($keyValue)) { if (in_array($keyName, $allowedKeys) && !empty($keyValue)) {
$stmt = $pdo->prepare("REPLACE INTO config (key_name, key_value) VALUES (?, ?)"); $stmt = $pdo->prepare("REPLACE INTO config (key_name, key_value) VALUES (?, ?)");
@@ -374,17 +271,59 @@ switch ($action) {
echo json_encode(array_merge($crit, $video)); echo json_encode(array_merge($crit, $video));
break; break;
case 'search_ean_full':
$ean = $_GET['ean'] ?? '';
if (!$ean) { echo json_encode(['error' => 'EAN manquant']); exit; }
$result = [
'ean' => $ean, 'title' => '', 'director' => '', 'year' => '',
'poster' => '', 'publisher' => '', 'format' => '',
'length' => '', 'number_of_discs' => 1, 'aspect_ratio' => ''
];
// 1. RECHERCHE UPCitemDB
$upcData = fetchUPCitemdb($ean, $pdo);
$tmdbQueryTitle = "";
if ($upcData) {
$tmdbQueryTitle = $upcData['title'];
$result['title'] = $upcData['title'];
$result['poster'] = $upcData['poster'];
$result['publisher'] = $upcData['publisher'];
$result['format'] = $upcData['format'];
}
// 2. CROISEMENT TMDB
$tmdbKey = getTmdbApiKey($pdo);
if ($tmdbKey && $tmdbQueryTitle) {
$tmdbData = fetchTMDBFull($tmdbQueryTitle, '', $tmdbKey, $pdo);
if ($tmdbData) {
// On privilégie le vrai nom du film et ses métadonnées officielles
if (!empty($tmdbData['title'])) $result['title'] = $tmdbData['title'];
if (empty($result['poster']) && !empty($tmdbData['poster'])) $result['poster'] = $tmdbData['poster'];
if (!empty($tmdbData['year'])) $result['year'] = $tmdbData['year'];
if (!empty($tmdbData['length'])) $result['length'] = $tmdbData['length'];
if (!empty($tmdbData['director'])) $result['director'] = $tmdbData['director'];
}
}
echo json_encode(['success' => true, 'data' => $result]);
break;
case 'save_film': case 'save_film':
checkAuth($pdo); checkAuth($pdo);
$type = $data['type'] ?? 'critique'; $type = $data['type'] ?? 'critique';
$id = !empty($data['id']) ? $data['id'] : makeStableId($data['title'] ?? '', $data['year'] ?? '0000'); $id = !empty($data['id']) ? $data['id'] : makeStableId($data['title'] ?? '', $data['year'] ?? '0000');
if (empty($data['director']) || empty($data['poster'])) { if (empty($data['director']) || empty($data['poster'])) {
$tmdbData = fetchTMDB($data['title'] ?? '', $data['year'] ?? '', getTmdbApiKey($pdo), $pdo); $tmdbData = fetchTMDBFull($data['title'] ?? '', $data['year'] ?? '', getTmdbApiKey($pdo), $pdo);
if ($tmdbData) { if ($tmdbData) {
if (empty($data['director'])) $data['director'] = $tmdbData['director']; if (empty($data['director'])) $data['director'] = $tmdbData['director'];
if (empty($data['poster'])) $data['poster'] = $tmdbData['poster']; if (empty($data['poster'])) $data['poster'] = $tmdbData['poster'];
if (empty($data['length']) && !empty($tmdbData['length'])) $data['length'] = $tmdbData['length'];
} }
} }
if ($type === 'critique') { if ($type === 'critique') {
$sql = "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)"; $sql = "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)";
$stmt = $pdo->prepare($sql); $stmt = $pdo->prepare($sql);
@@ -413,14 +352,14 @@ switch ($action) {
else { http_response_code(400); echo json_encode(["success" => false, "error" => "Aucun élément sélectionné."]); } else { http_response_code(400); echo json_encode(["success" => false, "error" => "Aucun élément sélectionné."]); }
break; break;
// ── IMPORT PAR LOTS OPTIMISÉ ── // ── IMPORT PAR LOTS CSV (CROISEMENT UPC + TMDB) ──
case 'import_batch': case 'import_batch':
checkAuth($pdo); checkAuth($pdo);
$items = $data['items'] ?? []; $items = $data['items'] ?? [];
$type = $data['type'] ?? 'videotheque'; $type = $data['type'] ?? 'videotheque';
$tmdbApiKey = getTmdbApiKey($pdo); $tmdbApiKey = getTmdbApiKey($pdo);
$imported = 0; $imported = 0;
$stats = ['mpdb_hits' => 0, 'upc_hits' => 0, 'tmdb_hits' => 0, 'no_image' => 0]; $stats = ['upc_hits' => 0, 'tmdb_hits' => 0, 'no_image' => 0];
$pdo->beginTransaction(); $pdo->beginTransaction();
@@ -446,49 +385,59 @@ switch ($action) {
$length = $rowData['length'] ?? $rowData['Length'] ?? ''; $length = $rowData['length'] ?? $rowData['Length'] ?? '';
$discs = $rowData['number_of_discs'] ?? 1; $discs = $rowData['number_of_discs'] ?? 1;
$aspect = $rowData['aspect_ratio'] ?? ''; $aspect = $rowData['aspect_ratio'] ?? '';
$format = $rowData['format'] ?? $rowData['Format'] ?? detectFormat($title, $description); $format = $rowData['format'] ?? $rowData['Format'] ?? '';
$poster = $rowData['poster'] ?? $rowData['Poster'] ?? $rowData['image'] ?? ''; $poster = $rowData['poster'] ?? $rowData['Poster'] ?? $rowData['image'] ?? '';
// ── RECHERCHE D'AFFICHE ADAPTÉE SELON LE TYPE ── // ── RECHERCHE CROISÉE ──
if ($type === 'videotheque') { if ($type === 'videotheque') {
// 1. Recherche prioritaire par EAN/UPC (UPCitemDB, EAN-Search, Barcode Lookup) // 1. UPCitemDB
if (empty($poster) && !empty($ean)) { if (!empty($ean)) {
$eanPoster = fetchPosterByEAN($ean, $pdo); $upcData = fetchUPCitemdb($ean, $pdo);
if ($eanPoster) { if ($upcData) {
$poster = $eanPoster; if (empty($poster) && !empty($upcData['poster'])) {
$stats['upc_hits']++; $poster = $upcData['poster'];
$stats['upc_hits']++;
}
// On garde le titre brut UPC uniquement si on n'a rien d'autre pour la suite
if ($title === 'Sans titre') $title = $upcData['title'];
if (empty($publisher)) $publisher = $upcData['publisher'];
if (empty($format)) $format = $upcData['format'];
}
} }
} if (empty($format)) $format = detectFormat($title, $description);
// 2. Fallback MoviePosterDB (par titre)
if (empty($poster)) { // 2. TMDB (Complète les vides avec la Data Officielle)
$mpdbData = fetchMoviePosterDB($title, $year, $pdo); if ($tmdbApiKey && !empty($title)) {
if ($mpdbData && !empty($mpdbData['poster'])) { $tmdbData = fetchTMDBFull($title, $year, $tmdbApiKey, $pdo);
$poster = $mpdbData['poster']; if ($tmdbData) {
$stats['mpdb_hits']++; // On sécurise un titre propre de film
if (!empty($tmdbData['title'])) $title = $tmdbData['title'];
if (empty($director) && !empty($tmdbData['director'])) $director = $tmdbData['director'];
if (empty($year) && !empty($tmdbData['year'])) $year = $tmdbData['year'];
if (empty($length) && !empty($tmdbData['length'])) $length = $tmdbData['length'];
if (empty($poster) && !empty($tmdbData['poster'])) {
$poster = $tmdbData['poster'];
$stats['tmdb_hits']++;
}
}
} }
} } else {
// ❌ TMDB SUPPRIMÉ POUR LA VIDÉOTHÈQUE (Conformément à la demande) // Pour les critiques : Seulement TMDB
} else { if ($tmdbApiKey && !empty($title)) {
// Pour les CRITIQUES, on garde l'ancien comportement (TMDB pour réalisateur/streaming/affiche) $tmdbData = fetchTMDBFull($title, $year, $tmdbApiKey, $pdo);
if (empty($poster)) { if ($tmdbData) {
$mpdbData = fetchMoviePosterDB($title, $year, $pdo); if (!empty($tmdbData['title'])) $title = $tmdbData['title'];
if ($mpdbData && !empty($mpdbData['poster'])) { if (empty($director)) $director = $tmdbData['director'];
$poster = $mpdbData['poster']; if (empty($year) && !empty($tmdbData['year'])) $year = $tmdbData['year'];
$stats['mpdb_hits']++; if (empty($poster) && !empty($tmdbData['poster'])) {
} $poster = $tmdbData['poster'];
} $stats['tmdb_hits']++;
if (empty($poster) && $tmdbApiKey) { }
$tmdbData = fetchTMDB($title, $year, $tmdbApiKey, $pdo); $streaming = $rowData['streaming'] ?? $rowData['Streaming'] ?? (!empty($tmdbData['streaming']) ? $tmdbData['streaming'] : 'Disponible en support physique ou Cinéma');
if ($tmdbData) {
if (empty($director)) $director = $tmdbData['director'];
if (!empty($tmdbData['poster'])) {
$poster = $tmdbData['poster'];
$stats['tmdb_hits']++;
} }
} }
} }
}
if (empty($poster)) $stats['no_image']++; if (empty($poster)) $stats['no_image']++;
@@ -497,7 +446,7 @@ switch ($action) {
if ($type === 'critique') { if ($type === 'critique') {
$rating = isset($rowData['rating']) && $rowData['rating'] !== '' ? (float)$rowData['rating'] : (isset($rowData['Rating']) ? (float)$rowData['Rating'] : 3.0); $rating = isset($rowData['rating']) && $rowData['rating'] !== '' ? (float)$rowData['rating'] : (isset($rowData['Rating']) ? (float)$rowData['Rating'] : 3.0);
$review = $rowData['review'] ?? $rowData['Review'] ?? $description; $review = $rowData['review'] ?? $rowData['Review'] ?? $description;
$streaming = $rowData['streaming'] ?? $rowData['Streaming'] ?? (!empty($tmdbData['streaming']) ? $tmdbData['streaming'] : 'Disponible en support physique ou Cinéma'); $streaming = $streaming ?? 'Inconnu';
$sql = "INSERT INTO critiques (id, title, year, director, poster, rating, review, streaming) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE rating=VALUES(rating), review=IF(VALUES(review)!='',VALUES(review),review), director=IF(VALUES(director)!='',VALUES(director),director), poster=IF(VALUES(poster)!='',VALUES(poster),poster), streaming=IF(VALUES(streaming)!='',VALUES(streaming),streaming)"; $sql = "INSERT INTO critiques (id, title, year, director, poster, rating, review, streaming) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE rating=VALUES(rating), review=IF(VALUES(review)!='',VALUES(review),review), director=IF(VALUES(director)!='',VALUES(director),director), poster=IF(VALUES(poster)!='',VALUES(poster),poster), streaming=IF(VALUES(streaming)!='',VALUES(streaming),streaming)";
$stmt = $pdo->prepare($sql); $stmt = $pdo->prepare($sql);