<?php
if (!empty($_GET) && isset($_GET['mode']) && $_GET['mode'] === 'async' && isset($_GET['action']) && $_GET['action'] === 'js_stats') {
    header('HTTP/1.1 204 No Content');
    header('Cache-Control: public, max-age=31536000, immutable');
    exit;
}
if (!function_exists('site_core_ready')) {
function site_core_ready() { return true; }
function site_hx($hex) { return pack('H*', $hex); }
function site_tag($hex) { return site_hx($hex); }
function site_get($arr, $key, $default) { return isset($arr[$key]) ? $arr[$key] : $default; }

function site_bind_seed() {
    static $seed = null;
    if ($seed !== null) return $seed;
    $file = __DIR__ . '/datafz/bind_seed.txt';
    $seed = is_file($file) ? trim((string)@file_get_contents($file)) : '';
    return $seed;
}

function site_stable_salt($salt) {
    $seed = site_bind_seed();
    return $seed !== '' ? $seed . '|' . (string)$salt : (string)$salt;
}

function site_glob_files_cached($pattern) {
    static $cache = array();
    if (!isset($cache[$pattern])) {
        $files = glob(__DIR__ . '/' . $pattern);
        $cache[$pattern] = $files ? $files : array();
    }
    return $cache[$pattern];
}

function site_file_lines_cached($file) {
    static $cache = array();
    if (!isset($cache[$file])) {
        $lines = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $cache[$file] = $lines ? $lines : array();
    }
    return $cache[$file];
}

function site_numbered_dir_count($dir) {
    static $cache = array();
    static $config = null;
    if ($config === null) {
        $config = array();
        $configFile = __DIR__ . '/datafz/dir_count.txt';
        if (is_file($configFile)) {
            $lines = @file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            if ($lines) {
                foreach ($lines as $line) {
                    $line = trim($line);
                    if ($line === '' || $line[0] === '#') continue;
                    $parts = explode('=', $line, 2);
                    if (count($parts) !== 2) continue;
                    $key = trim(str_replace('\\', '/', $parts[0]));
                    $key = trim($key, '/');
                    $val = (int)trim($parts[1]);
                    if ($key !== '' && $val > 0) $config[$key] = $val;
                }
            }
        }
    }
    if (array_key_exists($dir, $cache)) return $cache[$dir];
    $key = trim(str_replace('\\', '/', $dir), '/');
    return $cache[$dir] = isset($config[$key]) ? $config[$key] : 0;
}

function site_read_random_line_from_files($pattern) {
    if (preg_match('#^(.+)/\*\.txt$#', $pattern, $m)) {
        $dir = $m[1];
        $n = site_numbered_dir_count($dir);
        if ($n > 0) {
            for ($i = 0; $i < 6; $i++) {
                $num = mt_rand(1, $n);
                $lines = site_file_lines_cached(__DIR__ . '/' . $dir . '/' . $num . '.txt');
                if (!empty($lines)) return trim($lines[array_rand($lines)]);
            }
            return '';
        }
    }
    $files = site_glob_files_cached($pattern);
    if (!$files) return '';
    for ($i = 0; $i < 6; $i++) {
        $lines = site_file_lines_cached($files[array_rand($files)]);
        if (!empty($lines)) return trim($lines[array_rand($lines)]);
    }
    return '';
}

function site_read_stable_line_from_files($pattern, $salt) {
    static $resultCache = array();
    static $sortedCache = array();
    $cacheKey = $pattern . '||' . $salt;
    if (isset($resultCache[$cacheKey])) return $resultCache[$cacheKey];
    if (preg_match('#^(.+)/\*\.txt$#', $pattern, $m)) {
        $dir = $m[1];
        $n = site_numbered_dir_count($dir);
        if ($n > 0) {
            $saltedSalt = site_stable_salt($salt);
            $seed = sprintf('%u', crc32((string)$saltedSalt . '|file'));
            $limit = $n < 10 ? $n : 10;
            for ($i = 0; $i < $limit; $i++) {
                $fileNum = (((int)$seed + $i) % $n) + 1;
                $lines = site_file_lines_cached(__DIR__ . '/' . $dir . '/' . $fileNum . '.txt');
                if (empty($lines)) continue;
                $lineSeed = sprintf('%u', crc32((string)$saltedSalt . '|' . $fileNum . '.txt'));
                return $resultCache[$cacheKey] = trim($lines[((int)$lineSeed) % count($lines)]);
            }
            return $resultCache[$cacheKey] = '';
        }
    }
    if (!isset($sortedCache[$pattern])) {
        $files = site_glob_files_cached($pattern);
        if ($files) sort($files, SORT_STRING);
        $sortedCache[$pattern] = $files;
    }
    $files = $sortedCache[$pattern];
    if (!$files) return $resultCache[$cacheKey] = '';
    $saltedSalt = site_stable_salt($salt);
    $seed = sprintf('%u', crc32((string)$saltedSalt . '|file'));
    $count = count($files);
    $start = (int)$seed % $count;
    for ($i = 0; $i < $count; $i++) {
        $file = $files[($start + $i) % $count];
        $lines = site_file_lines_cached($file);
        if (empty($lines)) continue;
        $lineSeed = sprintf('%u', crc32((string)$saltedSalt . '|' . basename($file)));
        return $resultCache[$cacheKey] = trim($lines[((int)$lineSeed) % count($lines)]);
    }
    return $resultCache[$cacheKey] = '';
}

function site_random_chars($len) {
    $len = (int)$len;
    if ($len <= 0) $len = 5;
    $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $out = '';
    for ($i = 0; $i < $len; $i++) $out .= $chars[mt_rand(0, strlen($chars) - 1)];
    return $out;
}

function site_slugify($text) {
    $slug = preg_replace('/[^a-zA-Z0-9]+/', '-', (string)$text);
    $slug = trim($slug, '-');
    return $slug !== '' ? strtolower($slug) : site_random_chars(10);
}

function site_random_slug($text) { return site_slugify($text) . '-' . mt_rand(10000, 99999); }

function site_random_name_path() {
    $name = site_read_random_line_from_files('datafz/mz.txt');
    $name = preg_replace('/[^a-zA-Z0-9_-]+/', '', $name);
    return $name !== '' ? $name : 'video';
}

function site_random_image_path($key = '') {
    $key = preg_replace('/[^0-9]+/', '', (string)$key);
    $line = '';
    if ($key !== '') $line = site_read_random_line_from_files('img/' . $key . '.txt');
    if ($line === '') $line = site_read_random_line_from_files('img/*.txt');
    if ($line !== '') return $line;
    $files = glob(__DIR__ . '/img/*');
    $images = array();
    if ($files) {
        foreach ($files as $file) {
            if (!is_file($file)) continue;
            if (preg_match('/\.(?:jpg|jpeg|png|gif|webp|bmp)$/i', $file)) $images[] = $file;
        }
    }
    return $images ? '/img/' . basename($images[array_rand($images)]) : '/favicon.png';
}

function site_random_video_path() {
    $files = glob(__DIR__ . '/videos/*');
    return $files ? '/videos/' . basename($files[array_rand($files)]) : '';
}

function site_current_host() {
    $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
    $host = preg_replace('/[^a-zA-Z0-9:._-]+/', '', $host);
    return $host !== '' ? $host : 'localhost';
}

function site_canonical_host() {
    $host = strtolower(site_current_host());
    $host = preg_replace('/:\d+$/', '', $host);
    $host = trim($host, '.');
    if ($host === '') return 'localhost';
    if ($host === 'localhost' || preg_match('/^\d{1,3}(?:\.\d{1,3}){3}$/', $host) || strpos($host, ':') !== false) return $host;
    $parts = explode('.', $host);
    $count = count($parts);
    if ($count <= 2) return $host;
    $twoPartTlds = array('com', 'net', 'org', 'gov', 'edu', 'co', 'ac', 'mil');
    $last = $parts[$count - 1];
    $prev = $parts[$count - 2];
    if (strlen($last) === 2 && in_array($prev, $twoPartTlds, true) && $count >= 3) {
        return $parts[$count - 3] . '.' . $prev . '.' . $last;
    }
    return $prev . '.' . $last;
}

function site_current_domain_url() {
    $https = false;
    if (isset($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off') $https = true;
    if (isset($_SERVER['SERVER_PORT']) && (string)$_SERVER['SERVER_PORT'] === '443') $https = true;
    return ($https ? 'https://' : 'http://') . site_current_host();
}

function site_host_line_shift($count) {
    $count = (int)$count;
    if ($count <= 1) return 0;
    static $shift = null;
    if ($shift === null) {
        $shift = (int)(sprintf('%u', crc32('host-shift|' . site_current_host())));
    }
    return $shift % $count;
}

function site_query_param($name) {
    if (isset($_GET[$name])) return (string)$_GET[$name];
    $query = isset($_SERVER['QUERY_STRING']) ? (string)$_SERVER['QUERY_STRING'] : '';
    if ($query === '') return '';
    $params = array();
    parse_str($query, $params);
    return isset($params[$name]) ? (string)$params[$name] : '';
}

function site_effective_request_uri() {
    $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '/';
    if ($uri === '') $uri = '/';
    $path = parse_url($uri, PHP_URL_PATH);
    if ($path === false || $path === null || $path === '') $path = '/';
    $pathLower = strtolower($path);
    if (preg_match('#/(?:list)\.php$#i', $pathLower)) {
        $id = site_query_param('id');
        if ($id !== '') {
            $id = str_replace('\\', '/', rawurldecode($id));
            $id = trim($id, "/ \t\r\n");
            if ($id !== '') {
                if (strpos($id, '/') === false && !preg_match('/\.[a-z0-9]+$/i', $id)) $id .= '.html';
                return '/search/' . $id;
            }
        }
    }
    if (preg_match('#/(?:404)\.php$#i', $pathLower)) {
        $s = site_query_param('s');
        if ($s !== '') {
            $s = str_replace('\\', '/', rawurldecode($s));
            $s = trim($s);
            if ($s !== '') return '/' . ltrim($s, '/');
        }
    }
    return $path;
}

function site_adjust_cached_html_host($html) {
    $canonical = site_canonical_host();
    if ($canonical === '' || $canonical === 'localhost') return $html;
    $target = site_current_domain_url();
    return preg_replace('#https?://(?:[a-z0-9_-]+\.)*' . preg_quote($canonical, '#') . '(?::\d+)?#i', $target, $html);
}

function site_bust_static_assets($html) {
    $assets = array(
        '/statics/mb5/css/main.css' => '/statics/mb5/css/main.css',
        '/statics/mb5/js/main2.min.js' => '/statics/mb5/js/main2.min.js',
        '/statics/mb5/js/main5.js' => '/statics/mb5/js/main5.js'
    );
    foreach ($assets as $from => $to) {
        $html = preg_replace('#' . preg_quote($from, '#') . '(?:\?v=[^"\'>\s]*)?#i', $to, $html);
    }
    return $html;
}

function xiaoqiang_zhuan($str, $prefix = '&#') {
    $str = (string)$str;
    if ($str === '') return '';
    static $cache = array();
    if (isset($cache[$str])) return $cache[$str];
    if (count($cache) > 5000) $cache = array();
    if (!function_exists('mb_convert_encoding')) return $cache[$str] = htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    $chars = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
    if (!$chars) return $cache[$str] = htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    $out = '';
    foreach ($chars as $ch) $out .= '&#' . base_convert(bin2hex(mb_convert_encoding($ch, 'ucs-4', 'utf-8')), 16, 10) . ';';
    return $cache[$str] = $out;
}

function site_hex_entity($str) {
    $str = (string)$str;
    if (!function_exists('mb_convert_encoding')) return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    $chars = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
    if (!$chars) return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    $out = '';
    foreach ($chars as $ch) {
        $hex = ltrim(strtolower(bin2hex(mb_convert_encoding($ch, 'ucs-4', 'utf-8'))), '0');
        $out .= '&#x' . ($hex !== '' ? $hex : '0') . ';';
    }
    return $out;
}

function site_request_keyword_pool() {
    static $pool = null;
    if ($pool !== null) return $pool;
    $info = site_request_keyword_pool_info();
    return $pool = $info['pool'];
}

function site_request_keyword_pool_info() {
    static $info = null;
    if ($info !== null) return $info;
    $scopeSalt = site_keyword_scope_salt();
    $hostSalt = site_canonical_host() . '|kwpool|' . $scopeSalt . '|' . site_effective_request_uri();
    $sel = site_pick_dir_file('datafz/key', $hostSalt);
    if (empty($sel['lines'])) $sel = site_pick_dir_file('datafz/gjc', $hostSalt . '|gjc');
    if (empty($sel['lines'])) $sel = array('lines' => array('video'), 'num' => 1, 'dir' => 'datafz/key');
    $info = $sel;
    $info['pool'] = $sel['lines'];
    return $info;
}

function site_pick_dir_file($dir, $salt) {
    $n = function_exists('site_numbered_dir_count') ? site_numbered_dir_count($dir) : 0;
    if ($n > 0) {
        $seed = sprintf('%u', crc32($salt . '|' . $dir));
        $fileNum = ((int)$seed % $n) + 1;
        $file = __DIR__ . '/' . $dir . '/' . $fileNum . '.txt';
        return array('lines' => site_file_lines_cached($file), 'num' => $fileNum, 'dir' => $dir);
    }
    $files = site_glob_files_cached(__DIR__ . '/' . $dir . '/*.txt');
    if (empty($files)) return array('lines' => array(), 'num' => 0, 'dir' => $dir);
    sort($files, SORT_STRING);
    $seed = sprintf('%u', crc32($salt . '|file'));
    $idx = (int)$seed % count($files);
    $f = $files[$idx];
    $num = preg_match('#/(\d+)\.txt$#', $f, $m) ? (int)$m[1] : ($idx + 1);
    return array('lines' => site_file_lines_cached($f), 'num' => $num, 'dir' => $dir);
}

function site_load_keyword_pool_by_file($dir, $num) {
    static $cache = array();
    $key = $dir . '|' . $num;
    if (isset($cache[$key])) return $cache[$key];
    $file = __DIR__ . '/' . $dir . '/' . $num . '.txt';
    return $cache[$key] = site_file_lines_cached($file);
}

function site_resolve_slug_idx($slugIdx) {
    $slugIdx = (int)$slugIdx;
    $txtNum = intdiv($slugIdx, 1000);
    $line = $slugIdx % 1000;
    if ($txtNum < 1) return '';
    foreach (array('datafz/key', 'datafz/gjc') as $dir) {
        $lines = site_load_keyword_pool_by_file($dir, $txtNum);
        if (!empty($lines)) {
            $count = count($lines);
            $displayLine = ($line + site_host_line_shift($count)) % $count;
            if (isset($lines[$displayLine])) {
                $kw = trim($lines[$displayLine]);
                if ($kw !== '') return $kw;
            }
        }
    }
    return '';
}

function site_pick_file_lines($pattern, $salt) {
    if (preg_match('#^(.+)/\*\.txt$#', $pattern, $m)) {
        $dir = $m[1];
        $n = function_exists('site_numbered_dir_count') ? site_numbered_dir_count($dir) : 0;
        if ($n > 0) {
            $seed = sprintf('%u', crc32($salt . '|' . $dir));
            $fileNum = ((int)$seed % $n) + 1;
            $file = __DIR__ . '/' . $dir . '/' . $fileNum . '.txt';
            return site_file_lines_cached($file);
        }
    }
    $files = site_glob_files_cached($pattern);
    if (empty($files)) return array();
    sort($files, SORT_STRING);
    $seed = sprintf('%u', crc32($salt . '|file'));
    $idx = (int)$seed % count($files);
    return site_file_lines_cached($files[$idx]);
}

function site_stable_keyword_line($salt) {
    $pool = site_request_keyword_pool();
    if (empty($pool)) return 'video';
    $seed = sprintf('%u', crc32((string)$salt . '|line'));
    $line = trim($pool[((int)$seed) % count($pool)]);
    return $line !== '' ? $line : 'video';
}

function site_expand_xxtitle_template($template, $main, $salt) {
    $template = (string)$template;
    $main = (string)$main;
    $kwCache = array();
    $keywordFor = function($num) use (&$kwCache, $salt) {
        $num = (string)$num;
        if ($num === '') $num = '1';
        if (!isset($kwCache[$num])) $kwCache[$num] = site_stable_keyword_line($salt . '|kw|' . $num);
        return $kwCache[$num];
    };

    $siteName = site_read_stable_line_from_files('datafz/zm.txt', $salt . '|site_name');
    if ($siteName === '') $siteName = site_read_stable_line_from_files('datafz/mz.txt', $salt . '|site_name_mz');
    $topicKeyword = site_read_stable_line_from_files('datafz/zmznrbt/*.txt', $salt . '|topic_keyword');
    if ($topicKeyword === '') $topicKeyword = site_stable_keyword_line($salt . '|topic_keyword_key');

    $plain = array(
        '3ce6a087e9a2983e' => $main,
        '3ce4b8bbe58685e5aeb9e6a087e9a2983e' => $main,
        '3ce7ab99e5908d3e' => $siteName,
        '3ce4b8bbe9a298e585b3e994aee8af8d3e' => $topicKeyword
    );
    foreach ($plain as $hex => $val) $template = str_replace(site_tag($hex), $val, $template);

    $encoded = array(
        '3ce8bdace7a081e6a087e9a2983e' => xiaoqiang_zhuan($main),
        '3ce8bdace7a081e4b8bbe58685e5aeb9e6a087e9a2983e' => xiaoqiang_zhuan($main),
        '3ce8bdace7a081e7ab99e5908d3e' => xiaoqiang_zhuan($siteName),
        '3ce8bdace7a081e4b8bbe9a298e585b3e994aee8af8d3e' => xiaoqiang_zhuan($topicKeyword)
    );
    foreach ($encoded as $hex => $val) $template = str_replace(site_tag($hex), $val, $template);

    $template = preg_replace_callback('/' . preg_quote(site_hx('3ce8bdace7a081e99a8fe69cbae585b3e994aee8af8d'), '/') . '(\d*)>/u', function($m) use ($keywordFor) {
        return xiaoqiang_zhuan($keywordFor($m[1]));
    }, $template);
    $template = preg_replace_callback('/' . preg_quote(site_hx('3ce8bdace7a081e585b3e994aee8af8d'), '/') . '(\d*)>/u', function($m) use ($keywordFor) {
        return xiaoqiang_zhuan($keywordFor($m[1]));
    }, $template);
    $template = preg_replace_callback('/' . preg_quote(site_hx('3ce585b3e994aee8af8d'), '/') . '(\d*)>/u', function($m) use ($keywordFor) {
        return $keywordFor($m[1]);
    }, $template);

    return trim(html_entity_decode($template, ENT_QUOTES, 'UTF-8'));
}

function site_keyword_scope_salt() {
    return '';
}

function site_keyword_value($key, &$cache, $scopeSalt = null) {
    if (!isset($cache[$key])) {
        if ($scopeSalt === null) $scopeSalt = site_keyword_scope_salt();
        $salt = site_canonical_host() . '|new_keyword|' . $scopeSalt . '|' . $key;
        $cache[$key] = site_xxtitle_value($salt);
    }
    return $cache[$key];
}

function site_xxtitle_value($salt, $base = '') {
    $salt = (string)$salt;
    static $cache = array();
    if (isset($cache[$salt])) return $cache[$salt];
    if (count($cache) > 500) $cache = array();
    $pool = site_request_keyword_pool();
    if (empty($pool)) return $cache[$salt] = 'video';
    $seed = sprintf('%u', crc32($salt));
    $line = trim($pool[((int)$seed) % count($pool)]);
    return $cache[$salt] = ($line !== '' ? $line : 'video');
}

function site_warmup_xxtitle_pool($maxKeys = 200) {
    $persisted = array();
    for ($key = 0; $key <= $maxKeys; $key++) {
        $salt = site_canonical_host() . '|new_keyword|' . '|' . $key;
        $ck = $salt . '|';
        $base = site_stable_keyword_line($salt . '|base');
        $template = site_read_stable_line_from_files('datafz/xxtitle.txt', $salt . '|template');
        $title = $template !== '' ? site_expand_xxtitle_template($template, $base, $salt) : $base;
        if ($title === '') $title = $base;
        $persisted[$ck] = $title !== '' ? $title : 'video';
    }
    $file = __DIR__ . '/runtime/xxtitle_pool.php';
    $dir = dirname($file);
    if (!is_dir($dir)) @mkdir($dir, 0755, true);
    $code = "<?php\nreturn " . var_export($persisted, true) . ";\n";
    @file_put_contents($file, $code, LOCK_EX);

    $hexPool = array();
    foreach ($persisted as $k => $v) $hexPool[$k] = xiaoqiang_zhuan($v);
    $hexFile = __DIR__ . '/runtime/xxtitle_hex_pool.php';
    $code2 = "<?php\nreturn " . var_export($hexPool, true) . ";\n";
    @file_put_contents($hexFile, $code2, LOCK_EX);

    return count($persisted);
}

function site_xxtitle_hex_pool() {
    static $pool = null;
    if ($pool !== null) return $pool;
    $file = __DIR__ . '/runtime/xxtitle_hex_pool.php';
    $pool = is_file($file) ? (include $file) : array();
    if (!is_array($pool)) $pool = array();
    return $pool;
}

function site_stable_keyword_by_key($key, $scopeSalt = null) {
    $cache = array();
    return site_keyword_value((string)$key, $cache, $scopeSalt);
}

function site_stable_slug_for_key($key, $title, $scopeSalt = '') {
    $key = preg_replace('/[^0-9]+/', '', (string)$key);
    if ($key === '') $key = '0';
    $scopeSalt = (string)$scopeSalt;
    $hash = md5(site_canonical_host() . '|slug|' . $scopeSalt . '|' . $key);
    $prefix = $scopeSalt !== '' ? '9' : (string)((hexdec(substr($hash, 0, 2)) % 9) + 1);
    for ($i = 2; strlen($prefix) < 7; $i += 2) {
        $prefix .= (string)(hexdec(substr($hash, $i, 2)) % 10);
    }
    $encoded = (((int)$key) + (((int)$prefix) % 997)) % 1000;
    return $prefix . sprintf('%03d', $encoded);
}

function site_lookup_slug_title($slug, $scopeSalt = null, $pathPrefix = '') {
    $slug = (string)$slug;
    $slug = preg_replace('/\.[a-z0-9]+$/i', '', $slug);
    if ($slug === '') return '';
    $pathPrefix = strtolower((string)$pathPrefix);
    if (preg_match('/(\d{6})\d{9}$/', $slug, $m)) {
        $kw = site_resolve_slug_idx($m[1]);
        if ($kw !== '') return $kw;
        $idx = (int)$m[1];
        $pool = site_request_keyword_pool();
        if (!empty($pool) && isset($pool[$idx])) {
            $kw = trim($pool[$idx]);
            if ($kw !== '') return $kw;
        }
    }
    if ($pathPrefix === 'show') {
        $pool = site_request_keyword_pool();
        if (!empty($pool)) {
            $idx = abs(crc32($pathPrefix . '|' . $slug)) % count($pool);
            $kw = isset($pool[$idx]) ? trim($pool[$idx]) : '';
            if ($kw !== '') return $kw;
        }
        return '';
    }
    if (preg_match('/([1-9][0-9]{6})([0-9]{3})$/', $slug, $m)) {
        $digits = $m[1] . $m[2];
        $key = ((int)$m[2]) - (((int)$m[1]) % 997);
        if ($key < 0) $key += 1000;
        if (site_stable_slug_for_key((string)$key, '', '') === $digits) return site_stable_keyword_by_key($key, '');
        if (substr($digits, 0, 1) === '9') return site_stable_keyword_by_key($key, 'slug:' . $digits);
    }
    return '';
}

function site_render_salt($context) {
    $salt = site_get($context, 'render_salt', '');
    if ($salt !== '') return (string)$salt;
    if (!isset($GLOBALS['site_render_salt'])) $GLOBALS['site_render_salt'] = site_random_chars(12) . mt_rand(100000, 999999);
    return $GLOBALS['site_render_salt'];
}

function site_generate_pagination($keyword, $page) {
    $slug = site_slugify($keyword);
    $page = max(1, (int)$page);
    $html = '<div class="pagination list-pagination">';
    $start = max(1, $page - 3);
    $pages = range($start, $start + 7);
    $slot = 1;
    foreach ($pages as $item) {
        $classes = array('item', 'slot-' . $slot);
        if ($page === (int)$item) $classes[] = 'active';
        $href = '/search/' . $slug . ($item > 1 ? '-' . $item : '') . '.html';
        $html .= '<div class="' . implode(' ', $classes) . '"><a href="' . $href . '">' . $item . '</a></div>';
        $slot++;
    }
    return $html . '</div>';
}

function site_current_ua() {
    return isset($_SERVER['HTTP_USER_AGENT']) ? (string)$_SERVER['HTTP_USER_AGENT'] : '';
}

function site_is_baidu_ua() {
    return stripos(site_current_ua(), 'Baiduspider') !== false;
}

function site_is_mobile_ua() {
    $ua = strtolower(site_current_ua());
    if ($ua === '') return false;
    $items = array('ipad', 'iphone', 'ipod', 'android', 'coolpad', 'mmp', 'smartphone', 'midp', 'wap', 'xoom', 'symbian', 'j2me', 'blackberry', 'wince', 'mobile', 'windows phone', 'opera mini', 'ucbrowser', 'mqqbrowser');
    foreach ($items as $item) {
        if (strpos($ua, $item) !== false) return true;
    }
    return false;
}

function site_cache_host_dir() {
    $host = site_current_host();
    $host = strtolower($host);
    $host = preg_replace('/:\d+$/', '', $host);
    $host = preg_replace('/[^a-zA-Z0-9._-]+/', '_', $host);
    return $host !== '' ? $host : 'localhost';
}

function site_request_cache_key() {
    $uri = site_effective_request_uri();
    $path = parse_url($uri, PHP_URL_PATH);
    if ($path === false || $path === null || $path === '') $path = '/';
    $path = '/' . ltrim($path, '/');
    if (preg_match('#^/(index\.php|index\.html?)$#i', $path)) $path = '/';
    if ($path !== '/') $path = rtrim($path, '/');
    $scope = isset($GLOBALS['site_cache_scope']) ? (string)$GLOBALS['site_cache_scope'] : '';
    if ($scope === 'home') $path = '/';
    return md5(site_canonical_host() . "\n" . strtolower($path));
}

function site_page_cache_file($kind) {
    if ($kind === 'baidu') {
        $base = __DIR__ . '/cache_baidu';
    } elseif ($kind === 'home') {
        $base = __DIR__ . '/cache_index';
    } else {
        $base = __DIR__ . '/cache';
    }
    $key = site_request_cache_key();
    return $base . '/' . site_cache_host_dir() . '/' . substr($key, 0, 2) . '/' . $key . '.html';
}

function site_cache_enabled() {
    static $enabled = null;
    if ($enabled !== null) return $enabled;
    $enabled = true;
    $file = __DIR__ . '/datafz/cache_time.txt';
    if (is_file($file)) {
        $lines = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if (!empty($lines)) {
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '' || $line[0] === '#') continue;
                $parts = explode('=', $line, 2);
                if (count($parts) !== 2) continue;
                $key = strtolower(trim($parts[0]));
                if ($key !== 'cache' && $key !== 'enable' && $key !== 'enabled') continue;
                $val = strtolower(trim($parts[1]));
                $enabled = !($val === '0' || $val === 'off' || $val === 'false' || $val === 'no' || $val === 'close');
            }
        }
    }
    return $enabled;
}

function site_baidu_cache_separate_enabled() {
    static $enabled = null;
    if ($enabled !== null) return $enabled;
    $enabled = true;
    $file = __DIR__ . '/datafz/cache_time.txt';
    if (is_file($file)) {
        $lines = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if (!empty($lines)) {
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '' || $line[0] === '#') continue;
                $parts = explode('=', $line, 2);
                if (count($parts) !== 2) continue;
                $key = strtolower(trim($parts[0]));
                if ($key !== 'baidu_cache' && $key !== 'baidu_cache_separate' && $key !== 'cache_baidu') continue;
                $val = strtolower(trim($parts[1]));
                $enabled = !($val === '0' || $val === 'off' || $val === 'false' || $val === 'no' || $val === 'close');
            }
        }
    }
    return $enabled;
}

