<?php
$nosession=true;
$nosecu=true;
include("./includes/common.php");
if(!isset($_SESSION)) session_start();

$pwd = isset($_GET['pwd']) ? $_GET['pwd'] : null;
$hash = isset($_GET['hash']) ? $_GET['hash'] : null;

if(empty($hash)){
    $path = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    if(empty($path) && isset($_SERVER['REQUEST_URI'])){
        $request_uri = explode('?', $_SERVER['REQUEST_URI'])[0];
        $script_name = $_SERVER['SCRIPT_NAME'];
        if(strpos($request_uri, $script_name) === 0){
            $path = substr($request_uri, strlen($script_name));
        }elseif(preg_match('/down\.php\/(.+)$/', $request_uri, $matches)){
            $path = $matches[1];
        }
    }
    
    $path = trim($path, '/');
    if($path !== ''){
        if(($pos = strpos($path, '/')) !== false){
            $path = substr($path, 0, $pos);
        }
        $pwdPart = null;
        if(($ampPos = strpos($path, '&')) !== false){
            $pwdPart = substr($path, $ampPos + 1);
            $path = substr($path, 0, $ampPos);
        }
        if($pwd === null && $pwdPart !== null){
            $pwd = $pwdPart;
        }
        if(strpos($path, ".") !== false){
            $hash = substr($path, 0, strpos($path, "."));
        }else{
            $hash = $path;
        }
    }
}

if(empty($hash)){
    exit('404 Not Found');
}

$row = $DB->getRow("SELECT * FROM `pre_file` WHERE `hash`=:hash limit 1", [':hash'=>$hash]);
if(!$row)exit('404 Not Found');
if($row['block']>=1)exit('File is blocked!');

