<?php

class PublicAction extends Action {
	
	public function index() {

	}

	public function login() {
		$furl = $_SERVER['HTTP_REFERER'];
		if (IS_POST) {
			$this->loginPost();
			exit();
		}
		$this->furl = $furl;
		$this->title = '用戶登錄';
		$this->display();
	}


	public function loginPost() {

		if (!IS_POST) exit();

		$furl = I('furl', '','htmlspecialchars,trim');
		if (empty($furl) || strpos($furl, 'register') || strpos($furl, 'login') || strpos($furl, 'logout') || strpos($furl, 'activate') || strpos($furl, 'sendActivate')) {
			$furl = U(GROUP_NAME. '/Member/index');
	
		}

		$email = I('email','','htmlspecialchars,trim');
		$password = I('password','');
		
		$verify = I('vcode','','md5');
		if (C('cfg_verify_login') == 1 && $_SESSION['verify'] != $verify) {
			$this->error('驗證碼不正確');
		}

		if ($email == '') {
			$this->error('請輸入帳號！', '', array('input'=>'email'));//支持ajax,$this->error(info,url,array);
		}

		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			$this->error('賬號為郵箱地址，格式不正確！', '', array('input'=>'email'));//支持ajax,$this->error(info,url,array);
		}

		if (strlen($password)<4 || strlen($password)>20) {
			$this->error('密碼必須是4-20位的字符！', '', array('input'=>'password'));
		}

	
		$user = M('member')->where(array('email' => $email))->find();

		if (!$user || ($user['password'] != get_password($password, $user['encrypt']))) {
			$this->error('賬號或密碼錯誤', '', array('input'=>'password'));
		}

		if ($user['islock']) {
			$this->error('用戶被鎖定！', '', array('input'=>''));
		}
		//更新數據庫的參數
		$data = array('id' => $user['id'] ,//保存時會自動為此ID的更新
				'logintime' => time(),
				'loginip' => get_client_ip(),
				'loginnum' => $user['loginnum']+1,

		);
		//更新數據庫
		M('member')->save($data);

		//保存Session
		//session(C('USER_AUTH_KEY'), $user['id']);
		//保存到cookie
		set_cookie( array('name' => 'uid', 'value' => $user['id'] ));
		set_cookie( array('name' => 'email', 'value' => $user['email'] ));
		set_cookie( array('name' => 'nickname', 'value' => $user['nickname'] ));
		set_cookie( array('name' => 'groupid', 'value' => $user['groupid'] ));//20140801
		set_cookie( array('name' => 'logintime', 'value' => date('Y-m-d H:i:s', $user['logintime'])));
		set_cookie( array('name' => 'loginip', 'value' => $user['loginip']));
		set_cookie( array('name' => 'status', 'value' => $user['status']));//激活狀態
		set_cookie( array('name' => 'verifytime', 'value' => time()));//激活狀態