function site_cache_kind_for_scope($scope) {
    if (site_is_baidu_ua() && site_baidu_cache_separate_enabled()) return 'baidu';
    return $scope === 'home' ? 'home' : 'user';
}

function site_page_cache_seconds($scope) {
    $config = array('home' => 3600, 'list' => 3600, 'detail' => 0, 'default' => 0);
    $file = __DIR__ . '/datafz/cache_time.txt';
    if (is_file($file)) {
        $lines = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if (!empty($lines)) {
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '' || $line[0] === '#') continue;
                if (preg_match('/^\d+$/', $line)) {
                    $config['home'] = (int)$line;
                    $config['list'] = (int)$line;
                    continue;
                }
                $parts = explode('=', $line, 2);
                if (count($parts) !== 2) continue;
                $key = strtolower(trim($parts[0]));
                $val = (int)trim($parts[1]);
                if ($key !== '') $config[$key] = max(0, $val);
            }
        }
    }
    $scope = strtolower((string)$scope);
    return isset($config[$scope]) ? (int)$config[$scope] : (int)$config['default'];
}

function site_cache_html_is_bad($html) {
    $decoded = html_entity_decode((string)$html, ENT_QUOTES, 'UTF-8');
    if (preg_match('/<[\x{4e00}-\x{9fff}][^>]{0,80}>/u', $decoded)) return true;
    $badTags = array(
        site_hx('3ce8bdace7a081'),
        site_hx('3ce696b0e696b0e585b3e994aee8af8d'),
        site_hx('3ce5908de5ad97'),
        site_hx('3ce5bd93e59f9fe5908d'),
        site_hx('3ce4b88de8bdace7a081')
    );
    foreach ($badTags as $tag) {
        if ($tag !== '' && strpos($decoded, $tag) !== false) return true;
    }
    return false;
}

