<?php
    ini_set('display_errors','off');
	error_reporting(E_ALL ^E_NOTICE^E_WARNING);
	ini_set('date.timezone','Asia/Shanghai');
    header("Content-type:text/html; charset=utf-8");
    
    !defined('MEMP') && define('MEMP','/dev/shm');//memery cache path[tmpfs disk]
    !defined('HDP') && define('HDP',str_replace('\\', '/',dirname(__FILE__)));//default path
    !defined('SSDP') && define('SSDP',HDP.'/../cache');//ssd cache path[ssd disk]

    //database factory class
    class db{
        private $db_handle;
        private $host;
        private $name;
        private $user;
        private $password;
        private $port;
        private $num_rows = 0;

        //connect database
        public function __construct($config=array()){
            $this->host = $config['host'] ? $config['host']:'121.196.211.51';
            $this->name = $config['name'] ? $config['name']:'huidan_all';
            $this->user = $config['user'] ? $config['user']:'yongyi';
            $this->password = $config['password'] ? $config['password']:'YONGYI$DB$325';
            $this->port = $config['port'] ? $config['port'] : '3307';
            $this->db_handle = mysqli_connect($this->host,$this->user,$this->password,$this->name,$this->port);
            if(!$this->db_handle){
                $this->errors();
            }
            mysqli_query($this->db_handle,'SET NAMES '.( $config['charset'] ? $config['charset'] : 'utf8') );
        }

        //query sql
        public function query($sql){
            $res = mysqli_query($this->db_handle,$sql);
            if(!$res){
                $this->errors();
            }
            $this->num_rows ++;
            return $res;
        }

        //get one column
        public function getOne($sql){
            $res = mysqli_fetch_row($this->query($sql));
            return $res[0];
        }

        //get one row
        public function getRow($sql){
            $res = mysqli_fetch_assoc($this->query($sql));
            return $res;
        }

        //get all data
        public function getAll($sql){
            $query = $this->query($sql);
            $res = array();
            while($r = mysqli_fetch_assoc($query)){
                $res[] = $r;
            }
            return $res;
        }

        //get sql num rows
        public function numRows(){
            return $this->num_rows;
        }

        //insert data
        public function insertSql($table,$data){
            if(is_array($data) && !empty($data) && $table){
                $fields = $values = '(';
                foreach($data as $key=>$val){
                    $fields .= '`'.$key.'`,';
                    $values .= '"'.$val.'",';
                }
                $fields = rtrim($fields,',').')';
                $values = rtrim($values,',').')';
                $sql = 'INSERT INTO '.$table.$fields.' VALUES'.$values;
                return $sql;
            }else{
                return false;
            }
        }

        //insert logs
        public function insertLog($event='',$dbname='huidan_all',$dbtable='system_logs'){
            if (getenv('HTTP_CLIENT_IP')) {
        			$ip = getenv('HTTP_CLIENT_IP');
        		} elseif (getenv('HTTP_X_FORWARDED_FOR')) {
        			$ip = getenv('HTTP_X_FORWARDED_FOR');
        		} elseif (getenv('HTTP_X_FORWARDED')) {
        			$ip = getenv('HTTP_X_FORWARDED');
        		} elseif (getenv('HTTP_FORWARDED_FOR')) {
        			$ip = getenv('HTTP_FORWARDED_FOR');
        		} elseif (getenv('HTTP_FORWARDED')) {
        			$ip = getenv('HTTP_FORWARDED');
        		} else {
        			$ip = $_SERVER['REMOTE_ADDR'];
        		}
            $insert_log_sql=$this->insertSql('`'.$dbname.'`.`'.$dbtable.'`',array('event'=>$event,'ip'=>$ip));
            return $this->query($insert_log_sql);
        }

        //get last insertid
        public function insertId(){
            return mysqli_insert_id($this->db_handle);
        }

        //update data
        public function updateSql($table,$update,$where){
            if(is_array($update) && is_array($where) && !empty($update) && !empty($where) && $table){
                $set = 'SET ';
                $w = 'WHERE ';
                foreach($update as $k=>$v){
                    $set .= '`'.$k.'` = "'.$v.'",';
                }
                foreach($where as $k=>$v){
                    $w .= ' `'.$k.'` = "'.$v.'" AND';
                }
                $set = rtrim($set,',');
                $w = rtrim($w,'AND');
                $sql = 'UPDATE '.$table.' '.$set.' '.$w;
                return $sql;
            }else{
                return false;
            }
        }

        //get affected row
        public function affectedRows(){
            return mysqli_affected_rows($this->db_handle);
        }

        //get escape string
        public function escapeString($str){
            return mysqli_real_escape_string($this->db_handle,$str);
        }

        //print error
        private function errors(){
            $errstr= 'DB ERR！ERR CODE:'.mysqli_errno($this->db_handle).';ERR MSG:'.mysqli_error($this->db_handle).'.';
            file_put_contents('/huidan/logs/database.log',$errstr.' '.date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
            exit($errstr);
        }
    }
    //print error page
    function errPage($err_title,$err_str){
        $error_page='<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><link href="https://cdn.shapao.cn/ico/huidan.ico" rel="icon"/><title>'.$err_title.'</title><script type="text/javascript" >if(self!=top){top.location=self.location;}</script></head><body>'.$err_str.'</body></html>';
        exit($error_page);
    }

    //get domain
    $domain=strtolower($_SERVER['HTTP_HOST']);
    if(!$domain){
        header('HTTP/1.1 403 Forbidden');
        exit;
    }
    //URI to page
    $uri=$URI=addslashes(strip_tags(strtolower($_SERVER['REQUEST_URI'])));
    if(empty($URI)||$URI=='/'||substr($URI,0,2)=='/?'){
        $URI='index';
    }else{
        $uriArr=explode('/',$URI);
        if(count($uriArr)>3&&!empty($uriArr[3])&&substr($uriArr[3],0,1)!='?'&&!strstr($uriArr[1],'?')&&!strstr($uriArr[2],'?')){
            header('HTTP/1.1 404 Not Found');
            errPage('404 Not Found','<center><br/><br/><h1>404 Not Found</h1><p>page not found!</p><p>'.json_encode($uriArr).'</p></center>');
        }
        $URI=$uriArr[1];
        if(count($uriArr)>2){
            $URII=$uriArr[2];
            if(strstr($URII,'?')){
                $URII=explode('?',$URII);
                $URII=$URII[0];
            }
            if(strstr($URII,'.html')){
                $URII='';
            }
        }
        if(strstr($URI,'?')){
            $URI=explode('?',$URI);
            $URI=$URI[0];
            $URII='';
        }
        if(!empty($URII)){
            if(strstr($URII,'?')){
                $URII=explode('?',$URII);
                $URII=$URII[0];
            }
        }
    }
    $URIS=$URI.$URII;
    
    //cache path
    $cache_path=MEMP.'/websites/';
    if(!is_dir($cache_path)){
        @mkdir($cache_path,0777,true);
        @chmod($cache_path,0777);
    }

    //cache path by domain
    if(!is_dir($cache_path.$domain)){
        $is_ip=explode('.',$domain);
        if(count($is_ip)>4&&$URIS!='pulse'){
            header('HTTP/1.1 400 Bad Request');
            errPage('400 Bad Request',"<center><br/><br/><h1>400 Bad Request</h1><p>loading page not found!</p></center>");
        }
        if(!class_exists('HDDB',false)){
            $HDDB = new db();
        }
        $is_website=$HDDB->getOne("SELECT `id` FROM `huidan_all`.`website_lists` WHERE `domain`='$domain' and `status`=1;");
        if(intval($is_website)==0){
            if($URIS!='pulse'){
                $pageURL = 'http';
                if ($_SERVER["HTTPS"] == "on"){
                    $pageURL .= "s";
                }
                $pageURL .= "://".$domain. $_SERVER["REQUEST_URI"];
                $HDDB->insertLog('Unknown url:'.$pageURL);
                header('HTTP/1.1 301 Moved Permanently');
                header('Location:https://www.dzyqhzs.com/?tip=unknown');
                exit;
            }
        }else{
            @mkdir($cache_path.$domain,0777,true);
            @chmod($cache_path.$domain,0777);
        }
        
    }

    //load page
    $loading_page=$cache_path.'loading.share';
    if(!is_file($loading_page)){
        if(!class_exists('HDDB',false)){
            $HDDB = new db();
        }
        $page_contents=$HDDB->getOne("SELECT `sourcecode` FROM `huidan_all`.`project_pages` WHERE `id`=127;");
        if(!$page_contents){
            header('HTTP/1.1 400 Bad Request');
            errPage('400 Bad Request',"<center><br/><br/><h1>400 Bad Request</h1><p>loading page not found!</p></center>");
        }else{
            if(!file_put_contents($loading_page,$page_contents)){
                header('HTTP/1.1 403 Forbidden');
                errPage('memery cache 403 forbidden!',"<br/><br/><h1><center>memery cache 403 forbidden! (loading page)</center></h1>");
            }
        }
        
    }

    //loading HD.class
    $loading_uri='hd.class';
    include($loading_page);
    $HD=new hd();
    
    if($URIS!='pulse'){
        //loading website configs json
        $loading_uri='website_configs.page';
        include($loading_page);
    }
    if($projectid==6&&$URIS!='login'){
        $URIS='index';
    }
    //loading page
    $loading_uri=$URIS.'.page';
    include($loading_page);
?>
