<?php
class indexAction extends BackendAction {

    public function _initialize() {
        parent::_initialize();
        $this->_mod = D('menu');
    }

    public function index() {
        $top_menus = $this->_mod->admin_menu(0);
        $this->assign('top_menus', $top_menus);
        $my_admin = array('username'=>$_SESSION['douhaocms']['username'], 'roleid'=>$_SESSION['douhaocms']['role_id'], 'rolename'=>$_SESSION['douhaocms']['role_name']);
        $this->assign('my_admin', $my_admin);
        $this->display();
    }
    protected function getversion(){
		$url = "https://cms.douhao.com/?m=api&a=getversion";
		$ch = curl_init();      
		$timeout = 60;       
		curl_setopt($ch, CURLOPT_URL, $url);     
		curl_setopt($ch, CURLOPT_REFERER, $_SERVER["QUERY_STRING"]);  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		 
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_TIMEOUT , 10);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		$source = curl_exec($ch);      
		curl_close($ch);
		$arr = json_decode($source,true);		
		if(!$arr['msg']){
		return 	$arr['version'];
		}
	}
    public function panel() {
		$version = $this->getversion();			
        $message = array();		
		if($version>DOUHAO_CMS_BANBEN){
			
		$message[] = array(
                'type' => 'Error',
                'content' => "逗号CMS有新版本更新啦！<a href=\"?g=admin&m=update&a=index&menuid=184\">点此立即升级吧！</a>【当前版本：V ".DOUHAO_CMS_BANBEN."，最新版本：V ".$version."】",
            );	
		}
        if (is_dir('./install')) {
            $message[] = array(
                'type' => 'Error',
                'content' => "您还没有删除 install 文件夹，出于安全的考虑，我们建议您删除 install 文件夹。",
            );
        }
        if (APP_DEBUG == true) {
            $message[] = array(
                'type' => 'Error',
                'content' => "您网站的 DEBUG 没有关闭，出于安全考虑，我们建议您关闭程序 DEBUG。",
            );
        }
        if (!function_exists("curl_getinfo")) {
            $message[] = array(
                'type' => 'Error',
                'content' => "系统不支持 CURL。",
            );
        }
		if(M('admin')->where(array('username' => 'admin'))->getField('password')){
			$password = M('admin')->where(array('username' => 'admin'))->getField('password');
			if($password=='21232f297a57a5a743894a0e4a801fc3'){
			$message[] = array(
                'type' => 'Error',
                'content' => '请修改系统默认的管理员账号admin和登陆密码。<a href="?g=admin&m=admin&a=index&menuid=61">立即修改</a>',
            );	
			}else{
		    $message[] = array(
                'type' => 'Error',
                'content' => '请修改系统默认的管理员账号admin。<a href="?g=admin&m=admin&a=index&menuid=61">立即修改</a>',
            );	
			}
		}
		$tlist = D('theme_log')->field('title,theme_key,theme_version')->order('id asc')->select();		
		if($tlist){
		foreach($tlist as $key=>$val){ 		   		   
		   $theme_version = $this->checktheme($val['theme_key'],$val['theme_version']);
		   if($val['theme_version']<$theme_version['theme_version']){
			   $message[] = array(
                'type' => 'Show',
                'content' => '<span class="blue">主题【<span class="red">'.$val['title'].'</span>】有新补丁待升级。<a href="?g=admin&m=theme_log&a=index&menuid=196">去升级</a></span>',
               );
		   }
		}
		}
		$plist = D('plugin_log')->field('title,plugin_key,plugin_version')->order('id asc')->select();		
		if($plist){
		foreach($plist as $key=>$val){ 		   		   
		   $plugin_version = $this->checkplugin($val['plugin_key'],$val['plugin_version']);
		   if($val['plugin_version']<$plugin_version['plugin_version']){
			   $message[] = array(
                'type' => 'Show',
                'content' => '<span class="blue">插件【<span class="red">'.$val['title'].'</span>】有新补丁待升级。<a href="?g=admin&m=plugin_log&a=index&menuid=197">去升级</a></span>',
               );
		   }
		}
		}
        $this->assign('message', $message);
		if (version_compare(substr(phpversion(), 0, 3), '7.0', '>=') && version_compare(substr(phpversion(), 0, 3), '7.4', '<=')) {
		$conn = mysqli_connect(C('DB_HOST') . ':' . C('DB_PORT'), C('DB_USER'), C('DB_PWD'),C('DB_NAME'));
		$mysql_version = mysqli_get_server_info($conn);
		}else{
		$mysql_version = mysql_get_server_info();	
		}
        $system_info = array(            
		    'douhaocms_version' => DOUHAO_CMS_BANBEN, 
            'server_os' => PHP_OS,
            'web_server' => $_SERVER["SERVER_SOFTWARE"],
            'php_version' => PHP_VERSION,   
			'mysql_version' => $mysql_version,
            'upload_max_filesize' => ini_get('upload_max_filesize'),
            'max_execution_time' => ini_get('max_execution_time') . '秒',
            'safe_mode' => (boolean) ini_get('safe_mode') ?  'onCorrect' : 'onError',
            'zlib' => function_exists('gzclose') ?  'onCorrect' : 'onError',
            'curl' => function_exists("curl_getinfo") ? 'onCorrect' : 'onError',
            'timezone' => function_exists("date_default_timezone_get") ? date_default_timezone_get() : L('no')
        );
        $this->assign('system_info', $system_info);
		$my_admin = array('username'=>$_SESSION['douhaocms']['username'], 'roleid'=>$_SESSION['douhaocms']['role_id'], 'rolename'=>$_SESSION['douhaocms']['role_name']); 
        $this->assign('my_admin', $my_admin);
		$this->assign('time',date('Y-m-d H:i'));
		$this->assign('ip',get_client_ip());
        $this->display();
    }
    protected function checktheme($key,$v){	
	    $url = 'https://cms.douhao.com/?m=xiazai&a=theme_up_version';
		$post = array(
	    'mod' => 'theme_up_version',
        'key' => $key,
		'v' => $v
	    );
		$data = $this->curl_post($url,$post);	
		$item = json_decode($data,true);		
		return $item;
	}
	protected function checkplugin($key,$v){	
	    $url = 'https://cms.douhao.com/?m=down&a=plugin_up_version';
		$post = array(
	    'mod' => 'plugin_up_version',
        'key' => $key,
		'v' => $v
	    );
		$data = $this->curl_post($url,$post);	
		$item = json_decode($data,true);		
		return $item;
	}
	public function curl_post($url,$post){
		$post = $post + array(
	    'from' => C('ftx_site_url'),
		'svs'=>$_SERVER["SERVER_ADDR"]
	    );		
		$post = http_build_query($post);
		$ch = curl_init();      
	    $timeout = 60;       
	    curl_setopt($ch, CURLOPT_URL, $url);         
		curl_setopt($ch, CURLOPT_REFERER, $_SERVER["HTTP_REFERER"]);  
	    curl_setopt($ch, CURLOPT_POST, true);      
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);      
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
		curl_setopt($ch, CURLOPT_TIMEOUT , 10);
	    $source = curl_exec($ch);      
	    curl_close($ch);	
		return $source;
	}
    public function login() {		
        if (IS_POST) {
			$this->_api = new douhaocms();
			$username = $this->_post('username', 'trim');
            $password = $this->_post('password', 'trim');
			if(!$username || !$password ){
                $this->error(L('input_empty'));
            }
            if(C('ftx_site_login_code')){
            $verify_code = $this->_post('verify_code', 'trim');
			$verify_code = strtolower($verify_code);
            if(session('verify') != md5($verify_code)){
                $this->error(L('verify_code_error'));
            }
			}
            $admin = M('admin')->where(array('username'=>$username, 'status'=>1))->find();
            if (!$admin) {
                $this->error(L('admin_not_exist'));
            }
            if ($admin['password'] != md5($password)) {
                $this->error(L('password_error'));
            }
			$login = $this->_api->sendurl($_SERVER['HTTP_HOST']);
			if($login == 1){
			$this->error('您好，您的网站使用的模板并未获得逗号CMS官方域名授权，请联系<a style="color:#red" target="_blank" href="https://cms.douhao.com/">逗号CMS系统</a>官方客服获取授权，感谢您的支持！','',30);	
			}
			if($login == 2){
			$this->error('您好，您的网址被相关部门监测有非法内容，请您清除非法内容后去腾讯申诉（<a style="color:#red" target="_blank" href="https://urlsec.qq.com/complain.html">点此申诉</a> ），申诉成功后会自动解除限制！','',30);	
			}            
            $admin_role = M('admin_role')->where(array('id'=>$admin['role_id']))->find();
            session('douhaocms', array(
                'id' => $admin['id'],
                'role_id' => $admin['role_id'],
                'role_name' => $admin_role['name'],
                'username' => $admin['username'],
            ));
            M('admin')->where(array('id'=>$admin['id']))->save(array('last_time'=>time(), 'last_ip'=>get_client_ip()));		
			$data['url'] = $_SERVER['HTTP_HOST'];
			$data['time'] = time();
			$data['ip'] = get_client_ip();
			$config_file = CONF_PATH . 'index/config.php';
            $config = include $config_file;
			$data['mulu'] = $config['DEFAULT_THEME'];
			$data['version'] = DOUHAO_CMS_BANBEN;
			$this->_api->sendlog($data);
			if($login == 3){
			$this->success('您好，您的网址被相关部门监测有非法内容，请您清除非法内容后去腾讯申诉（<a style="color:#red" target="_blank" href="https://urlsec.qq.com/complain.html">点此申诉</a> ），申诉成功后会自动解除限制！','',30);	
			}
            $this->success(L('login_success'), U('index/index'));
        } else {			
			if(!$_SERVER['HTTP_REFERER']){
			header("HTTP/1.1 403 Unauthorized");
	        exit();	
			}else{
			$this->display();	
			}			
            
        }
    }
    
    public function logout() {
        session('douhaocms', null);
        $this->success(L('logout_success'), U('index/login'));
        exit;
    }

    public function verify_code() {
        Image::buildImageVerify(5, 5, 'png', '84', '28', 'verify');
    }

    public function left() {
        $menuid = $this->_request('menuid', 'intval');
        if ($menuid) {
            $left_menu = $this->_mod->admin_menu($menuid);
            foreach ($left_menu as $key=>$val) {
                $left_menu[$key]['sub'] = $this->_mod->admin_menu($val['id']);
            }
        } else {
            $left_menu[0] = array('id'=>0,'name'=>L('common_menu'));
            $left_menu[0]['sub'] = array();
            if ($r = $this->_mod->where(array('often'=>1))->select()) {
                $left_menu[0]['sub'] = $r;
            }
            array_unshift($left_menu[0]['sub'], array('id'=>0,'name'=>L('common_menu_set'),'module_name'=>'index','action_name'=>'often_menu'));
        }
		$map['auth'] = 3;  
		$count = D('user')->where($map)->count('id');
		$this->assign('noauth', $count);
        $this->assign('left_menu', $left_menu);
        $this->display();
    }

    public function often() {
        if (isset($_POST['do'])) {
            $id_arr = isset($_POST['id']) && is_array($_POST['id']) ? $_POST['id'] : '';
            $this->_mod->where(array('ofen'=>1))->save(array('often'=>0));
            $id_str = implode(',', $id_arr);
            $this->_mod->where('id IN('.$id_str.')')->save(array('often'=>1));
            $this->success(L('operation_success'));
        } else {
            $r = $this->_mod->admin_menu(0);
            $list = array();
            foreach ($r as $v) {
                $v['sub'] = $this->_mod->admin_menu($v['id']);
                foreach ($v['sub'] as $key=>$sv) {
                    $v['sub'][$key]['sub'] = $this->_mod->admin_menu($sv['id']);
                }
                $list[] = $v;
            }
            $this->assign('list', $list);
            $this->display();
        }
    }
   	
	
		
    public function map() {
        $r = $this->_mod->admin_menu(0);
        $list = array();
        foreach ($r as $v) {
            $v['sub'] = $this->_mod->admin_menu($v['id']);
            foreach ($v['sub'] as $key=>$sv) {
                $v['sub'][$key]['sub'] = $this->_mod->admin_menu($sv['id']);
            }
            $list[] = $v;
        }
        $this->assign('list', $list);
        $this->display();
    }
}