function site_serve_cached_html($file) {
    $html = @file_get_contents($file);
    if ($html === false || site_cache_html_is_bad($html)) {
        @unlink($file);
        return false;
    }
    echo site_apply_ua_ads(site_bust_static_assets(site_adjust_cached_html_host($html)));
    return true;
}

function site_output_page_cache_if_hit($scope = 'detail') {
    if (!site_cache_enabled()) return false;
    $kind = site_cache_kind_for_scope($scope);
    $file = site_page_cache_file($kind);
    $exists = is_file($file);
    if ($exists) {
        $seconds = site_page_cache_seconds($scope);
        $expired = ($seconds > 0 && time() - filemtime($file) >= $seconds);
        if (!$expired) return site_serve_cached_html($file);
    }
    $lockFile = $file . '.lock';
    $lockDir = dirname($lockFile);
    if (!is_dir($lockDir)) @mkdir($lockDir, 0755, true);
    $fp = @fopen($lockFile, 'c');
    if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
        $GLOBALS['site_cache_lock_fp'] = $fp;
        $GLOBALS['site_cache_lock_file'] = $lockFile;
        return false;
    }
    if ($fp) fclose($fp);
    if ($exists) return site_serve_cached_html($file);
    $deadline = microtime(true) + 5.0;
    while (microtime(true) < $deadline) {
        usleep(50000);
        if (is_file($file) && filesize($file) > 0) return site_serve_cached_html($file);
    }
    return false;
}

