Add PHP Media API scaffold and Docker configs

Initial project scaffold for a PHP Media API including routing, controllers, models and services under api/ (Router, Media/Cast/Image/Settings controllers, models, database/bootstrap files and automatic docs service). Adds Docker support (Dockerfile, docker-compose.yml, DOCKER_README.md, php-custom.ini), .htaccess for pretty URLs, API documentation and example payloads (API_EXAMPLES.md, api/README.md, api_examples/*.json), image handling service and logging, plus a comprehensive .gitignore. This commit provides a runnable development environment and example requests to get the API up and tested quickly.
This commit is contained in:
Lars Behrends
2026-04-12 00:46:30 +02:00
commit 66f69bc90d
54 changed files with 6035 additions and 0 deletions

85
api/models/Adult.php Normal file
View File

@@ -0,0 +1,85 @@
<?php
require_once __DIR__ . '/MediaType.php';
require_once __DIR__ . '/../services/ImageHandler.php';
class Adult extends MediaType {
private $imageHandler;
private $isUpdate = false;
private $mediaId = null;
public function __construct($pdo) {
parent::__construct($pdo);
$this->imageHandler = new ImageHandler();
}
protected function getType() {
return 'Adult';
}
protected function getTypeSpecificFields() {
return [];
}
protected function validateTypeSpecificFields($data) {
// Adult spezifische Validierung
// Eventuell Altersverifikation etc.
}
protected function processPosterField($data) {
error_log("Adult::processPosterField - Checking for poster field, isUpdate: " . ($this->isUpdate ? 'yes' : 'no'));
if ($this->isUpdate && $this->mediaId && isset($data['poster']) && !empty($data['poster'])) {
$currentMedia = $this->findById($this->mediaId);
if ($currentMedia && !empty($currentMedia['poster'])) {
$oldPoster = $currentMedia['poster'];
if (strpos($oldPoster, '/images/') === 0) {
error_log("Adult::processPosterField - Deleting old poster: " . $oldPoster);
$this->imageHandler->deleteImage($oldPoster);
}
}
}
if (isset($data['poster']) && !empty($data['poster'])) {
error_log("Adult::processPosterField - Poster found, length: " . strlen($data['poster']));
if (strpos($data['poster'], '/images/') === 0 || filter_var($data['poster'], FILTER_VALIDATE_URL)) {
error_log("Adult::processPosterField - Poster is already a path or URL, skipping processing");
return $data;
}
$posterPath = $this->imageHandler->saveBase64Image($data['poster'], 'adult/poster');
error_log("Adult::processPosterField - ImageHandler returned: " . ($posterPath ?: 'null'));
if ($posterPath) {
$data['poster'] = $posterPath;
error_log("Adult::processPosterField - Poster path set to: " . $posterPath);
} else {
error_log("Adult::processPosterField - Failed to process poster, keeping original data");
}
} else {
error_log("Adult::processPosterField - No poster field found or empty");
}
return $data;
}
public function createWithRelations($data) {
$data['type'] = 'Adult';
$this->validateTypeSpecificFields($data);
$data = $this->processPosterField($data);
return parent::createWithRelations($data);
}
public function updateWithRelations($id, $data) {
$this->isUpdate = true;
$this->mediaId = $id;
$this->validateTypeSpecificFields($data);
$data = $this->processPosterField($data);
parent::updateWithRelations($id, $data);
}
public function search($filters = [], $page = 1, $limit = 20) {
// Nur Adult Content suchen
$filters['type'] = 'Adult';
return parent::search($filters, $page, $limit);
}
}

295
api/models/AdultCast.php Normal file
View File

@@ -0,0 +1,295 @@
<?php
require_once __DIR__ . '/Cast.php';
require_once __DIR__ . '/../services/ApiLogger.php';
class AdultCast extends Cast {
public function getWithAdultSpecifics($id) {
$cast = $this->getWithFilmography($id);
if (!$cast) {
return null;
}
$cast['adult_specifics'] = $this->getAdultSpecifics($id);
return $cast;
}
public function getAdultSpecifics($castId) {
$stmt = $this->pdo->prepare("SELECT * FROM adult_cast_specifics WHERE cast_id = ?");
$stmt->execute([$castId]);
return $stmt->fetch();
}
public function createWithAdultSpecifics($data) {
ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics called with data: " . json_encode($data));
$name = $data['name'] ?? null;
if (!$name) {
throw new Exception('Name is required');
}
// cleanname generieren
$cleanname = generateCleanName($name);
// Process photo field (base64 to file path)
$data = $this->processPhotoField($data);
// Zuerst Basis-Cast erstellen
$castData = [
'name' => $name,
'cleanname' => $cleanname,
'photo' => $data['photo'] ?? null,
'bio' => $data['bio'] ?? null,
'birthDate' => $data['birthDate'] ?? null,
'birthPlace' => $data['birthPlace'] ?? null
];
$castId = $this->create($castData);
ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: Base cast created with id: $castId");
// Occupations speichern
if (isset($data['occupations']) && is_array($data['occupations'])) {
ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: Saving occupations: " . json_encode($data['occupations']));
$this->saveRelatedItems('occupations', $castId, $data['occupations'], 'cast_id');
}
// Adult-spezifische Daten speichern
if (isset($data['adult_specifics']) && is_array($data['adult_specifics'])) {
ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: Saving adult_specifics");
$this->saveAdultSpecifics($castId, $data['adult_specifics']);
} else {
ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: No adult_specifics found in data");
}
return $castId;
}
public function updateWithAdultSpecifics($id, $data) {
ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics called with id: $id, data: " . json_encode($data));
// Set update flag for image replacement
$this->isUpdate = true;
$this->castId = $id;
// Process photo field (base64 to file path)
$data = $this->processPhotoField($data);
// Basis-Cast aktualisieren
$castData = [];
foreach (['name', 'photo', 'bio', 'birthDate', 'birthPlace'] as $field) {
if (array_key_exists($field, $data)) {
$castData[$field] = $data[$field];
}
}
if (!empty($castData)) {
ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: Updating base cast data: " . json_encode($castData));
$this->update($id, $castData);
}
// Occupations aktualisieren
if (isset($data['occupations']) && is_array($data['occupations'])) {
ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: Updating occupations: " . json_encode($data['occupations']));
$this->pdo->prepare("DELETE FROM occupations WHERE cast_id = ?")->execute([$id]);
$this->saveRelatedItems('occupations', $id, $data['occupations'], 'cast_id');
}
// Adult-spezifische Daten aktualisieren
if (isset($data['adult_specifics']) && is_array($data['adult_specifics'])) {
ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: Saving adult_specifics");
ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: adult_specifics data: " . json_encode($data['adult_specifics']));
$this->saveAdultSpecifics($id, $data['adult_specifics']);
} else {
ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: No adult_specifics found in data");
}
return true;
}
protected function saveAdultSpecifics($castId, $specifics) {
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics called for cast_id: $castId");
ApiLogger::getInstance()->logDebug("Specifics data: " . json_encode($specifics));
// Prüfen ob bereits Eintrag existiert
$stmt = $this->pdo->prepare("SELECT * FROM adult_cast_specifics WHERE cast_id = ?");
$stmt->execute([$castId]);
$existing = $stmt->fetch();
ApiLogger::getInstance()->logDebug("Existing entry: " . ($existing ? 'yes' : 'no'));
$fields = ['bust_size', 'cup_size', 'waist_size', 'hip_size', 'height', 'weight',
'hair_color', 'eye_color', 'ethnicity', 'tattoos', 'piercings', 'measurements', 'shoe_size'];
if ($existing) {
// Update
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: Existing entry found, doing UPDATE");
$updateFields = [];
$params = [];
foreach ($fields as $field) {
if (array_key_exists($field, $specifics)) {
$updateFields[] = "$field = ?";
$params[] = $specifics[$field];
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: Found field $field with value: " . json_encode($specifics[$field] ?? 'null'));
}
}
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: Update fields: " . implode(', ', $updateFields));
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: Total update fields count: " . count($updateFields));
if (!empty($updateFields)) {
$params[] = $castId;
$query = "UPDATE adult_cast_specifics SET " . implode(', ', $updateFields) . " WHERE cast_id = ?";
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: Executing query: $query");
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: With params: " . json_encode($params));
$stmt = $this->pdo->prepare($query);
try {
$stmt->execute($params);
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: UPDATE successful");
} catch (Exception $e) {
// Fehler loggen
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics Error: " . $e->getMessage());
ApiLogger::getInstance()->logDebug("Query: $query");
ApiLogger::getInstance()->logDebug("Params: " . json_encode($params));
}
} else {
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: No fields to update");
}
} else {
// Insert
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: No existing entry, doing INSERT");
$insertFields = [];
$values = [];
$params = [];
$insertFields[] = 'cast_id';
$values[] = '?';
$params[] = $castId;
foreach ($fields as $field) {
if (array_key_exists($field, $specifics)) {
$insertFields[] = $field;
$values[] = '?';
$params[] = $specifics[$field];
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: Found field $field with value: " . json_encode($specifics[$field] ?? 'null'));
}
}
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: Insert fields: " . implode(', ', $insertFields));
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: Total fields count: " . count($insertFields));
if (count($insertFields) > 1) {
$query = "INSERT INTO adult_cast_specifics (" . implode(', ', $insertFields) . ") VALUES (" . implode(', ', $values) . ")";
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: Executing query: $query");
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: With params: " . json_encode($params));
$stmt = $this->pdo->prepare($query);
try {
$stmt->execute($params);
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: INSERT successful");
} catch (Exception $e) {
// Fehler loggen
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics Error: " . $e->getMessage());
ApiLogger::getInstance()->logDebug("Query: " . $query);
ApiLogger::getInstance()->logDebug("Params: " . json_encode($params));
}
} else {
// Keine Felder zum Speichern
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics: Keine Felder zum Speichern für cast_id $castId");
}
}
}
public function deleteAdultSpecifics($castId) {
$stmt = $this->pdo->prepare("DELETE FROM adult_cast_specifics WHERE cast_id = ?");
$stmt->execute([$castId]);
return $stmt->rowCount() > 0;
}
public function searchAdultActors($filters = [], $page = 1, $limit = 2000000000) {
// Adult Actors mit Specifics suchen
$query = "
SELECT cs.*,
acs.bust_size, acs.cup_size, acs.waist_size, acs.hip_size,
acs.height, acs.weight, acs.hair_color, acs.eye_color, acs.ethnicity
FROM cast_staff cs
LEFT JOIN adult_cast_specifics acs ON cs.id = acs.cast_id
WHERE acs.cast_id IS NOT NULL
";
$params = [];
if (isset($filters['search'])) {
$query .= " AND cs.name LIKE ?";
$params[] = "%" . $filters['search'] . "%";
}
if (isset($filters['ethnicity'])) {
$query .= " AND acs.ethnicity = ?";
$params[] = $filters['ethnicity'];
}
if (isset($filters['hair_color'])) {
$query .= " AND acs.hair_color = ?";
$params[] = $filters['hair_color'];
}
$query .= " ORDER BY cs.createdAt DESC";
$offset = ($page - 1) * $limit;
$query .= " LIMIT " . (int)2000000000000 . " OFFSET " . (int)$offset;
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
$items = $stmt->fetchAll();
ApiLogger::getInstance()->logDebug("AdultCast searchAdultActors: Found " . count($items) . " cast members");
foreach ($items as $item) {
ApiLogger::getInstance()->logDebug("AdultCast searchAdultActors: Cast ID {$item['id']} - {$item['name']}");
}
// Occupations und Filmography für jeden laden
foreach ($items as &$item) {
$item['occupations'] = $this->getRelatedItems('occupations', $item['id'], 'cast_id');
// Add filmography information
$item['filmography'] = $this->getMediaForCast($item['id']);
// Extract unique media types
$mediaTypes = array_unique(array_column($item['filmography'], 'category'));
$item['media_types'] = array_values($mediaTypes);
ApiLogger::getInstance()->logDebug("AdultCast searchAdultActors: Cast ID {$item['id']} has " . count($item['filmography']) . " filmography items");
}
// Total count
$countQuery = "
SELECT COUNT(*)
FROM cast_staff cs
INNER JOIN adult_cast_specifics acs ON cs.id = acs.cast_id
WHERE 1=1
";
$countParams = [];
if (isset($filters['search'])) {
$countQuery .= " AND cs.name LIKE ?";
$countParams[] = "%" . $filters['search'] . "%";
}
if (isset($filters['ethnicity'])) {
$countQuery .= " AND acs.ethnicity = ?";
$countParams[] = $filters['ethnicity'];
}
if (isset($filters['hair_color'])) {
$countQuery .= " AND acs.hair_color = ?";
$countParams[] = $filters['hair_color'];
}
$countStmt = $this->pdo->prepare($countQuery);
$countStmt->execute($countParams);
$total = $countStmt->fetchColumn();
return [
'items' => $items,
'total' => $total,
'page' => $page,
'limit' => $limit
];
}
}

100
api/models/BaseModel.php Normal file
View File

@@ -0,0 +1,100 @@
<?php
abstract class BaseModel {
protected $pdo;
protected $table;
public function __construct($pdo) {
$this->pdo = $pdo;
}
protected function findById($id) {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch();
}
protected function findAll($conditions = [], $orderBy = 'createdAt DESC', $limit = null, $offset = null) {
$query = "SELECT * FROM {$this->table} WHERE 1=1";
$params = [];
foreach ($conditions as $field => $value) {
if (is_array($value)) {
// LIKE Operator
$query .= " AND $field LIKE ?";
$params[] = $value[0];
} else {
$query .= " AND $field = ?";
$params[] = $value;
}
}
$query .= " ORDER BY $orderBy";
if ($limit) {
$query .= " LIMIT " . (int)$limit;
}
if ($offset) {
$query .= " OFFSET " . (int)$offset;
}
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
return $stmt->fetchAll();
}
protected function count($conditions = []) {
$query = "SELECT COUNT(*) FROM {$this->table} WHERE 1=1";
$params = [];
foreach ($conditions as $field => $value) {
if (is_array($value)) {
$query .= " AND $field LIKE ?";
$params[] = $value[0];
} else {
$query .= " AND $field = ?";
$params[] = $value;
}
}
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
return $stmt->fetchColumn();
}
protected function create($data) {
$fields = array_keys($data);
$placeholders = array_fill(0, count($fields), '?');
$query = "INSERT INTO {$this->table} (" . implode(', ', $fields) . ") VALUES (" . implode(', ', $placeholders) . ")";
$stmt = $this->pdo->prepare($query);
$stmt->execute(array_values($data));
return $this->pdo->lastInsertId();
}
protected function update($id, $data) {
$fields = [];
$params = [];
foreach ($data as $field => $value) {
$fields[] = "$field = ?";
$params[] = $value;
}
$params[] = $id;
$query = "UPDATE {$this->table} SET " . implode(', ', $fields) . " WHERE id = ?";
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
return $stmt->rowCount() > 0;
}
protected function delete($id) {
$stmt = $this->pdo->prepare("DELETE FROM {$this->table} WHERE id = ?");
$stmt->execute([$id]);
return $stmt->rowCount() > 0;
}
}

190
api/models/Cast.php Normal file
View File

@@ -0,0 +1,190 @@
<?php
require_once __DIR__ . '/BaseModel.php';
require_once __DIR__ . '/../services/ImageHandler.php';
class Cast extends BaseModel {
protected $table = 'cast_staff';
private $imageHandler;
protected $isUpdate = false;
protected $castId = null;
public function __construct($pdo) {
parent::__construct($pdo);
$this->imageHandler = new ImageHandler();
}
public function getWithFilmography($id) {
$cast = $this->findById($id);
if (!$cast) {
return null;
}
$cast['occupations'] = $this->getRelatedItems('occupations', $id, 'cast_id');
$cast['filmography'] = $this->getMediaForCast($id);
return $cast;
}
public function getMediaForCast($castId) {
$stmt = $this->pdo->prepare("
SELECT m.id, m.title, m.year, m.poster, m.category, m.type, mc.role, mc.characterName
FROM media m
INNER JOIN media_cast mc ON m.id = mc.media_id
WHERE mc.cast_id = ?
ORDER BY m.year DESC
");
$stmt->execute([$castId]);
return $stmt->fetchAll();
}
public function search($filters = [], $page = 1, $limit = 20) {
$conditions = [];
if (isset($filters['search'])) {
$conditions['name'] = ["%" . $filters['search'] . "%"];
}
$offset = ($page - 1) * $limit;
$items = $this->findAll($conditions, 'createdAt DESC', $limit, $offset);
$total = $this->count($conditions);
// Add filmography to each cast member
foreach ($items as &$item) {
$item['filmography'] = $this->getMediaForCast($item['id']);
// Extract unique media types
$mediaTypes = array_unique(array_column($item['filmography'], 'category'));
$item['media_types'] = array_values($mediaTypes);
}
return [
'items' => $items,
'total' => $total,
'page' => $page,
'limit' => $limit
];
}
protected function processPhotoField($data) {
error_log("Cast::processPhotoField - Checking for photo field, isUpdate: " . ($this->isUpdate ? 'yes' : 'no'));
if ($this->isUpdate && $this->castId && isset($data['photo']) && !empty($data['photo'])) {
$currentCast = $this->findById($this->castId);
if ($currentCast && !empty($currentCast['photo'])) {
$oldPhoto = $currentCast['photo'];
if (strpos($oldPhoto, '/images/') === 0) {
error_log("Cast::processPhotoField - Deleting old photo: " . $oldPhoto);
$this->imageHandler->deleteImage($oldPhoto);
}
}
}
if (isset($data['photo']) && !empty($data['photo'])) {
error_log("Cast::processPhotoField - Photo found, length: " . strlen($data['photo']));
if (strpos($data['photo'], '/images/') === 0 || filter_var($data['photo'], FILTER_VALIDATE_URL)) {
error_log("Cast::processPhotoField - Photo is already a path or URL, skipping processing");
return $data;
}
$photoPath = $this->imageHandler->saveBase64Image($data['photo'], 'cast/photo');
error_log("Cast::processPhotoField - ImageHandler returned: " . ($photoPath ?: 'null'));
if ($photoPath) {
$data['photo'] = $photoPath;
error_log("Cast::processPhotoField - Photo path set to: " . $photoPath);
} else {
error_log("Cast::processPhotoField - Failed to process photo, keeping original data");
}
} else {
error_log("Cast::processPhotoField - No photo field found or empty");
}
return $data;
}
public function createWithOccupations($data) {
$name = $data['name'] ?? null;
if (!$name) {
throw new Exception('Name is required');
}
// cleanname generieren
$cleanname = generateCleanName($name);
$data = $this->processPhotoField($data);
$castData = [
'name' => $name,
'cleanname' => $cleanname,
'photo' => $data['photo'] ?? null,
'bio' => $data['bio'] ?? null,
'birthDate' => $data['birthDate'] ?? null,
'birthPlace' => $data['birthPlace'] ?? null
];
$castId = $this->create($castData);
if (isset($data['occupations']) && is_array($data['occupations'])) {
$this->saveRelatedItems('occupations', $castId, $data['occupations'], 'cast_id');
}
return $castId;
}
public function updateWithOccupations($id, $data) {
$this->isUpdate = true;
$this->castId = $id;
$data = $this->processPhotoField($data);
$castData = [];
foreach (['name', 'photo', 'bio', 'birthDate', 'birthPlace'] as $field) {
if (array_key_exists($field, $data)) {
$castData[$field] = $data[$field];
}
}
// Wenn name geändert wurde, cleanname aktualisieren
if (isset($data['name'])) {
$castData['cleanname'] = generateCleanName($data['name']);
}
if (!empty($castData)) {
$this->update($id, $castData);
}
if (isset($data['occupations']) && is_array($data['occupations'])) {
$this->pdo->prepare("DELETE FROM occupations WHERE cast_id = ?")->execute([$id]);
$this->saveRelatedItems('occupations', $id, $data['occupations'], 'cast_id');
}
return true;
}
public function findByCleanName($cleanname) {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE cleanname = ?");
$stmt->execute([$cleanname]);
return $stmt->fetch();
}
protected function getRelatedItems($table, $id, $fkColumn = 'media_id') {
$stmt = $this->pdo->prepare("SELECT * FROM $table WHERE $fkColumn = ?");
$stmt->execute([$id]);
$items = $stmt->fetchAll();
$result = [];
foreach ($items as $item) {
$result[] = $fkColumn === 'cast_id' ? $item['occupation'] : $item['genre'];
}
return $result;
}
protected function saveRelatedItems($table, $id, $items, $fkColumn = 'media_id') {
$valueColumn = $fkColumn === 'cast_id' ? 'occupation' : 'genre';
$stmt = $this->pdo->prepare("INSERT INTO $table ($fkColumn, $valueColumn) VALUES (?, ?)");
foreach ($items as $item) {
$stmt->execute([$id, $item]);
}
}
}

23
api/models/Console.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
require_once __DIR__ . '/MediaType.php';
class Console extends MediaType {
protected function getType() {
return 'Console';
}
protected function getTypeSpecificFields() {
return [];
}
protected function validateTypeSpecificFields($data) {
// Console spezifische Validierung
}
public function search($filters = [], $page = 1, $limit = 20) {
// Nur Consoles suchen
$filters['type'] = 'Console';
return parent::search($filters, $page, $limit);
}
}

469
api/models/Game.php Normal file
View File

@@ -0,0 +1,469 @@
<?php
require_once __DIR__ . '/MediaType.php';
require_once __DIR__ . '/../services/ImageHandler.php';
class Game extends MediaType {
private $imageHandler;
private $isUpdate = false;
private $mediaId = null;
public function __construct($pdo) {
parent::__construct($pdo);
$this->imageHandler = new ImageHandler();
}
protected function getType() {
return 'Game';
}
protected function getTypeSpecificFields() {
return [];
}
protected function validateTypeSpecificFields($data) {
// Game spezifische Validierung
if (isset($data['hasIcon'])) {
$data['hasIcon'] = is_numeric($data['hasIcon']) ? (int)$data['hasIcon'] : 0;
}
if (isset($data['hasCover'])) {
$data['hasCover'] = is_numeric($data['hasCover']) ? (int)$data['hasCover'] : 0;
}
if (isset($data['hasBackground'])) {
$data['hasBackground'] = is_numeric($data['hasBackground']) ? (int)$data['hasBackground'] : 0;
}
if (isset($data['playtime']) && !is_numeric($data['playtime'])) {
$data['playtime'] = is_numeric($data['playtime']) ? (int)$data['playtime'] : 0;
}
if (isset($data['isInstalled'])) {
$data['isInstalled'] = is_numeric($data['isInstalled']) ? (int)$data['isInstalled'] : 0;
}
if (isset($data['hidden'])) {
$data['hidden'] = is_numeric($data['hidden']) ? (int)$data['hidden'] : 0;
}
if (isset($data['favorite'])) {
$data['favorite'] = is_numeric($data['favorite']) ? (int)$data['favorite'] : 0;
}
return $data;
}
/**
* Process poster field - convert base64 to file path
*/
protected function processImageField($data, $type) {
if ($this->isUpdate && $this->mediaId && isset($data[$type]) && !empty($data[$type])) {
$currentMedia = $this->findById($this->mediaId);
if ($currentMedia && !empty($currentMedia[$type])) {
$oldPoster = $currentMedia[$type];
if (strpos($oldPoster, '/images/') === 0) {
$this->imageHandler->deleteImage($oldPoster);
}
}
}
if (isset($data[$type]) && !empty($data[$type])) {
if (strpos($data[$type], '/images/') === 0 || filter_var($data[$type], FILTER_VALIDATE_URL)) {
return $data;
}
$posterPath = $this->imageHandler->saveBase64Image($data[$type], 'games/'.$type.'/');
if ($posterPath) {
$data[$type] = $posterPath;
}
}
return $data;
}
public function createWithRelations($data) {
// Typ setzen
$data['type'] = 'Game';
// Typ-spezifische Validierung
$data = $this->validateTypeSpecificFields($data);
// Poster verarbeiten (Base64 zu Dateipfad)
$data = $this->processImageField($data, 'poster');
$data = $this->processImageField($data, 'banner');
$data = $this->processImageField($data, 'icon');
// Basis-Media erstellen
$mediaId = parent::createWithRelations($data);
// Media-Games Eintrag erstellen
$gameData = [
'media_id' => $mediaId,
'sortingName' => $data['sortingName'] ?? null,
'notes' => $data['notes'] ?? null,
'completionStatus' => $data['completionStatus'] ?? null,
'source' => $data['source'] ?? null,
'gameId' => $data['gameId'] ?? null,
'pluginId' => $data['pluginId'] ?? null,
'isInstalled' => $data['isInstalled'] ?? false,
'installDirectory' => $data['installDirectory'] ?? null,
'installSize' => $data['installSize'] ?? 0,
'hidden' => $data['hidden'] ?? false,
'favorite' => $data['favorite'] ?? false,
'playCount' => $data['playCount'] ?? 0,
'lastActivity' => $data['lastActivity'] ?? null,
'added' => null,
'modified' => null,
'communityScore' => $data['communityScore'] ?? 0,
'criticScore' => $data['criticScore'] ?? 0,
'userScore' => $data['userScore'] ?? 0,
'hasIcon' => $data['hasIcon'] ?? 0,
'hasCover' => $data['hasCover'] ?? 0,
'hasBackground' => $data['hasBackground'] ?? 0,
'version' => $data['version'] ?? null,
'playtime' => $data['playtime'] ?? 0
];
$mediaGameId = $this->createMediaGame($gameData);
// Relationen speichern
if (isset($data['achievements']) && is_array($data['achievements'])) {
$this->saveAchievements($mediaGameId, $data['achievements']);
}
if (isset($data['categories']) && is_array($data['categories'])) {
$this->saveGameRelation('game_categories', $mediaGameId, $data['categories'], 'category');
}
if (isset($data['features']) && is_array($data['features'])) {
$this->saveGameRelation('game_features', $mediaGameId, $data['features'], 'feature');
}
if (isset($data['platforms']) && is_array($data['platforms'])) {
$this->saveGameRelationWithConsole('game_platforms', $mediaGameId, $data['platforms'], 'platform');
}
if (isset($data['developers']) && is_array($data['developers'])) {
$this->saveGameRelation('game_developers', $mediaGameId, $data['developers'], 'developer');
}
if (isset($data['publishers']) && is_array($data['publishers'])) {
$this->saveGameRelation('game_publishers', $mediaGameId, $data['publishers'], 'publisher');
}
if (isset($data['series']) && is_array($data['series'])) {
$this->saveGameRelation('game_series', $mediaGameId, $data['series'], 'series');
}
if (isset($data['ageRatings']) && is_array($data['ageRatings'])) {
$this->saveGameRelation('game_age_ratings', $mediaGameId, $data['ageRatings'], 'age_rating');
}
if (isset($data['regions']) && is_array($data['regions'])) {
$this->saveGameRelation('game_regions', $mediaGameId, $data['regions'], 'region');
}
if (isset($data['links']) && is_array($data['links'])) {
$this->saveLinks($mediaGameId, $data['links']);
}
return $mediaId;
}
public function updateWithRelations($id, $data) {
// Set update flag and mediaId for image replacement
$this->isUpdate = true;
$this->mediaId = $id;
// Typ-spezifische Validierung
$this->validateTypeSpecificFields($data);
// Poster verarbeiten (Base64 zu Dateipfad)
$data = $this->processImageField($data, 'poster');
$data = $this->processImageField($data, 'banner');
$data = $this->processImageField($data, 'icon');
// Basis-Media aktualisieren
parent::updateWithRelations($id, $data);
// Media-Games Eintrag aktualisieren
$gameData = [];
$gameFields = ['sortingName', 'notes', 'completionStatus', 'source', 'gameId', 'pluginId',
'isInstalled', 'installDirectory', 'installSize', 'hidden', 'favorite',
'playCount', 'lastActivity', 'added', 'modified', 'communityScore',
'criticScore', 'userScore', 'hasIcon', 'hasCover', 'hasBackground',
'version', 'playtime'];
foreach ($gameFields as $field) {
if (array_key_exists($field, $data)) {
$gameData[$field] = $data[$field];
}
}
if (!empty($gameData)) {
$this->updateMediaGame($id, $gameData);
}
// Media-Games ID abrufen
$mediaGameId = $this->getMediaGameId($id);
if ($mediaGameId) {
// Relationen aktualisieren
if (isset($data['achievements']) && is_array($data['achievements'])) {
$this->pdo->prepare("DELETE FROM achievements WHERE media_game_id = ?")->execute([$mediaGameId]);
$this->saveAchievements($mediaGameId, $data['achievements']);
}
if (isset($data['categories']) && is_array($data['categories'])) {
$this->pdo->prepare("DELETE FROM game_categories WHERE media_game_id = ?")->execute([$mediaGameId]);
$this->saveGameRelation('game_categories', $mediaGameId, $data['categories'], 'category');
}
if (isset($data['features']) && is_array($data['features'])) {
$this->pdo->prepare("DELETE FROM game_features WHERE media_game_id = ?")->execute([$mediaGameId]);
$this->saveGameRelation('game_features', $mediaGameId, $data['features'], 'feature');
}
if (isset($data['platforms']) && is_array($data['platforms'])) {
$this->pdo->prepare("DELETE FROM game_platforms WHERE media_game_id = ?")->execute([$mediaGameId]);
$this->saveGameRelationWithConsole('game_platforms', $mediaGameId, $data['platforms'], 'platform');
}
if (isset($data['developers']) && is_array($data['developers'])) {
$this->pdo->prepare("DELETE FROM game_developers WHERE media_game_id = ?")->execute([$mediaGameId]);
$this->saveGameRelation('game_developers', $mediaGameId, $data['developers'], 'developer');
}
if (isset($data['publishers']) && is_array($data['publishers'])) {
$this->pdo->prepare("DELETE FROM game_publishers WHERE media_game_id = ?")->execute([$mediaGameId]);
$this->saveGameRelation('game_publishers', $mediaGameId, $data['publishers'], 'publisher');
}
if (isset($data['series']) && is_array($data['series'])) {
$this->pdo->prepare("DELETE FROM game_series WHERE media_game_id = ?")->execute([$mediaGameId]);
$this->saveGameRelation('game_series', $mediaGameId, $data['series'], 'series');
}
if (isset($data['ageRatings']) && is_array($data['ageRatings'])) {
$this->pdo->prepare("DELETE FROM game_age_ratings WHERE media_game_id = ?")->execute([$mediaGameId]);
$this->saveGameRelation('game_age_ratings', $mediaGameId, $data['ageRatings'], 'age_rating');
}
if (isset($data['regions']) && is_array($data['regions'])) {
$this->pdo->prepare("DELETE FROM game_regions WHERE media_game_id = ?")->execute([$mediaGameId]);
$this->saveGameRelation('game_regions', $mediaGameId, $data['regions'], 'region');
}
if (isset($data['links']) && is_array($data['links'])) {
$this->pdo->prepare("DELETE FROM game_links WHERE media_game_id = ?")->execute([$mediaGameId]);
$this->saveLinks($mediaGameId, $data['links']);
}
}
return true;
}
public function getWithGameInfo($id) {
$media = parent::getWithRelations($id);
if (!$media) {
return null;
}
// Media-Games Daten abrufen
$mediaGameId = $this->getMediaGameId($id);
if ($mediaGameId) {
$gameInfo = $this->getMediaGameData($mediaGameId);
$media = array_merge($media, $gameInfo);
// Relationen abrufen
$media['achievements'] = $this->getAchievements($mediaGameId);
$media['categories'] = $this->getGameRelation('game_categories', $mediaGameId, 'category');
$media['features'] = $this->getGameRelation('game_features', $mediaGameId, 'feature');
$media['platforms'] = $this->getGameRelation('game_platforms', $mediaGameId, 'platform');
$media['developers'] = $this->getGameRelation('game_developers', $mediaGameId, 'developer');
$media['publishers'] = $this->getGameRelation('game_publishers', $mediaGameId, 'publisher');
$media['series'] = $this->getGameRelation('game_series', $mediaGameId, 'series');
$media['ageRatings'] = $this->getGameRelation('game_age_ratings', $mediaGameId, 'age_rating');
$media['regions'] = $this->getGameRelation('game_regions', $mediaGameId, 'region');
$media['links'] = $this->getLinks($mediaGameId);
}
return $media;
}
public function getGameInfoForList($mediaId) {
// Media-Games Daten abrufen (ohne vollständige Relationen für Performance)
$mediaGameId = $this->getMediaGameId($mediaId);
if (!$mediaGameId) {
return null;
}
$gameInfo = $this->getMediaGameData($mediaGameId);
// Nur wichtige Relationen für Listenansicht laden
$gameInfo['categories'] = $this->getGameRelation('game_categories', $mediaGameId, 'category');
$gameInfo['platforms'] = $this->getGameRelation('game_platforms', $mediaGameId, 'platform');
$gameInfo['developers'] = $this->getGameRelation('game_developers', $mediaGameId, 'developer');
return $gameInfo;
}
public static function interpolateQuery($query, $params) {
$keys = array();
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:'.$key.'/';
} else {
$keys[] = '/[?]/';
}
}
$query = preg_replace($keys, $params, $query, 1, $count);
#trigger_error('replaced '.$count.' keys');
return $query;
}
protected function createMediaGame($data) {
$stmt = $this->pdo->prepare("
INSERT INTO media_games (media_id, sortingName, notes, completionStatus, source, gameId, pluginId,
isInstalled, installDirectory, installSize, hidden, favorite, playCount,
lastActivity, added, modified, communityScore, criticScore, userScore,
hasIcon, hasCover, hasBackground, version, playtime)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$data['media_id'],
$data['sortingName'],
$data['notes'],
$data['completionStatus'],
$data['source'],
$data['gameId'],
$data['pluginId'],
$data['isInstalled'],
$data['installDirectory'],
$data['installSize'],
$data['hidden'],
$data['favorite'],
$data['playCount'],
$data['lastActivity'],
$data['added'],
$data['modified'],
$data['communityScore'],
$data['criticScore'],
$data['userScore'],
$data['hasIcon'],
$data['hasCover'],
$data['hasBackground'],
$data['version'],
$data['playtime']
]);
return $this->pdo->lastInsertId();
}
protected function updateMediaGame($mediaId, $data) {
$setClause = [];
$params = [];
foreach ($data as $key => $value) {
$setClause[] = "$key = ?";
$params[] = $value;
}
$params[] = $mediaId;
$stmt = $this->pdo->prepare("
UPDATE media_games SET " . implode(', ', $setClause) . " WHERE media_id = ?
");
$stmt->execute($params);
}
protected function getMediaGameId($mediaId) {
$stmt = $this->pdo->prepare("SELECT id FROM media_games WHERE media_id = ?");
$stmt->execute([$mediaId]);
$result = $stmt->fetch();
return $result ? $result['id'] : null;
}
protected function getMediaGameData($mediaGameId) {
$stmt = $this->pdo->prepare("SELECT * FROM media_games WHERE id = ?");
$stmt->execute([$mediaGameId]);
$data = $stmt->fetch();
if ($data) {
unset($data['id'], $data['media_id']);
}
return $data ?: [];
}
protected function saveAchievements($mediaGameId, $achievements) {
$stmt = $this->pdo->prepare("
INSERT INTO achievements (media_game_id, name, description, icon, unlocked, unlocked_date)
VALUES (?, ?, ?, ?, ?, ?)
");
foreach ($achievements as $achievement) {
$unlockedDate = null;
if (isset($achievement['unlocked']) && $achievement['unlocked'] && isset($achievement['unlocked_date'])) {
$unlockedDate = $achievement['unlocked_date'];
}
$stmt->execute([
$mediaGameId,
$achievement['name'] ?? null,
$achievement['description'] ?? null,
$achievement['icon'] ?? null,
$achievement['unlocked'] ?? false,
$unlockedDate
]);
}
}
protected function getAchievements($mediaGameId) {
$stmt = $this->pdo->prepare("SELECT * FROM achievements WHERE media_game_id = ?");
$stmt->execute([$mediaGameId]);
return $stmt->fetchAll();
}
protected function saveGameRelation($table, $mediaGameId, $items, $field) {
$stmt = $this->pdo->prepare("INSERT INTO $table (media_game_id, $field) VALUES (?, ?)");
foreach ($items as $item) {
$stmt->execute([$mediaGameId, $item]);
}
}
protected function consoleExists($name) {
$stmt = $this->pdo->prepare("SELECT id FROM media WHERE type = 'Console' AND title = ?");
$stmt->execute([$name]);
return $stmt->fetch() !== false;
}
protected function createConsole($name) {
$stmt = $this->pdo->prepare("
INSERT INTO media (title, cleanname, type, createdAt, updatedAt)
VALUES (?, ?, 'Console', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
");
$stmt->execute([$name, strtolower(str_replace(' ', '-', $name))]);
return $this->pdo->lastInsertId();
}
protected function saveGameRelationWithConsole($table, $mediaGameId, $items, $field) {
$stmt = $this->pdo->prepare("INSERT INTO $table (media_game_id, $field) VALUES (?, ?)");
foreach ($items as $item) {
// Check if console exists, create if not
if ($field === 'platform' && !$this->consoleExists($item)) {
$this->createConsole($item);
}
$stmt->execute([$mediaGameId, $item]);
}
}
protected function getGameRelation($table, $mediaGameId, $field) {
$stmt = $this->pdo->prepare("SELECT $field FROM $table WHERE media_game_id = ?");
$stmt->execute([$mediaGameId]);
$items = $stmt->fetchAll();
return array_map(function($item) use ($field) {
return $item[$field];
}, $items);
}
protected function saveLinks($mediaGameId, $links) {
$stmt = $this->pdo->prepare("INSERT INTO game_links (media_game_id, name, url) VALUES (?, ?, ?)");
foreach ($links as $link) {
$stmt->execute([
$mediaGameId,
$link['name'] ?? null,
$link['url'] ?? null
]);
}
}
protected function getLinks($mediaGameId) {
$stmt = $this->pdo->prepare("SELECT name, url FROM game_links WHERE media_game_id = ?");
$stmt->execute([$mediaGameId]);
return $stmt->fetchAll();
}
public function search($filters = [], $page = 1, $limit = 20) {
// Nur Games suchen
$filters['type'] = 'Game';
return parent::search($filters, $page, $limit);
}
}

291
api/models/Media.php Normal file
View File

@@ -0,0 +1,291 @@
<?php
require_once __DIR__ . '/BaseModel.php';
class Media extends BaseModel {
protected $table = 'media';
public function getBase($id) {
return $this->findById($id);
}
public function getWithRelations($id) {
$media = $this->findById($id);
if (!$media) {
return null;
}
$media['genres'] = $this->getRelatedItems('genres', $id);
$media['tags'] = $this->getRelatedItems('tags', $id);
$media['studios'] = $this->getRelatedItems('studios', $id);
$media['staff'] = $this->getCastForMedia($id);
return $media;
}
public function search($filters = [], $page = 1, $limit = 20) {
$conditions = [];
if (isset($filters['category'])) {
$conditions['category'] = $filters['category'];
}
if (isset($filters['type'])) {
$conditions['type'] = $filters['type'];
}
if (isset($filters['search'])) {
$searchTerm = "%" . $filters['search'] . "%";
$conditions['title'] = [$searchTerm];
// OR Bedingung für description wird separat behandelt
}
$offset = ($page - 1) * $limit;
if (isset($filters['search'])) {
// Komplexe Suche mit OR
$query = "SELECT * FROM {$this->table} WHERE 1=1";
$params = [];
if (isset($filters['category'])) {
$query .= " AND category = ?";
$params[] = $filters['category'];
}
if (isset($filters['type'])) {
$query .= " AND type = ?";
$params[] = $filters['type'];
}
$query .= " AND (title LIKE ? OR description LIKE ?)";
$searchTerm = "%" . $filters['search'] . "%";
$params[] = $searchTerm;
$params[] = $searchTerm;
$query .= " ORDER BY createdAt DESC LIMIT " . (int)$limit . " OFFSET " . (int)$offset;
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
$items = $stmt->fetchAll();
// Cast-Mitglieder für jedes Medium laden
foreach ($items as &$item) {
$item['staff'] = $this->getCastForMedia($item['id']);
}
// Count Query
$countQuery = "SELECT COUNT(*) FROM {$this->table} WHERE 1=1";
$countParams = [];
if (isset($filters['category'])) {
$countQuery .= " AND category = ?";
$countParams[] = $filters['category'];
}
if (isset($filters['type'])) {
$countQuery .= " AND type = ?";
$countParams[] = $filters['type'];
}
$countQuery .= " AND (title LIKE ? OR description LIKE ?)";
$countParams[] = $searchTerm;
$countParams[] = $searchTerm;
$countStmt = $this->pdo->prepare($countQuery);
$countStmt->execute($countParams);
$total = $countStmt->fetchColumn();
} else {
$items = $this->findAll($conditions, 'createdAt DESC', $limit, $offset);
$total = $this->count($conditions);
// Cast-Mitglieder für jedes Medium laden
foreach ($items as &$item) {
$item['staff'] = $this->getCastForMedia($item['id']);
}
}
return [
'items' => $items,
'total' => $total,
'page' => $page,
'limit' => $limit,
'totalPages' => ceil($total / $limit)
];
}
public function createWithRelations($data) {
$title = $data['title'] ?? null;
if (!$title) {
throw new Exception('Title is required');
}
// cleanname generieren
$cleanname = generateCleanName($title);
// Basis-Media-Daten extrahieren
$mediaData = [
'title' => $title,
'cleanname' => $cleanname,
'year' => $data['year'] ?? null,
'poster' => $data['poster'] ?? null,
'banner' => $data['banner'] ?? null,
'description' => $data['description'] ?? null,
'rating' => $data['rating'] ?? null,
'category' => $data['category'] ?? null,
'type' => $data['type'] ?? null,
'status' => $data['status'] ?? null,
'aspectRatio' => $data['aspectRatio'] ?? null,
'runtime' => $data['runtime'] ?? null,
'director' => $data['director'] ?? null,
'writer' => $data['writer'] ?? null,
'source' => $data['source'] ?? null,
'releaseDate' => $data['releaseDate'] ?? null
];
$mediaId = $this->create($mediaData);
// Relationen speichern
if (isset($data['genres']) && is_array($data['genres'])) {
$this->saveRelatedItems('genres', $mediaId, $data['genres']);
}
if (isset($data['tags']) && is_array($data['tags'])) {
$this->saveRelatedItems('tags', $mediaId, $data['tags']);
}
if (isset($data['studios']) && is_array($data['studios'])) {
$this->saveRelatedItems('studios', $mediaId, $data['studios']);
}
if (isset($data['staff']) && is_array($data['staff'])) {
$this->saveCastAssignments($mediaId, $data['staff']);
}
return $mediaId;
}
public function updateWithRelations($id, $data) {
$mediaData = [];
foreach (['title', 'year', 'poster', 'banner', 'description', 'rating', 'category', 'type', 'status', 'aspectRatio', 'runtime', 'director', 'writer', 'releaseDate', 'source'] as $field) {
if (array_key_exists($field, $data)) {
$mediaData[$field] = $data[$field];
}
}
// Wenn title geändert wurde, cleanname aktualisieren
if (isset($data['title'])) {
$mediaData['cleanname'] = generateCleanName($data['title']);
}
if (!empty($mediaData)) {
$this->update($id, $mediaData);
}
// Relationen aktualisieren
if (isset($data['genres']) && is_array($data['genres'])) {
$this->pdo->prepare("DELETE FROM genres WHERE media_id = ?")->execute([$id]);
$this->saveRelatedItems('genres', $id, $data['genres']);
}
if (isset($data['tags']) && is_array($data['tags'])) {
$this->pdo->prepare("DELETE FROM tags WHERE media_id = ?")->execute([$id]);
$this->saveRelatedItems('tags', $id, $data['tags']);
}
if (isset($data['studios']) && is_array($data['studios'])) {
$this->pdo->prepare("DELETE FROM studios WHERE media_id = ?")->execute([$id]);
$this->saveRelatedItems('studios', $id, $data['studios']);
}
if (isset($data['staff']) && is_array($data['staff'])) {
$this->pdo->prepare("DELETE FROM media_cast WHERE media_id = ?")->execute([$id]);
$this->saveCastAssignments($id, $data['staff']);
}
return true;
}
public function findByCleanName($cleanname) {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE cleanname = ?");
$stmt->execute([$cleanname]);
return $stmt->fetch();
}
protected function saveRelatedItems($table, $id, $items, $fkColumn = 'media_id') {
$valueColumn = $table === 'genres' ? 'genre' : ($table === 'tags' ? 'tag' : ($table === 'occupations' ? 'occupation' : 'studio'));
$stmt = $this->pdo->prepare("INSERT INTO $table ($fkColumn, $valueColumn) VALUES (?, ?)");
foreach ($items as $item) {
$stmt->execute([$id, $item]);
}
}
protected function getCastForMedia($mediaId) {
$stmt = $this->pdo->prepare("
SELECT cs.*, mc.role, mc.characterName, mc.characterImage
FROM cast_staff cs
INNER JOIN media_cast mc ON cs.id = mc.cast_id
WHERE mc.media_id = ?
");
$stmt->execute([$mediaId]);
$cast = $stmt->fetchAll();
foreach ($cast as &$member) {
$member['occupations'] = $this->getRelatedItems('occupations', $member['id'], 'cast_id');
}
return $cast;
}
protected function getRelatedItems($table, $id, $fkColumn = 'media_id') {
$stmt = $this->pdo->prepare("SELECT * FROM $table WHERE $fkColumn = ?");
$stmt->execute([$id]);
$items = $stmt->fetchAll();
$result = [];
foreach ($items as $item) {
if ($fkColumn === 'cast_id') {
$result[] = $item['occupation'];
} else {
$result[] = $table === 'genres' ? $item['genre'] : ($table === 'tags' ? $item['tag'] : $item['studio']);
}
}
return $result;
}
protected function saveCastAssignments($mediaId, $castData) {
foreach ($castData as $member) {
$castId = null;
if (isset($member['id']) && $member['id']) {
$castId = $member['id'];
} elseif (isset($member['name'])) {
$stmt = $this->pdo->prepare("SELECT id FROM cast_staff WHERE name = ? LIMIT 1");
$stmt->execute([$member['name']]);
$existing = $stmt->fetch();
if ($existing) {
$castId = $existing['id'];
} else {
$cleanname = generateCleanName($member['name']);
$stmt = $this->pdo->prepare("
INSERT INTO cast_staff (name, cleanname, photo, bio, birthDate, birthPlace)
VALUES (?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$member['name'] ?? null,
$cleanname,
$member['photo'] ?? null,
$member['bio'] ?? null,
$member['birthDate'] ?? null,
$member['birthPlace'] ?? null
]);
$castId = $this->pdo->lastInsertId();
if (isset($member['occupations']) && is_array($member['occupations'])) {
$this->saveRelatedItems('occupations', $castId, $member['occupations'], 'cast_id');
}
}
}
if ($castId) {
$stmt = $this->pdo->prepare("
INSERT INTO media_cast (media_id, cast_id, role, characterName, characterImage)
VALUES (?, ?, ?, ?, ?)
");
$stmt->execute([
$mediaId,
$castId,
$member['role'] ?? null,
$member['characterName'] ?? null,
$member['characterImage'] ?? null
]);
}
}
}
}

39
api/models/MediaType.php Normal file
View File

@@ -0,0 +1,39 @@
<?php
require_once __DIR__ . '/Media.php';
abstract class MediaType extends Media {
protected $type;
public function __construct($pdo) {
parent::__construct($pdo);
$this->type = $this->getType();
}
abstract protected function getType();
abstract protected function validateTypeSpecificFields($data);
abstract protected function getTypeSpecificFields();
public function createWithRelations($data) {
// Typ setzen
$data['type'] = $this->type;
// Typ-spezifische Validierung
$this->validateTypeSpecificFields($data);
return parent::createWithRelations($data);
}
public function updateWithRelations($id, $data) {
// Typ-spezifische Validierung
$this->validateTypeSpecificFields($data);
return parent::updateWithRelations($id, $data);
}
protected function getRequiredFields() {
return [];
}
}

88
api/models/Movie.php Normal file
View File

@@ -0,0 +1,88 @@
<?php
require_once __DIR__ . '/MediaType.php';
require_once __DIR__ . '/../services/ImageHandler.php';
class Movie extends MediaType {
private $imageHandler;
private $isUpdate = false;
private $mediaId = null;
public function __construct($pdo) {
parent::__construct($pdo);
$this->imageHandler = new ImageHandler();
}
protected function getType() {
return 'Movie';
}
protected function getTypeSpecificFields() {
return ['runtime', 'director', 'writer'];
}
protected function validateTypeSpecificFields($data) {
// Movies sollten bestimmte Felder haben
if (isset($data['runtime']) && !is_numeric($data['runtime'])) {
throw new Exception('Runtime must be a number');
}
}
protected function processPosterField($data) {
error_log("Movie::processPosterField - Checking for poster field, isUpdate: " . ($this->isUpdate ? 'yes' : 'no'));
// If this is an update and poster is being changed, delete old image
if ($this->isUpdate && $this->mediaId && isset($data['poster']) && !empty($data['poster'])) {
$currentMedia = $this->findById($this->mediaId);
if ($currentMedia && !empty($currentMedia['poster'])) {
$oldPoster = $currentMedia['poster'];
if (strpos($oldPoster, '/images/') === 0) {
error_log("Movie::processPosterField - Deleting old poster: " . $oldPoster);
$this->imageHandler->deleteImage($oldPoster);
}
}
}
if (isset($data['poster']) && !empty($data['poster'])) {
error_log("Movie::processPosterField - Poster found, length: " . strlen($data['poster']));
if (strpos($data['poster'], '/images/') === 0 || filter_var($data['poster'], FILTER_VALIDATE_URL)) {
error_log("Movie::processPosterField - Poster is already a path or URL, skipping processing");
return $data;
}
$posterPath = $this->imageHandler->saveBase64Image($data['poster'], 'movies/poster');
error_log("Movie::processPosterField - ImageHandler returned: " . ($posterPath ?: 'null'));
if ($posterPath) {
$data['poster'] = $posterPath;
error_log("Movie::processPosterField - Poster path set to: " . $posterPath);
} else {
error_log("Movie::processPosterField - Failed to process poster, keeping original data");
}
} else {
error_log("Movie::processPosterField - No poster field found or empty");
}
return $data;
}
public function createWithRelations($data) {
$data['type'] = 'Movie';
$data = $this->validateTypeSpecificFields($data);
$data = $this->processPosterField($data);
return parent::createWithRelations($data);
}
public function updateWithRelations($id, $data) {
$this->isUpdate = true;
$this->mediaId = $id;
$this->validateTypeSpecificFields($data);
$data = $this->processPosterField($data);
parent::updateWithRelations($id, $data);
}
public function search($filters = [], $page = 1, $limit = 20) {
// Nur Movies suchen
$filters['type'] = 'Movie';
return parent::search($filters, $page, $limit);
}
}

112
api/models/Music.php Normal file
View File

@@ -0,0 +1,112 @@
<?php
require_once __DIR__ . '/MediaType.php';
class Music extends MediaType {
protected function getType() {
return 'Album';
}
protected function getTypeSpecificFields() {
return ['artist', 'album_type', 'release_date'];
}
protected function validateTypeSpecificFields($data) {
// Music spezifische Validierung
}
public function search($filters = [], $page = 1, $limit = 20) {
// Nur Music suchen
$filters['type'] = 'Album';
return parent::search($filters, $page, $limit);
}
public function getWithTracks($id) {
$media = $this->getWithRelations($id);
if (!$media) {
return null;
}
$media['tracks'] = $this->getTracks($id);
return $media;
}
public function getTracks($mediaId) {
$stmt = $this->pdo->prepare("
SELECT * FROM tracks WHERE media_id = ? ORDER BY track_number
");
$stmt->execute([$mediaId]);
return $stmt->fetchAll();
}
public function addTrack($mediaId, $trackData) {
$stmt = $this->pdo->prepare("
INSERT INTO tracks (media_id, track_number, title, artist)
VALUES (?, ?, ?, ?)
");
$stmt->execute([
$mediaId,
$trackData['track_number'] ?? null,
$trackData['title'] ?? null,
//$trackData['duration'] ?? null,
$trackData['artist'] ?? null
]);
return $this->pdo->lastInsertId();
}
public function updateTrack($trackId, $trackData) {
$fields = [];
$params = [];
foreach (['track_number', 'title', 'artist'] as $field) {
if (array_key_exists($field, $trackData)) {
$fields[] = "$field = ?";
$params[] = $trackData[$field];
}
}
if (!empty($fields)) {
$params[] = $trackId;
$stmt = $this->pdo->prepare("UPDATE tracks SET " . implode(', ', $fields) . " WHERE id = ?");
$stmt->execute($params);
return true;
}
return false;
}
public function deleteTrack($trackId) {
$stmt = $this->pdo->prepare("DELETE FROM tracks WHERE id = ?");
$stmt->execute([$trackId]);
return $stmt->rowCount() > 0;
}
public function createWithRelations($data) {
$mediaId = parent::createWithRelations($data);
// Tracks speichern
if (isset($data['tracks']) && is_array($data['tracks'])) {
foreach ($data['tracks'] as $track) {
$this->addTrack($mediaId, $track);
}
}
return $mediaId;
}
public function updateWithRelations($id, $data) {
parent::updateWithRelations($id, $data);
// Tracks aktualisieren
if (isset($data['tracks']) && is_array($data['tracks'])) {
// Alle existierenden Tracks löschen
$this->pdo->prepare("DELETE FROM tracks WHERE media_id = ?")->execute([$id]);
// Neue Tracks hinzufügen
foreach ($data['tracks'] as $track) {
$this->addTrack($id, $track);
}
}
return true;
}
}

140
api/models/Series.php Normal file
View File

@@ -0,0 +1,140 @@
<?php
require_once __DIR__ . '/MediaType.php';
class Series extends MediaType {
protected function getType() {
return 'TV';
}
protected function getTypeSpecificFields() {
return ['runtime', 'director', 'writer'];
}
protected function validateTypeSpecificFields($data) {
// Series Validierung
if (isset($data['runtime']) && !is_numeric($data['runtime'])) {
throw new Exception('Runtime must be a number');
}
}
public function search($filters = [], $page = 1, $limit = 20) {
// Nur Series suchen
$filters['type'] = 'TV';
return parent::search($filters, $page, $limit);
}
public function getWithEpisodes($id) {
$media = $this->getWithRelations($id);
if (!$media) {
return null;
}
$media['episodes'] = $this->getEpisodes($id);
$media['seasons'] = $this->getSeasons($id);
return $media;
}
public function getEpisodes($mediaId, $season = null) {
$query = "SELECT * FROM episodes WHERE media_id = ?";
$params = [$mediaId];
if ($season !== null) {
$query .= " AND season = ?";
$params[] = $season;
}
$query .= " ORDER BY season, episode_number";
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
return $stmt->fetchAll();
}
public function getSeasons($mediaId) {
$stmt = $this->pdo->prepare("
SELECT DISTINCT season, COUNT(*) as episode_count,
MIN(air_date) as first_air_date, MAX(air_date) as last_air_date
FROM episodes
WHERE media_id = ?
GROUP BY season
ORDER BY season
");
$stmt->execute([$mediaId]);
return $stmt->fetchAll();
}
public function addEpisode($mediaId, $episodeData) {
$stmt = $this->pdo->prepare("
INSERT INTO episodes (media_id, season, episode_number, title, description, air_date, duration, thumbnail)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$mediaId,
$episodeData['season'] ?? 1,
$episodeData['episode_number'] ?? null,
$episodeData['title'] ?? null,
$episodeData['description'] ?? null,
$episodeData['air_date'] ?? null,
$episodeData['duration'] ?? null,
$episodeData['thumbnail'] ?? null
]);
return $this->pdo->lastInsertId();
}
public function updateEpisode($episodeId, $episodeData) {
$fields = [];
$params = [];
foreach (['season', 'episode_number', 'title', 'description', 'air_date', 'duration', 'thumbnail'] as $field) {
if (array_key_exists($field, $episodeData)) {
$fields[] = "$field = ?";
$params[] = $episodeData[$field];
}
}
if (!empty($fields)) {
$params[] = $episodeId;
$stmt = $this->pdo->prepare("UPDATE episodes SET " . implode(', ', $fields) . " WHERE id = ?");
$stmt->execute($params);
return true;
}
return false;
}
public function deleteEpisode($episodeId) {
$stmt = $this->pdo->prepare("DELETE FROM episodes WHERE id = ?");
$stmt->execute([$episodeId]);
return $stmt->rowCount() > 0;
}
public function createWithRelations($data) {
$mediaId = parent::createWithRelations($data);
// Episoden speichern
if (isset($data['episodes']) && is_array($data['episodes'])) {
foreach ($data['episodes'] as $episode) {
$this->addEpisode($mediaId, $episode);
}
}
return $mediaId;
}
public function updateWithRelations($id, $data) {
parent::updateWithRelations($id, $data);
// Episoden aktualisieren
if (isset($data['episodes']) && is_array($data['episodes'])) {
// Alle existierenden Episoden löschen
$this->pdo->prepare("DELETE FROM episodes WHERE media_id = ?")->execute([$id]);
// Neue Episoden hinzufügen
foreach ($data['episodes'] as $episode) {
$this->addEpisode($id, $episode);
}
}
return true;
}
}

82
api/models/Settings.php Normal file
View File

@@ -0,0 +1,82 @@
<?php
require_once __DIR__ . '/BaseModel.php';
class Settings extends BaseModel {
protected $table = 'settings';
public function __construct($pdo) {
parent::__construct($pdo);
}
public function getSettings() {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = 1");
$stmt->execute();
$settings = $stmt->fetch();
if ($settings) {
// Decode enabled_categories from JSON
$settings['enabled_categories'] = $settings['enabled_categories'] ? json_decode($settings['enabled_categories'], true) : [];
// Convert boolean fields from tinyint to boolean
$settings['show_adult_content'] = (bool)$settings['show_adult_content'];
$settings['auto_play_trailers'] = (bool)$settings['auto_play_trailers'];
}
return $settings;
}
public function updateSettings($data) {
$updateData = [];
if (isset($data['enabled_categories']) && is_array($data['enabled_categories'])) {
$updateData['enabled_categories'] = json_encode($data['enabled_categories']);
}
if (isset($data['items_per_page'])) {
$updateData['items_per_page'] = (int)$data['items_per_page'];
}
if (isset($data['default_view'])) {
$updateData['default_view'] = $data['default_view'];
}
if (isset($data['show_adult_content'])) {
$updateData['show_adult_content'] = $data['show_adult_content'] ? 1 : 0;
}
if (isset($data['auto_play_trailers'])) {
$updateData['auto_play_trailers'] = $data['auto_play_trailers'] ? 1 : 0;
}
if (isset($data['language'])) {
$updateData['language'] = $data['language'];
}
if (isset($data['theme'])) {
$updateData['theme'] = $data['theme'];
}
// Check if settings row exists
$existing = $this->findById(1);
if ($existing) {
$this->update(1, $updateData);
return $this->getSettings();
} else {
// Create default settings if not exists
$defaultData = [
'enabled_categories' => json_encode(['Anime', 'Movies', 'TV Series', 'Music', 'Books', 'Consoles', 'Games', 'Adult']),
'items_per_page' => 20,
'default_view' => 'grid',
'show_adult_content' => 0,
'auto_play_trailers' => 0,
'language' => 'en',
'theme' => 'system',
'theme' => 'system'
];
$mergedData = array_merge($defaultData, $updateData);
$this->create($mergedData);
return $this->getSettings();
}
}
}