<?php 

// h-source, a web software to build a community of people that want to share their hardware information.
// Copyright (C) 2010  Antonio Gallo (h-source-copyright.txt)
//
// This file is part of h-source
//
// h-source is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// h-source is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with h-source.  If not, see <http://www.gnu.org/licenses/>.

if (!defined('EG')) die('Direct access not allowed!');

class UsersController extends BaseController
{

	public function __construct($model, $controller, $queryString)
	{
		parent::__construct($model, $controller, $queryString);
		
		$this->model('UsersModel');
		$this->model('ProfileModel');
		$this->model('HardwareModel');

		$data['title'] = 'Login';
		$this->append($data);
	}
	
	public function login($lang = 'en')
	{
		$data = array();
		
		if ( strcmp($this->_updating,'no') === 0 )
		{
			$data['flag'] = isset($type) ? 'setted' : null;

			$data['title'] = 'Login - '.Website::$generalName;

			$redirect = $this->request->get('redirect','','sanitizeAll');
			
			$data['action'] = Url::getRoot("users/login/".$this->lang."?redirect=$redirect");
			
			$data['notice'] = null;
			
			$this->s['registered']->checkStatus();
				
			if ($this->s['registered']->status['status']=='logged') { //check if already logged
				$this->redirect('home/index/'.Lang::$current,3,'You are already logged...');
				die();
			}
			if (isset($_POST['username']) and isset($_POST['password']))
			{
				$username = ctype_alnum($_POST['username']) ? sanitizeAll($_POST['username']) : '';
				$choice = $this->s['registered']->login($username,$_POST['password']);

				switch($choice) {
					case 'logged':
						$this->redirect('home/index/'.Lang::$current,3,'You are already logged...');
						break;
					case 'accepted':
						if (strcmp($redirect,'') !== 0)
						{
							$redirect = html_entity_decode($redirect,ENT_QUOTES,DEFAULT_CHARSET);
							header('Location: http://'.DOMAIN_NAME."/".$redirect);
						}
						else
						{
							$this->redirect('home/index/'.Lang::$current,0);
						}
						break;
					case 'login-error':
						$data['notice'] = '<div class="alert">Wrong username or password</div>';
						break;
					case 'wait':
						$data['notice'] = '<div class="alert">You have to wait 5 seconds before you can try to login another time</div>';
						break;
				}
			}
		}
		
		$this->append($data);
		$this->load('login');
	}

	public function logout($lang = 'en')
	{
		$res = $this->s['registered']->logout();
		
		if ($res === 'not-logged')
		{
			$data['notice'] = "<div class='alert'>You can't logout because you are not logged...</div>\n";
		}
		else if ($res === 'was-logged')
		{
			$this->redirect('home/index/'.Lang::$current,0);
		}
		else if ($res === 'error')
		{

		}

		$this->append($data);
		$this->load('logout');
	}

	public function add($lang = 'en')
	{
		$data['title'] = 'create account - '.Website::$generalName;
		
		if ( strcmp($this->_updating,'no') === 0 )
		{
			//start session for captcha
			session_start();
			
			if ( isset($_SESSION['status']) ) unset($_SESSION['status']);
			
			$this->shift(1);
			
			$this->m['UsersModel']->strongConditions['insert'] = array(
				"checkAlphanum"		=>	"username",
				"checkLength|35"	=>	"username",
				"checkMail"			=>	"e_mail",
				"+checkLength|60"	=>	"e_mail",
				"checkEqual"		=>	"password,confirmation",
				"checkMatch|/^[a-zA-Z0-9\_\-\!]+$/"	=> "password,confirmation|characters allowed for the password: a-z A-Z 0-9 - _ !"
			);
			
			$this->m['UsersModel']->databaseConditions['insert'] = array(
				"checkUnique"		=>	"username|the username is already present",
				"+checkUnique"		=>	"e_mail|the e-mail address is already present"
			);
			
			if ($this->s['registered']->status['status'] === 'logged')
			{
				$this->redirect('home/index/'.$this->lang,2,'you are already logged..');
			}
			else
			{
				$data['notice'] = null;
				
				$this->m['UsersModel']->setFields('username:sanitizeAll,e_mail:sanitizeAll,password:sha1','none');
				
				$this->m['UsersModel']->updateTable('insert');
				
				$data['notice'] = $this->m['UsersModel']->notice;
				
				$values = $this->m['UsersModel']->getFormValues('insert','sanitizeHtml');
				$values['confirmation'] = '';

				$data['values'] = $values;

				$this->append($data);
				
				$this->load('add');
				$this->right();
			}
		}
		else
		{
			$this->redirect('users/login/'.$this->lang,0);
		}
	}
	