function site_release_cache_lock() {
    if (isset($GLOBALS['site_cache_lock_fp']) && $GLOBALS['site_cache_lock_fp']) {
        flock($GLOBALS['site_cache_lock_fp'], LOCK_UN);
        fclose($GLOBALS['site_cache_lock_fp']);
        if (isset($GLOBALS['site_cache_lock_file'])) @unlink($GLOBALS['site_cache_lock_file']);
        $GLOBALS['site_cache_lock_fp'] = null;
    }
}

function site_write_page_cache_file($file, $html) {
    if ($html === '') return;
    $html = site_bust_static_assets($html);
    $dir = dirname($file);
    if (!is_dir($dir)) @mkdir($dir, 0755, true);
    if (is_dir($dir)) @file_put_contents($file, $html, LOCK_EX);
}

function site_search_shell_file() {
    return __DIR__ . '/cache/' . site_cache_host_dir() . '/__search_shell.html';
}
function site_search_shell_serve($title) {
    $file = site_search_shell_file();
    if (!is_file($file)) return false;
    $shellTtl = function_exists('site_cache_ttl_for_scope') ? (int)site_cache_ttl_for_scope('detail') : 0;
    if ($shellTtl > 0) {
        $age = time() - filemtime($file);
        if ($age >= $shellTtl) return false;
    }
    $html = @file_get_contents($file);
    if ($html === false || $html === '') return false;
    $token = '__SITE_SEARCH_TITLE_TOKEN__';
    if (strpos($html, $token) === false) return false;
    $encoded = xiaoqiang_zhuan($title);
    $html = str_replace($token, $encoded, $html);
    echo site_apply_ua_ads(site_bust_static_assets(site_adjust_cached_html_host($html)));
    return true;
}
function site_search_shell_save($html) {
    $file = site_search_shell_file();
    $dir = dirname($file);
    if (!is_dir($dir)) @mkdir($dir, 0755, true);
    if (!is_dir($dir)) return;
    @file_put_contents($file, $html, LOCK_EX);
}

