<?php
/**
 *----------------------------------------------------------------------------*
 * 版权所有 2010-2016 HuCart.COM，并保留所有权利。
 * 此程序是HuCart的一部分。  
 * 根据MIT许可证授权(在软件和软件的所有副本中都必须包含版权声明和许可声明。)
 * 官方网址:http://Www.HuCart.Com
 * 技术支持:http://Www.cheermi.com
 * 对于完整的版权和许可证信息，请参阅MIT-LICENSE.TXT
 * 程序的再发布必须保留以上版权声明。
 *
 *@author pgmk<pgmk@hucart.com>
 *@copyright pgmk<pgmk@hucart.com>
 *@link http://www.hucart.com
 *@license The MIT License.
 *----------------------------------------------------------------------------*
**/
if (!defined('HUCART_COM')) exit('HuCart.COM No direct script access allowed');
class Login extends HC_Controller
{
	//注意无须构造函数,使用了构造函数得重构父类 parent::__construct();
	function __construct()
	{
		parent::__construct();
		$this->load_lang(USER_PATH.'/login');
		
		$this -> load_model('web_config'); 	//加载模型
		$web_config = $this -> web_config_mod -> get_sys_config();
		$this -> view -> assign('web_config', $web_config);
		//var_dump($web_config);
		$this -> load('helper'); //加载辅助类
		$user_menu = $this -> web_config_mod ->  get_user_menu();
		$get_menu = $this -> web_config_mod -> get_web_menu();
		$get_link = $this -> web_config_mod -> get_link();
		$get_user_link = $this -> session->get_user_link( $this->lang['user_link'] );
		$this -> load_lib('safety');
		
		$this -> view -> assign('user_menu',$user_menu);
		$this -> view -> assign('get_menu',$get_menu);
		$this -> view -> assign('get_link',$get_link);
		$this -> view -> assign('get_user_link',$get_user_link);
		
	}
	
	public function act()
	{
		//var_dump($this);
		//缓存一天 //60 *  60 * 24 缓存时间 一天
		//$this -> view -> caching = true;
		//$this -> view -> cache_lifetime = 86400 ;  
		//$this -> view -> assign('copyright',COPYRIGHT);	//版权
		
		$this -> view -> assign('act_url',"./index.php?load=login&act=act_login");
		$this -> view -> display('login.tpl');
	}
	public function act_login(  )
	{
		$this -> load_db();
		$this -> load('helper'); //加载辅助类
		//var_dump( $this->input->post );
		//var_dump($this->get);
		
		$this -> del_session();
		
		$use_name 		= $this -> input -> post["use_name"]; 
		$use_pwd 		= $this -> input -> post["use_pwd"]; 
		$use_captchaval 	= $this -> input -> post["use_captcha"];
		if( $use_captchaval != $_SESSION["img_code"]['num'] )
		{
				$this -> view -> assign('info_title',$this->lang['err_captcha']);
				$this -> view -> assign('URL_TIME',URL_TIME);
				$this -> view -> assign('get_url',USER_WEBURL."/index.php?load=login&act=act");
				$this -> view -> display('suggestion.tpl');
		}else{
			
			if($this -> input -> check_illegal_str("use_name")){
					$this -> view -> assign('info_title',$this->lang['err_user_str']);
					$this -> view -> assign('URL_TIME',URL_TIME);
					$this -> view -> assign('get_url',USER_WEBURL."/index.php?load=login&act=act");
					$this -> view -> display('suggestion.tpl');
					
			}else{
			
				$user_ip = $this -> helper -> get_ip();
				
				//$this -> logincount($user_ip);
			
			
			
				$sql_query = " SELECT use_id,use_name,use_email  FROM ".$this -> db -> prefix."users WHERE use_name= '".$use_name."' AND  use_pwd = '".md5($use_pwd)."' and use_enabled = 1  ";
				//exit();
				$user_info["user"] = $this -> db -> select_one($sql_query);
	
				if($user_info["user"]["use_id"])
				{
					$this -> session -> set_session_arr( $user_info );
	
					$now 	   =  time();
					
					
					//登录成功更新用户信息
					$sql_update = " UPDATE ".$this -> db -> prefix."users  SET  use_login_count = use_login_count +1 , use_login_ip = '".$user_ip."', use_login_time = '".$now."'  WHERE  use_name= '".$use_name."'  and use_id = ".$user_info["user"]["use_id"]." " ;
					$this -> db -> query_sql($sql_update);
					
					//登录成功！重置IP错误信息清0！
					//$updateip = "UPDATE `".$this -> db -> prefix."use_login_error` SET usl_count =  0  WHERE  usl_ip = '".$user_ip."' AND usl_type = 'login' ";
					
					//$this -> db -> query_sql( $updateip );
					
					//写入IP记录
					$sql_insert = "INSERT INTO  `".$this -> db -> prefix."user_login_log` (`use_id` ,`usl_ip` ,`usl_time` ,`usl_type`)VALUES ( '".$user_info["user"]["use_id"]."','".$user_ip."','".$now."', 1)";
					$this -> db -> query_sql( $sql_insert );
					
					$this -> view -> assign('info_title',$this->lang['login_success']);
					$this -> view -> assign('URL_TIME',URL_TIME);
					$this -> view -> assign('get_url',USER_WEBURL);
					$this -> view -> display('suggestion.tpl');
					
					//var_dump($_SESSION);
					
				}else{
				
					$this -> view -> assign('info_title',$this->lang['err_user_pwd']);
					$this -> view -> assign('URL_TIME',URL_TIME);
					$this -> view -> assign('get_url',USER_WEBURL."/index.php?load=login&act=act");
					$this -> view -> display('suggestion.tpl');	
				}
			}
		}
	}
	
