PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
$stmt = $pdo->prepare("SELECT password FROM " . DB_TABLE . " WHERE username = :email AND active = true LIMIT 1");
$stmt->execute(['email' => $username]);
$user = $stmt->fetch();
if ($user && !empty($user['password'])) {
$clean_hash = preg_replace('/^\{[A-Z0-9_-]+\}/', '', $user['password']);
if (password_verify($password, $clean_hash)) { return true; }
}
} catch (PDOException $e) { return false; }
return false;
}
if (isset($_GET['logout'])) { session_destroy(); header("Location: ?"); exit; }
$error_msg = '';
if (isset($_POST['action']) && $_POST['action'] === 'login') {
$login = trim($_POST['login'] ?? '');
$pass = $_POST['password'] ?? '';
if (authenticate_user($login, $pass)) {
$clean_folder = preg_replace('/[^a-zA-Z0-9_\.-]/', '_', explode('@', $login)[0]);
$_SESSION['user'] = $login;
$_SESSION['home'] = BASE_STORAGE . $clean_folder . '/';
if (!file_exists($_SESSION['home'])) { mkdir($_SESSION['home'], 0755, true); }
header("Location: ?"); exit;
} else { $error_msg = 'Неверный логин или пароль.'; }
}
if (!isset($_SESSION['user'])) {
echo '
Вход☁️ Вход в Обменник
';
if($error_msg){echo '
'.htmlspecialchars($error_msg).'
';}
echo '
';
exit;
}
$base_dir = $_SESSION['home'];
$sub_dir = '';
if (isset($_GET['dir']) && !empty($_GET['dir'])) {
$sub_dir = str_replace(['../', '..\\', './'], '', $_GET['dir']);
$sub_dir = trim($sub_dir, '/') . '/';
}
$current_dir = $base_dir . $sub_dir;
if (!file_exists($current_dir) || !is_dir($current_dir)) { $sub_dir = ''; $current_dir = $base_dir; }
if (isset($_GET['delete'])) {
$item = basename($_GET['delete']); $target = $current_dir . $item;
if (file_exists($target)) {
if (is_dir($target)) {
foreach (array_diff(scandir($target), ['.', '..']) as $f) { @unlink("$target/$f"); }
@rmdir($target);
} else { @unlink($target); }
}
header("Location: ?dir=" . urlencode(rtrim($sub_dir, '/'))); exit;
}
if (isset($_POST['create_folder']) && !empty($_POST['folder_name'])) {
$folder = basename($_POST['folder_name']);
if (!file_exists($current_dir . $folder)) { mkdir($current_dir . $folder, 0755, true); }
header("Location: ?dir=" . urlencode(rtrim($sub_dir, '/'))); exit;
}
if (isset($_GET['download'])) {
$file = basename($_GET['download']); $path = $current_dir . $file;
if (file_exists($path) && is_file($path)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Length: ' . filesize($path));
readfile($path); exit;
}
}
if (isset($_POST['upload']) && isset($_FILES['file'])) {
$file = $_FILES['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
// Проверяем, передан ли НЕПУСТОЙ относительный путь папки (Drag and Drop)
if (isset($_POST['rel_path']) && trim($_POST['rel_path']) !== '') {
// Очищаем путь от возможных инъекций вроде "../"
$rel_path = str_replace(['../', '..\\'], '', $_POST['rel_path']);
$full_target_path = $current_dir . $rel_path;
// Получаем путь к директории, в которой должен лежать файл
$dirname = dirname($full_target_path);
// Если такой папки еще нет на сервере, создаем её рекурсивно
if (!is_dir($dirname)) {
mkdir($dirname, 0755, true);
}
// Сохраняем файл внутрь созданной папки
move_uploaded_file($file['tmp_name'], $full_target_path);
} else {
// Обычная загрузка через кнопку (сохраняем файл в корень текущей директории)
$target_path = $current_dir . basename($file['name']);
move_uploaded_file($file['tmp_name'], $target_path);
}
}
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
echo json_encode(['status' => 'success']); exit;
}
header("Location: ?dir=" . urlencode(rtrim($sub_dir, '/'))); exit;
}
$items = array_diff(scandir($current_dir), ['.', '..']);
usort($items, function($a, $b) use ($current_dir) {
$is_dir_a = is_dir($current_dir . $a);
$is_dir_b = is_dir($current_dir . $b);
if ($is_dir_a && !$is_dir_b) return -1; // Папка идет вверх
if (!$is_dir_a && $is_dir_b) return 1; // Файл идет вниз
return strnatcasecmp($a, $b); // Сортировка по имени (без учета регистра)
});
echo 'Диск| Название | Тип | Размер | Действия |
';
if(!empty($sub_dir)){$up=dirname(rtrim($sub_dir,'/'));$up_lnk=($up==='.'||$up==='/')?'':'?dir='.urlencode($up);echo '| 🔙 .. (Вверх) |
';}
// 1. Сортируем массив $items: сначала папки, потом файлы, внутри групп - по алфавиту
usort($items, function($a, $b) use ($current_dir) {
$is_dir_a = is_dir($current_dir . $a);
$is_dir_b = is_dir($current_dir . $b);
if ($is_dir_a && !$is_dir_b) return -1; // Папка идет вверх
if (!$is_dir_a && $is_dir_b) return 1; // Файл идет вниз
return strnatcasecmp($a, $b); // Сортировка по имени (без учета регистра)
});
// 2. Выводим таблицу с новыми иконками
foreach($items as $f){
$p = $current_dir . $f;
$is_d = is_dir($p);
$type = $is_d ? 'Папка' : 'Файл';
$size = $is_d ? '—' : round(filesize($p)/1024, 2).' KB';
$dir_param = urlencode(rtrim($sub_dir, '/'));
echo '';
// Вывод названия элемента
if($is_d){
echo '| 📁 '.htmlspecialchars($f).' | ';
} else {
echo '📄 '.htmlspecialchars($f).' | ';
}
echo ''.$type.' | ';
// Закрываем тег echo, который выводил размер файла
// Вывели размер файла
// Вывели размер файла
echo ''.$size.' | ';
// Выходим из PHP режима для вывода HTML кнопок
?>
|
';