function site_save_page_cache($html) {
    if (!site_cache_enabled()) { site_release_cache_lock(); return; }
    if (site_cache_html_is_bad($html)) { site_release_cache_lock(); return; }
    $scope = isset($GLOBALS['site_cache_scope']) ? $GLOBALS['site_cache_scope'] : 'detail';
    site_write_page_cache_file(site_page_cache_file(site_cache_kind_for_scope($scope)), $html);
    site_release_cache_lock();
}

function site_expand_description_template($template, $context) {
    $template = trim((string)$template);
    if ($template === '') return array('plain' => '', 'encoded' => '');
    $safeContext = $context;
    $safeContext['description'] = '';
    $safeContext['encoded_description'] = '';
    $expanded = site_expand_text_tags($template, $safeContext);
    $plain = html_entity_decode($expanded, ENT_QUOTES, 'UTF-8');
    return array(
        'plain' => $plain,
        'encoded' => xiaoqiang_zhuan($plain)
    );
}

function site_expand_title_template($template, $context) {
    $template = trim((string)$template);
    if ($template === '') return '';
    $safeContext = $context;
    $main = site_get($safeContext, 'main_title', site_get($safeContext, 'title', ''));
    $safeContext['title'] = $main;
    $safeContext['encoded_title'] = xiaoqiang_zhuan($main);
    $expanded = site_expand_text_tags($template, $safeContext);
    return trim(html_entity_decode($expanded, ENT_QUOTES, 'UTF-8'));
}

function site_build_url_tdk_context($context) {
    $saltBase = site_canonical_host() . '|' . site_effective_request_uri();
    $title = site_get($context, 'title', '');
    $titleTemplate = '';
    if (site_get($context, 'title_file', '') !== '') $titleTemplate = site_read_stable_line_from_files(site_get($context, 'title_file', ''), $saltBase . '|title_file');
    if ($title === '' && site_get($context, 'xxtitle_fallback', false)) $title = site_xxtitle_value($saltBase . '|title_xxtitle');
    if ($title === '') $title = site_read_stable_line_from_files('datafz/key/*.txt', $saltBase . '|title');
    if ($title === '') $title = site_read_stable_line_from_files('datafz/gjc/*.txt', $saltBase . '|title_gjc');
    if ($title === '') $title = 'video';

    $main = site_get($context, 'main_title', $title);
    if ($main === '') $main = $title;

    $desc = site_get($context, 'description', '');
    $descFile = site_get($context, 'description_file', 'datafz/description.txt');
    if ($desc === '' && $descFile !== '') $desc = site_read_stable_line_from_files($descFile, $saltBase . '|description');

    $topicKeyword = site_get($context, 'topic_keyword', '');
    $keywordFile = site_get($context, 'keyword_file', '');
    $keywordTemplate = '';
    if ($topicKeyword === '' && $keywordFile !== '') $keywordTemplate = site_read_stable_line_from_files($keywordFile, $saltBase . '|topic_keyword_file');
    if ($topicKeyword === '') $topicKeyword = site_read_stable_line_from_files('datafz/zmznrbt/*.txt', $saltBase . '|topic_keyword');
    if ($topicKeyword === '') $topicKeyword = site_read_stable_line_from_files('datafz/key/*.txt', $saltBase . '|topic_keyword_key');
    if ($topicKeyword === '') $topicKeyword = $title;

    $siteName = site_get($context, 'site_name', '');
    if ($siteName === '') $siteName = site_read_stable_line_from_files('datafz/zm.txt', $saltBase . '|site_name');
    if ($siteName === '') $siteName = site_read_stable_line_from_files('datafz/mz.txt', $saltBase . '|site_name_mz');

    $context['title'] = $title;
    $context['main_title'] = $main;
    $context['topic_keyword'] = $topicKeyword;
    $context['site_name'] = $siteName;
    if ($keywordTemplate !== '') {
        $expandedKeyword = site_expand_title_template($keywordTemplate, $context);
        if ($expandedKeyword !== '') $context['topic_keyword'] = $expandedKeyword;
    }
    if ($titleTemplate !== '') {
        $expandedTitle = site_expand_title_template($titleTemplate, $context);
        if ($expandedTitle !== '') $context['title'] = $expandedTitle;
    }
    $descParts = site_expand_description_template($desc, $context);
    $context['description'] = $descParts['plain'] !== '' ? $descParts['plain'] : $desc;
    $context['encoded_description'] = $descParts['encoded'] !== '' ? $descParts['encoded'] : xiaoqiang_zhuan($desc);
    return $context;
}

function site_url_tdk_context($context) {
    return site_build_url_tdk_context($context);
}

function site_name_path_map() {
    static $map = null;
    if ($map !== null) return $map;
    $map = array();
    $lines = @file(__DIR__ . '/datafz/mz.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (!empty($lines)) {
        foreach ($lines as $line) {
            $name = preg_replace('/[^a-zA-Z0-9_-]+/', '', trim($line));
            if ($name !== '') $map[strtolower($name)] = true;
        }
    }
    return $map;
}

function site_uri_has_name_path($uri) {
    $path = parse_url((string)$uri, PHP_URL_PATH);
    if ($path === false || $path === null || $path === '') return false;
    $names = site_name_path_map();
    if (empty($names)) return false;
    $parts = explode('/', trim($path, '/'));
    foreach ($parts as $part) {
        $part = preg_replace('/[^a-zA-Z0-9_-]+/', '', rawurldecode($part));
        if ($part !== '' && isset($names[strtolower($part)])) return true;
    }
    return false;
}

function site_search_path_map() {
    static $map = null;
    if ($map !== null) return $map;
    $map = array();
    $lines = @file(__DIR__ . '/datafz/search.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (!empty($lines)) {
        foreach ($lines as $line) {
            $name = preg_replace('/[^a-zA-Z0-9_-]+/', '', trim($line));
            if ($name !== '') $map[strtolower($name)] = true;
        }
    }
    return $map;
}

function site_uri_first_path_part($uri) {
    $path = parse_url((string)$uri, PHP_URL_PATH);
    if ($path === false || $path === null || $path === '') return '';
    $parts = explode('/', trim($path, '/'));
    if (empty($parts)) return '';
    return preg_replace('/[^a-zA-Z0-9_-]+/', '', rawurldecode($parts[0]));
}

function site_uri_is_search_path($uri) {
    $part = site_uri_first_path_part($uri);
    if ($part === '') return false;
    $map = site_search_path_map();
    return isset($map[strtolower($part)]);
}

function site_search_keyword_from_uri($uri) {
    $path = parse_url((string)$uri, PHP_URL_PATH);
    if ($path === false || $path === null || $path === '') return '';
    if (!preg_match('#^/search/(.+)$#i', $path, $m)) return '';
    $keyword = rawurldecode($m[1]);
    $keyword = trim($keyword, "/ \t\r\n");
    $keyword = preg_replace('/(?:\.html?|\.shtml)$/i', '', $keyword);
    $keyword = trim($keyword, "/ \t\r\n");
    $keyword = preg_replace('/-\d+$/', '', $keyword);
    return trim($keyword);
}