	public function login_count( $user_ip = '')
	{
		
		
		//0000-00-00 00:00:00
		$now 	   =  date("Y-m-d H:i:s");
		$yesterday =  date("Y-m-d H:i:s",strtotime("-1 day"));
		
		
		if( $user_ip!='Unknown' and $user_ip!='' )
		{
			//查询记录是否存在 use_session_id
			
			$sqlip = " SELECT usl_id , usl_session_id , usl_count , usl_start_time   FROM  ".$this -> db -> prefix."use_login_error WHERE usl_ip = '".$user_ip."' AND usl_type = 'login' LIMIT 1 ";
			$user_login_info = $this -> db -> select_one($sqlip);
			
			if($user_login_info["usl_id"])
			{
				//超过一天。重置时间及数量 更新用户登录当天1次
				if( $user_login_info["usl_start_time"] < $yesterday )
				{
				
					
					$update_login = "UPDATE `".$this -> db -> prefix."use_login_error` SET `usl_session_id` = '".$_SESSION["session_id"]."' , usl_start_time ='".$now."' ,usl_count = '1'  WHERE  usl_ip = '".$user_ip."' AND usl_type = 'login'   ";
					$this -> db -> query_sql( $update_login );

				}elseif( $user_login_info["usl_count"] >= 20 )
				{
						$updateip = "UPDATE `".$this -> db -> prefix."use_login_error` SET usl_count = usl_count + 1  WHERE  usl_ip = '".$user_ip."' AND usl_type = 'login' ";
						$this -> db -> query_sql( $updateip );
						$this -> view -> assign('info_title',$this->lang['err_need_tomorrow']);
						$this -> view -> assign('URL_TIME',URL_TIME);
						$this -> view -> assign('get_url',USER_WEBURL."/index.php?load=login&act=act");
						$this -> view -> display('suggestion.tpl');
					
				}else{
					if( $user_login_info["usl_count"] < 5 )
					{
						$updateip = "UPDATE `".$this -> db -> prefix."use_login_error` SET usl_count = usl_count + 1  WHERE  usl_ip = '".$user_ip."' AND usl_type = 'login' ";
						$this -> db -> query_sql($updateip);
						
					}elseif( $user_login_info["start_time"] > ( $now - 3600) )
					{
						$updateip = "UPDATE `".$this -> db -> prefix."use_login_error` SET usl_count = usl_count + 1  WHERE  usl_ip = '".$user_ip."' AND usl_type = 'login' ";
						$this -> db -> query_sql($updateip);

						$this -> view -> assign('info_title',$this->lang['err_count']);
						$this -> view -> assign('URL_TIME',URL_TIME);
						$this -> view -> assign('get_url',USER_WEBURL."/index.php?load=login&act=act");
						$this -> view -> display('suggestion.tpl');
						
					}else{
						$updateip = "UPDATE `".$this -> db -> prefix."use_login_error` SET  usl_count = usl_count + 1 ,usl_session_id = '".$_SESSION["session_id"]."'   WHERE  usl_ip = '".$user_ip."' AND usl_type = 'login' ";
						$this -> db -> query_sql($updateip);
					}


				}
				
				//时间未超过1小时，状态有效，数量是否超过5次
				//未超过5次更新+1
				

			}else{
				$insertip ="INSERT INTO `".$this -> db -> prefix."use_login_error` (`usl_session_id` , `usl_count` , `usl_ip` , `usl_start_time` , `usl_type` ) VALUES (  '".$_SESSION["session_id"]."', '1', '$user_ip', '$now', 'login')";
				$this -> db -> query_sql($insertip);	
			}
			
		}else{
		
			$this -> view -> assign('info_title',$this->lang['err_no_ip']);
			$this -> view -> assign('URL_TIME',URL_TIME);
			$this -> view -> assign('get_url',USER_WEBURL."/index.php?load=login&act=act");
			$this -> view -> display('suggestion.tpl');
			
		}
	
	}
	
