-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
496 lines (495 loc) · 21.2 KB
/
index.php
File metadata and controls
496 lines (495 loc) · 21.2 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
<?php
/**
* index.php — Main controller (PHP 8.5.1 / IIS 10)
*/
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/lang.php';
require_once __DIR__ . '/includes/directory.php';
require_once __DIR__ . '/includes/download.php';
if ($config['debug'] ?? false) {
error_reporting(E_ALL);
ini_set('display_errors', 1);
}
$request = ($_SERVER['REQUEST_METHOD'] === 'POST') ? $_POST : $_GET;
$isRealAjax = (
isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'
);
if (isset($request['ajax']) && !$isRealAjax && $_SERVER['REQUEST_METHOD'] === 'GET') {
$cleanParams = $_GET;
unset($cleanParams['ajax'], $cleanParams['action'], $cleanParams['file']);
$queryString = http_build_query($cleanParams);
$location = strtok($_SERVER["REQUEST_URI"], '?') . ($queryString ? '?' . $queryString : '');
header("Location: " . $location);
exit;
}
// --- IMAGE THUMBNAIL (GET ?thumb=<rel_path>) ---
// Thumbnail is generated by GD in memory and sent directly to the browser.
// Nothing is written to disk — not to /tmp or anywhere else.
// Browser-side caching (Cache-Control: private, max-age=3600).
if (isset($_GET['thumb'])) {
$baseDir = rtrim(str_replace('\\', '/', $config['base_dir']), '/');
// Normalize path: forward slashes, remove ../ and ./ traversal
// realpath() is not used — unreliable with Cyrillic paths on Windows/IIS
$rel = str_replace('\\', '/', trim($_GET['thumb'], '/\\ '));
$parts = [];
foreach (explode('/', $rel) as $part) {
if ($part === '' || $part === '.') continue;
if ($part === '..') { array_pop($parts); continue; }
$parts[] = $part;
}
$rel = implode('/', $parts);
$full = $baseDir . '/' . $rel;
// Path traversal check via string comparison
$fullNorm = str_replace('\\', '/', $full);
$baseNorm = str_replace('\\', '/', $baseDir);
if (!str_starts_with($fullNorm, $baseNorm . '/')) {
http_response_code(403); exit;
}
$allowed = ['jpg' => 'jpeg', 'jpeg' => 'jpeg', 'png' => 'png',
'gif' => 'gif', 'webp' => 'webp', 'avif' => 'avif',
'bmp' => 'bmp', 'ico' => 'ico', 'svg' => 'svg'];
$ext = strtolower(pathinfo($full, PATHINFO_EXTENSION));
if (!is_file($full) || !isset($allowed[$ext])) {
http_response_code(404); exit;
}
$thumbSize = 220;
// GD not available — serve original as-is (browser will scale)
if (!function_exists('imagecreatetruecolor')) {
$mime = mime_content_type($full) ?: 'image/jpeg';
header('Content-Type: ' . $mime);
header('Cache-Control: private, max-age=3600');
readfile($full);
exit;
}
// ico and svg — GD cannot handle them, serve directly BEFORE getimagesize()
// (getimagesize() does not understand SVG → returns false → 415)
if ($allowed[$ext] === 'ico' || $allowed[$ext] === 'svg') {
$mime = ($allowed[$ext] === 'svg') ? 'image/svg+xml' : 'image/x-icon';
while (ob_get_level()) ob_end_clean();
header('Content-Type: ' . $mime);
header('Cache-Control: private, max-age=3600, immutable');
readfile($full);
exit;
}
// Check image dimensions BEFORE loading into memory
$imgInfo = @getimagesize($full);
if (!$imgInfo) {
http_response_code(415); exit;
}
[$origW, $origH] = [$imgInfo[0], $imgInfo[1]];
// Estimate required memory: source + destination + margin
// Parse memory_limit correctly: "128M", "1G", "-1"
$memNeeded = $origW * $origH * 4 * 2 + 8 * 1024 * 1024;
$memLimitStr = ini_get('memory_limit');
$memLimit = (function(string $v): int {
$v = trim($v);
if ($v === '-1') return PHP_INT_MAX;
$num = (int) $v;
$unit = strtolower(substr($v, -1));
return match($unit) {
'g' => $num * 1073741824,
'm' => $num * 1048576,
'k' => $num * 1024,
default => $num,
};
})($memLimitStr);
$memUsed = memory_get_usage(true);
if ($memLimit !== PHP_INT_MAX && ($memUsed + $memNeeded) > $memLimit) {
$newLimit = (int)ceil(($memUsed + $memNeeded) / 1048576) + 32;
@ini_set('memory_limit', $newLimit . 'M');
}
$src = match($allowed[$ext]) {
'jpeg' => @imagecreatefromjpeg($full),
'png' => @imagecreatefrompng($full),
'gif' => @imagecreatefromgif($full),
'webp' => function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($full) : false,
'avif' => function_exists('imagecreatefromavif') ? @imagecreatefromavif($full) : false,
'bmp' => function_exists('imagecreatefrombmp') ? @imagecreatefrombmp($full) : false,
default => false,
};
if (!$src) {
// GD failed to open — serve original
$mime = mime_content_type($full) ?: 'image/jpeg';
header('Content-Type: ' . $mime);
header('Cache-Control: private, max-age=3600');
readfile($full);
exit;
}
// Two-step scaling for large images (memory saving)
if ($origW > 2000 || $origH > 2000) {
$mid = imagescale($src, (int)($origW / 2), (int)($origH / 2), IMG_BICUBIC_FIXED);
if ($mid) {
imagedestroy($src);
$src = $mid;
$origW = imagesx($src);
$origH = imagesy($src);
}
}
$ratio = min($thumbSize / $origW, $thumbSize / $origH, 1.0);
$newW = max(1, (int)round($origW * $ratio));
$newH = max(1, (int)round($origH * $ratio));
$dst = imagecreatetruecolor($newW, $newH);
imagealphablending($dst, false);
imagesavealpha($dst, true);
// White background for JPEG (in case of PNG with transparency)
$white = imagecolorallocate($dst, 255, 255, 255);
imagefill($dst, 0, 0, $white);
imagealphablending($dst, true);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newW, $newH, $origW, $origH);
imagedestroy($src);
// Flush all active output buffers — IIS/FastCGI may have several.
while (ob_get_level()) ob_end_clean();
header('Content-Type: image/jpeg');
header('Cache-Control: private, max-age=3600, immutable');
imagejpeg($dst, null, 85);
imagedestroy($dst);
exit;
}
$dirParam = trim($request['dir'] ?? $request['currentRel'] ?? '', '/\\ ');
$searchQuery = isset($request['q']) ? trim($request['q']) : '';
$page = max(1, (int)($request['page'] ?? 1));
$perPageReq = $request['per_page'] ?? '20';
$perPage = ($perPageReq === 'all') ? 10000 : (int)$perPageReq;
$sortBy = in_array($request['sort'] ?? '', ['name', 'mtime', 'size']) ? $request['sort'] : 'mtime';
$sortOrder = in_array($request['order'] ?? '', ['asc', 'desc']) ? $request['order'] : 'desc';
// --- CONFIG FLAGS ---
$isSearchEnabled = (bool)($config['enable_search'] ?? true);
$isDownloadEnabled = (bool)($config['enable_download'] ?? true);
$isUploadEnabled = (bool)($config['enable_upload'] ?? false);
$isDeleteEnabled = (bool)($config['enable_delete'] ?? false);
$isSearch = false;
if ($searchQuery !== '') {
if ($isSearchEnabled) {
$isSearch = true;
} else {
$searchQuery = '';
ob_start();
showMessage("Search is temporarily disabled by administrator.", "warning", "Search unavailable");
$errorMsgHtml = ob_get_clean();
if (isset($request['ajax']) && $isRealAjax) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['success' => true, 'html' => $errorMsgHtml]);
exit;
}
$config['filter_error'] = "Search is disabled in settings.";
}
}
// Path resolution
$baseDir = realpath($config['base_dir']);
$currentFull = realpath($baseDir . DIRECTORY_SEPARATOR . $dirParam) ?: $baseDir;
if (!str_starts_with($currentFull, $baseDir)) {
$currentFull = $baseDir;
$dirParam = '';
}
$currentRel = ltrim(str_replace($baseDir, '', $currentFull), DIRECTORY_SEPARATOR);
// --- FILE RENAME (AJAX POST) ---
if (
$_SERVER['REQUEST_METHOD'] === 'POST' &&
($request['action'] ?? '') === 'rename_file' &&
$isRealAjax
) {
header('Content-Type: application/json; charset=utf-8');
if (!$isUploadEnabled) {
echo json_encode(['success' => false, 'message' => 'Renaming is disabled by administrator.']);
exit;
}
$fileRel = trim($_POST['file'] ?? '', '/\\ ');
$newName = trim($_POST['new_name'] ?? '');
$fullPath = realpath($baseDir . DIRECTORY_SEPARATOR . $fileRel);
if (!$fullPath || !str_starts_with($fullPath, $baseDir) || (!is_file($fullPath) && !is_dir($fullPath))) {
echo json_encode(['success' => false, 'message' => 'File or folder not found.']);
exit;
}
$isDir = is_dir($fullPath);
if ($newName === '' || preg_match('/[\/\\\\:*?"<>|]/', $newName) || str_starts_with($newName, '.')) {
echo json_encode(['success' => false, 'message' => $isDir ? 'Invalid folder name.' : 'Invalid file name.']);
exit;
}
$newPath = dirname($fullPath) . DIRECTORY_SEPARATOR . $newName;
if (file_exists($newPath)) {
echo json_encode(['success' => false, 'message' => ($isDir ? 'Folder' : 'File') . ' with this name already exists.']);
exit;
}
if (!is_writable(dirname($fullPath))) {
echo json_encode(['success' => false, 'message' => 'No permission to rename.']);
exit;
}
if (rename($fullPath, $newPath)) {
$label = $isDir ? 'Folder' : 'File';
echo json_encode(['success' => true, 'message' => $label . ' renamed to <b>' . htmlspecialchars($newName) . '</b>.']);
} else {
echo json_encode(['success' => false, 'message' => 'Failed to rename.']);
}
exit;
}
// --- FOLDER CREATION (AJAX POST) ---
if (
$_SERVER['REQUEST_METHOD'] === 'POST' &&
($request['action'] ?? '') === 'create_folder' &&
$isRealAjax
) {
header('Content-Type: application/json; charset=utf-8');
if (!$isUploadEnabled) {
echo json_encode(['success' => false, 'message' => 'Folder creation is disabled by administrator.']);
exit;
}
$folderName = trim($_POST['folder_name'] ?? '');
if ($folderName === '' || preg_match('/[\/\\\\:*?"<>|]/', $folderName) || str_starts_with($folderName, '.')) {
echo json_encode(['success' => false, 'message' => 'Invalid folder name.']);
exit;
}
$newDir = $currentFull . DIRECTORY_SEPARATOR . $folderName;
if (file_exists($newDir)) {
echo json_encode(['success' => false, 'message' => 'Folder with this name already exists.']);
exit;
}
if (!is_writable($currentFull)) {
echo json_encode(['success' => false, 'message' => 'No permission to create folder.']);
exit;
}
if (mkdir($newDir, 0755)) {
echo json_encode(['success' => true, 'message' => 'Folder <b>' . htmlspecialchars($folderName) . '</b> created.']);
} else {
echo json_encode(['success' => false, 'message' => 'Failed to create folder.']);
}
exit;
}
// --- FILE DELETION (AJAX POST) ---
if (
$_SERVER['REQUEST_METHOD'] === 'POST' &&
($request['action'] ?? '') === 'delete_file' &&
$isRealAjax
) {
header('Content-Type: application/json; charset=utf-8');
if (!$isDeleteEnabled) {
echo json_encode(['success' => false, 'message' => 'File deletion is disabled by administrator.']);
exit;
}
$fileRel = trim($_POST['file'] ?? '', '/\\ ');
$fullPath = realpath($baseDir . DIRECTORY_SEPARATOR . $fileRel);
if (!$fullPath || !str_starts_with($fullPath, $baseDir)) {
echo json_encode(['success' => false, 'message' => 'Invalid file path.']);
exit;
}
if (!is_file($fullPath)) {
echo json_encode(['success' => false, 'message' => 'File не найден.']);
exit;
}
if (!is_writable($fullPath)) {
echo json_encode(['success' => false, 'message' => 'No permission to delete file.']);
exit;
}
$fileName = basename($fullPath);
if (unlink($fullPath)) {
echo json_encode(['success' => true, 'message' => 'File <b>' . htmlspecialchars($fileName) . '</b> deleted.']);
} else {
echo json_encode(['success' => false, 'message' => 'Failed to delete file.']);
}
exit;
}
// --- FILE UPLOAD (AJAX POST) ---
if (
$_SERVER['REQUEST_METHOD'] === 'POST' &&
($request['action'] ?? '') === 'upload_file' &&
$isRealAjax
) {
header('Content-Type: application/json; charset=utf-8');
if (!$isUploadEnabled) {
echo json_encode(['success' => false, 'message' => 'File upload is disabled by administrator.']);
exit;
}
if (empty($_FILES['upload_file']) || $_FILES['upload_file']['error'] === UPLOAD_ERR_NO_FILE) {
echo json_encode(['success' => false, 'message' => 'File не выбран.']);
exit;
}
$file = $_FILES['upload_file'];
$error = $file['error'];
if ($error !== UPLOAD_ERR_OK) {
$uploadErrors = [
UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize in php.ini.',
UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE in the form.',
UPLOAD_ERR_PARTIAL => 'File was only partially uploaded.',
UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder.',
UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
UPLOAD_ERR_EXTENSION => 'Upload stopped by PHP extension.',
];
echo json_encode(['success' => false, 'message' => $uploadErrors[$error] ?? 'Unknown upload error.']);
exit;
}
// Check size limit from conf.ini
$maxSizeRaw = trim($config['max_upload_size'] ?? '0');
if ($maxSizeRaw !== '0' && $maxSizeRaw !== '') {
if (preg_match('/^(\d+(?:\.\d+)?)\s*(g|gb|m|mb|k|kb|b)?$/i', $maxSizeRaw, $m)) {
$num = (float)$m[1];
$suffix = strtolower($m[2] ?? 'b');
$maxBytes = match(true) {
str_starts_with($suffix, 'g') => (int)($num * 1073741824),
str_starts_with($suffix, 'm') => (int)($num * 1048576),
str_starts_with($suffix, 'k') => (int)($num * 1024),
default => (int)$num,
};
if ($file['size'] > $maxBytes) {
echo json_encode(['success' => false, 'message' =>
'File слишком большой. Максимально допустимый размер: <b>' . htmlspecialchars($maxSizeRaw) . '</b>.'
]);
exit;
}
}
}
$uploadDir = $currentFull;
if (!is_dir($uploadDir) || !is_writable($uploadDir)) {
echo json_encode(['success' => false, 'message' => 'Folder недоступна для записи.']);
exit;
}
$originalName = basename($file['name']);
$safeName = preg_replace('/[^\w\.\-]/u', '_', $originalName);
$safeName = ltrim($safeName, '.');
if ($safeName === '' || $safeName === '_') {
$safeName = 'upload_' . time();
}
$destPath = $uploadDir . DIRECTORY_SEPARATOR . $safeName;
if (file_exists($destPath)) {
$info = pathinfo($safeName);
$baseName = $info['filename'];
$ext = isset($info['extension']) ? '.' . $info['extension'] : '';
$counter = 1;
do {
$destPath = $uploadDir . DIRECTORY_SEPARATOR . $baseName . '_' . $counter . $ext;
$counter++;
} while (file_exists($destPath));
$safeName = basename($destPath);
}
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
echo json_encode(['success' => false, 'message' => 'Failed to save file.']);
exit;
}
echo json_encode(['success' => true, 'message' => 'File <b>' . htmlspecialchars($safeName) . '</b> uploaded successfully.']);
exit;
}
// --- AJAX PREVIEW ---
if (isset($request['ajax']) && $isRealAjax && ($request['action'] ?? '') === 'get_preview') {
header('Content-Type: application/json; charset=utf-8');
if (isset($_REQUEST['type']) && $_REQUEST['type'] === 'audio_playlist') {
$allAudioFiles = $_REQUEST['all_audio'] ?? [];
if (!empty($allAudioFiles)) {
$audioList = [];
foreach ($allAudioFiles as $rel) {
$audioList[] = ['rel' => $rel, 'name' => basename($rel)];
}
showAudioPlayer($audioList, "Current page playlist");
} else {
echo json_encode(['success' => false, 'message' => 'Audio list is empty']);
}
exit;
}
// Rename modal
if (isset($_REQUEST['type']) && $_REQUEST['type'] === 'rename') {
if (!$isUploadEnabled) {
echo json_encode(['success' => false, 'message' => 'Renaming is disabled.']);
exit;
}
$fileRel = $request['file'] ?? '';
$fullPath = realpath($baseDir . DIRECTORY_SEPARATOR . $fileRel);
$isDir = $fullPath && is_dir($fullPath);
$fileName = $fullPath ? basename($fullPath) : '';
if (!$fileName || (!is_file($fullPath) && !$isDir)) {
echo json_encode(['success' => false, 'message' => 'File or folder not found.']);
exit;
}
ob_start();
include __DIR__ . '/templates/edit_name.php';
$html = ob_get_clean();
echo json_encode(['success' => true, 'html' => $html]);
exit;
}
$fileRel = $request['file'] ?? '';
$fullPath = realpath($baseDir . DIRECTORY_SEPARATOR . $fileRel);
$fileName = ($fullPath && is_file($fullPath)) ? basename($fullPath) : '';
$extension = $fileName ? strtolower(pathinfo($fileName, PATHINFO_EXTENSION)) : '';
ob_start();
if (!$fullPath || !str_starts_with($fullPath, $baseDir) || !is_file($fullPath)) {
showMessage("File not found or access denied.", "danger", "Error");
} else {
switch ($extension) {
case 'pdf': showFilePreviewPDF($fileRel, $fileName); break;
case 'txt': case 'log': case 'md':
showFilePreviewTXT($fullPath, $fileName); break;
case 'ini': case 'sql': case 'conf': case 'cfg':
case 'xml': case 'json': case 'yaml': case 'yml':
case 'php': case 'py': case 'js': case 'ts': case 'go':
case 'c': case 'cpp': case 'cs': case 'java': case 'kt':
case 'swift': case 'rb': case 'rs': case 'sh': case 'bash':
case 'ps1': case 'lua': case 'pl': case 'r':
case 'html': case 'htm': case 'css': case 'scss': case 'less':
case 'toml': case 'dockerfile': case 'makefile':
showFilePreviewCode($fullPath, $fileName); break;
case 'jpg': case 'jpeg': case 'png': case 'webp': case 'gif':
case 'bmp': case 'ico': case 'svg':
showFilePreviewIMG($fileRel, $fileName); break;
case 'csv': showFilePreviewCSV($fullPath, $fileName); break;
case 'mp4': case 'webm': case 'ogg': case 'mov': case 'avi':
showFilePreviewVideo($fileRel, $fileName); break;
case 'mp3': case 'wav': case 'flac': case 'm4a': case 'm4b':
showFilePreviewAudioSingle($fileRel, $fileName); break;
default:
showMessage("Preview for format <b>.{$extension}</b> is not supported.", "warning", "Warning");
break;
}
}
$htmlOutput = ob_get_clean();
echo json_encode(['success' => true, 'html' => $htmlOutput]);
exit;
}
// --- DOWNLOAD ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($request['action'] ?? '') === 'download_selected') {
if ($isDownloadEnabled) {
if (!empty($_POST['selected']) && is_array($_POST['selected'])) {
downloadSelected($baseDir, $_POST['selected']);
exit;
}
} else {
ob_start();
showMessage("Archive download is disabled by administrator.", "danger", "Access denied");
$errorHtml = ob_get_clean();
if (isset($request['ajax']) && $isRealAjax) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['success' => true, 'html' => $errorHtml]);
exit;
}
$config['filter_error'] = "Download is disabled.";
}
}
if (isset($_GET['download'])) {
if ($isDownloadEnabled) {
handleDownload($baseDir);
exit;
} else {
require __DIR__ . '/templates/header.php';
showMessage("File download is disabled in server configuration.", "danger", "Access restricted");
require __DIR__ . '/templates/footer.php';
exit;
}
}
// --- LISTING DATA PREPARATION ---
$allItems = fetchItems($currentFull, $isSearch, $searchQuery, $config, $sortBy, $sortOrder);
$total = count($allItems);
$totalPages = max(1, ceil($total / $perPage));
$page = min($page, $totalPages);
$offset = ($page - 1) * $perPage;
$items = array_slice($allItems, $offset, $perPage);
$from = ($total > 0) ? $offset + 1 : 0;
$to = $offset + count($items);
// --- OUTPUT ---
if (isset($request['ajax']) && $isRealAjax) {
header('Content-Type: application/json; charset=utf-8');
ob_start();
include __DIR__ . '/templates/listing.php';
$htmlContent = ob_get_clean();
echo json_encode(['success' => true, 'html' => $htmlContent]);
exit;
}
require __DIR__ . '/templates/header.php';
include __DIR__ . '/templates/listing.php';
require __DIR__ . '/templates/footer.php';