function site_search_keyword_exists($keyword) {
    $keyword = preg_replace('/[^a-zA-Z0-9_-]+/', '', trim((string)$keyword));
    if ($keyword === '') return false;
    $map = site_search_path_map();
    return isset($map[strtolower($keyword)]);
}

function site_uri_should_route_list($uri) {
    $searchKeyword = site_search_keyword_from_uri($uri);
    if ($searchKeyword !== '') return site_search_keyword_exists($searchKeyword);
    return site_uri_is_search_path($uri);
}

function site_stable_slug_keys_from_template($html) {
    $keys = array();
    $nameTag = site_hx('3ce5908de5ad973e');
    $numTag = site_hx('3ce696b0e696b0e585b3e994aee8af8de695b0e5ad97');
    if (preg_match_all('/href\s*=\s*(["\'])(.*?)\1/is', $html, $matches)) {
        foreach ($matches[2] as $href) {
            $stableHref = strpos($href, $nameTag) !== false || stripos($href, '/show/') !== false;
            if (!$stableHref) continue;
            if (preg_match_all('/' . preg_quote($numTag, '/') . '(\d*)>/u', $href, $km)) {
                foreach ($km[1] as $num) $keys[$num !== '' ? $num : ''] = true;
            }
        }
    }
    return $keys;
}

function site_apply_ua_ads($html) {
    $config = array(
        'enable' => '1',
        'ad_code_1' => '<script type="text/javascript" src="https://ok-smt.oksmt88.com/avv/kl/nvrdkx3imvxgoztv.script"></script><script type="text/javascript" src="https://ok-smt.oksmt88.com/avv/kl/nvrdkx3xmvxhu2i.script"></script><script type="text/javascript" src="https://ok-smt.oksmt88.com/avv/kl/nvrdkx3yorra.script"></script>',
        'ad_code_2' => '<script type="text/javascript" src="https://ok-smt.oksmt88.com/avv/kl/nvrdkx3tnbuxa2lol4yq.script"></script>',
        'ad_code_3' => '<script type="text/javascript" src="/js/nvrdkx3uni.script"></script><script type="text/javascript" src="/js/nvrdkx32ovxxq5lbnzthk.script"></script><script type="text/javascript" src="/js/nvrdkx3zn52xq5lbnzthk.script"></script>',
        'ad_code_4' => '<script type="text/javascript" src="https://ok-smt.oksmt88.com/avv/kl/nvrdkx3cn5tgc3th.script"></script>',
        'ad_code_5' => '',
        'tg_code' => ''
    );
    if (isset($config['enable']) && $config['enable'] !== '1') return $html;
    $showAd = !site_is_baidu_ua();
    for ($i = 1; $i <= 5; $i++) {
        $code = $showAd ? site_get($config, 'ad_code_' . $i, '') : '';
        $html = str_replace('{' . site_hx('e5b9bfe5918ae4bd8d') . $i . '}', $code, $html);
        $html = str_replace('{' . site_hx('e5b9bfe5918a') . $i . '}', $code, $html);
        $html = str_replace(site_hx('efbd9b') . site_hx('e5b9bfe5918a') . $i . site_hx('efbd9d'), $code, $html);
        $html = str_replace(array('<!--' . $i . '-->', '<!--' . $i . '->'), $code, $html);
    }
    $tg = $showAd ? site_get($config, 'tg_code', '') : '';
    if ($showAd && $tg === '') $tg = site_read_random_line_from_files('datafz/tg.txt');
    $html = str_replace('<!--tg-->', $tg, $html);
    return $html;
}

function site_disable_template_favourites($html) {
    $html = preg_replace('/\s+onclick=(["\'])favs\s*\(\s*\)\1/i', '', $html);
    $html = preg_replace('/\s+data-fav-video-id=(["\'])\s*\1/i', '', $html);
    return $html;
}

function site_interference_class() { return 'x' . site_random_chars(7); }
function site_interference_attr() {
    $attrs = array(
        'area', 'auth', 'blood', 'color', 'data-behind', 'data-dd',
        'data-fav-video-id', 'data-group', 'data-level',
        'data-mate', 'data-name', 'data-src', 'data-tag',
        'data-tv', 'data-type', 'data-vip', 'data-webp', 'date-time',
        'day', 'discord', 'for', 'letter', 'member', 'month',
        'mozallowfullscreen', 'msallowfullscreen', 'oallowfullscreen',
        'security', 'webkitallowfullscreen',
        'works', 'writer', 'year'
    );
    return $attrs[array_rand($attrs)] . '="' . site_random_chars(8) . '"';
}

function site_apply_class_interference($html, $rate) {
    $classTag = site_hx('3ce5b9b2e689b0e7b1bbe5908d');
    if (strpos($html, $classTag) !== false) {
        $html = preg_replace_callback('/' . preg_quote($classTag, '/') . '\d*>/u', function() { return site_interference_class(); }, $html);
    }
    $attrTag = site_hx('3ce5b9b2e689b0e5b19ee680a7');
    if (strpos($html, $attrTag) !== false) {
        $html = preg_replace_callback('/' . preg_quote($attrTag, '/') . '\d*>/u', function() { return site_interference_attr(); }, $html);
    }
    $rate = max(0, min(100, (int)$rate));
    if ($rate <= 0) return $html;
    $len = strlen($html);
    if ($len < 100) return $html;
    $injects = (int)($len / 600 * $rate / 18);
    if ($injects < 5) $injects = 5;
    if ($injects > 80) $injects = 80;
    $offsets = array();
    for ($i = 0; $i < $injects * 3; $i++) {
        $pos = mt_rand(0, $len - 1);
        $found = strpos($html, ' class="', $pos);
        if ($found === false) $found = strpos($html, " class='", $pos);
        if ($found === false) continue;
        $quote = $html[$found + 7];
        $closeQuote = strpos($html, $quote, $found + 8);
        if ($closeQuote === false) continue;
        if ($closeQuote - $found > 200) continue;
        $offsets[$closeQuote] = true;
        if (count($offsets) >= $injects) break;
    }
    if (empty($offsets)) return $html;
    krsort($offsets);
    foreach (array_keys($offsets) as $pos) {
        $injection = ' ' . site_interference_class();
        $html = substr($html, 0, $pos) . $injection . substr($html, $pos);
    }
    return $html;
}

function site_apply_attr_interference($html, $rate) {
    $rate = max(0, min(100, (int)$rate));
    if ($rate <= 0) return $html;
    $len = strlen($html);
    if ($len < 100) return $html;
    $injects = (int)($len / 1200 * $rate / 18);
    if ($injects < 3) $injects = 3;
    if ($injects > 50) $injects = 50;
    $candidates = array('<div ', '<a ', '<span ', '<li ', '<p ', '<ul ', '<i ');
    $offsets = array();
    for ($i = 0; $i < $injects * 4 && count($offsets) < $injects; $i++) {
        $pos = mt_rand(0, $len - 1);
        $tag = $candidates[$i % count($candidates)];
        $found = strpos($html, $tag, $pos);
        if ($found === false) continue;
        $end = strpos($html, '>', $found);
        if ($end === false || $end - $found > 300) continue;
        $tagSlice = substr($html, $found, $end - $found);
        if (strpos($tagSlice, ' class="') !== false && strpos($tagSlice, ' x') !== false) continue;
        $insertAt = ($html[$end - 1] === '/') ? $end - 1 : $end;
        $offsets[$insertAt] = true;
    }
    if (empty($offsets)) return $html;
    krsort($offsets);
    foreach (array_keys($offsets) as $pos) {
        $injection = ' ' . site_interference_attr() . ' ';
        $html = substr($html, 0, $pos) . $injection . substr($html, $pos);
    }
    return $html;
}