	function find_pwd()
	{
		$this -> view -> assign('act_url',"./index.php?load=login&act=act_find_pwd");
		$this -> view -> display('find_pwd.tpl');	
	}
	
	
	function logout()
	{
		$this -> load('user'); 
		$this -> user -> drop_user_session();
		header("location:".USER_WEBURL."/index.php?load=login&act=act");
		exit();
	}
	
	function act_find_pwd()
	{
		exit('need_config_systeim!');
	}
	
	function reg()
	{
		//$this -> load_db();
		$this -> load_model('sys_config');
		
		$need_reg_info = $this -> sys_config_mod -> get_sys_config( $sys_type = 'reg' );
		
		if( $need_reg_info )
		{
			foreach($need_reg_info as $key => $val)
			{
				$needReg[$val["sys_code"]] = explode('|',$val["sys_value"]);	
			}
		}

		
		$this -> view -> assign('user_link',$this -> session -> get_user_link( $this->lang['user_link'] ));
		
		
		$webtitle = '免费注册';
		
		//处理你现在的位置
		$now_address = '您的位置：<a href="'.BASE_WEBURL.'/">首页</a> > <a href="'.BASE_WEBURL.'/user/login.php?load=login&act=reg">免费注册</a>';


		$this -> view -> assign('webtitle',$webtitle);
		$this -> view -> assign('now_address',$now_address);
		//var_dump($needReg);
		
		$this -> view -> assign('needReg',$needReg);

		$this -> view -> display('reg.tpl');
		

	}

	public function get_img_code()
	{
		$this -> load_lib('imgcode'); //加载辅助类
		$this -> imgcode_lib -> build_img_code();
	}
	
