<?php
$url = $_GET['url'] ?? '';
if (!$url) die('');

$target = 'lanzouf.com';
$url = preg_replace('/lanzou[a-z]\.com/', $target, $url);
if (strpos($url, $target) === false) {
    $path = explode('.com/', $url)[1] ?? explode('/', $url)[3] ?? '';
    $url = "https://www.{$target}/{$path}";
}

$headerStr = "User-Agent: Mozilla/5.0 (Linux; Android 13; V2190A) AppleWebKit/537.36\r\n" .
             "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" .
             "Accept-Language: zh-CN,zh;q=0.9\r\n" .
             "X-Requested-With: mark.via2\r\n";

$ctx = stream_context_create([
    'http' => ['header' => $headerStr, 'follow_location' => 1],
    'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
]);

// 第1步
$html1 = file_get_contents($url, false, $ctx);
preg_match('/href="(\/tp\/[^"]+)"/', $html1, $tp);
if (!$tp) die('');

// 第2步
$tpUrl = "https://www.{$target}{$tp[1]}";
$ctx2 = stream_context_create([
    'http' => ['header' => $headerStr . "Referer: {$url}\r\n", 'follow_location' => 1],
    'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
]);
$html2 = file_get_contents($tpUrl, false, $ctx2);

preg_match("/var\s+vkjxld\s*=\s*'([^']+)'/", $html2, $v);
preg_match("/var\s+hyggid\s*=\s*'([^']+)'/", $html2, $h);
if (!$v || !$h) die('');

$apiUrl = $v[1] . $h[1];
$parsed = parse_url($apiUrl);
$host = $parsed['host'];
$path = ($parsed['path'] ?? '') . '?' . ($parsed['query'] ?? '');
$port = $parsed['port'] ?? 443;

// 第3步：socket裸连
$fp = fsockopen("ssl://{$host}", $port, $errno, $errstr, 10);
if (!$fp) die('');

$request = "GET {$path} HTTP/1.1\r\n" .
           "Host: {$host}\r\n" .
           "User-Agent: Mozilla/5.0 (Linux; Android 13; V2190A) AppleWebKit/537.36\r\n" .
           "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" .
           "Accept-Language: zh-CN,zh;q=0.9\r\n" .
           "Referer: {$url}\r\n" .
           "Sec-Fetch-Site: cross-site\r\n" .
           "X-Requested-With: mark.via2\r\n" .
           "Cookie: down_ip=1\r\n" .
           "Connection: close\r\n\r\n";

fwrite($fp, $request);

$response = '';
while (!feof($fp)) {
    $response .= fread($fp, 8192);
}
fclose($fp);

$headerEnd = strpos($response, "\r\n\r\n");
$headerStr3 = substr($response, 0, $headerEnd);

preg_match('/Location:\s*(.+)/i', $headerStr3, $location);

if ($location) {
    die(trim($location[1]));
}
die('');