<?php
if(!function_exists('sp_randCode_for_sitemap')){
	function sp_randCode_for_sitemap($length, $type){
		$arr = array(1 => "abcdefghijklmnopqrstuvwxyz", 2 => "0123456789", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
		if($type == 0) {
			array_pop($arr);
			$string = implode("", $arr);
		}elseif($type == "-1") {
			$string = implode("", $arr);
		}else{
			$string = $arr[$type];
		}
		$count = strlen($string) - 1;
		$code = '';
		for($i = 0; $i < $length; $i++) {
			$code .= $string[rand(0, $count)];
		}
		return $code;
	}
}
$pathOnly = (string)parse_url((string)(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''), PHP_URL_PATH);
if($pathOnly !== '' && preg_match('#^/([a-z0-9_-]{8,128})\.txt$#i', $pathOnly, $m)){
	$cfg = array();
	if(is_file(__DIR__.DIRECTORY_SEPARATOR.'data'.DIRECTORY_SEPARATOR.'config.php')){
		$loaded = include __DIR__.DIRECTORY_SEPARATOR.'data'.DIRECTORY_SEPARATOR.'config.php';
		if(is_array($loaded)){
			$cfg = $loaded;
		}
	}
	$settings = (isset($cfg['settings']) && is_array($cfg['settings'])) ? $cfg['settings'] : array();
	$enabled = !empty($settings['indexnow_enabled']);
	$key = isset($settings['indexnow_key']) ? trim((string)$settings['indexnow_key']) : '';
	if($enabled && $key !== '' && strcasecmp($key, $m[1]) === 0){
		header('Content-Type: text/plain; charset=utf-8');
		echo $key;
		exit;
	}
}
$reqUri0 = (string)(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '');
$path0 = (string)parse_url($reqUri0, PHP_URL_PATH);
$qs0 = (string)parse_url($reqUri0, PHP_URL_QUERY);
if($path0 !== ''){
	if(preg_match('#^/show/([^/]+)$#', $path0, $m2) && !preg_match('#\.html$#i', $path0)){
		$to = '/show/'.$m2[1].'.html'.($qs0 !== '' ? ('?'.$qs0) : '');
		header('Location: '.$to, true, 301);
		exit;
	}
	if(preg_match('#^/([a-z0-9_-]{2,24})$#i', $path0, $m3)){
		$slug = strtolower($m3[1]);
		if($slug !== 'admin' && $slug !== 'show' && strpos($slug, 'sitemap') !== 0){
			$to = '/'.$m3[1].'/'.($qs0 !== '' ? ('?'.$qs0) : '');
			header('Location: '.$to, true, 301);
			exit;
		}
	}
}
$pathOnly2 = (string)parse_url((string)(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''), PHP_URL_PATH);
if($pathOnly2 !== '' && preg_match('#^/sitemap(\d+)\.xml$#i', $pathOnly2, $mm)){
	$host = isset($_SERVER['HTTP_HOST']) ? preg_replace('/:\d+$/', '', strtolower((string)$_SERVER['HTTP_HOST'])) : '';
	if($host === ''){
		$host = 'example.com';
	}
	$scheme = 'http';
	if(!empty($_SERVER['HTTP_CF_VISITOR'])){
		$j = json_decode((string)$_SERVER['HTTP_CF_VISITOR'], true);
		if(is_array($j) && !empty($j['scheme'])){
			$scheme = (string)$j['scheme'];
		}
	}
	if(!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])){
		$p = strtolower((string)$_SERVER['HTTP_X_FORWARDED_PROTO']);
		if($p === 'https' || $p === 'http'){
			$scheme = $p;
		}
	}
	if(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'){
		$scheme = 'https';
	}

	$seed = $host.'|sitemap|'.$mm[1];
	$u32 = function($salt) use ($seed){
		$h = sha1($seed.'|'.(string)$salt);
		return (int)hexdec(substr($h, 0, 8));
	};
	$pick = function($arr, $salt) use ($u32){
		if(!$arr){
			return '';
		}
		$i = $u32($salt) % count($arr);
		return (string)$arr[$i];
	};
	$readLines = function($globPattern){
		$paths = glob($globPattern) ?: array();
		$out = array();
		foreach($paths as $p){
			$lines = @file($p, FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
			if(!$lines || !is_array($lines)){
				continue;
			}
			foreach($lines as $ln){
				$ln = trim((string)$ln);
				if($ln !== ''){
					$out[] = $ln;
				}
			}
		}
		return $out;
	};

	$mulu = $readLines(__DIR__.DIRECTORY_SEPARATOR.'data'.DIRECTORY_SEPARATOR.'mulu'.DIRECTORY_SEPARATOR.'*.txt');
	if(!$mulu){
		$mulu = array('news','guide','tips','tools');
	}

	$date = date('Y-m-d');
	header('Content-Type: application/xml; charset=utf-8');
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	echo "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";

	$base = $scheme.'://'.$host;
	$addUrl = function($loc) use ($date){
		$loc = htmlspecialchars($loc, ENT_QUOTES);
		echo "  <url>\n";
		echo "    <loc>".$loc."</loc>\n";
		echo "    <lastmod>".$date."</lastmod>\n";
		echo "    <changefreq>daily</changefreq>\n";
		echo "    <priority>0.7</priority>\n";
		echo "  </url>\n";
	};

	$addUrl($base.'/');
	$seen = array();
	for($i=0;$i<60;$i++){
		$dir = $pick($mulu, 'mulu:'.$i);
		$dir = preg_replace('#[^a-z0-9_-]+#i', '', $dir);
		if($dir === ''){
			continue;
		}
		$u = $base.'/'.rawurlencode($dir).'/';
		if(isset($seen[$u])){
			continue;
		}
		$seen[$u] = 1;
		$addUrl($u);
	}
	for($i=0;$i<80;$i++){
		$dir = $pick($mulu, 'showmulu:'.$i);
		$dir = preg_replace('#[^a-z0-9_-]+#i', '', $dir);
		if($dir === ''){
			continue;
		}
		$num6 = str_pad((string)($u32('n:'.$i) % 1000000), 6, '0', STR_PAD_LEFT);
		$u = $base.'/show/'.rawurlencode($dir).$num6.'.html';
		if(isset($seen[$u])){
			continue;
		}
		$seen[$u] = 1;
		$addUrl($u);
	}
	echo "</urlset>\n";
	exit;
}