	public function reg_ajax(){
		
		//array(4) { ["load"]=> string(5) "login" ["act"]=> string(8) "reg_ajax" ["typeval"]=> string(4) "user" ["typename"]=> string(8) "use_name" } 
		$load 		= $this -> input -> get["load"]; 
		$act 		= $this -> input -> get["act"];
		$typeval 	= $this -> input -> post["typeval"];
		$typename 	= $this -> input -> post["typename"];
		if( $load == 'login' and $act =='reg_ajax' and $typeval !='' and $typename !='' ){
			
			if($typename=='use_name'){
				
				if (!eregi("^[_a-z0-9-]+([a-z0-9-]+)*$",$typeval))
				{ 
					 echo '帐号应为4-20个字符，只能使用小写字母(a-z)、数字(0-9)，且以字母或数字组合';
					 
				}else{
					
					//查询数据用户名是否存在
					$typeval = $this  -> safety_lib ->del_ext($typeval);
					$is_true = $this -> check_value( $typeval , 'use_name' );
					 if( $is_true )
					 {
						 echo 'success';	
					 }else{
					 	echo '该会员名已被注册使用。您可以:1、重新输入其他会员帐号。2、使用该会员名<a href="'.BASE_WEBURL.'/user/index.php?load=login&act=act" style="color:#FF0000" target="_blank">登录</a>';
						exit();
					 }
						  
				}
			}elseif($typename=='use_email'){
				if($this -> helper -> check_email( $typeval ))
				{ 
					 //查询数据用户名是否存在
					 $is_true = $this -> check_value( $typeval , 'use_email' );
					 if( $is_true )
					 {
						 echo 'success';	
					 }else{
					 	echo '该电子邮件已被使用。请重新输入其他电子邮件！';
						exit();
					 }
					
				}else{
					 echo '电子邮件格式不正确，请输入正确的电子邮件地址！';	 
					 exit();  
				}
				
			}else if($typename=='reg_qq')
			{
				if (!eregi("^[0-9-]+*$",$typeval))
				{ 
					 //查询数据用户名是否存在
					 $is_true = $this -> check_detail_value( $typeval , 'usd_qq' );
					 if( $info["CNUM"] < 1 )
					 {
						 echo 'success';	
					 }else{
					 	echo '该QQ号已被使用。请重新输入其他QQ号！';
						exit();
					 }
					
				}else{
					 echo 'QQ号格式不正确，请输入正确的QQ号！';	 
					 exit();  
				}
			 
			}else{
				echo '信息有误！';
			}
		
		
		
		}else{
			echo '信息不能为空！';
			
		}
		//var_dump($_REQUEST);
	}

