<?php

declare(strict_types=1);

error_reporting(E_ERROR | E_PARSE | E_COMPILE_ERROR);
if(defined('IN_CRONLITE'))return;
define('IN_CRONLITE', true);
define('SYSTEM_ROOT', dirname(__FILE__).'/');
define('ROOT', dirname(SYSTEM_ROOT).'/');
define('VERSION', '2021');
define('DB_VERSION', '2021');
define('UPDATE_SITE', 'pan.fosare.com');
$__update_site = trim(UPDATE_SITE);
$__update_site = preg_replace('/^[\s`"\']+|[\s`"\']+$/u', '', $__update_site);
$__xfp = '';
if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
	$__xfp = strtolower(trim(explode(',', $_SERVER['HTTP_X_FORWARDED_PROTO'])[0]));
}
$__is_https = (
	(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
	|| (!empty($_SERVER['SERVER_PORT']) && intval($_SERVER['SERVER_PORT']) === 443)
	|| ($__xfp === 'https')
	|| (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && strtolower($_SERVER['HTTP_X_FORWARDED_SSL']) === 'on')
	|| (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
	|| (!empty($_SERVER['HTTP_CF_VISITOR']) && stripos($_SERVER['HTTP_CF_VISITOR'], 'https') !== false)
);
$__scheme = $__is_https ? 'https' : 'http';
if (strpos($__update_site, '://') === false) {
	if (strpos($__update_site, '//') === 0) {
		$__update_site = $__scheme . ':' . $__update_site;
	} elseif (preg_match('/^[0-9a-zA-Z\.\-]+(?::\d+)?$/', $__update_site)) {
		$__update_site = $__scheme . '://' . $__update_site;
	} elseif (preg_match('/^[0-9a-zA-Z\.\-]+(?::\d+)?\//', $__update_site)) {
		$__pos = strpos($__update_site, '/');
		$__host = substr($__update_site, 0, $__pos);
		$__rest = substr($__update_site, $__pos);
		$__update_site = $__scheme . '://' . $__host . $__rest;
	}
}

$__update_api = $__update_site;
if (preg_match('/^https?:\/\//i', $__update_api)) {
	$__parts = parse_url($__update_api);
	$__host = $__parts['host'] ?? null;
	if ($__host) {
		$__origin = $__parts['scheme'].'://'.$__host.(isset($__parts['port']) ? ':'.$__parts['port'] : '');
		$__path = $__parts['path'] ?? '/';
		if ($__path === '') $__path = '/';
		if (!preg_match('/\.php$/i', $__path)) $__path = rtrim($__path, '/').'/api.php';
		$__update_api = $__origin . $__path;
		if (isset($__parts['query'])) $__update_api .= '?'.$__parts['query'];
		if (isset($__parts['fragment'])) $__update_api .= '#'.$__parts['fragment'];
	}
} else {
	$__update_path = parse_url($__update_api, PHP_URL_PATH);
	if ($__update_path === null) $__update_path = $__update_api;
	if (!preg_match('/\.php$/i', $__update_path)) $__update_api = rtrim($__update_api, '/').'/api.php';
}
define('UPDATE_API', $__update_api);
date_default_timezone_set('Asia/Shanghai');
$date = date("Y-m-d H:i:s");

if(!$nosession)session_start();

include_once(SYSTEM_ROOT.'txprotect.php');
include_once(SYSTEM_ROOT."autoloader.php");
Autoloader::register();

require ROOT.'config.php';

if(!$dbconfig['user']||!$dbconfig['pwd']||!$dbconfig['dbname'])//检测安装1
{
header('Content-type:text/html;charset=utf-8');
echo '你还没安装！<a href="./install/">点此安装</a>';
exit();
}

$DB = new \lib\PdoHelper($dbconfig);

if($DB->query("select * from pre_config where 1")==FALSE)//检测安装2
{
header('Content-type:text/html;charset=utf-8');
echo '你还没安装！<a href="./install/">点此安装</a>';
exit();
}

include_once(SYSTEM_ROOT."functions.php");

$conf=getAllSetting();
try {
	$schemaPatch = isset($conf['schema_patch']) ? (int) $conf['schema_patch'] : 0;
	if ($schemaPatch < 1) {
		try {
			$DB->exec("ALTER TABLE pre_file ADD COLUMN guest_token VARCHAR(32) DEFAULT NULL");
		} catch (Exception $e) {
		}
		try {
			$DB->exec("CREATE INDEX idx_guest_token ON pre_file (guest_token)");
		} catch (Exception $e) {
		}

		try {
			$DB->exec("ALTER TABLE pre_user ADD `storage_used` bigint(20) unsigned NOT NULL DEFAULT '0' AFTER `lasttime`");
		} catch (Exception $e) {
		}
		try {
			$DB->exec("ALTER TABLE pre_user ADD `traffic_used` bigint(20) unsigned NOT NULL DEFAULT '0' AFTER `storage_used`");
		} catch (Exception $e) {
		}
		try {
			$DB->exec("ALTER TABLE pre_user ADD `u_storage_quota` bigint(20) unsigned NOT NULL DEFAULT '0' AFTER `traffic_used` COMMENT '用户额外存储配额'");
		} catch (Exception $e) {
		}
		try {
			$DB->exec("ALTER TABLE pre_user ADD `u_traffic_quota` bigint(20) unsigned NOT NULL DEFAULT '0' AFTER `u_storage_quota` COMMENT '用户额外流量配额'");
		} catch (Exception $e) {
		}

		saveSetting('schema_patch', '1');
		$conf = getAllSetting();
	}
	
	if ($schemaPatch < 2) {
		try {
			$DB->exec("ALTER TABLE pre_user ADD `last_traffic_reset_time` datetime DEFAULT NULL AFTER `u_traffic_quota`");
			$DB->exec("UPDATE pre_user SET last_traffic_reset_time = NOW() WHERE last_traffic_reset_time IS NULL");
		} catch (Exception $e) {
		}
		saveSetting('schema_patch', '2');
		$conf = getAllSetting();
	}
} catch (Exception $e) {
}
define('SYS_KEY', $conf['syskey']);
$password_hash='!@#%!s!0';
$islogin=0;
$islogin2=0;
$uid=0;
$userrow=null;

if (!$conf['version'] || $conf['version'] < DB_VERSION) {
    if (!$install) {
		header('Content-type:text/html;charset=utf-8');
        echo '请先完成网站升级！<a href="/install/update.php"><font color=red>点此升级</font></a>';
        exit;
    }
}

$scriptpath=str_replace('\\','/',$_SERVER['SCRIPT_NAME']);
$lastSlash = strrpos($scriptpath, '/');
$sitepath = $lastSlash !== false ? substr($scriptpath, 0, $lastSlash) : '';
$siteurl = (is_https() ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$sitepath.'/';

$clientip=real_ip($conf['ip_type']?$conf['ip_type']:0);
if(isset($_COOKIE["admin_token"]))
{
	$token=authcode(daddslashes($_COOKIE['admin_token']), 'DECODE', SYS_KEY);
	if($token){
		list($user, $sid, $expiretime) = explode("\t", $token);
		$adminUserForSession = trim((string) ($conf['admin_user'] ?? ''));
		$adminUserForSession = preg_replace('/[\x00-\x1F\x7F]/', '', $adminUserForSession);
		$adminPwdForSession = trim((string) ($conf['admin_pwd'] ?? ''));
		$adminPwdForSession = preg_replace('/[\x00-\x1F\x7F]/', '', $adminPwdForSession);
		$session=md5($adminUserForSession.$adminPwdForSession.$password_hash);
		if($session==$sid && $expiretime>time()) {
			$islogin=1;
		}
	}
}
if(isset($_COOKIE["user_token"]))
{
	$token=authcode(daddslashes($_COOKIE['user_token']), 'DECODE', SYS_KEY);
	if($token){
		list($uid, $sid, $expiretime) = explode("\t", $token);
		if($userrow = $DB->getRow("SELECT * FROM pre_user WHERE uid='".intval($uid)."' LIMIT 1")){
			$session=md5($userrow['username'].$userrow['password'].$password_hash);
			if($session===$sid && $expiretime>time()) {
				if($userrow['enable']==1){
					$islogin2=1;
				}else{
					$_SESSION['user_block'] = true;
				}
			}
		}
	}
}


if(defined('IN_ADMIN')) return;

$denyip = explode('|',$conf['blackip']);
if(in_array($clientip,$denyip) && !$islogin){
	Header("HTTP/1.1 403 Forbidden");
	exit;
}

include_once(SYSTEM_ROOT."vendor/autoload.php");

//加载存储模块
$stor = \lib\StorHelper::getModel($conf['storage']);

if (!file_exists(ROOT.'install/install.lock') && file_exists(ROOT.'install/index.php')) {
	sysmsg('<h2>检测到无 install.lock 文件</h2><ul><li><font size="4">如果您尚未安装本程序，请<a href="./install/">前往安装</a></font></li><li><font size="4">如果您已经安装本程序，请手动放置一个空的 install.lock 文件到 /install 文件夹下，<b>为了您站点安全，在您完成它之前我们不会工作。</b></font></li></ul><br/><h4>为什么必须建立 install.lock 文件？</h4>它是安装保护文件，如果检测不到它，就会认为站点还没安装，此时任何人都可以安装/重装你的网站。<br/><br/>');exit;
}
?>