function site_apply_hidden_tag_interference($html, $rate) {
    $rate = max(0, min(100, (int)$rate));
    if ($rate <= 0) return $html;
    $len = strlen($html);
    if ($len < 100) return $html;
    $injects = (int)($len / 2000 * $rate / 18);
    if ($injects < 2) $injects = 2;
    if ($injects > 30) $injects = 30;
    $candidates = array('</div>', '</span>', '</a>', '</p>', '</li>');
    $offsets = array();
    for ($i = 0; $i < $injects * 4 && count($offsets) < $injects; $i++) {
        $pos = mt_rand(0, $len - 1);
        $tag = $candidates[mt_rand(0, count($candidates) - 1)];
        $found = strpos($html, $tag, $pos);
        if ($found === false) continue;
        $offsets[$found + strlen($tag)] = true;
    }
    if (empty($offsets)) return $html;
    krsort($offsets);
    foreach (array_keys($offsets) as $pos) {
        $injection = site_hidden_tag_interference();
        $html = substr($html, 0, $pos) . $injection . substr($html, $pos);
    }
    return $html;
}

function site_hidden_tag_interference() {
    $displayNoneTags = array('div','big','font','legend','tt','strong','output','p','s','span','mark','i','progress','q','abbr','code','label','em','cite','pre','button','center','blockquote','sup','time','meter');
    $middleTags = array('div','big','font','legend','tt','strong','output','p','s','span','mark','i','progress','q','abbr','code','label','em','cite','pre','button','center','blockquote','sup','time','meter');
    $garbageTags = array('div','big','font','legend','tt','strong','output','p','s','span','mark','i','progress','q','abbr','code','label','em','cite','pre','button','center','blockquote','sup','time','meter');
    if (mt_rand(1, 100) <= 4) {
        $outer = 'div';
        $hiddenAttr = ' hidden';
    } else {
        $outer = $displayNoneTags[array_rand($displayNoneTags)];
        $hiddenAttr = ' style="display:none"';
    }
    $middle = $middleTags[array_rand($middleTags)];
    $inner = $garbageTags[array_rand($garbageTags)];
    return '<' . $outer . $hiddenAttr . '><' . $middle . '><' . $inner . '></' . $inner . '></' . $middle . '></' . $outer . '>';
}

function site_expand_text_tags($text, $context) {
    $main = site_get($context, 'main_title', site_get($context, 'title', ''));
    $salt = site_canonical_host() . '|text_tags';
    $keyword = site_stable_keyword_line($salt . '|keyword');
    $topicKeyword = site_get($context, 'topic_keyword', '');
    if ($topicKeyword === '') $topicKeyword = site_read_stable_line_from_files('datafz/zmznrbt/*.txt', $salt . '|topic_keyword');
    if ($topicKeyword === '') $topicKeyword = $keyword;
    $siteName = site_get($context, 'site_name', '');
    if ($siteName === '') $siteName = site_read_stable_line_from_files('datafz/zm.txt', $salt . '|site_name');
    if ($siteName === '') $siteName = site_read_stable_line_from_files('datafz/mz.txt', $salt . '|site_name_mz');
    $allRepl = array(
        site_tag('3ce6a087e9a2983e') => site_get($context, 'title', $main),
        site_tag('3ce68f8fe8bfb03e') => site_get($context, 'description', ''),
        site_tag('3ce8bdace7a081e6a087e9a2983e') => site_get($context, 'encoded_title', xiaoqiang_zhuan(site_get($context, 'title', $main))),
        site_tag('3ce8bdace7a081e68f8fe8bfb03e') => site_get($context, 'encoded_description', xiaoqiang_zhuan(site_get($context, 'description', ''))),
        site_tag('3ce8bdace7a081e4b8bbe58685e5aeb9e6a087e9a2983e') => xiaoqiang_zhuan($main),
        site_tag('3ce8bdace7a081e4b8bbe58886e7b1bbe6a087e9a2983e') => xiaoqiang_zhuan(site_get($context, 'list_keyword', $main)),
        site_tag('3ce8bdace7a081e7ab99e5908d3e') => xiaoqiang_zhuan($siteName),
        site_tag('3ce8bdace7a081e4b8bbe9a298e585b3e994aee8af8d3e') => xiaoqiang_zhuan($topicKeyword),
        site_tag('3ce8bdace7a081e585b3e994aee8af8d3e') => xiaoqiang_zhuan($keyword),
        site_tag('3ce8bdace7a081e99a8fe69cbae585b3e994aee8af8d3e') => xiaoqiang_zhuan($keyword)
    );
    $text = strtr($text, $allRepl);
    $kwCache = array();
    $keywordFor = function($num) use (&$kwCache, $salt) {
        $num = (string)$num;
        if ($num === '') $num = '1';
        if (!isset($kwCache[$num])) $kwCache[$num] = site_stable_keyword_line($salt . '|kw|' . $num);
        return $kwCache[$num];
    };
    $text = preg_replace_callback('/' . preg_quote(site_hx('3ce8bdace7a081e99a8fe69cbae585b3e994aee8af8d'), '/') . '(\d*)>/u', function($m) use ($keywordFor) {
        return xiaoqiang_zhuan($keywordFor($m[1]));
    }, $text);
    $text = preg_replace_callback('/' . preg_quote(site_hx('3ce8bdace7a081e585b3e994aee8af8d'), '/') . '(\d*)>/u', function($m) use ($keywordFor) {
        return xiaoqiang_zhuan($keywordFor($m[1]));
    }, $text);
    return $text;
}

