<?php
require_once __DIR__ . '/data/mysql.php';
$config =  require_once __DIR__ . '/data/data.php';
require_once __DIR__ . '/data/redis_client.php'; 

function getRootDomain($domain) {
    $domain = preg_replace('/^https?:\/\/|^www\./i', '', $domain);
    $dotPos = strpos($domain, '.');
    $domain = substr($domain, $dotPos + 1);
    return $domain;
}

//防止被任意域名访问
$host = @$_SERVER['HTTP_HOST'];
$rootDomain = getRootDomain($host);
$origin = preg_replace(['/^https?:\/\//i', '/:\d+$/', '/[\/?#].*/'], ['', '', ''], $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '');
   

$rdtList = @executeQuery("SELECT zt, l, suiji, t FROM ym WHERE t = :t OR t=:d OR (suiji != 0 AND t = :rootDomain)", ['t' => $host, 'd' => $origin, 'rootDomain' => $rootDomain])['data'];
if (empty($rdtList)&&$host!==$config['zd']['GGURL']&&$host!==$config['zd']['HTURL']&&$host!==$config['zd']['DLURL']&&$host!==$config['zd']['FJURL']) {
header("HTTP/1.1 404 Not Found");exit('404');
}

$rdtList[]=['zt'=>3,'l'=>6,'suiji'=>0,'t'=>$config['zd']['HTURL']];
$rdtList[]=['zt'=>3,'l'=>7,'suiji'=>0,'t'=>$config['zd']['DLURL']];
$rdtList[]=['zt'=>3,'l'=>8,'suiji'=>0,'t'=>$config['zd']['FJURL']];


$LANG = $config['zd']['LANG'];
$ip = filter_var($_SERVER['REMOTE_ADDR'] ?? '', FILTER_VALIDATE_IP);
if ($ip === false) {
    http_response_code(404); exit;
}

//$ip = '155.55.66.68';


    

if($config['zd']['DLURL']==$host&&$config['zd']['GcURL']){
$ip = @$_SERVER['HTTP_X_REAL_IP'];                 //使用代理传递的IP
$config['zd']['GGURL'] =  $config['zd']['GcURL']; //如果是反向代理访问，就使用反向代理的域名
}
   
   

$ipmd5 = md5($ip . 'ws66'); 
$md58 = substr($ipmd5, 0, 8);
$md53 = 'a' . substr($md58, 0, 5);
$md54 = 'a' . substr($md58, 0, 4);
$md57 = substr($ipmd5, 4, 12);
$md56 = substr($ipmd5, -6);
$md507 = substr($ipmd5, 10, 7);
$md504 = substr($ipmd5, 25, 5);
$adidd = 'a'.substr($ipmd5, 12, 8);
$mb = isset($_GET['ss01']) ? glml($_GET['ss01']) : null;



  


