<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-08-16
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\home\controller;
use app\common\model\Diyfields;
use think\Controller;

class Base extends Controller
{
	// 站点信息
	protected $siteinfo;
	// html模板目录
	protected $htmldir;
	// 站点模板目录
	protected $tempdir;
	// 静态首页路径
	protected $indexhtml;
	// SEO信息
	protected $seoinfo;
	// 站点列表
	protected $navlist;
	// 会员信息
	protected $userinfo;

	protected function initialize()
	{
		error_reporting(E_ALL ^ E_NOTICE);
		// 站点信息
		$this->siteinfo = $this->request->siteinfo;
		if(!$this->siteinfo['expired']) $this->error('站点过期');
		if(!$this->siteinfo['status']) $this->error($this->siteinfo['offline']);
		// 栏目分离
		$this->navlist = $this->siteinfo['navlist'];
		unset($this->siteinfo['navlist']);
		// 全局变量
		$this->siteinfo['ext'] = Diyfields::whereStatus(1)->whereTablename('site')->whereSiteId($this->siteinfo['id'])->cache(config("app.home.homecache"))->column('value','name');
		// 构建站点信息标签{$site_*形式}
		$siteinfo = arr2one($this->siteinfo,'site');
		// SEO信息
		$this->seoinfo['seo_title'] = $this->siteinfo['index_title'] ? getTKD($siteinfo,$this->siteinfo['index_title']) : $this->siteinfo['name'];
		$this->seoinfo['seo_keys'] = $this->siteinfo['keys'];
		$this->seoinfo['seo_desc'] = getTKD($siteinfo,$this->siteinfo['desc']);
		$this->seoinfo['seo_nav_title'] = getTKD($siteinfo,$this->siteinfo['nav_title']);
		$this->seoinfo['seo_nav_desc'] = $this->siteinfo['nav_desc'] ? getTKD($siteinfo,$this->siteinfo['nav_desc']) : $this->seoinfo['seo_desc'];
		$this->seoinfo['seo_info_title'] = getTKD($siteinfo,$this->siteinfo['info_title']);
		$this->assign($siteinfo);
		// 全局url
		$url = [
			'url_form'	=> $this->siteinfo['isdefault']?'/form/':'/'.$this->siteinfo['alias'].'/form/',
			'url_search'	=> $this->siteinfo['isdefault']?'/search/':'/'.$this->siteinfo['alias'].'/search/'
			];
		$this->assign($url);
		// P和W模板页面文件目录
		if($this->request->isMobile() && $this->siteinfo['wapstatus']) {
			$this->htmldir = env('root_path') . 'public' . DS . config('tpl_path') . DS . $this->siteinfo['waptemplate'] . DS . $this->siteinfo['waphtml'] . DS;
			$tempdir = '/public/' . config('tpl_path') . '/' . $this->siteinfo['waptemplate'];
			$this->indexhtml = env("root_path").'public'.DS.'index'.DS.$this->siteinfo['alias'].'_wap_index.html';
			$lang_file = './public/'. config('tpl_path') .'/'.$this->siteinfo['waptemplate'].'/lang/'.$this->siteinfo['alias'].'.lang.php';
		} else {
			$this->htmldir = env('root_path') . 'public' . DS . config('tpl_path') . DS . $this->siteinfo['pctemplate'] . DS . $this->siteinfo['pchtml'] . DS;
			$tempdir = '/public/' . config('tpl_path') . '/' . $this->siteinfo['pctemplate'];
			$this->indexhtml = env("root_path").'public'.DS.'index'.DS.$this->siteinfo['alias'].'_pc_index.html';
			$lang_file = './public/'. config('tpl_path') .'/'.$this->siteinfo['pctemplate'].'/lang/'.$this->siteinfo['alias'].'.lang.php';
		}
		if(file_exists($lang_file)) {
			\think\facade\Lang::load($lang_file);
		}
		// 会员信息
		if(session('?userid')) {
			$this->userinfo = \app\common\model\User::hasWhere('usergroup',['Usergroup.status'=>1])->where(['User.status'=>1,'User.id' => session('userid')])->with('usergroup')->hidden(['password','salt'])->find()->toArray();
			if(!$this->userinfo) {
				session('userid',NULL);
				$this->userinfo['islogin'] = false;
			} else {
				$this->userinfo['islogin'] = true;
			}
		} else {
			$this->userinfo['islogin'] = false;
		}
		$userinfo = arr2one($this->userinfo,'user');
		$this->assign($userinfo);
		// 设置模板路径
		$this->view->config('view_path',$this->htmldir);
		// 模板目录标签
		$this->assign('tempdir',$tempdir);
		// 渲染
		$this->view->filter(function($content) {
			if(config('app.seo.autobaidu')) {
				if(preg_match('/<\/body(\s*)>/is',$content,$match)) {
					$autobaidu = "<script>".PHP_EOL."(function(){".PHP_EOL."var bp = document.createElement('script');".PHP_EOL."var curProtocol = window.location.protocol.split(':')[0];".PHP_EOL."if (curProtocol === 'https'){".PHP_EOL."bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';".PHP_EOL."}".PHP_EOL."else{".PHP_EOL."bp.src = 'http://push.zhanzhang.baidu.com/push.js';".PHP_EOL."}".PHP_EOL."var s = document.getElementsByTagName('script')[0];".PHP_EOL."s.parentNode.insertBefore(bp, s);".PHP_EOL."})();".PHP_EOL."</script>".PHP_EOL."";
					$content = str_replace($match[0],$autobaidu.$match[0],$content);
				}
			};
			if(!empty(config('app.seo.checkbaiducontent'))) {
                if(preg_match('/<\/head(\s*)>/is',$content,$match)) {
                    $checkbaiducontent = '<meta name="baidu-site-verification" content="'.config('app.seo.checkbaiducontent').'" />'.PHP_EOL;
                    $content = str_replace($match[0],$checkbaiducontent.$match[0],$content);
                }
            };
			if(!empty(config('app.home.blackwords'))) {
				$content = guolv($content);
			};
			return $content;
		});
		// 记录蜘蛛
		$this->spider();
		// 防刷新机制
		$this->refresh();
		// 记录访客信息
		$this->visits();
	}

