<?php
error_reporting(0); //抑制所有错误信息
include_once './h.php';
include_once './class/Http.php';
include_once './class/Guard.php';

/**
 * 解密苹果 CMS encrypt=2 传来的播放地址
 * 格式：AES-128-CBC(明文url|时间戳) → hex →（CMS 侧再 base64+escape，player.js 会解回 hex）
 */
function art_cms_decrypt($cipher, array $config)
{
    $cipher = trim((string) $cipher);
    if ($cipher === '') {
        return null;
    }

    // 兼容偶发仍带着 base64/escape 的情况
    if (!ctype_xdigit($cipher)) {
        $tmp = @base64_decode(rawurldecode($cipher), true);
        if ($tmp !== false && $tmp !== '') {
            $cipher = rawurldecode($tmp);
        }
        $cipher = preg_replace('/[^0-9a-fA-F]/', '', $cipher);
    }

    if ($cipher === '' || (strlen($cipher) % 2) !== 0) {
        return null;
    }

    $key = substr(md5($config['cms_key'] ?? 'MiKihuazidm866669'), 0, 16);
    $plain = openssl_decrypt(hex2bin($cipher), 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $key);
    if ($plain === false || $plain === '') {
        return null;
    }

    $parts = explode('|', $plain, 2);
    $playUrl = $parts[0] ?? '';
    $ts = (int) ($parts[1] ?? 0);
    $ttl = (int) ($config['cms_ttl'] ?? 1800);

    if ($playUrl === '' || ($ttl > 0 && $ts > 0 && ($ts + $ttl) < time())) {
        return null;
    }

    return $playUrl;
}

/**
 * 背景图：同 MiKA，从 360 壁纸随机取一张 CDN 图（响应快）
 * h.php 里 background=auto 时启用；填具体地址则用固定图
 */
function art_wallpaper($config)
{
    $fallback = 'http://p5.qhimg.com/bdm/1280_800_85/t01344a9e6aeccb2a41.jpg';
    $bg = trim((string) ($config['background'] ?? 'auto'));
    if ($bg !== '' && $bg !== 'auto') {
        return $bg;
    }

    $ctx = stream_context_create([
        'http' => ['timeout' => 2, 'header' => "User-Agent: Mozilla/5.0\r\n"],
        'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
    ]);
    $raw = @file_get_contents(
        'http://wallpaper.apc.360.cn/index.php?c=WallPaper&a=getAppsByCategory&cid=26&start=0&count=100&from=360chrome',
        false,
        $ctx
    );
    $list = @json_decode((string) $raw, true)['data'] ?? [];
    if (!is_array($list) || $list === []) {
        return $fallback;
    }

    $item = $list[mt_rand(0, count($list) - 1)];
    $image = (string) ($item['url'] ?? '');
    $image = str_replace(['\\', 'http:'], ['', 'https:'], $image);
    $image = str_replace('mac:', 'https:', $image);

    return $image !== '' ? $image : $fallback;
}

if (check_wap()) {
    if ($_GET['url'] == '') {
        exit($homewap);
    }
} else {
    if ($_GET['url'] == '') {
        exit($home);
    }
}

$url = preg_replace("/url=/", "", $_SERVER["QUERY_STRING"], 1);
// 去掉可能附带的其它查询参数干扰（CMS 密文为纯 hex，无 &）
if (($pos = strpos($url, '&')) !== false) {
    // 仅当不像完整 http 地址时截断；明文带 & 的直链保留
    if (stripos($url, 'http') !== 0) {
        $url = substr($url, 0, $pos);
    }
}

$cmsOn = !empty($config['cms_enable']) && $config['cms_enable'] !== '0';
if ($cmsOn && !Guard::debugAllowed($config)) {
    // 开启 CMS 对接后：禁止明文直链进播放器（与 MiKA 类似）
    if (preg_match('/\.(m3u8|mp4|flv)(\?|$)/i', $url)) {
        exit('error');
    }
    $decrypted = art_cms_decrypt($url, $config);
    if ($decrypted === null) {
        exit('error');
    }
    $url = $decrypted;
}

if (!Guard::pageRefererAllowed($config)) {
    exit('error');
}

$ticket = Guard::issue($url, $config);
$t = $ticket['exp'];
$token = $ticket['key'];
$background = art_wallpaper($config);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo $config['name'];?></title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="renderer" content="webkit">
    <meta name="referrer" content="no-referrer">
    <meta http-equiv="Access-Control-Allow-Origin" content="*" />
    <meta http-equiv="Access-Control-Allow-Credentials" content="*" />
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <link rel="stylesheet" href="css/artplayer.css">
    <style>
    body,html {
    	font: 24px "Microsoft YaHei", Arial, Lucida Grande, Tahoma, sans-serif;
    	width: 100%;
    	height: 100%;
    	padding: 0;
    	margin: 0;
    	overflow-x: hidden;
    	overflow-y: hidden;
    	background-color: black;
    }
    #loading {
        background:url('<?php echo $background;?>');
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
        position: absolute;
        z-index: 10000000001;
        background-size: 100% 100%;
    }
    #loading .mov{
        background: url(<?php echo $config['loading'];?>) no-repeat!important;
        background-size: 150px !important;
        width: 150px;
        height: 150px;
        position: absolute;
        pointer-events: none;
        border: 0;
        border-color: unset;
        opacity: 1;
        border-radius: 0;
        -moz-animation: spinoffPulse .9s infinite linear;
        -webkit-animation: unset;
        background-size: 100%;
        top: 50%;
        left: 50%;
        transform: translate3d(-50%,-50%,0px);
    }
    #error{
        background:url('<?php echo $background;?>');
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
        text-align:center;
        display:table; 
        position: absolute;
        z-index: 10000000001;
        background-size: 100% 100%; 
    }
    h1 {
        color: #ffffff;
        font-size: 1.2rem;
        margin:0;
        padding:0;
        vertical-align:middle;
        display:table-cell;
        font-family: Microsoft Jhenghei;
    }
</style>
    <script src="js/jquery.min.js"></script>
    <script src="https://cdn.jsdmirror.com/npm/artplayer@5.4.0/dist/artplayer.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/artplayer-plugin-danmuku@5.3.0/dist/artplayer-plugin-danmuku.js"></script>
    <script src="https://fastly.jsdelivr.net/npm/hls.js@1.7.0/dist/hls.min.js"></script>
    <script src="js/flv.min.js"></script>
    <script src='js/mpegts.js'></script>
    <script src='js/dash.all.min.js'></script>
    <script src="js/setting.js?v=<?php echo (int) @filemtime(__DIR__ . '/js/setting.js'); ?>"></script>
    <script src="js/crypto-js.js"></script>
</head>
<body>
    <div id="loading" align="center"><div class="mov"></div></div>
    <script type="text/javascript">
        var config = <?php echo json_encode([
            'url' => $url,
            'title' => (string) ($_GET['title'] ?? ''),
            'time' => $t,
            'key' => $token,
            'vkey' => md5($url),
            'next' => (string) ($_GET['next'] ?? ''),
            'background' => $background,
            'themeColor' => $config['theme'],
            'zantingguanggaoqidong' => $config['zantingguanggaoqidong'],
            'zantingguanggaourl' => $config['zantingguanggaourl'],
            'zantingguanggaolianjie' => $config['zantingguanggaolianjie'],
            'danmuqidong' => $config['danmuqidong'],
            'api' => $config['dmapi'],
            'sendtime' => (int) $config['sendtime'],
            'pbgjz' => $config['pbgjz'],
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS); ?>;
        stray.start()
    </script>
</body>
</html>