		//跳轉
		//$this->redirect(GROUP_NAME.'/Member/index');
		//redirect(__GROUP__);
		$this->success('登錄成功', $furl , array('input'=>''));
	}

		//退出
	public function logout() {

		$furl = $_SERVER['HTTP_REFERER'];
	
		if (empty($furl) || strpos($furl, 'register') || strpos($furl, 'login') || strpos($furl, 'activate') || strpos($furl, 'sendActivate')) {
			$furl = U(GROUP_NAME. '/Public/login');
	
		}

		//session_unset();
		//session_destroy();
		del_cookie(array('name' => 'uid'));
		del_cookie(array('name' => 'email'));
		del_cookie(array('name' => 'nickname'));		
		del_cookie(array('name' => 'groupid'));
		del_cookie(array('name' => 'logintime'));
		del_cookie(array('name' => 'loginip'));
		del_cookie(array('name' => 'status'));


		//$this->redirect(GROUP_NAME.'/Public/login');
		$this->success('安全退出', $furl);
	}



		//自動登錄後，js驗證，更新積分
	public function loginChk() {

		if (!IS_AJAX) exit();

		

		$uid = intval(get_cookie('uid'));
		$email = get_cookie('email');
		$nickname = get_cookie('nickname');
		$logintime = get_cookie('logintime');
		$loginip = get_cookie('loginip');
		$verifytime = intval(get_cookie('verifytime'));//上次登錄時間

		$furl = '';

		$nickname = empty($nickname)? $email : $nickname;


		if ($uid <= 0 || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
			del_cookie(array('name' => 'uid'));
			del_cookie(array('name' => 'nickname'));
			del_cookie(array('name' => 'verifytime'));
			del_cookie(array('name' => 'logintime'));
			$this->error('請登錄', '');//支持ajax,$this->error(info,url,array);
		}

		if (date('Y-m-d', $verifytime) != date('Y-m-d', time())) {
			$user = M('member')->where(array('id'=> $uid, 'email' => $email))->find();
			if (!$user) {
				del_cookie(array('name' => 'uid'));
				del_cookie(array('name' => 'nickname'));
				del_cookie(array('name' => 'verifytime'));
				del_cookie(array('name' => 'logintime'));
				$this->error('請登錄!', '');
			}
			set_cookie( array('name' => 'verifytime', 'value' => time()));//本次狀態

		}

		$this->success('已登錄', $furl , array('nickname'=>$nickname));
	}


	//註冊
	public function register() {

		if (IS_POST) {
			$this->registerPost();
			exit();
		}

		$this->title = '用戶註冊';
		$this->display();
	}

	//兼容v1.5之前的註冊提交
	public function registerHandle() {
		$this->register();		
	}


	//註冊
	public function registerPost() {

		if (!IS_POST) {
			exit(0);
		}

		$password = I('password', '');

		
		$verify = I('vcode','','md5');
		if (C('cfg_verify_register') == 1 && $_SESSION['verify'] != $verify) {
			$this->error('驗證碼不正確');
		}
		//M驗證
		$validate = array(
			array('email','require','電子郵箱必須填寫！'),
			array('email','email','郵箱格式不符合要求。'), 
			//array('groupid','require','請選擇會員組！'), 
			array('password','require','密碼必須填寫！'), 
			array('rpassword','require','確認密碼必須填寫！'), 
			array('password','rpassword','兩次密碼不一致',0,'confirm'),
			array('email','','郵箱已經存在！',0,'unique',1), //使用這個是否存在，auto就不能自動完成
		);

				

		$db = M('member');
		if (!$db->validate($validate)->create()) {
			$this->error($db->getError());
		}
		
		if (strlen($password)<4 || strlen($password)>20) {
			$this->error('密碼必須是4-20位的字符！', '', array('input'=>'password'));
		}

		$nickname = I('nickname', '', 'htmlspecialchars,trim');
		$notallowname = explode(',', C('cfg_member_notallow'));
		if (in_array($nickname, $notallowname)) {
			$this->error('此暱稱系統禁用，請重新更換一個！');
		}

		//判斷後台是否開始郵件驗證
		$data['groupid'] = 2;//註冊會員
		/*
		$mGroup = M('membergroup')->Field('id')->find();
		if ($mGroup) {
			$data['groupid'] = $mGroup['id'];
		}
		*/


		$email = I('email', '', 'htmlspecialchars,trim');
		$data['email'] = $email;
		$data['nickname'] = $nickname;
		$data['nickname'] = I('nickname', '');
		//代替自動完成
		$data['regtime'] = time();
		$passwordinfo = I('password', '','get_password');
		$data['password'] = $passwordinfo['password'];
		$data['encrypt'] = $passwordinfo['encrypt'];
		$regtime = date('Y年m月d日', time());
		$nextday = date('Y年m月d日 H:i', strtotime("+2 day"));




		if($id = $db->add($data)) {
			$msg = '註冊會員成功<br/>'; 
			$active['expire'] = strtotime("+2 day")  ;//二天後時間截,相當於time() + 2 * 24 * 60 * 60
			$active['code'] = get_randomstr(11);
			$active['userid'] = $id;
			$active['id'] = M('active')->add($active);


		    $url = rtrim(C('cfg_weburl'),'/'). "/index.php?g=". GROUP_NAME ."&m=Public&a=activate&va={$active['id']}&vc={$active['code']}";
		    //$url = preg_replace("#http:\/\/#i", '', $url);
		    //$url = 'http://'.preg_replace("#\/\/#i", '/', $url);
		   
		    $webname = C('cfg_webname');
		    $weburl = C('cfg_weburl');
		    $weburl2 = str_replace('http://www.', '', $weburl);
		    $webqq = C('cfg_qq');
		    $webmail = C('cfg_email');
		   
			$subject = "[{$webname}]請激活你的帳號，完成註冊";
			$message = <<<str
<p>您於 {$regtime} 註冊{$webname}帳號 <a href="mailto:{$email}">{$email}</a> ，點擊以下鏈接，即可激活該帳號：</p>
<p><a href="{$url}" target="_blank">{$url}</a></p>
<p>(如果您無法點擊此鏈接，請將它複製到瀏覽器地址欄後訪問)</p>
<p>為了保障您帳號的安全性，請在 48小時內完成激活，此鏈接將在您激活過一次後失效！</p>
<p>此郵件由系統發送，請勿直接回復。</p>
str;
			if (C('cfg_member_verifyemail')) {
				if (SendMail($email, $subject , $message) == true) 
				{
					$msg .= '驗證郵件已發送，請盡快查收郵件，激活該帳號';
				} else {

					$msg .= '驗證郵件發送失敗，請寫管理員聯繫';
				}
			}
			
			$this->success($msg ,U(GROUP_NAME. '/Public/login'));
		}else {
			$this->error('註冊失敗');
		}

	}


	public function sendActivate() {


		$uid = get_cookie('uid');
		if (empty($uid)) {
			$this->error('請登錄後嘗試');
		}

		$user = M('member')->find($uid);		
		$email = $user['email'];
		$regtime = date('Y年m月d日', $user['regtime']);

		if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
	        $this->error('你的郵箱格式有錯誤！');
	    }

	    if($user['status'] == 1)
	    {
	        $this->error('你的帳號郵件已經激活，本操作無效！');
	    }

	    $actinfo = M('active')->where(array('userid' => $uid, 'expire' => array('gt', time())))->find();
	    $data = array();
	    //有記錄
	    if ($actinfo) {
	    	$data['id'] = $actinfo['id'];
	    	$data['expire'] = $actinfo['expire'] ;
			$data['code'] = $actinfo['code'];
			$data['userid'] = $uid;
	    }else {

	    	$data['expire'] = strtotime("+2 day")  ;//二天後時間截,相當於time() + 2 * 24 * 60 * 60
			$data['code'] = get_randomstr(11);
			$data['userid'] = $uid;
			//M('active')->delete($uid);//清除有的記錄
			$data['id'] = M('active')->add($data);

	    }
		
		$nextday = date('Y年m月d日 H:i', $data['expire']);

	    $url = rtrim(C('cfg_weburl'),'/'). "/index.php?g=". GROUP_NAME ."&m=Public&a=activate&va={$data['id']}&vc={$data['code']}";
	    //$url = preg_replace("#http:\/\/#i", '', $url);
	    //$url = 'http://'.preg_replace("#\/\/#i", '/', $url);

	    $webname = C('cfg_webname');
	    $weburl = C('cfg_weburl');
	    $weburl2 = str_replace('http://www.', '', $weburl);
	    $webqq = C('cfg_qq');
	    $webmail = C('cfg_email');
	   
	    $subject = "[{$webname}]會員郵件驗證通知，完成激活";
		$message = <<<str