	// 检测会员权限
    public function CheckUgids($ugids='')
    {
        if(empty($ugids)) return true;
        return in_array(session('usergroup_id'), explode(',',$ugids));
    }

    // 蜘蛛来访记录
	private function spider()
	{
	    $useragent = addslashes(strtolower(request()->header('user-agent')));
	    if (strpos($useragent, 'googlebot')!== false){$bot = 'Google';}
	    elseif (strpos($useragent,'mediapartners-google') !== false){$bot = 'Google Adsense';}
	    elseif (strpos($useragent,'baiduspider') !== false){$bot = 'Baidu';}
	    elseif (strpos($useragent,'sogou spider') !== false){$bot = 'Sogou';}
	    elseif (strpos($useragent,'sogou web') !== false){$bot = 'Sogou web';}
	    elseif (strpos($useragent,'sosospider') !== false){$bot = 'SOSO';}
	    elseif (strpos($useragent,'yahoo') !== false){$bot = 'Yahoo';}
	    elseif (strpos($useragent,'msn') !== false){$bot = 'MSN';}
	    elseif (strpos($useragent,'msnbot') !== false){$bot = 'msnbot';}
	    elseif (strpos($useragent,'sohu') !== false){$bot = 'Sohu';}
	    elseif (strpos($useragent,'yodaoBot') !== false){$bot = 'Yodao';}
	    elseif (strpos($useragent,'twiceler') !== false){$bot = 'Twiceler';}
	    elseif (strpos($useragent,'ia_archiver') !== false){$bot = 'Alexa_';}
	    elseif (strpos($useragent,'iaarchiver') !== false){$bot = 'Alexa';}
	    elseif (strpos($useragent,'slurp') !== false){$bot = '雅虎';}
	    elseif (strpos($useragent,'bot') !== false){$bot = '其它蜘蛛';}
	    if(isset($bot)){
	        $data = [
	            'bot' => $bot,
	            'ip' => request()->ip(),
	            'url' => request()->url(true),
	            'create_time' => request()->time(),
	            'method' => request()->method(),
	            'site_id' => SITEID
	        ];
	        $spider = new \app\common\model\Spider;
	        $spider::create($data,true);
	        // if(config('sys.spider_count')) {
	        // 	$count = $spider->count()-intval(config('sys.spider_count'));
	        // 	if($count > 0) {
	        // 		$ids = $spider->limit($count)->order('id asc')->column('id');
	        // 		$spider->whereIn('id',$ids)->delete();
		       //  }
	        // }
	        
	    }
	}

	// 访客信息
	private function visits()
	{
		$ip = request()->ip();
		$ip_arr = explode('.',$ip);
		if($ip_arr[0] == '127' || ($ip_arr[0] == '192' && $ip_arr[1] == '168')) return;
		$visits = new \app\common\model\Visits;
		$last_time = $visits::whereIp($ip)->whereSiteId(SITEID)->max('create_time');
		if(time()-$last_time > config('sys.visits_second')) {
			$data = [
				'ip' => $ip,
				'url' => request()->url(true),
				'create_time' => request()->time(),
				'method' => request()->method(),
	            'site_id' => SITEID,
	            'type' => request()->isMobile() ? 1 : 0,
	            'fromwhere' => getFromPage()
				];
			$visits::create($data,true);
			// if(config('sys.visits_count')) {
			// 	$count = $visits->count()-config('sys.visits_count');
			// 	if($count > 0) {
			// 		$ids = $visits->limit($count)->order('id asc')->column('id');
			// 		$visits->whereIn('id',$ids)->delete();
			// 	}
			// }
		}
	}

	// 防刷新
	private function refresh()
	{
		// 禁止代理访问
		empty($_SERVER['HTTP_VIA']) or $this->error(lang('no_access'));
		$seconds = config('sys.refresh_second'); //时间段[秒]
		$refresh = config('sys.refresh_times'); //刷新次数
		//设置监控变量
		$cur_time = time();
		if(session('?last_time')){
			session('refresh_times',session('refresh_times') + 1);
		}else{
			session('refresh_times',1);
			session('last_time',$cur_time);
		}
		//处理监控结果
		if($cur_time - session('last_time') < $seconds){
			if(session('refresh_times') >= $refresh){
				$this->error(lang('many_refresh'));
			}
		}else{
			session('refresh_times',0);
			session('last_time',$cur_time);
		}
	}
}