if (!$mb) {

    $mbs = isset($_GET['css01']) ? wjgl($_GET['css01']) : null;

    if ($mbs) {
        $md56c = substr($mbs, 0, 6);
        if ($md56c !== substr($ipmd5, -6)&&!$config['zd']['FJURL']) {
        http_response_code(404);exit;
        }
         
        $fi = '/h5/' . str_replace($md56c . "/", "", $mbs);
        header('Content-Type: ' . lxx($mbs));
        header('X-Accel-Redirect: ' . $fi);
        header('Cache-Control: max-age=31536000, immutable');
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT');
        header('Pragma: cache');
        exit;
    
         
    } else {
        
        $mbs = isset($_GET['pp01']) ? wjgl($_GET['pp01']) : null;
        //伪装图片暗桩
        if($mbs=='loading.png'){
        $fi = 'data/g_imgping.php';
        if (file_exists($fi)) {
        include $fi;
        exit;
        }
        }

       header('Content-Type: application/octet-stream');
        if ($mbs) {
            $md56c = substr($mbs, 0, 5);
            if ($md56c !== $md504) {
                http_response_code(404);
                exit;
            }
           
            $matchedItems = array_filter($rdtList, function($item) use ($origin) { return isset($item['t'], $item['l']) && $item['t'] == $origin && $item['l'] == 6; });
            if($host!==$config['zd']['GGURL']&&$host!==$config['zd']['DLURL']&&!$matchedItems){
            http_response_code(404);exit;   
            }
    

            $dn = str_replace($md56c, "", $mbs); 
            $mapping = [
                '1' => 'admin_dl',
                '2' => 'admin_bc',
                '3' => 'admin_ys',
                '4' => 'admin_imgup',
                '5' => 'admin_xg',
                '6' => 'admin_sc',
                '7' => 'admin_xz',
                '8' => 'admin_cj',
                '9' => 'admin_cjbd',
                '10' => 'admin_cjrk',
                '11' => 'admin_uslb',
                '12' => 'admin_fbl',
                '13' => 'admin_ip',
                '14' => 'dl_dl',
                '15' => 'dl_uslb',
                '16' => 'dl_xz',
                '17' => 'dl_class',
                '18' => 'dl_xg',
                '19' => 'dl_sc',
                '20' => 'admin_kf',
                '21' => 'admin_kfms',
                '22' => 'admin_kfda',
                '23' => 'admin_wpay',
                '24' => 'admin_ym',
                '51' => 'us_dl',
                '52' => 'us_yh',
                '53' => 'us_ys',
                '54' => 'us_sc',
                '55' => 'us_kf', 
                '56' => 'us_tx', 
                '57' => 'us_bd', 
                '58' => 'us_wtk', 
                '59' => 'us_tdsz', 
                '60' => 'us_tdls',
                '61' => 'zd_video',
                '62' => 'zd_videobf',
                '63' => 'zd_m3u8ts302',
                '64' => 'zd_shendu2',
                '65' => 'us_ddz',
                '66' => 'admin_ad',
                '67' => 'admin_tj',
                '68' => 'admin_zbjc',
                '69' => 'app_us',
                '70' => 'd_danye',
                '71' => 'g_imgping',
                '72' => 'zd_dju',
                '73' => 'us_paihang',
                '74' => 'admin_dqip',
                '99' => 'us_tj'
                
                
            ];
           
            
            $dnarr = explode('/', $dn);
            $cdcs0 = isset($dnarr[0]) ? $dnarr[0] : 999;
            
            $cdcs1 = isset($dnarr[1]) ? $dnarr[1] : '';
            
            $dn = $mapping[$cdcs0] ?? exit;
       
            if (strpos($dn, 'admin_') !== false || strpos($dn, 'dl_') !== false) {
                session_name($adidd);
                session_start();
            }
            $fi = 'data/' . $dn . ".php";
             

             
            if (file_exists($fi)) {
                include $fi;
                exit;
            }
        }
        http_response_code(404);
        exit;
    }
}

$arr = explode("/", $mb);
$prefixMap = [
    $config['zd']['ADMINLJ'] => 'admin_',
    $config['zd']['USLJ'] => 'us_',
    $config['zd']['QDLJ'] => 'zd_',
    $config['zd']['DLLJ'] => 'dl_',
    $config['zd']['DWLJ'] => 'dw_',
    $config['zd']['TZLJ'] => 'tz_',
    $config['zd']['APP'] => 'app_',
    $config['zd']['DANYE'] => 'd_'
];

  
  
