<?PHP
/*
 * date:
 */
/** Zend_Controller_Action */

class LoginController extends Zend_Controller_Action
{

	public $msg;
	public $registry;	
	public $config;
	public $view;
    /**
     * Initialize object.
     *
     * @return void
     */
	function init()
    {
        $this->registry = Zend_Registry::getInstance();
        $this->config = $this->registry['config'];
        $this->view = $this->registry['view'];
        $this->view->title = $this->config->webname;
        $this->view->author = $this->config->author;
        $this->view->baseUrl = $this->_request->getBaseUrl();
        $this->view->basePath = $this->_request->getBasePath();
        $this->view->user = (array)Zend_Auth::getInstance()->getIdentity();
    }
    public function indexAction()
    {
 		$this->view->moduletitle = '用户登录';   	
    	echo $this->view->render('index/showlogin.phtml');
    }
 	public function showloginAction()
	{
		$this->view->moduletitle = '用户登录';
        echo $this->view->render('index/showlogin.phtml');
	}
	public function loginAction()
	{
		if ($this->_request->isPost())
		{
			$StripTags = new Zend_Filter_StripTags();
            $username = $StripTags->filter($this->_request->getPost('username'));
            $password = $StripTags->filter($this->_request->getPost('password'));
		    if (empty($username)) 
		    {
                $this->view->msg = 'Please provide a username.';
            } 
            else 
            {
                $db = $this->registry['db'];
                $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'zf_members', 'username', 'password');
                $authAdapter->setIdentity($username);            
                $authAdapter->setCredential(md5($password));
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                if ($result->isValid()) 
                {
                    $data = $authAdapter->getResultRowObject(null, 'password');
                    $auth->getStorage()->write($data);
                    //$this->view->username= $username;
                    $this->_redirect('/');
                    return;
                } 
                else 
                {
                    // failure: clear database row from session
                    $this->view->msg = 'Login failed.';
                }
            }
		}
		$this->view->moduletitle = '用户登录';
		echo $this->view->render('index/showlogin.phtml');
	}
	public function showregAction()
	{
		$this->view->moduletitle = '用户注册';
        echo $this->view->render('index/showreg.phtml');
	}
	public function regAction()
	{
        $this->view->msg = '正在验证注册信息……<br>';
        if ($this->_request->isPost())
		{
            $StripTags = new Zend_Filter_StripTags();
		    $StringToLower = new Zend_Filter_StringToLower();
            $username = $StringToLower->filter($StripTags->filter($this->_request->getPost('username')));
            $email = $StripTags->filter($this->_request->getPost('email'));
		    $password = $this->_request->getPost('password');
		    $passwordc = $this->_request->getPost('passwordc');
		    $errno = false;
		    require_once 'Zend/Validate.php';
		    if (!Zend_Validate::is($username, 'NotEmpty'))
		    {
			    $this->view->msg .= '用户名不能为空！<BR>';
			    $errno = true;
		    }
		    if (!Zend_Validate::is($username,'StringLength',array(3, 10)))
		    {
			    $this->view->msg .= '用户名字符长度应在3-10之间！<BR>';
			    $errno = true;
		    }
		    if (!Zend_Validate::is($username,'Alnum'))
		    {
		    	$this->view->msg .= '用户名应该为字母和数字的组合！<BR>';
		    	$errno = true;
		    }		
		    if (!Zend_Validate::is($password, 'NotEmpty'))
		    {
		    	$this->view->msg .= '密码不能为空！<BR>';
		    	$errno = true;
		    }
		    if($password != $passwordc)
		    {
		    	$this->view->msg .= '两次密码不一致！<BR>';
		    	$errno = true;
		    }
		    if (!Zend_Validate::is($email, 'NotEmpty'))
		    {
		    	$this->view->msg .= 'Email不能为空！<BR>';
		    	$errno = true;
	    	}		
		    if (!Zend_Validate::is($email, 'EmailAddress'))
		    {
		    	$this->view->msg .= '电子邮件格式不符合标准！<BR>';
		    	$errno = true;
		    }
		    $db = $this->registry['db'];
		    $select = $db->select();
		    $select->from('zf_members', 'id')
		           ->where('username = ?', $username);
		    //$sql = $select->__toString();
		    $result = $db->fetchAll($select);  
		    //$params = array('username' => $username,'password' => $password);
		    //$result = $db->fetchAll($select, $params);
			$this->view->moduletitle = '用户注册';	    
		    if($result)
		    {
			    $this->view->msg .= $username.' 用户名已经存在！';	  
                echo $this->view->render('index/showreg.phtml');
		        return ;			      	
		    }
		    if($errno === true)
		    {
		    	//$this->view->message = $this->msg;
                echo $this->view->render('index/showreg.phtml');
		    	//echo '<br><br>三秒后跳转到注册页面……';
		        //header("refresh:3;url=./showreg");
		        return ;
		    }
		    echo '<br><br>开始注册……';
            $table = new ZfMembers();
		    $data = array(
		        'username' => $username,
		        'password'  => md5($password),    
		        'email' => $email,
		    );
		    $id = $table->insert($data);
		    if($id > 0)
		    {
                $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'zf_members', 'username', 'password');  
                $authAdapter->setIdentity($username);            
                $authAdapter->setCredential(md5($password));
                
                // do the authentication
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                if ($result->isValid()) 
                {
                    // success: store database row to auth's storage
                    // system. (Not the password though!)
                    $data = $authAdapter->getResultRowObject(null, 'password');
                    $auth->getStorage()->write($data);
                    //$this->view->username= $username;
                    $this->_redirect('/');
                    return;
                } 
		    	$this->_redirect('/showlogin');
		    	return;
		    }
		    $this->_redirect('/showreg');
		}

	}
	public function regsucAction()
	{
		echo '<br><br>';			
		echo '恭喜您，注册成功！';
		echo '<br><br>';
		echo '<a href='.$this->view->baseUrl.'>点击这里进入</a>';	
	}
	public function loginoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/');
	}
    /**
     * 缺省动作时调用
     */
    public function __call($method, $args)    
    {        
    	if ('Action' == substr($method, -6)) 
    	{            
    		// If the action method was not found, forward to the index action            
    		return $this->_forward('index');        
    	}        
    	// all other methods throw an exception        
    	throw new Exception('Invalid method "' . $method . '" called');    
    }	
}
?>