$is_owner = ($islogin2 && $uid == $row['uid']) || (!$islogin2 && ((isset($_SESSION['fileids']) && in_array($row['id'], $_SESSION['fileids'])) || in_array($row['id'], get_guest_file_ids())) && strtotime($row['addtime'])>strtotime("-7 days"));
if($row['pwd']!=null && !$is_owner){
    $is_valid = false;
    if($pwd !== null){
        $info = password_get_info($row['pwd']);
        if($info['algo'] != 0){
            if(password_verify($pwd, $row['pwd'])){
                $is_valid = true;
            }
        }else{
            if($row['pwd'] === $pwd){
                $is_valid = true;
            }
        }
    }
    if(!$is_valid){ ?>
    <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <title>请输入密码下载文件</title>
    <script src="https://s4.zstatic.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <style>
    body { display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; background: linear-gradient(135deg, #f5f7fa 0%, #e8f5f3 100%); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
    .pwd-card { background: #fff; border-radius: 20px; padding: 50px 40px; max-width: 400px; width: 90%; text-align: center; box-shadow: 0 20px 60px rgba(15,118,110,0.15); }
    .pwd-icon { width: 90px; height: 90px; background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 30px; }
    .pwd-icon i { font-size: 40px; color: #fff; }
    .pwd-card h1 { margin: 0 0 10px; font-size: 24px; color: #333; }
    .pwd-card p { margin: 0 0 30px; color: #666; }
    .pwd-card input { width: 100%; padding: 15px; border: 2px solid #e8e8e8; border-radius: 12px; font-size: 16px; box-sizing: border-box; text-align: center; margin-bottom: 15px; }
    .pwd-card input:focus { outline: none; border-color: #14b8a6; }
    .pwd-card button { width: 100%; padding: 15px; background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%); color: #fff; border: none; border-radius: 12px; font-size: 16px; font-weight: 600; cursor: pointer; }
    .pwd-card button:hover { opacity: 0.9; }
    .pwd-back { margin-top: 20px; }
    .pwd-back a { color: #14b8a6; text-decoration: none; }
    .error-msg { color: #dc2626; font-size: 14px; margin-bottom: 15px; display: none; }
    </style>
</head>
<body>
    <div class="pwd-card">
        <div class="pwd-icon"><i class="fa fa-lock"></i></div>
        <h1>文件已加密</h1>
        <p>请输入访问密码以下载文件</p>
        <div class="error-msg" id="error-msg"><i class="fa fa-exclamation-circle"></i> 密码错误，请重试</div>
        <form method="get" action="">
            <input type="hidden" name="hash" value="<?php echo $hash; ?>">
            <input type="password" name="pwd" id="pwd-input" placeholder="请输入访问密码" autofocus required>
            <button type="submit">验证密码</button>
        </form>
        <div class="pwd-back">
            <a href="javascript:history.back();"><i class="fa fa-arrow-left"></i> 返回上一页</a>
        </div>
    </div>
    <script>
    var urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('pwd')) {
        document.getElementById('error-msg').style.display = 'block';
    }
    </script>
</body>
</html>
<?php
        exit;
    }
}

if($stor->exists($hash))
{
    $owner_uid = $row['uid'];
    $visitor_uid = $uid;
    $visitor_ip = $clientip;
    $is_owner = ($islogin2 && $visitor_uid == $owner_uid);
    $is_admin = ($islogin == 1);
    
    $range = get_file_range($row['size']);
    $traffic_size = $range ? ($range[1] - $range[0] + 1) : $row['size'];
    
    if($owner_uid > 0){
        $user = $DB->getRow("SELECT * FROM pre_user WHERE uid=:uid LIMIT 1", [':uid'=>$owner_uid]);
        if($user){
            $quota = check_user_quota($user, $is_owner || $is_admin, 'traffic');
            
            if($conf['traffic_debug']){
                $log = sprintf("[%s] OwnerUID:%d, VisitorUID:%d, Owner:%d, Admin:%d, Used:%d, Limit:%s, Code:%d\n", 
                    date('Y-m-d H:i:s'), $owner_uid, $visitor_uid, $is_owner, $is_admin, $user['traffic_used'], 
                    isset($conf[$user['level']>0?'user_traffic_quota_vip':'user_traffic_quota_normal'])?$conf[$user['level']>0?'user_traffic_quota_vip':'user_traffic_quota_normal']:'N/A',
                    $quota['code']);
                file_put_contents(ROOT.'traffic_debug.log', $log, FILE_APPEND);
            }

            if($quota['code'] !== 0){
                exit($quota['msg']);
            }
        }
    }
    
    // 检查IP是否被封禁（对非所有者和非管理员进行封禁检查）
    if (!$is_owner && !$is_admin) {
        $ban_check = check_guest_quota_with_ban($visitor_ip);
        if ($ban_check['code'] !== 0) {
            $message = sprintf(
                '<div style="text-align:center;padding:50px 20px;">'.
                '<h3 style="color:#dc3545;"><i class="fa fa-ban"></i> 访问受限</h3>'.
                '<p style="margin:20px 0;color:#666;">%s</p>'.
                '<p style="margin:20px 0;">'.
                '<strong>解决方案：</strong><br/>'.
                '1. 等待封禁时间结束后再次访问<br/>'.
                '2. <a href="%s" style="color:#007bff;text-decoration:none;">注册账号</a> 登录后使用<br/>'.
                '3. 联系网站管理员处理'.
                '</p>'.
                '</div>',
                htmlspecialchars($ban_check['msg']),
                $siteurl . 'login.php'
            );
            echo $message;
            exit;
        }
    }
    
    // 异常流量检测 - 检测到恶意刷流量时封禁
    if(isset($conf['traffic_anomaly_detection']) && $conf['traffic_anomaly_detection'] == 1){
        $anomaly = detect_traffic_anomaly($visitor_uid > 0 ? $visitor_uid : null, $visitor_uid == 0 ? $visitor_ip : null);
        if($anomaly && $anomaly['is_anomaly']){
            writeLog(sprintf("Traffic anomaly detected - UID:%d, IP:%s, AccessCount:%d, TotalTraffic:%d, Reason:%s", 
                $visitor_uid, $visitor_ip, $anomaly['access_count'], $anomaly['total_traffic'], $anomaly['anomaly_reason']));
            
            // 对游客IP进行封禁
            if($visitor_uid == 0 && !$is_owner && !$is_admin){
                $ban_reason = sprintf('检测到异常流量行为（%s）：%d分钟内访问%d次，总流量%s', 
                    $anomaly['anomaly_reason'],
                    $anomaly['window_minutes'],
                    $anomaly['access_count'], 
                    size_format($anomaly['total_traffic'])
                );
                $ban_duration = isset($conf['guest_ban_duration']) ? intval($conf['guest_ban_duration']) : 86400;
                ban_ip($visitor_ip, 'auto', $ban_reason, $ban_duration, 0, [
                    'access_count' => $anomaly['access_count'],
                    'total_traffic' => $anomaly['total_traffic'],
                    'avg_traffic' => $anomaly['avg_traffic'],
                    'anomaly_reason' => $anomaly['anomaly_reason']
                ]);
                
                $message = sprintf(
                    '<div style="text-align:center;padding:50px 20px;">'.
                    '<h3 style="color:#dc3545;"><i class="fa fa-ban"></i> 访问受限</h3>'.
                    '<p style="margin:20px 0;color:#666;">您的IP已被临时封禁，原因：%s，解封时间：%s</p>'.
                    '<p style="margin:20px 0;">'.
                    '<strong>解决方案：</strong><br/>'.
                    '1. 等待封禁时间结束后再次访问<br/>'.
                    '2. <a href="%s" style="color:#007bff;text-decoration:none;">注册账号</a> 登录后使用<br/>'.
                    '3. 联系网站管理员处理'.
                    '</p>'.
                    '</div>',
                    htmlspecialchars($ban_reason),
                    date('Y-m-d H:i:s', time() + $ban_duration),
                    $siteurl . 'login.php'
                );
                echo $message;
                exit;
            }
            
            // 对登录用户进行账号封禁（如果开启）
            if($visitor_uid > 0 && !$is_owner && !$is_admin){
                $user_anomaly_ban = isset($conf['user_anomaly_ban_enabled']) ? $conf['user_anomaly_ban_enabled'] : 0;
                if($user_anomaly_ban == 1){
                    $ban_duration = isset($conf['user_anomaly_ban_duration']) ? intval($conf['user_anomaly_ban_duration']) : 86400;
                    $ban_end = date('Y-m-d H:i:s', time() + $ban_duration);
                    
                    // 更新用户状态为禁用
                    $DB->exec("UPDATE pre_user SET enable=0 WHERE uid=:uid", [':uid' => $visitor_uid]);
                    
                    writeLog(sprintf("User banned for anomaly - UID:%d, Reason:%s, Duration:%d seconds", 
                        $visitor_uid, $anomaly['anomaly_reason'], $ban_duration));
                    
                    // 清除登录状态
                    if(isset($_SESSION['user_login'])){
                        unset($_SESSION['user_login']);
                        unset($_SESSION['user_uid']);
                    }
                    
                    $message = sprintf(
                        '<div style="text-align:center;padding:50px 20px;">'.
                        '<h3 style="color:#dc3545;"><i class="fa fa-ban"></i> 账号已被封禁</h3>'.
                        '<p style="margin:20px 0;color:#666;">您的账号因检测到异常流量行为已被临时封禁</p>'.
                        '<p style="margin:20px 0;color:#666;">原因：%s（%d分钟内访问%d次）</p>'.
                        '<p style="margin:20px 0;">'.
                        '<strong>解封时间：%s</strong><br/>'.
                        '如有疑问请联系网站管理员'.
                        '</p>'.
                        '</div>',
                        htmlspecialchars($anomaly['anomaly_reason']),
                        $anomaly['window_minutes'],
                        $anomaly['access_count'],
                        $ban_end
                    );
                    echo $message;
                    exit;
                }
            }
        }
    }
    
    if(!$is_owner && !$is_admin){
        if($owner_uid > 0){
            update_traffic_usage($owner_uid, null, $traffic_size);
        }
    }
    
    if(isset($conf['traffic_log_enabled']) && $conf['traffic_log_enabled'] == 1){
        log_traffic_usage(
            $row['id'],
            $row['hash'],
            $row['name'],
            $row['size'],
            $row['type'],
            $owner_uid,
            $visitor_uid,
            $visitor_ip,
            'download',
            $traffic_size,
            $range ? $range[0] : null,
            $range ? $range[1] : null
        );
    }
    
    $DB->exec("UPDATE `pre_file` SET `lasttime`=NOW(),`count`=`count`+1 WHERE `id`='{$row['id']}'");

    if($is_admin){
        header("Pragma: no-cache");
        header("Cache-Control: no-store, no-cache, must-revalidate");
    }else{
        header("Cache-Control: no-cache");
        header("Pragma: no-cache");
    }

    file_output($hash, $row['type'], $row['size'], $row['name'], false, $is_admin);
}
else{
    exit('File Not Found');
}