$prefix = '';
if (isset($arr[1]) && isset($arr[2])) {
    $prefix = $prefixMap[$arr[1]] ?? null; 
    if ($prefix) {

        $hasPermission = false;
        foreach ($rdtList as $rdt) {
            $domainMatch = ($rdt['suiji'] != 0) ? (getRootDomain($rdt['t']) == $rootDomain) : ($rdt['t'] == $host);
            if ($domainMatch && (
                ($prefix == 'admin_' && $rdt['l'] == 6) ||
                ($prefix == 'dl_') ||
                ($prefix == 'dw_' && $rdt['l'] == 1 ) ||
                ($prefix == 'tz_' && $rdt['l'] == 2 && $rdt['zt'] == 3) ||
                ($prefix == 'zd_' && $rdt['l'] == 3 && $rdt['zt'] == 3) ||
                ($prefix == 'zd_' && $rdt['l'] == 88 && $rdt['zt'] == 3) ||
                ($prefix == 'zd_' && $rdt['l'] == 7 && $rdt['zt'] == 3) ||
                ($prefix == 'd_' && $rdt['l'] == 3 && $rdt['zt'] == 3) ||
                ($prefix == 'us_'&& $rdt['l'] == 3) ||
                ($prefix == 'us_'&& $rdt['l'] == 6&& $rdt['zt'] == 3) ||
                ($prefix == 'us_'&& $rdt['l'] == 7&& $rdt['zt'] == 3) ||
                ($prefix == 'us_'&& $rdt['l'] == 88&& $rdt['zt'] == 3) ||
                ($prefix == 'app_')||
                ($prefix == 'd_' && $rdt['l'] == 9 && $rdt['zt'] == 3 )  
            )) {
                $hasPermission = true;
                break; 
            }
        }


    
        if (!$hasPermission) {
            header("HTTP/1.1 404 Not Found");  exit('404');
        }

     
        //短地址
        if($prefix=='dw_'&&$arr[2]){
        $cutStr = substr($arr[2], 0, 10); 
        $us = @executeQuery("SELECT data,created_at FROM code_sequence WHERE code = :code  ", ['code'=>$cutStr] )['data'][0]['data'];    
        if($us){
            

        $second_slash = strpos($us, '/', 1); 
        $target = substr($us, 1, $second_slash - 1); 
        if($config['zd']['USLJ']==$target){$lid = 99998;}else if($config['zd']['QDLJ']==$target){$lid = 99999;}else{$lid = 0; }
       
      
        //随机抽取跳转域名    
        $resultArr = @executeQuery("SELECT t, suiji FROM ym WHERE l = 2 AND zt = 3  ORDER BY (lei = $lid) DESC, RAND() LIMIT 1", [] )['data'][0];  if(!$resultArr){  header("HTTP/1.1 404 Not Found");  exit('404');  } 
        $ym = @$resultArr['t'];
        $suiji = @$resultArr['suiji'];
        if($suiji){
        $randStr = 'h';    
        $redis = getRedisInstance();
        if ($redis) {
        $key = 'tiaoz'.$ym;
        $randStr = $redis->get($key);
        if(!$randStr){
        $expireSeconds = 60 * $suiji;
        $CHARS = '0123456789abcdefghijklmnopqrstuvwxyz';
        $randStr = 'a' . implode('', array_map(function() use ($CHARS) {return $CHARS[rand(0, 35)];}, range(1, rand(3, 6)))); 
        $redis->setex($key, $expireSeconds, $randStr);
        }
        }
        $ym = $randStr.'.'.getRootDomain($ym); 
        }

        //判断是否为单页推广
        if($config['zd']['DANYE']==$target){ $zt= 9;  }else{ $zt= 3; }
        //随机抽取落地域名
        $resultArrdl = @executeQuery("SELECT t, suiji FROM ym WHERE l = $zt AND zt = 3  ORDER BY (lei = $lid) DESC, RAND() LIMIT 1", [] )['data'][0];
        if(!$resultArrdl){
        $resultArrdl = @executeQuery("SELECT t, suiji FROM ym WHERE l = 3 AND zt = 3  ORDER BY (lei = $lid) DESC, RAND() LIMIT 1", [] )['data'][0];    
        if(!$resultArrdl){  header("HTTP/1.1 404 Not Found");  exit('404');  }      
        }  
        
        $ymld = @$resultArrdl['t'];
        $suijidl = @$resultArrdl['suiji'];
        $random5 = substr((string)strtotime(date('Y-m-d 00:00:00')), -5); //当天密钥
        $gogo = 'https://'.$ym.'/'.$config['zd']['TZLJ'].'/'.a5a3fx($randStr.'|'.$suijidl.'|'.$ymld.'|'.$us.'|'.time(), $random5, 0).'/m-9.html';
        header("Location: ".$gogo);   
        exit();    
        }else{
        header("HTTP/1.1 404 Not Found");  exit('404');    
        } 
        }
     
        $mb = $prefix . $arr[2];
    

        //中间跳转处理
        if ($prefix === 'tz_'&&$arr[2]&&$arr[3]) {
        $random5 = substr((string)strtotime(date('Y-m-d 00:00:00')), -5); //当天密钥   
        $jxi = @a5a3fx($arr[2],$random5,1); 
        $url = explode('|',$jxi);
        //1分钟过期
        $isValid = is_numeric($url[4]) && abs(time() - (int)$url[4]) <= 60 && (int)$url[4] > 0;
        if(!$isValid){ header("HTTP/1.1 404 Not Found");  exit('404'); }
        
        $shic = intval(@$url[1]);
        $gogo = @$url[2];
        if($shic){
            
   
        $redis = getRedisInstance();
        $randStr = 'p';
        if($redis) { 
        $key = 'luodi'.$gogo;
        $randStr = $redis->get($key);
        if(!$randStr){
        $CHARS = '0123456789abcdefghijklmnopqrstuvwxyz';
        $randStr = 'p' . implode('', array_map(function() use ($CHARS) {return $CHARS[rand(0, 35)];}, range(1, rand(3, 6)))); 
        $expireSeconds = 60 * $shic;
        $redis->setex($key, $expireSeconds, $randStr);
        }
        }
        
        $gogo = $randStr.'.'.getRootDomain($gogo); 
        }
        

        
        $u  ='https://'.$gogo.$url[3];
        

        //header("Location: ".$u); exit();
        
        
        //跳转赋到页面
        $zuhe =  'P'.base64_encode($u);
        $mb = $prefix.'go';
        
        if (strpos(@$_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) { $mb = 'wx_index';}else{header("Location: ".$u); exit();}
        
        
        $randomNumber = mt_rand(100, 999); $encryptedTitle = $randomNumber.a5a3fx('...', $randomNumber, 0);
        $script = '<script>document.write(\'<script src="//'.$config['zd']['GGURL'].'/js/'.$encryptedTitle.'3.js?p=\'+Math.random()+\'"><\\/script>'.$DV.'\');</script></head>';
        $filePath = __DIR__ . '/h5/' . $mb . '.html';  
        $template = @file_get_contents($filePath); 
        $replacements = [
        'class="' => 'class="' . $md57 . ' ',
        'aaa99aaa' =>$zuhe,
        '</head>' => $script,
        ]; 
        $template = str_replace(array_keys($replacements), array_values($replacements), $template);
        $reports = randomWeatherReports($ipmd5);
        if (preg_match_all('|</div>|', $template, $matches, PREG_OFFSET_CAPTURE) && count($matches[0]) >= 5) {
        $positions = array_slice($matches[0], 0, 5);
        rsort($positions);
        foreach ($positions as $match) {
        $index = array_search($match, $matches[0]);
        if (isset($reports[$index])) {
            $position = $match[1] + strlen('</div>');
            $template = substr_replace($template, "<!--" . $reports[$index] . "-->", $position, 0);
        }
        }
        }
        $comments = '';
        foreach ($reports as $report) {
        $comments .= "<!--$report-->";
        }
        exit($comments.$template);
        }
        
 
        
        if ($prefix === 'admin_' || $prefix === 'dl_') {
            session_name($adidd);
            session_start();
        }
        
        if ($prefix === 'admin_' && $arr[2] == 'dl') {
            $_SESSION['admindldl'] = null;
        }
        
     
         
        if ($prefix === 'admin_' && $arr[2] !== 'dl' && ($_SESSION['admindldl'] ?? '') !== 'ok') {
            header("Location: /{$config['zd']['ADMINLJ']}/dl");
            exit;
        }
        
        if ($prefix === 'dl_' && $arr[2] == 'dl') {
            $_SESSION['dlid'] = null;
        }
        
        if ($prefix === 'dl_' && $arr[2] !== 'dl' && ($_SESSION['dlid'] ?? '') == '') {
            header("Location: /{$config['zd']['DLLJ']}/dl");
            exit;
        }
        
        if ($prefix === 'us_') {
            $mb = $prefix . 'ad'; 
        }
        
        if ($prefix === 'app_') {
            $mb =  'app_us'; 
        }
        
        if ($prefix === 'd_') {
            $mb =  'd_tuiguang'; 
        }
        
    } else {
        $mb = '404';
    }
}



$filePath = __DIR__ . '/h5/' . $mb . '.html';  
$template = @file_get_contents($filePath);

if ($template === false){
    http_response_code(404);
    exit;
}

$randomNumber = mt_rand(100, 999); 
if (preg_match('/<title>([^<]*)<\/title>/', $template, $matches)) {
    
    if($arr[1]==$config['zd']['USLJ']){
        $go = 2; 
        $titlev = $config['zd']['ZM']; 
    }elseif($arr[1]==$config['zd']['QDLJ']){
        $go = 1; 
        $titlev = $config['zd']['BZM']; 
    }else{
        $go = 3; 
        $titlev = $matches[1];
    }
    $title = $matches[1];
    $newTitle = '<title>' . xxxq($ip) . '</title>';
    $encryptedTitle = $randomNumber.a5a3fx($titlev, $randomNumber, 0);
    if($go==2){
        $DV = '<script src="/'.$md58 . '/' . $md56.'/js/qr.js"><\\/script><script src="/'.$md58 . '/' . $md56.'/js/q.js"><\\/script><script src="/'.$md58 . '/' . $md56.'/js/zxing.min.js"><\\/script>';    
    }else{
        $DV = '';    
    }
    $script = '<script>document.write(\'<script src="//'.$config['zd']['GGURL'].'/js/'.$encryptedTitle.$go.'.js?p=\'+Math.random()+\'"><\\/script>'.$DV.'\');</script> 
</head>';

    $md54 = 'm'.$md58;
    $replacements = [
        '<title>' . $title . '</title>' => $newTitle,
        '</head>' => $script,
        'class="' => 'class="' . $md57 . ' ',
        'mub88888' => $md58 . '/' . $md56,
        'mub66666' => $md507 . '/' . $md504,
        'xxxxxx1' => $md54,
        'xxxxxx2' => "'".$md58."'",
        'xxxxxx3' => 'a'.$adidd,
        'xxxxxx4' => '//'.$config['zd']['GGURL'].'/imagesa/loading.png'
    ];
} else {
    
    $replacements = [
        'class="' => 'class="' . $md57 . ' ',
        'mub88888' => $md58 . '/' . $md56,
        'mub66666' => $md507 . '/' . $md504,
        'xxxxxx1' => $md54,
        'xxxxxx2' => $md53,
        'xxxxxx3' => 'a'.$adidd
    ];
}

if($prefix=='admin_'){
    
$replaceArray = [];
foreach ($config as $firstKey => $secondArray) {
    foreach ($secondArray as $secondKey => $value) {
        $key = '{'.$firstKey . '.' . $secondKey.'}';
        $replaceArray[$key] = $value;
    }
}
$replacements = array_merge($replaceArray, $replacements);
}

$template = str_replace(array_keys($replacements), array_values($replacements), $template);
$reports = randomWeatherReports($ipmd5);
if (preg_match_all('|</div>|', $template, $matches, PREG_OFFSET_CAPTURE) && count($matches[0]) >= 5) {
    $positions = array_slice($matches[0], 0, 5);
    rsort($positions);
    foreach ($positions as $match) {
        $index = array_search($match, $matches[0]);
        if (isset($reports[$index])) {
            $position = $match[1] + strlen('</div>');
            $template = substr_replace($template, "<!--" . $reports[$index] . "-->", $position, 0);
        }
    }
}
$comments = '';

foreach ($reports as $report) {
    $comments .= "<!--$report-->";
}
echo $comments.$template;