	public function confirm($lang = 'en', $id_user = 0, $confirmation_token = '')
	{
		$data['title'] = 'confirm account - '.Website::$generalName;
		
		if ( strcmp($this->_updating,'no') === 0 )
		{
			if ($this->s['registered']->status['status'] === 'logged')
			{
				$this->redirect('home/index/'.$this->lang,2,'you are already logged..');
			}
			else
			{
				$clean['id_user'] = (int)$id_user;
				$clean['confirmation_token'] = sanitizeAlphanum($confirmation_token);
				
				$data['status_confirm'] = false;
				
				$res = $this->m['UsersModel']->select('id_user,creation_time')->where(array("id_user"=>$clean['id_user'],"confirmation_token"=>$clean['confirmation_token'],"has_confirmed"=>1,"deleted"=>"no"))->send();
				
		// 		echo $this->m['UsersModel']->getQuery();
				
				if (count($res) > 0)
				{
					$now = time();
					$checkTime = $res[0]['regusers']['creation_time'] + Account::$confirmTime;
					if ($checkTime > $now)
					{
						$this->m['UsersModel']->values = array('has_confirmed' => 0, 'creation_time' => 0);
						if ($this->m['UsersModel']->update($clean['id_user']))
						{
							$data['status_confirm'] = true;
							
							//ad a record in the profile table
							$this->m['ProfileModel']->values = array('created_by' => $clean['id_user']);
							$this->m['ProfileModel']->insert();
							
						}
					}
				}
				
		// 		var_dump($data['status_confirm']);
				
				$this->append($data);
				$this->load('confirmation');
				$this->right();
			}
		}
		else
		{
			$this->redirect('users/login/'.$this->lang,0);
		}
	}

	public function change($lang = 'en', $id_user = 0, $forgot_token = '')
	{
		session_start();
		
		$data['title'] = 'change password - '.Website::$generalName;
		
		if ( strcmp($this->_updating,'no') === 0 )
		{
			if ($this->s['registered']->status['status'] === 'logged')
			{
				$this->redirect('home/index/'.$this->lang,2,'you are already logged..');
			}
			else
			{
				$clean['id_user'] = (int)$id_user;
				$clean['forgot_token'] = sanitizeAlphanum($forgot_token);
				
				$res = $this->m['UsersModel']->select('username,id_user,forgot_time,e_mail')->where(array("id_user"=>$clean['id_user'],"forgot_token"=>$clean['forgot_token'],"has_confirmed"=>0,"deleted"=>"no"))->send();
				
				if (count($res) > 0)
				{
					$now = time();
					$checkTime = $res[0]['regusers']['forgot_time'] + Account::$confirmTime;
					if ($checkTime > $now)
					{
						$username = $res[0]['regusers']['username'];
						$email = $res[0]['regusers']['e_mail'];
						
						$newPassword = generateString(10);
						$this->m['UsersModel']->values = array('password' => sha1($newPassword), 'forgot_time' => 0);
						if ($this->m['UsersModel']->update($clean['id_user']))
						{
							$result = Account::sendpassword($username,$email,$newPassword);
							
							if ($result)
							{
								$_SESSION['status'] = 'sent_new_password';
							}
							else
							{
								$_SESSION['status'] = 'sent_new_password_error';
							}
							
							$hed = new HeaderObj(DOMAIN_NAME);
							$hed->redirect('users/notice/'.Lang::$current,1);
							
						}
					}
				}
				
				$this->append($data);
				$this->load('change');
				$this->right();
			}
		}
		else
		{
			$this->redirect('users/login/'.$this->lang,0);
		}
	}

	public function forgot($lang = 'en')
	{
		$data['title'] = 'request password - '.Website::$generalName;
		
		if ( strcmp($this->_updating,'no') === 0 )
		{
			session_start();
			
			if ( isset($_SESSION['status']) ) unset($_SESSION['status']);
			
			$this->shift(1);
			
			if ($this->s['registered']->status['status'] === 'logged')
			{
				$this->redirect('home/index/'.$this->lang,2,'you are already logged..');
			}
			else
			{
				$data['notice'] = null;
				
				if (isset($_POST['forgotAction']))
				{
					if (isset($_POST['username']))
					{
						$this->m['UsersModel']->forgot($_POST['username']);
						$data['notice'] = $this->m['UsersModel']->notice;
					}
				}
			
				$this->append($data);
				
				$this->load('forgot');
				$this->right();
			}
		}
		else
		{
			$this->redirect('users/login/'.$this->lang,0);
		}
	}

	public function notice($lang = 'en')
	{
		$data['title'] = 'notice - '.Website::$generalName;
		
		if ( strcmp($this->_updating,'no') === 0 )
		{
			session_start();
			if ($this->s['registered']->status['status'] === 'logged')
			{
				$this->redirect('home/index/'.$this->lang,2,'you are already logged..');
			}
			else
			{
				$this->load('notice');
				$this->right();
			}
		}
		else
		{
			$this->redirect('users/login/'.$this->lang,0);
		}
	}

}