-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathctrl.php
More file actions
247 lines (205 loc) · 8.54 KB
/
ctrl.php
File metadata and controls
247 lines (205 loc) · 8.54 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<?php
/**
* API JSON pour l'application Share
* 3 actions : browse (lister fichiers), create (créer un lien), delete (supprimer un lien)
* Protégée par htpasswd via nginx (accès admin uniquement)
*/
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/functions.php';
header('Content-Type: application/json; charset=utf-8');
$action = $_GET['action'] ?? '';
// Validation CSRF pour les requêtes POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
session_start();
$input = json_decode(file_get_contents('php://input'), true);
$csrfToken = $input['csrf_token'] ?? '';
if (!hash_equals($_SESSION['csrf_token'] ?? '', $csrfToken)) {
http_response_code(403);
echo json_encode(['error' => 'Token CSRF invalide']);
exit;
}
}
try {
switch ($action) {
/**
* BROWSE — Liste les fichiers et dossiers d'un répertoire
* Paramètre : path (relatif à BASE_PATH)
* Retourne : tableau d'entrées {name, type, size}
*/
case 'browse':
$relPath = $_GET['path'] ?? '';
$fullPath = realpath(BASE_PATH . $relPath);
if (!is_path_within($fullPath, BASE_PATH)) {
http_response_code(403);
echo json_encode(['error' => 'Chemin interdit']);
exit;
}
if (!is_dir($fullPath)) {
http_response_code(400);
echo json_encode(['error' => 'Pas un répertoire']);
exit;
}
$entries = [];
$items = scandir($fullPath);
foreach ($items as $item) {
// On ignore les entrées spéciales et les fichiers cachés (commençant par un point)
if ($item[0] === '.') continue;
$itemPath = $fullPath . '/' . $item;
$isDir = is_dir($itemPath);
$entries[] = [
'name' => $item,
'type' => $isDir ? 'folder' : 'file',
'size' => $isDir ? null : filesize($itemPath),
];
}
// Tri : dossiers d'abord, puis par nom
usort($entries, function($a, $b) {
if ($a['type'] !== $b['type']) return $a['type'] === 'folder' ? -1 : 1;
return strnatcasecmp($a['name'], $b['name']);
});
echo json_encode(['path' => $relPath, 'entries' => $entries]);
break;
/**
* CREATE — Crée un nouveau lien de partage
* Paramètres POST : path, password (optionnel), expires (optionnel, en heures)
*/
case 'create':
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Méthode POST requise']);
exit;
}
$relPath = $input['path'] ?? '';
$password = $input['password'] ?? '';
$expiresHours = $input['expires'] ?? null;
$fullPath = realpath(BASE_PATH . $relPath);
if (!is_path_within($fullPath, BASE_PATH)) {
http_response_code(403);
echo json_encode(['error' => 'Chemin interdit']);
exit;
}
// Déterminer le type (fichier ou dossier)
$type = is_dir($fullPath) ? 'folder' : 'file';
$name = basename($fullPath);
// Hacher le mot de passe si fourni
$passwordHash = !empty($password) ? password_hash($password, PASSWORD_BCRYPT) : null;
// Calculer la date d'expiration si demandée
$expiresAt = null;
if ($expiresHours !== null && $expiresHours > 0) {
$expiresAt = date('c', time() + (int)$expiresHours * 3600);
}
$db = get_db();
// Générer un slug lisible à partir du nom + suffixe random
$token = generate_slug($name, $db);
$stmt = $db->prepare("
INSERT INTO links (token, path, type, name, password_hash, password_plain, expires_at)
VALUES (:token, :path, :type, :name, :password_hash, :password_plain, :expires_at)
");
$stmt->execute([
':token' => $token,
':path' => $fullPath,
':type' => $type,
':name' => $name,
':password_hash' => $passwordHash,
':password_plain' => !empty($password) ? $password : null,
':expires_at' => $expiresAt,
]);
echo json_encode([
'success' => true,
'token' => $token,
'url' => DL_BASE_URL . $token,
'name' => $name,
'type' => $type,
'expires_at' => $expiresAt,
]);
break;
/**
* DELETE — Supprime (révoque) un lien de partage
* Paramètre POST : id (identifiant du lien)
*/
case 'delete':
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Méthode POST requise']);
exit;
}
$id = (int)($input['id'] ?? 0);
if ($id <= 0) {
http_response_code(400);
echo json_encode(['error' => 'ID invalide']);
exit;
}
$db = get_db();
$stmt = $db->prepare("DELETE FROM links WHERE id = :id");
$stmt->execute([':id' => $id]);
echo json_encode(['success' => true]);
break;
/**
* SEND_EMAIL — Envoie un lien de partage par email
* Paramètres POST : id (identifiant du lien), email (adresse destinataire)
*/
case 'send_email':
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Méthode POST requise']);
exit;
}
$id = (int)($input['id'] ?? 0);
$email = trim($input['email'] ?? '');
if ($id <= 0) {
http_response_code(400);
echo json_encode(['error' => 'ID invalide']);
exit;
}
// Validation basique de l'email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo json_encode(['error' => 'Adresse email invalide']);
exit;
}
$db = get_db();
$stmt = $db->prepare("SELECT * FROM links WHERE id = :id");
$stmt->execute([':id' => $id]);
$link = $stmt->fetch();
if (!$link) {
http_response_code(404);
echo json_encode(['error' => 'Lien introuvable']);
exit;
}
// Construire l'URL complète
$host = preg_replace('/[^a-z0-9.\-:]/i', '', $_SERVER['HTTP_HOST'] ?? 'localhost');
$proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$fullUrl = $proto . '://' . $host . '/dl/' . $link['token'];
// Construire le corps du mail
$body = "Bonjour,\n\n";
$body .= "Un fichier a été partagé avec vous :\n\n";
$body .= "Nom : " . $link['name'] . "\n";
$body .= "Lien : " . $fullUrl . "\n";
if ($link['password_plain']) {
$body .= "Mot de passe : " . $link['password_plain'] . "\n";
}
if ($link['expires_at']) {
$body .= "Expire le : " . date('d/m/Y à H:i', strtotime($link['expires_at'])) . "\n";
}
$body .= "\nBonne réception !";
// Envoyer le mail via la fonction PHP mail()
$subject = str_replace(["\r", "\n"], '', "Partage : " . $link['name']);
$headers = "From: Share <noreply@" . $host . ">\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
$sent = mail($email, $subject, $body, $headers);
if ($sent) {
echo json_encode(['success' => true]);
} else {
http_response_code(500);
echo json_encode(['error' => 'Échec de l\'envoi du mail']);
}
break;
default:
http_response_code(400);
echo json_encode(['error' => 'Action inconnue']);
}
} catch (Exception $e) {
error_log('Share app error: ' . $e->getMessage());
http_response_code(500);
echo json_encode(['error' => 'Erreur serveur interne']);
}