	function reg_info()
	{
		$this -> del_session();

		$use_name 		= $this -> input -> post["use_name"];
		$use_email 		= $this -> input -> post["use_email"];
		

		$use_pwd 		= $this -> input -> post["use_pwd"];
		$reuse_pwd 		= $this -> input -> post["reuse_pwd"];
		
		$usd_truename 	= $this -> input -> post["usd_truename"];
		//$usd_province 	= $this -> input -> post["usd_province"];
		//$usd_cityval 		= $this -> input -> post["usd_city"];
		//$usd_district 	= $this -> input -> post["usd_district"];

		$usd_msn 			= $this -> input -> post["reg_msn"];
		$usd_qq 			= $this -> input -> post["reg_qq"];
		$usd_office_phone 	= $this -> input -> post["reg_phote"];
 		$usd_home_phone 	= $this -> input -> post["reg_home_phote"];
		$usd_tel 			= $this -> input -> post["reg_tel"];

		$use_name 		= $this  -> safety_lib ->del_ext($use_name);
		$use_email 		= $this  -> safety_lib ->del_ext($use_email);
		$usd_truename 	= $this  -> safety_lib ->del_ext($usd_truename);
		$usd_msn 		= $this  -> safety_lib ->del_ext($usd_msn);
		$reg_qq 		= $this  -> safety_lib ->del_ext($reg_qq);
		$usd_office_phone = $this  -> safety_lib ->del_ext($usd_office_phone);
		$usd_home_phone = $this  -> safety_lib ->del_ext($usd_home_phone);
		$usd_tel 		= $this  -> safety_lib ->del_ext($usd_tel);
		
		if($use_name !='' and $use_email !='' and $use_pwd !='' and $reuse_pwd == $use_pwd)
		{
			
			if (eregi("^[_a-z0-9-]+([a-z0-9-]+)*$",$use_name))
			{ 
				$is_use_name = $this -> check_value( $use_name , 'use_name' );
				if($is_use_name){
				
					$is_use_email = $this -> check_value( $use_email , 'use_email' );
					if($is_use_email){
					
							if($usd_tel!=''){
								$is_usd_tel = $this -> check_detail_value( $usd_tel , 'usd_tel' );
								if(!$is_usd_tel){
									$this -> view ->  assign('info_message',$this->lang["err_user_email_exist"]);
									$this -> view ->  assign('URL_TIME',URL_TIME);
									$this -> view ->  assign('get_url',BASE_WEBURL."/user/login.php?load=login&act=reg");
									$this -> view ->  display('suggestion.tpl');
								}
							}
							//可以注册
							//MD5加密码！！
							$md5use_pwd = md5($use_pwd);
							
							//最后收集信息
							$use_login_ip  = $this ->helper -> get_ip();
							$use_reg_timeval  = time();
							
							$insert_user ="INSERT INTO `".$this -> db -> prefix."users` (`use_name` ,  `use_email` , `use_pwd` ,`use_reg_time`,`use_login_ip` ) VALUES (  '$use_name',  '$use_email', '$md5use_pwd', '$use_reg_timeval','$use_login_ip')";
							
							$insertId = $this -> db -> insert_sql($insert_user);
							
							//`usd_province`,`usd_city`,`usd_district`, '$usd_province','$usd_cityval','$usd_district',
							$insert_detail ="INSERT INTO `".$this -> db -> prefix."user_detail` (`use_id` , `usd_truename`,`usd_msn` ,`usd_qq`,`usd_office_phone`,`usd_home_phone`,`usd_tel`) VALUES (  '$insertId',  '$usd_truename','$usd_msn','$usd_qq','$usd_office_phone','$usd_home_phone','$usd_tel')";
							$insertdetailId = $this -> db -> insert_sql($insert_detail);
							
							
							//登录设置
							$user_info["user"] = array('use_id' => $insertId ,'use_name' => $use_name, 'use_email' => $use_email);
							
							$this -> session -> set_session_arr( $user_info );
							
	
							
							$this -> view ->  assign('info_message',$this->lang["reg_susse"]);
							$this -> view ->  assign('URL_TIME',URL_TIME);
							$this -> view ->  assign('get_url',BASE_WEBURL."/user/");
							$this -> view ->  display('suggestion.tpl');
						
						
						
						
					
					}else{
						
						$this -> view ->  assign('info_message',$this->lang["err_user_email_exist"]);
						$this -> view ->  assign('URL_TIME',URL_TIME);
						$this -> view ->  assign('get_url',BASE_WEBURL."/user/login.php?load=login&act=reg");
						$this -> view ->  display('suggestion.tpl');
					}	
				
				
				}else{
					
					$this -> view ->  assign('info_message',$this->lang["err_user_name_exist"]);
					$this -> view ->  assign('URL_TIME',URL_TIME);
					$this -> view ->  assign('get_url',BASE_WEBURL."/user/login.php?load=login&act=reg");
					$this -> view ->  display('suggestion.tpl');
				}		
			}else{
				$this -> view ->  assign('info_message',$this->lang["err_user_str"]);
				$this -> view ->  assign('URL_TIME',URL_TIME);
				$this -> view ->  assign('get_url',BASE_WEBURL."/user/login.php?load=login&act=reg");
				$this -> view ->  display('suggestion.tpl');	
			}
			
			
			
			
		}else{
			
			$this -> view ->  assign('info_message',$this->lang["loss_error"]);
			$this -> view ->  assign('URL_TIME',URL_TIME);
			$this -> view ->  assign('get_url',BASE_WEBURL."/user/login.php?load=login&act=reg");
			$this -> view ->  display('suggestion.tpl');		
		}
	}

	private function check_value( $value = '' , $type='use_name' )
	{
			$this -> load_db();
			$sql_user = " SELECT count(1) as CNUM  FROM  ".$this -> db -> prefix."users  WHERE `".$type."` = '".$value."' ORDER BY `use_id` ";

			$info = $this -> db -> select_one($sql_user);
			if($info["CNUM"] < 1){
				return true;
			}else{
				return false;	
			}
	}
	
	private function check_detail_value( $value = '' , $type='reg_qq' )
	{
			$this -> load_db();
			$sql_user = " SELECT count(1) as CNUM  FROM  ".$this -> db -> prefix."user_detail  WHERE `".$type."` = '".$value."' ORDER BY `use_id` ";
			$info = $this -> db -> select_one($sql_user);
			if($info["CNUM"] < 1){
				return true;
			}else{
				return false;	
			}
	}
	
	private function del_session()
	{
		if (isset($_SESSION["img_code"]['time']) && $_SESSION["img_code"]['time'] + 30 < time()) {
			unset($_SESSION["img_code"]);
		}	
	}
	
}