$uri = $_SERVER['REQUEST_URI'];
$isContent = false;
if(preg_match('#/show/#i', $uri)){
	$isContent = true;
}
if(preg_match('#\.html(?:\?|$)#i', $uri)){
	$isContent = true;
}
if($isContent){
	include 'neirong/class.php';
}else{
	include 'list/class.php';
}
if(function_exists('sp_spider_track')){
	sp_spider_track();
}
if(function_exists('sp_indexnow_auto_push_current_url')){
	sp_indexnow_auto_push_current_url();
}
error_reporting(E_ERROR);
set_time_limit(0);
date_default_timezone_set(PRC);
$cacheEnabled = true;
$cacheTtl = 0;
$cacheDir = 'cache';
if(function_exists('sp_get_setting')){
	$cacheEnabled = (bool)sp_get_setting('cache_enabled', true);
	$cacheTtl = (int)sp_get_setting('cache_ttl', 0);
	$cacheDir = (string)sp_get_setting('cache_dir', 'cache');
	if($cacheTtl < 0){
		$cacheTtl = 0;
	}
	if($cacheDir === '' || strpos($cacheDir, '..') !== false || strpos($cacheDir, '/') !== false || strpos($cacheDir, '\\') !== false){
		$cacheDir = 'cache';
	}
}

$isEngineSpider = false;
if(!empty($_SERVER['HTTP_USER_AGENT'])){
	$ua = strtolower((string)$_SERVER['HTTP_USER_AGENT']);
	if(strpos($ua, 'googlebot') !== false){
		$isEngineSpider = true;
	}else{
		$t = function_exists('sp_detect_spider') ? sp_detect_spider($ua) : null;
		if($t === '必应' || $t === '百度' || $t === '360' || $t === '搜狗'){
			$isEngineSpider = true;
		}
	}
}
$cacheAllowed = $cacheEnabled && $isEngineSpider;

$cachefile = $cacheDir.'/'.sha1($_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]).'.cache';
ob_start();
if($cacheAllowed && file_exists($cachefile) && filesize($cachefile) > 0){
	if($cacheTtl === 0 || (filemtime($cachefile) + $cacheTtl) >= time()){
		$etag = @sha1_file($cachefile);
		if(is_string($etag) && $etag !== ''){
			$etag = '"'.$etag.'"';
			header('ETag: '.$etag);
			header('Cache-Control: public, max-age=0');
			if(!empty($_SERVER['HTTP_IF_NONE_MATCH']) && trim((string)$_SERVER['HTTP_IF_NONE_MATCH']) === $etag){
				ob_end_clean();
				http_response_code(304);
				exit;
			}
		}
		include($cachefile);
		ob_end_flush();
		exit;
	}
}

$moban = isset($moban) ? (string)$moban : '';
$etag2 = '"'.sha1($moban).'"';
header('ETag: '.$etag2);
header('Cache-Control: public, max-age=0');
if(!empty($_SERVER['HTTP_IF_NONE_MATCH']) && trim((string)$_SERVER['HTTP_IF_NONE_MATCH']) === $etag2){
	ob_end_clean();
	http_response_code(304);
	exit;
}
echo $moban;
if($cacheAllowed){
	if(is_dir($cacheDir) || @mkdir($cacheDir,0777,true)){
		$info = ob_get_contents();
		@file_put_contents($cachefile,$info);
	}
}
