-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.php
215 lines (191 loc) · 8.61 KB
/
upload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
<?php
ob_start(); // Activa el buffer de sortida per evitar problemes amb les capçaleres
function getMimeType($filePath) {
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
switch ($extension) {
case 'mp3':
return 'audio/mpeg';
case 'ogg':
return 'audio/ogg';
case 'txt':
return 'text/plain';
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'png':
return 'image/png';
case 'gif':
return 'image/gif';
default:
return 'application/octet-stream'; // tipus de fitxer per defecte
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Comprovar si s'ha enviat una sol·licitud per eliminar una cançó
if (isset($_POST['deleteSong'])) {
$songs = json_decode(file_get_contents('songs.json'), true) ?: [];
$songIdToDelete = intval($_POST['songId']);
foreach ($songs as $key => $song) {
if ($song['id'] === $songIdToDelete) {
// Eliminar el fitxer de música i la caràtula del servidor
unlink('uploads/' . $song['file']);
if ($song['cover'] && file_exists('uploads/' . $song['cover'])) {
unlink('uploads/' . $song['cover']);
}
// Eliminar la cançó de l'array
unset($songs[$key]);
break;
}
}
file_put_contents('songs.json', json_encode(array_values($songs), JSON_PRETTY_PRINT));
header('Location: music.php'); // Redirigir després de l'eliminació
exit();
}
$uploadDir = 'uploads/';
// Crear el directori si no existeix
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$songs = json_decode(file_get_contents('songs.json'), true) ?: [];
// Validació dels fitxers de música
if (isset($_FILES['song']) && $_FILES['song']['error'] == 0) {
$audioFileType = getMimeType($_FILES['song']['name']);
if (!in_array($audioFileType, ['audio/mpeg', 'audio/ogg'])) {
die('Format de cançó no vàlid. Només es permeten MP3 i OGG.');
}
} else {
die('Fitxer de música és obligatori.');
}
// Validació del fitxer de caràtula
if (isset($_FILES['cover']) && $_FILES['cover']['error'] == 0) {
$coverFileType = getMimeType($_FILES['cover']['name']);
if (!in_array($coverFileType, ['image/jpeg', 'image/png', 'image/gif'])) {
die('Format de caràtula no vàlid. Només es permeten JPG, PNG i GIF.');
}
}
// Validació del fitxer de joc
$gameFilePath = '';
if (isset($_FILES['gameFile']) && $_FILES['gameFile']['error'] == 0) {
$gameFileType = getMimeType($_FILES['gameFile']['name']);
if ($gameFileType !== 'text/plain') {
die('El fitxer de joc ha de ser un fitxer de text (.txt).');
}
$gameFilePath = $uploadDir . basename($_FILES['gameFile']['name']);
move_uploaded_file($_FILES['gameFile']['tmp_name'], $gameFilePath);
}
// Validació del textarea
$gameData = isset($_POST['gameData']) ? trim($_POST['gameData']) : '';
if (!empty($gameData) && empty($gameFilePath)) {
$lines = explode("\n", $gameData);
$numberOfElements = intval(array_shift($lines));
if ($numberOfElements <= 0) {
die('El número d\'elements ha de ser positiu.');
}
foreach ($lines as $line) {
$parts = explode('#', trim($line));
if (count($parts) < 3) {
die('Format de fitxer de joc no vàlid. Cada línia ha de contenir: tecla # instant inicial # instant final.');
}
// Validació dels valors
$key = trim($parts[0]);
$start = floatval(trim($parts[1]));
$end = floatval(trim($parts[2]));
if ($start < 0 || $end < 0 || $start >= $end) {
die('Els instants han de ser valors no negatius i l\'instant inicial ha de ser menor que l\'instant final.');
}
}
// Crear fitxer de joc
$gameFilePath = $uploadDir . uniqid('game_') . '.txt';
file_put_contents($gameFilePath, "$numberOfElements\n" . implode("\n", $lines));
}
// Pujar el fitxer de música
$uploadSongFile = $uploadDir . basename($_FILES['song']['name']);
move_uploaded_file($_FILES['song']['tmp_name'], $uploadSongFile);
// Crear un ID únic per a la nova cançó
$newId = count($songs) > 0 ? end($songs)['id'] + 1 : 1;
// Guardar les dades de la cançó
$newSong = [
'id' => $newId,
'title' => htmlspecialchars($_POST['songName']),
'artist' => htmlspecialchars($_POST['artist']),
'file' => basename($_FILES['song']['name']),
'url_game' => basename($gameFilePath),
'duration' => htmlspecialchars($_POST['duration']), // Utilitzem la duració obtinguda
'cover' => isset($_FILES['cover']) ? basename($_FILES['cover']['name']) : 'default_cover.png'
];
$songs[] = $newSong;
// Desar la caràtula
if (isset($_FILES['cover']) && $_FILES['cover']['error'] == 0) {
move_uploaded_file($_FILES['cover']['tmp_name'], $uploadDir . $newSong['cover']);
}
file_put_contents('songs.json', json_encode($songs, JSON_PRETTY_PRINT));
header('Location: music.php'); // Redirigir després de la pujada per evitar el reenviament
exit();
}
// Finalitzar el buffer de sortida
ob_end_flush();
?>
<!DOCTYPE html>
<html lang="ca">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gestor de Música</title>
<link rel="stylesheet" href="music.css">
<link href='https://fonts.googleapis.com/css?family=Press Start 2P' rel='stylesheet'>
</head>
<body>
<div class="container">
<div class="upload-form">
<h2>Afegeix una nova cançó</h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="text" name="songName" placeholder="Títol de la cançó" required>
<input type="text" name="artist" placeholder="Artista" required>
<input type="file" name="song" accept="audio/mpeg, audio/ogg" required onchange="calculateDuration(this)">
<input type="hidden" name="duration" id="durationInput"> <!-- Campo oculto para la duración -->
<div>
<label>Durada:</label>
<span id="durationDisplay">0:00</span> <!-- Elemento para mostrar la duración -->
</div>
<input type="file" name="cover" accept="image/jpeg, image/png, image/gif">
<input type="file" name="gameFile" accept=".txt">
<textarea name="gameData" placeholder="Datos del juego (opcional)"></textarea>
<button type="submit">Pujar</button>
</form>
</div>
<div class="playlist">
<h2>Playlist</h2>
<?php
if (!empty($songs)) {
foreach ($songs as $song) {
echo '<div class="song">';
echo '<h3>' . htmlspecialchars($song['title']) . '</h3>';
echo '<p>Artista: ' . htmlspecialchars($song['artist']) . '</p>';
echo '<audio controls><source src="uploads/' . htmlspecialchars($song['file']) . '" type="audio/mpeg"></audio>';
echo '<form action="upload.php" method="post">';
echo '<input type="hidden" name="songId" value="' . htmlspecialchars($song['id']) . '">';
echo '<button type="submit" name="deleteSong">Eliminar</button>';
echo '</form>';
echo '</div>';
}
} else {
echo '<p>No hi ha cançons a la playlist.</p>';
}
?>
</div>
</div>
<script>
function calculateDuration(input) {
const file = input.files[0];
const audio = new Audio(URL.createObjectURL(file));
audio.addEventListener('loadedmetadata', function() {
const duration = audio.duration; // Obtiene la duración en segundos
const minutes = Math.floor(duration / 60);
const seconds = Math.floor(duration % 60);
document.getElementById('durationInput').value = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`; // Formato mm:ss
document.getElementById('durationDisplay').textContent = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`; // Muestra la duración
});
}
</script>
</body>
</html>