From 8391400c0c78ebfdc887126e472de5da860acd88 Mon Sep 17 00:00:00 2001 From: Cedric Date: Sun, 21 Jun 2026 18:01:28 +0200 Subject: [PATCH] Actualiser api.php --- api.php | 296 ++++++++++++++++++++++---------------------------------- 1 file changed, 118 insertions(+), 178 deletions(-) diff --git a/api.php b/api.php index 23b639a..67ce903 100644 --- a/api.php +++ b/api.php @@ -8,7 +8,7 @@ header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; } define('ENCRYPTION_KEY', 'MaCleSecreteSuperRobuste123!'); -define('TMDB_CACHE_TTL', 604800); // 7 jours de cache +define('CACHE_TTL', 604800); // 7 jours try { $pdo = new PDO("mysql:host=localhost;dbname=mon_cinema;charset=utf8mb4", "root", "", [ @@ -21,28 +21,21 @@ try { $pdo->exec("ALTER TABLE critiques MODIFY COLUMN rating DECIMAL(3,1) DEFAULT 3.0;"); $pdo->exec("CREATE TABLE IF NOT EXISTS videotheque (id BIGINT PRIMARY KEY, title VARCHAR(255) NOT NULL, 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)"); - // 🆕 Tables de cache - $pdo->exec("CREATE TABLE IF NOT EXISTS cache_tmdb ( - cache_key VARCHAR(100) PRIMARY KEY, + // Cache unifié pour toutes les APIs + $pdo->exec("CREATE TABLE IF NOT EXISTS cache_api ( + cache_key VARCHAR(120) PRIMARY KEY, data TEXT NOT NULL, - created_at INT NOT NULL - )"); - $pdo->exec("CREATE TABLE IF NOT EXISTS cache_ean ( - ean VARCHAR(20) PRIMARY KEY, - image_url TEXT, - source VARCHAR(20), + source VARCHAR(20) NOT NULL, created_at INT NOT NULL )"); } catch (\PDOException $e) { echo json_encode(["error" => "Erreur BDD : " . $e->getMessage()]); exit; } function makeStableId($title, $year) { - $key = strtolower(trim($title ?? '')) . '|' . trim($year ?? ''); - return (abs(crc32($key)) % 2000000000) + 100000000; + return (abs(crc32(strtolower(trim($title ?? '')) . '|' . trim($year ?? ''))) % 2000000000) + 100000000; } function checkAuth($pdo) { - $stmtCheck = $pdo->query("SELECT COUNT(*) FROM users"); - if ($stmtCheck->fetchColumn() == 0) return true; + if ($pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() == 0) return true; $token = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; if (empty($token) && function_exists('apache_request_headers')) { $headers = apache_request_headers(); @@ -54,152 +47,121 @@ function checkAuth($pdo) { function encryptData($data) { $iv = openssl_random_pseudo_bytes(16); $key = hash('sha256', ENCRYPTION_KEY, true); - $encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv); - return base64_encode($encrypted . '::' . $iv); + return base64_encode(openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv) . '::' . $iv); } -function decryptData($encryptedStr) { - $decoded = base64_decode($encryptedStr); - if (strpos($decoded, '::') !== false) { list($encData, $iv) = explode('::', $decoded, 2); } else { return null; } - $key = hash('sha256', ENCRYPTION_KEY, true); - $iv = substr($iv, 0, 16); - return openssl_decrypt($encData, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv); +function decryptData($str) { + $decoded = base64_decode($str); + if (strpos($decoded, '::') === false) return null; + list($enc, $iv) = explode('::', $decoded, 2); + return openssl_decrypt($enc, 'AES-256-CBC', hash('sha256', ENCRYPTION_KEY, true), OPENSSL_RAW_DATA, substr($iv, 0, 16)); } function getTmdbApiKey($pdo) { $stmt = $pdo->prepare("SELECT key_value FROM config WHERE key_name = 'tmdb_api_key'"); $stmt->execute(); $row = $stmt->fetch(); - if (!$row) return null; - return decryptData($row['key_value']); + return $row ? decryptData($row['key_value']) : null; } -// ── HTTP unifié avec cURL ── -function httpGet($url, $timeout = 8) { - if (function_exists('curl_init')) { - $ch = curl_init($url); - curl_setopt_array($ch, [ - CURLOPT_RETURNTRANSFER => true, - CURLOPT_TIMEOUT => $timeout, - CURLOPT_SSL_VERIFYPEER => false, - CURLOPT_USERAGENT => 'MonCinema/3.0', - CURLOPT_FOLLOWLOCATION => true - ]); - $res = curl_exec($ch); - curl_close($ch); - return $res ?: null; +// ─ HTTP avec cURL (timeout court pour vitesse) ── +function httpGet($url, $timeout = 5) { + if (!function_exists('curl_init')) { + $ctx = stream_context_create(['http' => ['timeout' => $timeout, 'user_agent' => 'MonCinema/4.0']]); + return @file_get_contents($url, false, $ctx); } - $ctx = stream_context_create(['http' => ['timeout' => $timeout, 'user_agent' => 'MonCinema/3.0']]); - return @file_get_contents($url, false, $ctx); + $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]); + $res = curl_exec($ch); + curl_close($ch); + return $res ?: null; } -// ── NETTOYAGE TITRE (crucial pour TMDB) ── -function cleanTitleForTmdb($title) { - // Enlever tout ce qui est entre crochets/parenthèses +// ── Cache BDD ── +function getCache($pdo, $key) { + try { + $stmt = $pdo->prepare("SELECT data FROM cache_api WHERE cache_key = ? AND created_at > ?"); + $stmt->execute([$key, time() - CACHE_TTL]); + $row = $stmt->fetch(); + return $row ? json_decode($row['data'], true) : null; + } catch (\Exception $e) { return null; } +} + +function setCache($pdo, $key, $data, $source) { + try { + $stmt = $pdo->prepare("REPLACE INTO cache_api (cache_key, data, source, created_at) VALUES (?, ?, ?, ?)"); + $stmt->execute([$key, json_encode($data), $source, time()]); + } catch (\Exception $e) { /* ignore */ } +} + +// ── NETTOYAGE TITRE pour TMDB ── +function cleanTitle($title) { $clean = preg_replace('/\s*[\[\(].*?[\]\)]\s*/', '', $title); - // Enlever les mentions d'édition - $clean = preg_replace('/\s*-\s*(Édition|Edition|Collector|Simple|Spéciale|Speciale|Digibook|Ultimate|Intégrale|Integrale).*$/i', '', $clean); - // Enlever "Combo Blu-ray + DVD" - $clean = preg_replace('/\s*\[Combo.*?\]\s*/i', '', $clean); - // Enlever "Blu-ray", "DVD", "4K", "UHD" à la fin - $clean = preg_replace('/\s*(Blu-ray|DVD|4K|UHD|VHS)\s*$/i', '', $clean); - // Enlever " - Édition X DVD" + $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); $clean = preg_replace('/\s*-\s*Édition\s+\d+\s*DVD\s*$/i', '', $clean); - // Nettoyer les espaces multiples et tirets en trop - $clean = preg_replace('/\s*-\s*$/', '', $clean); - $clean = preg_replace('/\s{2,}/', ' ', $clean); - return trim($clean); + return trim(preg_replace('/\s{2,}/', ' ', $clean)); } -// ── RÉCUPÉRATION IMAGE VIA EAN (UPCitemdb - spécialisé DVD/Blu-ray) ── -function fetchImageByEAN($ean, $pdo = null) { +// ── 1. MOVIEPOSTERDB (spécialisé jaquettes DVD/Blu-ray) ── +function fetchMoviePosterDB($title, $year, $pdo) { + $cacheKey = 'mpdb_' . md5(strtolower(cleanTitle($title)) . '|' . $year); + $cached = getCache($pdo, $cacheKey); + if ($cached) return $cached; + + $url = "https://api.movieposterdb.com/v1/search?apikey=free&q=" . urlencode(cleanTitle($title)) . "&year=" . $year; + $res = httpGet($url, 4); + 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 fetchUPCitemdb($ean, $pdo) { if (empty($ean) || strlen($ean) < 10) return null; + $cacheKey = 'upc_' . $ean; + $cached = getCache($pdo, $cacheKey); + if ($cached) return $cached; - // Vérifier le cache - if ($pdo) { - try { - $stmt = $pdo->prepare("SELECT image_url FROM cache_ean WHERE ean = ? AND created_at > ?"); - $stmt->execute([$ean, time() - TMDB_CACHE_TTL]); - $row = $stmt->fetch(); - if ($row && !empty($row['image_url'])) return $row['image_url']; - } catch (\Exception $e) { /* ignore */ } - } - - // UPCitemdb API (gratuit, spécialisé DVD/Blu-ray/CD) $url = "https://api.upcitemdb.com/prod/trial/lookup?upc={$ean}"; - $res = httpGet($url, 6); + $res = httpGet($url, 4); + if (!$res) return null; - if ($res) { - $data = json_decode($res, true); - if (!empty($data['items'][0]['images'][0])) { - $imageUrl = $data['items'][0]['images'][0]; - // Sauvegarder dans le cache - if ($pdo) { - try { - $stmt = $pdo->prepare("REPLACE INTO cache_ean (ean, image_url, source, created_at) VALUES (?, ?, 'upcitemdb', ?)"); - $stmt->execute([$ean, $imageUrl, time()]); - } catch (\Exception $e) { /* ignore */ } - } - return $imageUrl; - } - } + $data = json_decode($res, true); + if (empty($data['items'][0]['images'][0])) return null; - // Fallback : Open Library (pour les livres/CD) - $url = "https://openlibrary.org/api/books?bibkeys=ISBN:{$ean}&jscmd=data&format=json"; - $res = httpGet($url, 5); - if ($res) { - $data = json_decode($res, true); - $key = "ISBN:{$ean}"; - if (isset($data[$key])) { - $cover = $data[$key]['cover'] ?? []; - $imageUrl = $cover['large'] ?? $cover['medium'] ?? $cover['small'] ?? null; - if ($imageUrl) { - if ($pdo) { - try { - $stmt = $pdo->prepare("REPLACE INTO cache_ean (ean, image_url, source, created_at) VALUES (?, ?, 'openlibrary', ?)"); - $stmt->execute([$ean, $imageUrl, time()]); - } catch (\Exception $e) { /* ignore */ } - } - return $imageUrl; - } - } - } - - return null; + $poster = $data['items'][0]['images'][0]; + setCache($pdo, $cacheKey, ['poster' => $poster], 'upc'); + return ['poster' => $poster]; } -// ── TMDB AVEC CACHE + curl_multi ── -function fetchTmdbData($title, $year, $apiKey, $pdo = null) { +// ── 3. TMDB (fallback avec curl_multi) ── +function fetchTMDB($title, $year, $apiKey, $pdo) { if (empty($apiKey) || empty($title)) return null; - - $cleanTitle = cleanTitleForTmdb($title); - $cacheKey = md5(strtolower($cleanTitle) . '|' . $year); - - // Vérifier le cache - if ($pdo) { - try { - $stmt = $pdo->prepare("SELECT data FROM cache_tmdb WHERE cache_key = ? AND created_at > ?"); - $stmt->execute([$cacheKey, time() - TMDB_CACHE_TTL]); - $row = $stmt->fetch(); - if ($row) return json_decode($row['data'], true); - } catch (\Exception $e) { /* ignore */ } - } + $cleanTitle = cleanTitle($title); + $cacheKey = 'tmdb_' . md5(strtolower($cleanTitle) . '|' . $year); + $cached = getCache($pdo, $cacheKey); + if ($cached) return $cached; $searchUrl = "https://api.themoviedb.org/3/search/movie?api_key={$apiKey}&query=" . urlencode($cleanTitle) . "&year={$year}&language=fr-FR"; - $searchRes = httpGet($searchUrl, 8); + $searchRes = httpGet($searchUrl, 5); if (!$searchRes) return null; $searchData = json_decode($searchRes, true); if (empty($searchData['results'])) { - // 2ème tentative sans l'année + // Retry sans année $searchUrl2 = "https://api.themoviedb.org/3/search/movie?api_key={$apiKey}&query=" . urlencode($cleanTitle) . "&language=fr-FR"; - $searchRes2 = httpGet($searchUrl2, 8); + $searchRes2 = httpGet($searchUrl2, 5); if ($searchRes2) { $searchData2 = json_decode($searchRes2, true); if (!empty($searchData2['results'])) $searchData = $searchData2; } } - if (empty($searchData['results'])) return null; $movie = $searchData['results'][0]; @@ -212,14 +174,10 @@ function fetchTmdbData($title, $year, $apiKey, $pdo = null) { if (function_exists('curl_multi_init')) { $mh = curl_multi_init(); - $handles = []; - $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 => 6, CURLOPT_SSL_VERIFYPEER => false]); - curl_setopt_array($ch2, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 6, CURLOPT_SSL_VERIFYPEER => false]); - + 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); @@ -228,7 +186,6 @@ function fetchTmdbData($title, $year, $apiKey, $pdo = null) { $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); @@ -241,7 +198,6 @@ function fetchTmdbData($title, $year, $apiKey, $pdo = null) { } } } - if ($watchRes) { $watchData = json_decode($watchRes, true); $frProviders = $watchData['results']['FR'] ?? []; @@ -256,20 +212,12 @@ function fetchTmdbData($title, $year, $apiKey, $pdo = null) { } $result = ['director' => $director, 'poster' => $poster, 'streaming' => $streaming]; - - // Sauvegarder dans le cache - if ($pdo) { - try { - $stmt = $pdo->prepare("REPLACE INTO cache_tmdb (cache_key, data, created_at) VALUES (?, ?, ?)"); - $stmt->execute([$cacheKey, json_encode($result), time()]); - } catch (\Exception $e) { /* ignore */ } - } - + setCache($pdo, $cacheKey, $result, 'tmdb'); return $result; } -function detectFormat($title, $description = '') { - $t = strtoupper($title . ' ' . $description); +function detectFormat($title, $desc = '') { + $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'; @@ -279,28 +227,28 @@ function detectFormat($title, $description = '') { } function extractYear($dateStr) { - if (preg_match('/(\d{4})/', $dateStr, $matches)) return $matches[1]; + if (preg_match('/(\d{4})/', $dateStr, $m)) return $m[1]; return ''; } -// ── ROUTEUR PRINCIPAL ── +// ── ROUTEUR ── $action = $_GET['action'] ?? ''; $data = json_decode(file_get_contents('php://input'), true) ?? []; switch ($action) { case 'check_security_status': - $stmt = $pdo->query("SELECT COUNT(*) FROM users"); - echo json_encode(["is_blank" => ($stmt->fetchColumn() == 0)]); + echo json_encode(["is_blank" => ($pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() == 0)]); break; case 'login': - $stmt = $pdo->query("SELECT COUNT(*) FROM users"); - if ($stmt->fetchColumn() == 0) { echo json_encode(["success" => true, "token" => md5(ENCRYPTION_KEY . 'session'), "blank" => true]); } - else { + 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(); - 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."]); } + 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."]); } } break; @@ -333,7 +281,7 @@ switch ($action) { $type = $data['type'] ?? 'critique'; $id = !empty($data['id']) ? $data['id'] : makeStableId($data['title'] ?? '', $data['year'] ?? '0000'); if (empty($data['director']) || empty($data['poster'])) { - $tmdbData = fetchTmdbData($data['title'] ?? '', $data['year'] ?? '', getTmdbApiKey($pdo), $pdo); + $tmdbData = fetchTMDB($data['title'] ?? '', $data['year'] ?? '', getTmdbApiKey($pdo), $pdo); if ($tmdbData) { if (empty($data['director'])) $data['director'] = $tmdbData['director']; if (empty($data['poster'])) $data['poster'] = $tmdbData['poster']; @@ -367,13 +315,14 @@ switch ($action) { else { http_response_code(400); echo json_encode(["success" => false, "error" => "Aucun élément sélectionné."]); } break; + // ── IMPORT PAR LOTS OPTIMISÉ ── case 'import_batch': checkAuth($pdo); $items = $data['items'] ?? []; $type = $data['type'] ?? 'videotheque'; $tmdbApiKey = getTmdbApiKey($pdo); $imported = 0; - $stats = ['ean_hits' => 0, 'tmdb_hits' => 0, 'no_image' => 0, 'ean_miss' => [], 'tmdb_miss' => []]; + $stats = ['mpdb_hits' => 0, 'upc_hits' => 0, 'tmdb_hits' => 0, 'no_image' => 0]; $pdo->beginTransaction(); @@ -403,30 +352,33 @@ switch ($action) { $poster = $rowData['poster'] ?? $rowData['Poster'] ?? $rowData['image'] ?? ''; - // 1. Priorité : EAN via UPCitemdb + // 1. UPCitemdb (par code-barres) - le plus fiable pour DVD/Blu-ray if (empty($poster) && !empty($ean)) { - $eanImage = fetchImageByEAN($ean, $pdo); - if ($eanImage) { - $poster = $eanImage; - $stats['ean_hits']++; - } else { - $stats['ean_miss'][] = $ean; + $upcData = fetchUPCitemdb($ean, $pdo); + if ($upcData && !empty($upcData['poster'])) { + $poster = $upcData['poster']; + $stats['upc_hits']++; } } - // 2. Fallback : TMDB avec titre nettoyé + // 2. MoviePosterDB (par titre) - spécialisé jaquettes physiques + if (empty($poster)) { + $mpdbData = fetchMoviePosterDB($title, $year, $pdo); + if ($mpdbData && !empty($mpdbData['poster'])) { + $poster = $mpdbData['poster']; + $stats['mpdb_hits']++; + } + } + + // 3. TMDB (fallback) - affiches de films if (empty($poster) && $tmdbApiKey) { - $tmdbData = fetchTmdbData($title, $year, $tmdbApiKey, $pdo); + $tmdbData = fetchTMDB($title, $year, $tmdbApiKey, $pdo); if ($tmdbData) { if (empty($director)) $director = $tmdbData['director']; if (!empty($tmdbData['poster'])) { $poster = $tmdbData['poster']; $stats['tmdb_hits']++; - } else { - $stats['tmdb_miss'][] = $title; } - } else { - $stats['tmdb_miss'][] = $title; } } @@ -453,16 +405,4 @@ switch ($action) { $pdo->commit(); echo json_encode(["success" => true, "imported" => $imported, "stats" => $stats]); break; -} - -function fetchPosterFromOMDb($title, $year) { - $apiKey = "VOTRE_CLE_OMDB"; // À ajouter dans votre table config - $url = "http://www.omdbapi.com/?t=" . urlencode($title) . "&y=" . $year . "&apikey=" . $apiKey; - $response = @file_get_contents($url); - $data = json_decode($response, true); - - if (isset($data['Poster']) && $data['Poster'] !== 'N/A') { - return $data['Poster']; - } - return null; } \ No newline at end of file