<p>您於 {$regtime} 註冊{$webname}帳號 <a href="mailto:{$email}">{$email}</a> ，點擊以下鏈接，即可激活該帳號：</p>
<p><a href="{$url}" target="_blank">{$url}</a></p>
<p>(如果您無法點擊此鏈接，請將它複製到瀏覽器地址欄後訪問)</p>
<p>為了保障您帳號的安全性，請在 48小時內完成激活，此鏈接將在您激活過一次後失效！</p>
<p>此郵件由系統發送，請勿直接回復。</p>
str;

	$msg = ''; 
	if (SendMail($email, $subject , $message) == true) {
		$msg .= '驗證郵件已發送，請盡快查收郵件，激活該帳號';
	} else {

		$msg .= '驗證郵件發送失敗，請寫管理員聯繫';
	}
	$this->success($msg ,U(GROUP_NAME. '/Member/index'), 10);
	    
	}

	public function activate() {
		header("Content-Type:text/html; charset=utf-8");

		$id = I('va', 0, 'intval');
		$code = I('vc', '', 'htmlspecialchars,trim');
	    if(empty($code) || $id == 0)
	    {
	        exit('你的效驗串不合法！<a href="'. C('cfg_weburl') .'">返回首頁</a>');
	    }
	    $row = M('active')->where(array('id' => $id, 'expire' => array('gt', time())))->find();
	    if($code != $row['code'])
	    {
	        exit('激活碼過期或錯誤！<a href="'. C('cfg_weburl') .'">返回首頁</a>');
	    }

	    M('member')->where(array('id' => $row['userid'] ))->setField('status','1');//激活用戶狀態設置
	    //M('active')->delete($id);//從激活表中刪除
	     M('active')->where(array('id' => $row['id'] ))->setField('expire','0');//激活用戶狀態設置
	    // 清除會員緩存
	    //DelCache($mid);
	    $this->success('激活操作成功，請重新登錄！' ,U(GROUP_NAME. '/Public/login'));

	}



	/*Send verification code*/
	public function sendCode() {
		header("Content-Type:text/html; charset=utf-8");
		if (!IS_POST) {
			exit();
		}
		
		$email = I('username','','htmlspecialchars,trim');
		$flag = I('flag', 0, 'intval');

		//$flag為1時，需要驗證email是否已經被使用，註冊必需未使用的email
		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			//exit(json_encode(array('status'=>0,'info'=>'E-mail格式不正確！','input'=>'email')));
			//$this->ajaxReturn(array('status'=>0,'info'=>'E-mail格式不正確！','input'=>'email'),'JSON');//Thinkphp內部
			$this->error('E-mail格式不正確！','', array('input'=>'email'));//TP3.1後，error和success支持ajax返回

		}
		

		if ($flag) {
			
			if ($user = M('member')->where(array('email' => $email))->find()) {
				$this->error('郵箱已經存在，請更換郵箱或直接登錄！','', array('input'=>'email'));
			}

		}

		//查詢active表，是否發送過註冊驗證碼，發過，則不再重新生成新的驗證碼，直接發送
		$actinfo = M('active')->where(array('email' => $email, 'type' => 1, 'expire' => array('gt', time())))->order('expire DESC')->find();
	    $data = array();
	    //有記錄
	    if ($actinfo) {
	    	$data['id'] = $actinfo['id'];
			$data['userid'] = 0;
			$data['code'] = $actinfo['code'];
	    	$data['expire'] = $actinfo['expire'] ;
			$data['type'] = $actinfo['type'];
			//小於3分鐘,則更新有效期(延長)
			if ($data['expire'] - time() < 3 * 60) {
				$data['expire'] = time()+ 20 * 60;//20 minutes
				M('active')->where(array('id' => $data['id']))->setField('expire', $data['expire']);
			}
	    }else {

			$data['userid'] = 0;
			$data['code'] = get_random(6, '1234567890');//產生數字
	    	$data['expire'] = time()+ 20 * 60;//20 minutes//strtotime("+2 day")  ;
			$data['email'] = $email;
			$data['type'] = 1;
			//M('active')->delete($uid);//清除有的記錄
			$data['id'] = M('active')->add($data);

	    }
		
		$nextday = date('Y年m月d日 H:i', $data['expire']);



		$regtime = date('Y年m月d日', time());
		$nextday = date('Y年m月d日 H:i', strtotime("+2 day"));


		//$url = rtrim(C('cfg_weburl'),'/'). "/index.php?g=". GROUP_NAME ."&m=Public&a=activate&va={$active['id']}&vc={$active['code']}";
		    //$url = preg_replace("#http:\/\/#i", '', $url);
		    //$url = 'http://'.preg_replace("#\/\/#i", '/', $url);
		   
	    $webname = C('cfg_webname');
	    $weburl = C('cfg_weburl');
	    $weburl2 = str_replace('http://www.', '', $weburl);
	    $webqq = C('cfg_qq');
	    $webmail = C('cfg_email');
	   
		$subject = "[{$webname}]會員註冊驗證碼";
		$message = <<<str