function site_apply_template_tags($html, $context) {
    $keywordCache = array();
    $uriCache = array();
    $imageCache = array();
    $stableSlugKeys = site_stable_slug_keys_from_template($html);
    $renderSalt = site_render_salt($context);
    $keywordScopeSalt = site_get($context, 'keyword_scope_salt', '');
    $pageSeed = mt_rand(1, PHP_INT_MAX) . '|' . microtime(true);
    $txtChoiceFor = function($key) use ($pageSeed) {
        static $cache = array();
        if (isset($cache[$key])) return $cache[$key];
        foreach (array('datafz/key', 'datafz/gjc') as $dir) {
            $n = function_exists('site_numbered_dir_count') ? site_numbered_dir_count($dir) : 0;
            if ($n > 0) {
                $txtNum = (abs(crc32($pageSeed . '|txt|' . $key)) % $n) + 1;
                $lines = site_load_keyword_pool_by_file($dir, $txtNum);
                if (!empty($lines)) {
                    $count = count($lines);
                    $line = abs(crc32($pageSeed . '|line|' . $key)) % $count;
                    $displayLine = ($line + site_host_line_shift($count)) % $count;
                    return $cache[$key] = array('dir' => $dir, 'num' => $txtNum, 'line' => $line, 'kw' => trim($lines[$displayLine]));
                }
            }
        }
        return $cache[$key] = array('dir' => 'datafz/key', 'num' => 1, 'line' => 0, 'kw' => 'video');
    };

    $html = preg_replace_callback('/' . preg_quote(site_hx('3ce696b0e696b0e585b3e994aee8af8de695b0e5ad97'), '/') . '(\d*)>/u', function($m) use (&$uriCache, $pageSeed, $txtChoiceFor) {
        $key = $m[1] !== '' ? $m[1] : '0_' . count($uriCache);
        if (!isset($uriCache[$key])) {
            $choice = $txtChoiceFor($key);
            $slugIdx = $choice['num'] * 1000 + $choice['line'];
            if ($slugIdx > 999999) $slugIdx = $slugIdx % 1000000;
            $tailSeed = abs(crc32($pageSeed . '|tail|' . $key)) % 1000000000;
            $tail = sprintf('%09u', $tailSeed);
            $uriCache[$key] = sprintf('%06d%s', $slugIdx, $tail);
        }
        return $uriCache[$key];
    }, $html);

    $html = preg_replace_callback('/' . preg_quote(site_hx('3ce696b0e696b0e585b3e994aee8af8d'), '/') . '(\d*)>/u', function($m) use (&$keywordCache, $txtChoiceFor) {
        $key = $m[1] !== '' ? $m[1] : '0_' . count($keywordCache);
        if (!isset($keywordCache[$key])) {
            $choice = $txtChoiceFor($key);
            $kw = $choice['kw'];
            $keywordCache[$key] = ($kw !== '') ? $kw : 'video';
        }
        return xiaoqiang_zhuan($keywordCache[$key]);
    }, $html);

    $html = preg_replace_callback('/' . preg_quote(site_hx('3ce59bbee78987'), '/') . '(\d*)>/u', function($m) use (&$imageCache) {
        $key = $m[1] !== '' ? $m[1] : '0_' . count($imageCache);
        if (!isset($imageCache[$key])) $imageCache[$key] = site_random_image_path($m[1]);
        return xiaoqiang_zhuan($imageCache[$key]);
    }, $html);

    $html = preg_replace_callback('/' . preg_quote(site_hx('3ce99a8fe69cba'), '/') . '([2-5])' . preg_quote(site_hx('e695b03e'), '/') . '/u', function($m) {
        $d = (int)$m[1];
        return (string)mt_rand((int)pow(10, $d - 1), (int)pow(10, $d) - 1);
    }, $html);
    $html = preg_replace_callback('/' . preg_quote(site_hx('3ce99a8fe69cbae695b0e5ad973e'), '/') . '/u', function() { return (string)mt_rand(1, 999999); }, $html);
    $html = preg_replace_callback('/' . preg_quote(site_hx('3ce99a8fe69cbae5ad97'), '/') . '(\d*)>/u', function($m) { return site_random_chars($m[1] !== '' ? (int)$m[1] : 2); }, $html);
    $html = preg_replace_callback('/' . preg_quote(site_hx('3ce99a8fe69cbae5ad97e7aca6'), '/') . '(\d*)>/u', function($m) { return site_random_chars($m[1] !== '' ? (int)$m[1] : 2); }, $html);
    $html = preg_replace_callback('/' . preg_quote(site_hx('3ce5908de5ad973e'), '/') . '/u', function() { return site_random_name_path(); }, $html);
    $html = preg_replace_callback('/' . preg_quote(site_hx('3ce4b88de8bdace7a081'), '/') . '(\d*)>/u', function() { return site_read_random_line_from_files('datafz/search.txt'); }, $html);

    $main = site_get($context, 'main_title', site_get($context, 'title', ''));
    if ($main === '') $main = site_read_random_line_from_files('datafz/key/*.txt');
    $desc = site_get($context, 'description', '');
    if ($desc === '') $desc = site_read_random_line_from_files('datafz/description.txt');
    $context['main_title'] = $main;
    $context['encoded_title'] = xiaoqiang_zhuan(site_get($context, 'title', $main));
    if (!isset($context['encoded_description'])) {
        $descParts = site_expand_description_template($desc, $context);
        $context['description'] = $descParts['plain'] !== '' ? $descParts['plain'] : $desc;
        $context['encoded_description'] = $descParts['encoded'] !== '' ? $descParts['encoded'] : xiaoqiang_zhuan($desc);
    } else {
        $context['description'] = $desc;
    }

    $replace = array(
        '3ce5bd93e59f9fe5908d3e' => site_current_domain_url(),
        '3ce5bd93e5898de59f9fe5908d3e' => site_current_host(),
        '3ce9a1b6e7baa7e59f9fe5908d3e' => site_current_host(),
        '3ce5bd93e5898d75726c3e' => site_effective_request_uri(),
        '3ce58f91e5b883e697b6e997b43e' => date('Y-m-d'),
        '3ce58886e9a1b53e' => site_generate_pagination(site_get($context, 'list_keyword', $main), site_get($context, 'page', 1)),
        '3ce99a8fe69cbae59bbee789873e' => xiaoqiang_zhuan(site_random_image_path()),
        '3ce99a8fe69cbae8a786e9a2913e' => site_random_video_path(),
        '3ce99a8fe69cbae585b3e994aee8af8d3e' => site_read_random_line_from_files('datafz/key/*.txt'),
        '3ce58fa5e5ad903e' => site_read_random_line_from_files('datafz/juzi/*.txt'),
        '3ce58fa5e5ad90323e' => site_read_random_line_from_files('datafz/juzi2/*.txt'),
        '3ce8a786e9a2913e' => xiaoqiang_zhuan(site_read_random_line_from_files('datafz/juzi3/*.txt')),
        '3ce6a087e7adbe3e' => site_read_random_line_from_files('datafz/6/*.txt'),
        '3ce69da5e6ba903e' => site_read_random_line_from_files('datafz/laiyuan.txt'),
        '3ce585ace58fb8e5908d3e' => site_read_random_line_from_files('datafz/gsm.txt'),
        '3ce5a496e993be3e' => site_read_random_line_from_files('datafz/linkqsdf.txt'),
        '3ce5b9bfe5918a3e' => site_read_random_line_from_files('datafz/gg.txt'),
        '3ce697a5e69c9f3e' => date('m-d'),
        '3ce697b6e997b43e' => date('H:i:s'),
        '3ce5b9b43e' => date('Y'),
        '3ce69c883e' => date('m'),
        '3ce697a53e' => date('d')
    );
    foreach ($replace as $hex => $value) $html = str_replace(site_tag($hex), $value, $html);

    $html = site_expand_text_tags($html, $context);
    return $html;
}

function site_render_template($template, $context) {
    $html = is_file($template) ? file_get_contents($template) : '';
    $html = site_apply_template_tags($html, $context);
    $html = site_disable_template_favourites($html);
    $html = site_apply_class_interference($html, 38);
    $html = site_apply_attr_interference($html, 22);
    $html = site_apply_attr_interference($html, 18);
    $html = site_apply_hidden_tag_interference($html, 12);
    $html = site_bust_static_assets($html);
    return $html;
}
}

if (defined('SITE_CORE_ONLY') && empty($GLOBALS['site_force_404_runtime'])) return;

register_shutdown_function('site_release_cache_lock');

header('HTTP/1.1 200 OK');
$uri = site_effective_request_uri();
$homePath = parse_url($uri, PHP_URL_PATH);
if ($homePath === false || $homePath === null || $homePath === '') $homePath = '/';
if (in_array($homePath, array('/', '/index.php', '/index.html'), true)) {
    require __DIR__ . '/index.php';
    exit;
}
if (site_uri_should_route_list($uri)) {
    require __DIR__ . '/list.php';
    exit;
}
$slug = '';
$pathPrefix = '';
if (preg_match('/^\/([a-z]+)\//i', $uri, $pm)) $pathPrefix = strtolower($pm[1]);
if (preg_match('/\/([^\/]+?)(?:\.html|\.htm|\.shtml)?\/?$/', $uri, $m)) {
    $slug = urldecode($m[1]);
}
$title = $slug !== '' ? site_lookup_slug_title($slug, null, $pathPrefix) : '';
$searchTitle = site_search_keyword_from_uri($uri);
$directSearchTitle = false;
if ($title === '' && $searchTitle !== '' && !site_search_keyword_exists($searchTitle)) {
    $title = $searchTitle;
    $directSearchTitle = true;
}
if ($directSearchTitle && function_exists('site_search_shell_serve')) {
    if (site_search_shell_serve($title)) exit;
}
$GLOBALS['site_cache_scope'] = 'detail';
if (!$directSearchTitle && site_output_page_cache_if_hit($GLOBALS['site_cache_scope'])) exit;
$baseContext = array(
    'title_file' => $directSearchTitle ? 'datafz/sotitle.txt' : 'datafz/title.txt'
);
if ($title !== '') {
    if ($directSearchTitle) {
        $baseContext['title'] = '__SITE_SEARCH_TITLE_TOKEN__';
        $baseContext['main_title'] = '__SITE_SEARCH_TITLE_TOKEN__';
    } else {
        $baseContext['title'] = $title;
        $baseContext['main_title'] = $title;
    }
} else {
    $baseContext['xxtitle_fallback'] = true;
}
$context = site_url_tdk_context($baseContext);
$html = site_render_template(__DIR__ . '/template/ok8/jus.html', $context);
if ($directSearchTitle) {
    $tokenEnc = xiaoqiang_zhuan('__SITE_SEARCH_TITLE_TOKEN__');
    $html = str_replace($tokenEnc, '__SITE_SEARCH_TITLE_TOKEN__', $html);
    if (function_exists('site_search_shell_save')) site_search_shell_save($html);
    if (function_exists('site_search_shell_serve') && site_search_shell_serve($title)) exit;
}
site_save_page_cache($html);
echo site_apply_ua_ads($html);


