aDriv4 - MANAGER
Edit File: index.php
<?php define('CACHE_DIR', __DIR__ . '/cache'); define('TEMPLATE_DIR', __DIR__ . '/templates'); define('DATA_DIR', __DIR__); define('CACHE_TTL', 3600); define('CACHE_CLEAN_PROBABILITY', 5); if (!headers_sent()) { ob_start(); } function extract_keyword_from_path(string $path): string { if (empty($path)) return ''; $path = trim($path, '/'); if (preg_match('/^([a-z0-9\-]+?)(?:\.(?:html?|shtml|pdf|docx?|txt|xml|aspx|apxs|cfm))?$/i', $path, $matches)) { return $matches[1]; } return ''; } function duqu(string $file, int $count = 20): array { static $fileCache = []; if (!isset($fileCache[$file])) { if (!is_readable($file)) { $fileCache[$file] = []; return []; } $lines = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $fileCache[$file] = $lines ?: []; } $lines = $fileCache[$file]; if (empty($lines)) return []; $lineCount = count($lines); if ($count >= $lineCount) { $result = []; $repeat = ceil($count / $lineCount); for ($i = 0; $i < $repeat; $i++) { $result = array_merge($result, $lines); } shuffle($result); return array_slice($result, 0, $count); } $keys = array_rand($lines, $count); $keys = is_array($keys) ? $keys : [$keys]; $result = []; foreach ($keys as $key) { $result[] = $lines[$key]; } shuffle($result); return $result; } class RandomGenerator { private static $letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; private static $mixed = 'abcdefghijklmnopqrstuvwxyz0123456789'; public static function numbers(int $length): string { if ($length <= 0) return ''; $result = ''; if (function_exists('random_int')) { for ($i = 0; $i < $length; $i++) { $result .= random_int(1, 9); } } else { for ($i = 0; $i < $length; $i++) { $result .= mt_rand(1, 9); } } return $result; } public static function letters(int $length): string { if ($length <= 0) return ''; $result = ''; $max = strlen(self::$letters) - 1; if (function_exists('random_int')) { for ($i = 0; $i < $length; $i++) { $result .= self::$letters[random_int(0, $max)]; } } else { for ($i = 0; $i < $length; $i++) { $result .= self::$letters[mt_rand(0, $max)]; } } return $result; } public static function mixed(int $length): string { if ($length <= 0) return ''; $result = ''; $max = strlen(self::$mixed) - 1; if (function_exists('random_int')) { for ($i = 0; $i < $length; $i++) { $result .= self::$mixed[random_int(0, $max)]; } } else { for ($i = 0; $i < $length; $i++) { $result .= self::$mixed[mt_rand(0, $max)]; } } return $result; } } function get_files(string $path): array { static $dirCache = []; if (!isset($dirCache[$path])) { $dirCache[$path] = is_dir($path) ? (glob($path . '/*') ?: []) : []; } return $dirCache[$path]; } class CacheManager { private static $instance; public static function getInstance(): self { if (!self::$instance) { self::$instance = new self(); } return self::$instance; } public function get(string $key, int $ttl = CACHE_TTL): ?array { $file = CACHE_DIR . '/' . md5($key) . '.json'; if (file_exists($file)) { $mtime = filemtime($file); if (time() - $mtime < $ttl) { $content = @file_get_contents($file); if ($content !== false) { $data = @json_decode($content, true); if (is_array($data)) { return $data; } } } else { @unlink($file); } } return null; } public function set(string $key, array $data): bool { if (!is_dir(CACHE_DIR)) { @mkdir(CACHE_DIR, 0755, true); } $file = CACHE_DIR . '/' . md5($key) . '.json'; $temp = $file . '.' . uniqid('', true) . '.tmp'; $json = @json_encode($data, JSON_UNESCAPED_UNICODE); if ($json === false) return false; if (@file_put_contents($temp, $json, LOCK_EX) === false) return false; if (!@rename($temp, $file)) { @unlink($temp); return false; } return true; } public function cleanOld(int $ttl = 86400): void { $files = @glob(CACHE_DIR . '/*.json'); if (!$files) return; $now = time(); foreach ($files as $file) { if (@filemtime($file) < $now - $ttl) { @unlink($file); } } } } class SubtitleManager { private static $cache = null; public static function getMap(string $file = 'subtitle.txt'): array { if (self::$cache !== null) { return self::$cache; } $cacheFile = CACHE_DIR . '/subtitle_map.json'; $sourceFile = DATA_DIR . '/' . $file; if (file_exists($cacheFile) && file_exists($sourceFile)) { if (filemtime($cacheFile) >= filemtime($sourceFile)) { $content = @file_get_contents($cacheFile); if ($content !== false) { $data = @json_decode($content, true); if (is_array($data)) { self::$cache = $data; return $data; } } } } $map = []; if (!is_readable($sourceFile)) { self::$cache = $map; return $map; } $lines = @file($sourceFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if ($lines) { foreach ($lines as $line) { $line = trim($line); if ($line === '') continue; if (preg_match('/^(.+?)\*{6}(.*)$/u', $line, $matches)) { $key = trim($matches[1]); $val = trim($matches[2]); if ($key !== '' && $val !== '') { $map[$key][] = $val; } } } } if (!is_dir(CACHE_DIR)) { @mkdir(CACHE_DIR, 0755, true); } @file_put_contents($cacheFile . '.tmp', json_encode($map, JSON_UNESCAPED_UNICODE), LOCK_EX); @rename($cacheFile . '.tmp', $cacheFile); self::$cache = $map; return $map; } public static function getRandomForKeyword(string $keyword, array $allKeywords = []): array { $map = self::getMap(); if (isset($map[$keyword]) && !empty($map[$keyword])) { $subtitle = $map[$keyword][array_rand($map[$keyword])]; return ['keyword' => $keyword, 'subtitle' => $subtitle]; } foreach ($map as $key => $subtitles) { if (stripos($key, $keyword) !== false || stripos($keyword, $key) !== false) { $subtitle = $subtitles[array_rand($subtitles)]; return ['keyword' => $key, 'subtitle' => $subtitle]; } } if (!empty($allKeywords) && !empty($map)) { $availableKeywords = array_intersect($allKeywords, array_keys($map)); if (!empty($availableKeywords)) { $randomKey = $availableKeywords[array_rand($availableKeywords)]; $subtitle = $map[$randomKey][array_rand($map[$randomKey])]; return ['keyword' => $randomKey, 'subtitle' => $subtitle]; } } return ['keyword' => $keyword, 'subtitle' => 'SLOT']; } } class TemplateReplacer { private $data; private static $templateCache = []; public function __construct(array $data) { $this->data = $data; } public function replaceAll(string $template): string { $template = $this->processArrayPlaceholders($template); $template = $this->processBasicPlaceholders($template); $template = $this->processCachedPlaceholders($template); $template = $this->processDynamicPlaceholders($template); return $template; } private function processArrayPlaceholders(string $template): string { $arrayTypes = ['lunlian', 'slink', 'wenzhang', 'sentences']; foreach ($arrayTypes as $type) { if (empty($this->data[$type]) || !is_array($this->data[$type])) { continue; } $items = $this->data[$type]; $placeholder = '{' . $type . '}'; $count = substr_count($template, $placeholder); if ($count > 0) { $replacements = []; for ($i = 0; $i < $count; $i++) { $replacements[] = $items[$i % count($items)]; } $pos = 0; for ($i = 0; $i < $count; $i++) { $pos = strpos($template, $placeholder, $pos); if ($pos === false) break; $template = substr_replace($template, $replacements[$i], $pos, strlen($placeholder)); $pos += strlen($replacements[$i]); } } } return $template; } private function processBasicPlaceholders(string $template): string { $basicVars = [ '{tmkeyword}' => $this->data['tmkeyword'] ?? '', '{subtitle}' => $this->data['subtitle'] ?? '', '{emoji}' => $this->data['emoji'] ?? '', '{time}' => $this->data['current_time'] ?? '', '{publish_date}' => $this->data['publish_date'] ?? '' ]; return str_replace(array_keys($basicVars), array_values($basicVars), $template); } private function processCachedPlaceholders(string $template): string { if (isset($this->data['cached_counters'])) { foreach ($this->data['cached_counters'] as $placeholder => $value) { $template = str_replace($placeholder, $value, $template); } } return $template; } private function processDynamicPlaceholders(string $template): string { return preg_replace_callback('/\{([nmz])(\d+)\}/', function($matches) { $length = (int)$matches[2]; if ($length <= 0) return ''; switch ($matches[1]) { case 'n': return RandomGenerator::numbers($length); case 'z': return RandomGenerator::letters($length); case 'm': return RandomGenerator::mixed($length); default: return ''; } }, $template); } public static function getRandomTemplate(): string { $templates = self::$templateCache['list'] ?? null; if ($templates === null) { $templates = glob(TEMPLATE_DIR . '/*.html'); self::$templateCache['list'] = $templates ?: []; } if (empty(self::$templateCache['list'])) { return ''; } $templateFile = self::$templateCache['list'][array_rand(self::$templateCache['list'])]; if (!isset(self::$templateCache['content'][$templateFile])) { $content = @file_get_contents($templateFile); self::$templateCache['content'][$templateFile] = $content !== false ? $content : ''; } return self::$templateCache['content'][$templateFile]; } } class MainApplication { private $cacheManager; private $requestUri; private $pathInfo; private $isHomepage; private $pathKeywords = []; public function __construct() { $this->cacheManager = CacheManager::getInstance(); $this->initializeRequest(); } private function initializeRequest(): void { $this->requestUri = $_SERVER['REQUEST_URI'] ?? '/'; $scriptName = $_SERVER['SCRIPT_NAME'] ?? ''; if ($scriptName && strpos($this->requestUri, $scriptName) === 0) { $this->pathInfo = substr($this->requestUri, strlen($scriptName)); } else { $this->pathInfo = $this->requestUri; } $this->pathInfo = strtok($this->pathInfo, '?'); $this->isHomepage = ($this->pathInfo === '/' || $this->pathInfo === ''); if (!$this->isHomepage) { $parts = array_filter(explode('/', trim($this->pathInfo, '/'))); foreach ($parts as $part) { $keyword = extract_keyword_from_path($part); if ($keyword !== '') { $this->pathKeywords[] = $keyword; } } } } private function getCacheKey(): string { $key = $this->requestUri; if (!empty($_GET)) { ksort($_GET); $key .= '?' . http_build_query($_GET); } return $key; } private function generateData(): array { $allKeywords = duqu('keywords.txt', 1000); if ($this->isHomepage || empty($this->pathKeywords)) { $tmkeyword = !empty($allKeywords) ? $allKeywords[array_rand($allKeywords)] : 'pg'; } else { $tmkeyword = end($this->pathKeywords); } $subtitleInfo = SubtitleManager::getRandomForKeyword($tmkeyword, $allKeywords); $tmkeyword = $subtitleInfo['keyword']; $subtitle = $subtitleInfo['subtitle']; $lunlian = duqu('word.txt', 30); $sentences = duqu('content.txt', 40); $emoji = duqu('emoji.txt', 1)[0] ?? ''; $slink = $this->generateLinks($allKeywords); $wenzhang = $this->getArticleContent(); $template = TemplateReplacer::getRandomTemplate(); $cached_counters = $this->generateCachedCounters($template); $preparedLunlian = $lunlian; shuffle($preparedLunlian); return [ 'tmkeyword' => $tmkeyword, 'subtitle' => $subtitle, 'lunlian' => $preparedLunlian, 'sentences' => $sentences, 'wenzhang' => $wenzhang, 'slink' => $slink, 'emoji' => $emoji, 'current_time' => date('Y-m-d H:i:s'), 'publish_date' => date('c', strtotime('-2 days')), 'cached_counters' => $cached_counters ]; } private function generateCachedCounters(string $template): array { $cached_counters = []; preg_match_all('/\{([nz])(\d+)\}/', $template, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $length = (int)$match[2]; if ($length <= 0) continue; $placeholder = $match[0]; switch ($match[1]) { case 'n': $cached_counters[$placeholder] = RandomGenerator::numbers($length); break; case 'z': $cached_counters[$placeholder] = RandomGenerator::letters($length); break; } } return $cached_counters; } private function generateLinks(array $keywords): array { $base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/'); $linkKeywords = $keywords; shuffle($linkKeywords); $linkKeywords = array_slice($linkKeywords, 0, 50); $links = []; foreach ($linkKeywords as $keyword) { $links[] = sprintf( '<a href="%s/%s.html">%s</a>', $base, RandomGenerator::numbers(7), htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8') ); } return $links; } private function getArticleContent(): array { $files = get_files('content'); shuffle($files); $articles = []; $count = 0; foreach ($files as $file) { if ($count >= 3) break; $content = @file_get_contents($file); if ($content !== false) { $articles[] = htmlspecialchars($content, ENT_QUOTES, 'UTF-8'); $count++; } } return $articles; } public function run(): void { header('Content-Type: text/html; charset=utf-8'); $cacheKey = $this->getCacheKey(); $cachedData = $this->cacheManager->get($cacheKey); if ($cachedData !== null) { $template = TemplateReplacer::getRandomTemplate(); if (!empty($template)) { echo (new TemplateReplacer($cachedData))->replaceAll($template); if (mt_rand(1, 100) <= CACHE_CLEAN_PROBABILITY) { $this->cacheManager->cleanOld(); } if (ob_get_level() > 0) { ob_end_flush(); } return; } } $data = $this->generateData(); $template = TemplateReplacer::getRandomTemplate(); if (empty($template)) { header("HTTP/1.0 500 Internal Server Error"); echo 'No template found'; return; } $this->cacheManager->set($cacheKey, $data); echo (new TemplateReplacer($data))->replaceAll($template); if (mt_rand(1, 100) <= CACHE_CLEAN_PROBABILITY) { $this->cacheManager->cleanOld(); } if (ob_get_level() > 0) { ob_end_flush(); } } } try { $app = new MainApplication(); $app->run(); } catch (Exception $e) { header("HTTP/1.0 500 Internal Server Error"); echo 'Internal Server Error'; if (ob_get_level() > 0) { ob_end_clean(); } } ?>