<p>您本次申請的驗證碼為：{$data['code']}</p>
<p> </p>
<p>1、為了保障您的安全，請不要將以上驗證碼告訴任何人，本站工作人員不會向您索取驗證碼。</p>
<p>2、如果本次驗證碼並非您本人申請，請忽略本郵件。。</p>
<p>此郵件由系統發送，請勿直接回復。</p>
str;
		$msg = '';
		if (SendMail($email, $subject , $message) == true) 
		{
			$msg .= '';//'驗證郵件已發送，請盡快查收郵件，激活該帳號';
		} else {

			$msg .= '!';//'驗證郵件發送失敗，請寫管理員聯繫';
		}


		$this->success('驗證碼發送成功,請到郵箱查收'.$msg,'', array('input'=>'email'));
	
	}


	//增加點擊數
	public function click(){	
		$id = I('id', 0, 'intval');
		$tablename = I('tn', '');
		if (C('HTML_CACHE_ON') == true) {
			echo 'document.write('. getClick($id, $tablename) .')';
		}
		else {
			echo getClick($id, $tablename);
		}
		
	}


	//證碼碼
	public function verify(){	
		import('ORG.Util.Image');//導入驗證碼Image類庫
		return Image::buildImageVerify(4, 1);
	}


	//online
	public function online(){

		if (C('cfg_online_mode') != 1) {
			return '';
		}

		$_cfg_online_style = C('cfg_online_style');
		$_cfg_online_style = empty($_cfg_online_style) ? 'blue' : $_cfg_online_style;
		$_cfg_online_qq = C('cfg_online_qq');
		$_cfg_online_wangwang = C('cfg_online_wangwang');
		if (empty($_cfg_online_qq)) {
			$_cfg_online_qq = array();
		}else {
			$_cfg_online_qq = explode('|||', $_cfg_online_qq );
		}
		if (empty($_cfg_online_wangwang)) {
			$_cfg_online_wangwang = array();
		}else {
			$_cfg_online_wangwang = explode('|||', $_cfg_online_wangwang );
		}
		$_cfg_online_qq_param = C('cfg_online_qq_param');
		$_cfg_online_wangwang_param = C('cfg_online_wangwang_param');
		//位置
		$_divL = C('cfg_online_h') == 1 ? (-C('cfg_online_h_margin')-0.01) : C('cfg_online_h_margin');//水平
		$_divT = C('cfg_online_v') == 1 ? (-C('cfg_online_v_margin')-0.01) : C('cfg_online_v_margin');
		$_divM = 0;
		if (C('cfg_online_h') == 2 && C('cfg_online_v') == 2) {
			$_divM = 2;
		}elseif (C('cfg_online_h') == 2) {
			$_divM = 1;
		}elseif (C('cfg_online_v') == 2) {
			$_divM = -1;
		}
		//$js_path = str_replace("/", "\/", __ROOT__.'/Data');
		$js_path =  __ROOT__.'/Data';
		

		$str =<<<str
//動態加載
function loadScript(url,callback){ 
   var script = document.createElement("script") 
   script.type = "text/javascript"; 
   if (script.readyState){//IE 
      script.onreadystatechange = function(){ 
         if (script.readyState ==  "loaded" || script.readyState == "complete"){ 
            script.onreadystatechange = null;

            callback(); 
         } 
      }; 
   } else { //Others: Firefox, Safari, Chrome, and Opera 
      script.onload = function(){ 
          callback(); 
      }; 
   } 
   script.src = url; 
   document.body.appendChild(script);

}
function online_show() {
	if(document.getElementById("XYHOnlineView")){
		new scrollx({id:"XYHOnlineView",l:{$_divL},t:{$_divT},f:1,m:{$_divM}});
	}
}
	document.write('<link href="{$js_path}/static/js_plugins/online/{$_cfg_online_style}.css" rel="stylesheet" type="text/css" />');
	document.write('<div id="XYHOnlineView" class="xyh_online_view">');
	document.write('<div class="top_b"></div>');
	document.write('<div class="body">');
	document.write('<dl>');
	document.write('<dd class="title">在線客服</dd>');
	document.write('<dd>');
	document.write('	<span class="ico_zx">在線咨詢</span>');
	document.write('</dd>');
str;
	
	foreach($_cfg_online_qq as $autoindex => $_qq):
		$_qq_array = explode('$$$', $_qq);
		$_qq_array[1] = isset($_qq_array[1]) ? $_qq_array[1] : '點擊這裡給我發消息';
		$str .= 'document.write(\'<dd class="qq">\');';
		$str .= "document.write('".str_replace(array('[客服號]', '[客服說明]',"\r\n","'"), array($_qq_array[0], $_qq_array[1], '', "\'"), $_cfg_online_qq_param)."');";
		$str .= "document.write('</dd>');\n";
	endforeach;

	
	foreach($_cfg_online_wangwang as $autoindex => $_wangwang):
		$_wangwang_array = explode('$$$', $_wangwang);
		$_wangwang_array[1] = isset($_wangwang_array[1]) ? $_wangwang_array[1] : '點擊這裡給我發消息';
		$str .= 'document.write(\'<dd class="qq">\');';
		$str .= "document.write('".str_replace(array('[客服號]', '[客服說明]',"\r\n","'"), array($_wangwang_array[0], $_wangwang_array[1], '', "\'"), $_cfg_online_wangwang_param)."');";
		$str .= "document.write('</dd>');";
	endforeach;
			
	$str .= "document.write('</dl>');";
	$str .= "document.write('<dl>');";
			 
	if(C('cfg_online_phone') == 1) {	
		$str .= 'document.write(\'<dd class="title bborder">電話咨詢</dd>\');';
		$str .= 'document.write(\'<dd><span class="ico_tel">'.C('cfg_phone').'</span></dd>\');';

	}			


	if(C('cfg_online_guestbook') == 1) {

		$str .= 'document.write(\'<dd class="msg noborder"><a href="'.U('Guestbook/index').'" target="_blank">給我們留言</a></dd>\');';
	}
		
		
	$str .= "document.write('</dl>');";
	$str .= "document.write('</div>');";
	$str .= "document.write('</div>');";
	$str .= 'loadScript("'.$js_path.'/static/js_plugins/online/scrollx.js",online_show)';


	echo $str;

	}



}


