<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

	class Auth
	{
		public $avatar_width=75;
		public $avatar_height=75;
		public $types=array(	1 => 'gif',
								2 => 'jpg',
								3 => 'png');
		public $use_openid=false;
		public $allow_register=false;
		public $allow_ask_new_pass=false;
		public $activation=false;
		public $default_group=2;
		
		public $providers=array();
		
		public $validation=1;
		
		/*actions*/
		
		function __construct()
		{
			//проверка полей на сервере и на клиенте
			$this->validation=HTML_QuickForm2_Rule::SERVER | HTML_QuickForm2_Rule::CLIENT;

			$this->allow_register=!empty(LabConfig::$mcfg['allow_register']);
			$this->use_openid=!empty(LabConfig::$mcfg['use_openid']);
			
			$this->allow_ask_new_pass=!empty(LabConfig::$mcfg['allow_ask_new_pass']);
			$this->activation=!empty(LabConfig::$mcfg['activation']);
			if (!empty(LabConfig::$mcfg['default_group'])) $this->default_group=LabConfig::$mcfg['default_group'];
		
			//размер аватары
			if(!empty(LabConfig::$mcfg['avatar_size']))
			{
				list ($this->avatar_width, $this->avatar_height) = explode('x', LabConfig::$mcfg['avatar_size']);
				if (intval($this->avatar_width)<=0 || intval($this->avatar_height)<=0)
				{
					$this->avatar_width=$this->avatar_height=75;
				}
			}
		}
		
		public function login()
		{
			$login_secsess=false;

			$form=$this->buildAuthForm();
			if ($form->validate())
			{
				$data=$form->getValue();
				if ($data['login'] && $data['pass'])
				{
					$login_secsess=$this->authUserByLogin($data);
				}
				elseif ($data['openid'])
				{
					$oid=new OpenId();
					$oid->returnTo=$oid->getTrustRoot()
									.LabCMS::i()->url(false, 'openid_auth')
									.'?'
									.(!empty($_POST['rememberme'])?"rememberme=1&":'')
									.(!empty($_REQUEST['redirect'])?"redirect=".urlencode((string)$_REQUEST['redirect']):'');
					$oid->SendOpenId($data['openid']);
				}
			}

			if($login_secsess)
			{
				$this->_setLAstLoginTime();
				$this->assign('_user', User::i());
				$this->assign('login_secsess', $login_secsess);
				if (empty($_REQUEST['redirect'])) refresh('', $_SERVER['REQUEST_URI']);
				else $this->assign('redirect', (string)$_REQUEST['redirect']);
			}
			else
			{
				$this->assign('form', $this->_render($form));
			}				
		}
		
		public function logout($redirect)
		{
			User::checkToken();
			User::i()->logout();
			$redirect = str_replace(array("\n", "\r"), '', $redirect);
			refresh('', $redirect);
		}


		public function OpenId()
		{
			$form=$this->buildChangeOpenIDForm(User::i()->id);
			
			if ($form->validate())
			{
				$data=$form->getValue();
				if ($data['delopenid']) $this->deleteOpenID(User::i()->id, array_keys($data['delopenid']));
				if ($data['openid'])
				{
					$oid=new OpenId();
					$oid->returnTo=$oid->getTrustRoot().LabCMS::i()->url(false, 'add_openid');
					$oid->SendOpenId($data['openid']);
					//User::i()->ForceResetSession();
				}
				else refresh('', LabCMS::i()->url(false, 'openid'));
			}
			
			$this->assign('form', $this->_render($form));
		}
		
		public function editInfo()
		{
			//если пользователь авторизовался более 10 минут назад - требуем повторную авторизацию
			if ($_SESSION['last_login_time']<(time()-60*10))
			{
				User::checkToken();
				User::i()->logout();
				refresh('', LabCMS::i()->url(false, false, false, false, LabCMS::i()->url(false, 'edit')));
			}
			
			$form=$this->buildUserInfoForm(User::i()->id);
			
			if ($form->validate())
			{
				$this->updateUserInfo(User::i()->id, $form->getValue());
			}
			
			$this->assign('form', $this->_render($form));
		}
		
		public function lostPassword()
		{
			$sended=false;
			$form=$this->buildLostPassForm();
			if ($form->validate())
			{
				$data=$form->getValue();
				$sended=$this->sendNewPassword($data['recover_info']);
			}

			if(!$sended) $this->assign('form', $this->_render($form));
		}
		
		
		public function register()
		{
			$is_ok=false;
			$form=$this->buildRegisterForm();
			
			isNotBot($_POST['login']);
			
			if ($form->validate())
			{
				$is_ok=$this->_checkRegisterForm($form->getValue());
				if ($is_ok && !$this->activation)
				{
					$this->_setUserLogged($is_ok);
					$this->setMessage('Спасибо за регистрацию!');
				}
			}

			if (!$is_ok) $this->assign('form', $this->_render($form));
		}
		
		public function registerByOpenId()
		{
			$is_ok=false;
			$data=$this->getRegisterByOpenIdData();
			if ($data)
			{
				$form=$this->buildRegisterByOpenIDForm($data);

				if ($form->validate())
				{
					$data=$form->getValue();
					$is_ok=$this->_insertUser($data);
					$this->_insertOpenID($is_ok, $data['openid']);
					if ($is_ok && !$this->activation)
					{
						$this->_setUserLogged($is_ok);
						$this->setMessage('Спасибо за регистрацию!');
						refresh();
					}
				}
				
				if (!$is_ok) $this->assign('form', $this->_render($form));
			}
		}
		
		function authUserByLogin($data)
		{
			if (User::i()->auth($data)) return true;
			else
			{
				$this->error("Не угадали логин или пароль! Попробуем еще раз?");
				return false;
			}
		}

		function authByOpenID()
		{
			
			if (!empty($_GET['openid_mode']) && $this->use_openid)
			{
				$oid=new OpenId();
				$open_id=$oid->CheckAuthByOpenId();
				if (!$open_id) return false;
				if (!User::i()->auth(array('openid'=>$open_id, 'rememberme'=>$_GET['rememberme']))) LabCMS::i()->error(sprintf(_m('Пользователь %s не найден'), $open_id), true);
				else
				{
					$this->_setLastLoginTime();
					if (empty($_REQUEST['redirect'])) refresh();
					$this->assign('redirect', $_REQUEST['redirect']);
					$this->assign('login_secsess', true);
				}
			}
		}

		protected function _setLastLoginTime()
		{
			$_SESSION['last_login_time']=time();
		}
		
		function reGetCode()
		{
			$form=$this->buildReGetCodeForm();
			$sended=false;
			if ($form->validate())
			{
				$data=$form->getValue();
				$sended=$this->_resendActivationCode($data['email']);
			}

			if(!$sended)	$this->assign('form', $this->_render($form));
		}
		
		function changePass()
		{
			$form=$this->buildChangePasswordForm();

			if ($form->validate())
			{
				$data=$form->getValue();
				$this->setNewPass($data['newpass']);
				$this->setMessage('Пароль изменен');
			}

			$this->assign('form', $this->_render($form));
		}
		
		function buildUserInfoForm($user_id)
		{
			$user=$this->getUserInfo($user_id);
			$form = new HTML_QuickForm2('profile', 'post', array('enctype'=>'multipart/form-data', 'action'=>LabCMS::i()->url(false, 'edit')));
			$token=$form->addElement('hidden', 'token', array('value' => User::i()->token));
			$form->addDataSource(new HTML_QuickForm2_DataSource_Array(array(
				'email'		=> $user['email'],
				'realname'	=> $user['realname'],
				'website'	=> $user['website'],
				'icq'		=> $user['icq']
			)));
			
			$token->addRule('callback', _m('Ошибка сессии'), array('callback'=>array('User', 'checkToken'), 'arguments'=>array(false)));
			
			$email=$form->addElement('text', 'email', array('maxlength'=>50), array('label' => 'Email:'));
			$this->_addEmailRules($email);
					
			$realname=$form->addElement('text', 'realname', null, array('label' => _m('Настоящее имя:')));
			$website=$form->addElement('text', 'website', null, array('label' => _m('Домашняя страница:')));
			$icq=$form->addElement('text', 'icq', null, array('label' => _m('ICQ:')));

			$maxfilesize=51200;
		
			$avatar=$form->addElement('file', 'avatar', null, array('label' => sprintf(_m('Аватар:').' <br />%s:', '('.$this->avatar_width.'px*'.$this->avatar_height.'px) <'.get_formatted_filesize($maxfilesize))));
			$avatar->addRule('mimetype', _m('Данный тип файла не поддерживается'),
                 array('image/gif', 'image/png', 'image/jpeg', 'image/pjpeg'));
			$avatar->addRule('maxfilesize', _m('Файл слишком большой. Разрешены файлы не больше ').get_formatted_filesize($maxfilesize), $maxfilesize);

			if($user['avatar']) 
			{
				$alabel='<br /><img src="/storage/Image/avatars/'.$user_id.'.'.$this->types[$user['avatar']].'?'.rand().'" />';
				$form->addElement('checkbox', 'del_avatar', null, array('label' => _m('Удалить аватар:').$alabel, 'content'=>''));
			}
			$form->addElement('submit', null, array('value'=>_m('Изменить')));
			return $form;
		}
		

		public function buildChangePasswordForm()
		{
			$form = new HTML_QuickForm2('password', 'post', array('action'=>''));
			$token=$form->addElement('hidden', 'token', array('value' => User::i()->token));
			$oldPassword=$form->addElement('password', 'pass', null, array('label' => _m('Текущий пароль:')));
			$newPassword=$form->addElement('password', 'newpass', null, array('label' => _m('Новый пароль:')));
			$repPassword=$form->addElement('password', 'repass', null, array('label' => _m('Ввести повторно:')));
			
			$token->addRule('callback', _m('Ошибка сессии'), array('callback'=>array('User', 'checkToken'), 'arguments'=>array(false)));
			$oldPassword->addRule('required');
			$newPassword->addRule('required');
			$repPassword->addRule('required');
			
			$oldPassword->addRule('nonempty')
						->or_($oldPassword->addRule('callback', _m('Неверно введен пароль'), array($this, 'checkOldPass')));

			$newPassword->addRule('nonempty', _m('Пароль не может быть пустым'));
			$newPassword->addRule('eq', _m('Пароли не совпадают'), $repPassword);
			$repPassword->addRule('eq', '&nbsp;', $newPassword);
			
			$form->addElement('submit', null, array('value'=>_m('Изменить')));
			return $form;
		}


		public function buildChangeOpenIDForm($user_id)
		{
			$form = new HTML_QuickForm2('openid_tool', 'post', array('action'=>''));
			$token=$form->addElement('hidden', 'token', array('value'=>User::i()->token));
			$token->addRule('callback', _m('Ошибка сессии'), array('callback'=>array('User', 'checkToken'), 'arguments'=>array(false)));
			
			$oids=$this->_getOpenIDs($user_id);
			if($oids) foreach($oids as $key=>$oid)
			{
				$form->addElement('checkbox', 'delopenid['.$key.']', null, array('label' => $oid.' '._m('(удалить):')));
			}
			
			$this->addOpenIDProvidersToForm($form);

			$form->addElement('submit', null, array('value'=>_m('Применить')));
			return $form;
		}
		

		public function buildAuthForm()
		{
			$form = new HTML_QuickForm2('auth_form', 'post', array('action'=>''));
			$token=$form->addElement('hidden', 'token', array('value'=>User::i()->token));
			$field=$form->addElement('fieldset')->setLabel(_m('Введите логин и пароль'));

			$login=$field->addElement('text', 'login', array('maxlength'=>20), array('label' => _m('Логин:')));
			$pass=$field->addElement('password', 'pass', null, array('label' => _m('Пароль:')));

			$token->addRule('callback', _m('Ошибка сессии'), array('callback'=>array('User', 'checkToken'), 'arguments'=>array(false)));
			$rule=$login->addRule('nonempty', _m('Нужно указать логин'), null, $this->validation);
			$login->addRule('nonempty', '', null, $this->validation)->and_($pass->createRule('nonempty', _m('Пароль не может быть пустым')));
					
			if ($this->use_openid)
			{
				$openid=$this->addOpenIDProvidersToField($form);
				$rule->or_($openid->createRule('nonempty', _m('или OpenId')));
			}

			$form->addElement('checkbox', 'rememberme', null, array('label' => _m('Запомнить меня:'), 'content'=>''));
			$form->addElement('submit', null, array('value'=>_m('Отправить')));
			
			return $form;
		}
		

		public function buildRegisterForm()
		{
			$form = new HTML_QuickForm2('register_form', 'post', array('action'=>''));
			$field=$form->addElement('fieldset')->setLabel(_m('Введите данные для регистрации'));

			$token=$form->addElement('hidden', 'token', array('value'=>User::i()->token));
			$login=$field->addElement('text', LabConfig::$cfg['catcher'], array('maxlength'=>20), array('label' => _m('Логин:').$this->getCatcher));
			$pass=$field->addElement('password', 'pass', null, array('label' => _m('Пароль:')));
			$repass=$field->addElement('password', 'repass', null, array('label' => _m('Ввести повторно:')));
			$email=$field->addElement('text', 'email', array('maxlength'=>50), array('label' => _m('Email:')));

			if ($this->use_openid)
			{
				$this->addOpenIDProvidersToField($form)
				->addRule('callback', 'Ошибка OpenId', array($this, 'sendRegOpenId'));
			}
			
			$form->addElement('submit', null, array('value'=>_m('Зарегистрироваться')));

			$token->addRule('callback', _m('Ошибка сессии'), array('callback'=>array('User', 'checkToken'), 'arguments'=>array(false)));
			$pass->addRule('required', _m('Пароль не может быть пустым'), null, $this->validation);
			$repass->addRule('required');
			$pass->addRule('eq', _m('Пароли не совпадают'), $repass, $this->validation);
			$repass->addRule('eq', '&nbsp;', $pass);
			
			$this->_addLoginRules($login);
			$this->_addEmailRules($email);
			
			return $form;
		}
		

		public function buildLostPassForm()
		{
			$form = new HTML_QuickForm2('recovery', 'post', array('action'=>''));
			$token=$form->addElement('hidden', 'token', array('value'=>User::i()->token));
			$recovery=$form->addElement('text', 'recover_info', null, array('label' => _m('Введите логин или email:')));
			$recovery->addRule('required', _m('Нужна хоть какая-то информация:)'), null, $this->validation);
			
			$token->addRule('callback', _m('Ошибка сессии'), array('callback'=>array('User', 'checkToken'), 'arguments'=>array(false)));
			
			$form->addElement('submit', null, array('value'=>_m('Восстановить пароль')));
			return $form;
		}
		
		public function buildReGetCodeForm()
		{
			$form = new HTML_QuickForm2('get_code', 'post', array('action'=>''));
			$token=$form->addElement('hidden', 'token', array('value'=>User::i()->token));
			$email=$form->addElement('text', 'email', array('maxlength'=>50), array('label' => _m('Введите email:')));
			$form->addElement('submit', null, array('value'=>_m('Запросить код')));

			$token->addRule('callback', _m('Ошибка сессии'), array('callback'=>array('User', 'checkToken'), 'arguments'=>array(false)));
			$email->addRule('required', _m('Нужно указать email'), null, $this->validation);
			$email->addRule('regex', _m('Сдается нам, таких email-ов не бывает'),
									  '/\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/i', $this->validation);
			
			return $form;
		}
		

		public function buildRegisterByOpenIDForm($data)
		{
			$form = new HTML_QuickForm2('register', 'post', array('action'=>''));
			
			if (is_array($data)) $form->addDataSource(new HTML_QuickForm2_DataSource_Array($data));
			$token=$form->addElement('hidden', 'token', array('value'=>User::i()->token));
			$token->addRule('callback', _m('Ошибка сессии'), array('callback'=>array('User', 'checkToken'), 'arguments'=>array(false)));
			
			$form->addElement('hidden', 'openid');
			$form->addElement('hidden', 'register_code');
			$login=$form->addElement('text', 'login', array('maxlength'=>20), array('label' => _m('Логин:')));
			$email=$form->addElement('text', 'email', array('maxlength'=>50), array('label' => _m('Email:')));
			$form->addElement('submit', null, array('value'=>_m('Зарегистрироваться')));

			$rule=$this->_addLoginRules($login);
			if ($data['login']) $rule->validate();
			$rule=$this->_addEmailRules($email);
			if ($data['email']) $rule->validate();
			
			return $form;
		}


		function addOpenID()
		{
			$oid=new OpenId();
			
			if ($openid=$oid->CheckAuthByOpenId())
			{
				if ($user_id=$this->getUserIdByOpenId($openid))
				{
					if ($user_id!=User::i()->id) $this->error('Такой OpenID уже зарегистрирован: '.$openid);
					else return $openid;
				}
				else
				{
					if ($this->_insertOpenID(User::i()->id, $openid))	return $openid;
				}
			}
			return false;
		}


		public function activation()
		{
			$user_data = Db::i()->selectRow("SELECT user_id, status, login, actkey  FROM ?_users WHERE user_id = ?", $_GET['var1']);
		
			if($user_data['user_id'])
			{
				if($user_data['status'] > 0)
				{
					$this->error("Аккаунт уже был активирован");
					return false;
				}
		
				if ($user_data['actkey']!=$_GET['var2'])
				{
					$this->error("Неправильный код активации!");
					return false;
				}
				else
				{
					Db::i()->query("UPDATE ?_users SET status = 1 WHERE user_id=?", $user_data['user_id']);
					$this->_setUserLogged($user_data['user_id']);
					$this->setMessage("Спасибо за активацию!");
					return true;
				}
			}
			else
			{
				$this->error("Такой пользователь в базе не числится!");
				return false;
			}
		}
		
		function sendNewPassword($identy)
		{
			$lost_info = Db::i()->select("SELECT login, email, realname, user_id FROM ?_users WHERE login=? OR email=? AND `status`>=0", trim($identy), trim($identy));

			if(!$lost_info)
			{
				$this->error("Пользователь не найден");
				return false;
			}
			
			if(count($lost_info)>1)
			{
				$this->error("Такой email у нескольких пользователей");
				return false;
			}
			
			$lost_info=$lost_info[0];
			
			$retrive = array(
			'user_id'=>$lost_info["user_id"],
			'login'=>$lost_info["login"],
			'email'=>$lost_info["email"],
			'new_pass'=>$this->_genKey(10),
			'key'=>md5($this->_genKey(10))
			);
			Db::i()->query("UPDATE ?_users SET ?a WHERE user_id = ?",array('new_pass'=>User::PassHash($retrive['new_pass']),'actkey'=>$retrive['key']),$lost_info["user_id"]);
			
			//TODO проверить работает ли отправка
			$email=array($lost_info["email"]=>($lost_info["realname"]?$lost_info["realname"]:$lost_info["login"]));
			$mail=new Mailer($email);
			$this->assign("retrive",$retrive);

			$message = Tpl::i()->fetch('login/newpass_mail.tpl');

			$mail->From     = 'robot@'.preg_replace('/^www\./i', '', $_SERVER["HTTP_HOST"]."");
			$mail->Subject = _m("Восстановление пароля для сайтa")." http://".$_SERVER["HTTP_HOST"];
			$mail->Body     =  $message;
			$mail->AltBody  =  strip_tags($message);
			if(!$mail->Send())
			{
				  $this->error("Ошибка работы почтового робота");
				  return false;
			}
			$this->setMessage(_m('Новый пароль отправлен на почтовый адрес ').$lost_info["email"], false, true);
			return true;
		}
		
		
		function updateUserInfo($user_id, $data)
		{
			if ($data['avatar']['size'])
				if (!$data['avatar']=$this->_addAvatar($data['avatar']['tmp_name'], $user_id)) return;
			if ($data['del_avatar']) $data['avatar']=$this->_removeAvatar($user_id);
	
			//убираем данные, которые в базе не нужны
			unset($data['del_avatar'], $data['qf__profile'], $data['token']);
			if (is_array($data['avatar'])) unset($data['avatar']);
			
			$data["website"] = preg_replace('#^https?://#i', '', $data["website"]);
			$data["icq"] = intval($data["icq"])?intval($data["icq"]):null;
			
			Db::i()->query("UPDATE ?_users SET  ?a WHERE `user_id` = ?", $data, $user_id);// Обновим пользователя

			//уничтожаем текущую сессии
			User::i()->ForceResetSession();
			
			$this->_setLAstLoginTime();
			refresh('', LabCMS::i()->url(false, 'profile'));

		}
		
		
		protected function _checkRegisterForm($data)
		{
			if ($this->activation) $this->_celeanUnactivatedUsers();
			
			$data['login']=$data[LabConfig::$cfg['catcher']];
			unset($data[LabConfig::$cfg['catcher']]);
			
			return $this->_insertUser($data);
		}
		
		protected function _insertUser($data)
		{
			$row["login"]=preg_replace('/\s+/', ' ', trim($data['login']));
			$row["email"]=trim($data['email']);
			$row['group_id']=$this->default_group;
			if ($data["pass"]) $row["pass"] = User::PassHash($data["pass"]);
			
			if ($this->activation) $row["actkey"] = $this->_genKey(12);
			else $row['status']=1;
			
			$row['user_id'] = Db::i()->query('INSERT INTO ?_users (?#, last_ip, register_date) VALUES(?a, INET_ATON(?), NOW())',array_keys($row),array_values($row), User::i()->getIP());

			if ($this->activation) $this->_sendActivationCode($row);
			return $row['user_id'];
		}
		
		
		public function getRegisterByOpenIdData()
		{
			$data=array();
			if($_SERVER['REQUEST_METHOD']=='GET' && $this->use_openid)
			{
				$oid=new OpenId();
				$openIdData=$oid->CheckAuthByOpenId($oid->getReturnTo());
				if ($openIdData) $_SESSION['register_code']=md5(rand()*rand());
				if (is_array($openIdData))
				{
					return array(	'login'=>$openIdData['nickname'],
									'email'=>$openIdData['email'],
									'openid'=>$openIdData['openid'],
									'register_code'=>$_SESSION['register_code']);
				}
				elseif($openIdData)
				{
					return array('openid'=>$openIdData, 'register_code'=>$_SESSION['register_code']);
				}
				else
				{
					$this->error("Не удалось получить от сервера корректный ответ");
					return false;
				}
			}
			return true;
		}

		
		protected function _insertOpenID($user_id, $openid)
		{
			return Db::i()->query("INSERT IGNORE INTO ?_openid (user_id, openid) VALUES(?, ?)", $user_id, $openid);
		}
		
		
		public function getUserInfo($user_id)
		{
			return User::i()->getUserInfo($user_id);
		}
		
		
		protected function _getOpenIDs($user_id)
		{
			return Db::i()->selectCol("SELECT id AS ARRAY_KEY, openid FROM ?_openid WHERE user_id=?", $user_id);
		}
		
		function addOpenIDProvidersToField(&$form)
		{
			$field=$form->addElement('fieldset')->setLabel(_m('или используйте OpenID'));
			return $this->addOpenIDProvidersToForm($field);
		}
		
		function addOpenIDProvidersToForm(&$form)
		{
			
			$openid=$form->addElement('text', 'openid', array('id'=>'openid', 'class'=>'openid_input'), array('label' => 'OpenID:'));
			/*$fsOid = $form->addElement('fieldset', null, array('id'=>'openid_buttons'))->setLabel(_m('Я пользователь:'));
			
			foreach($this->providers as $value)
			{
				$fsOid->addElement('button', 'openid', array('type' => 'submit', 'value'=>$value['url'], 'class'=>'openid_icon info', 'title'=>htmlspecialchars($value['name'])), array('content' => '<img alt="'.htmlspecialchars($value['name']).'" src="'.$value['img'].'" />'));
			}*/
			return $openid;
		}
		
		
		protected function _addAvatar($file, $user_id)
		{
			if (!is_dir(LAB_PATH_ROOT.'/storage/Image/avatars/'))
				if (!mkdir(LAB_PATH_ROOT.'/storage/Image/avatars/', 0777, true)) return LabCMS::i()->error(sprintf(_m('Не могу создать каталог %s'), '/storage/Image/avatars/'), true);
			$size=getimagesize($file);
			
			$img=new Image_Resize();
			$img->file=$file;
			$img->width=$this->avatar_width;
			$img->height=$this->avatar_height;
			$img->crop=true;
			$img->file_dest=LAB_PATH_ROOT.'/storage/Image/avatars/'.$user_id.'.'.$this->types[$size[2]];
			if ($img->go()) return $size[2];
			return LabCMS::i()->error('Не удалось загрузить изображение');;
		}
		
		
		protected function _removeAvatar($user_id)
		{
			$avatars=glob(LAB_PATH_ROOT.'/storage/Image/avatars/'.$user_id.'.*');
			if ($avatars[0]) unlink($avatars[0]);
			return 0;
		}
		
		
		public function deleteOpenID($user_id, $openid)
		{
			if (!is_array($openid)) $openid=array($openid);
			if (count($openid))
			{
				Db::i()->query("DELETE FROM ?_openid WHERE user_id=? AND id IN (?a)", $user_id, $openid);
			}
		}
		
		
		function checkOldPass($pass)
		{
			$data=array('login'=>User::i()->login, 'pass'=>$pass);
			return (User::i()->id==User::i()->getUserId($data));
		}
		
		
		public function setNewPass($pass)
		{
			return Db::i()->query("UPDATE ?_users SET pass=? WHERE user_id=?", User::PassHash($pass), User::i()->id);
		}
		
		
		public function retrivePassword()
		{
			if ($_GET['var1'] && $_GET['var2'])
			{
				if (Db::i()->query("UPDATE ?_users SET pass=new_pass, new_pass='', actkey='' WHERE user_id=? AND actkey=?", $_GET['var1'], $_GET['var2']))
				{
					$this->setMessage("Пароль изменен.");
					return true;
				}
			}
			$this->error("Неверный код активации!");
			return false;
		}
		
		
		protected function _sendActivationCode($data)
		{
			$this->assign('reg',$data);
			
			if (Tpl::i()->templateExists(LabCMS::i()->getModuleName().'/activation_mail.tpl'))
				$mess = Tpl::i()->fetch(LabCMS::i()->getModuleName().'/activation_mail.tpl');
			else
				$mess = Tpl::i()->fetch('login/activation_mail.tpl');
			
			$mail=new Mailer(array($data["email"]=>$data["login"]));
			$mail->From     = 'robot@'.preg_replace('/^www\./i', '', $_SERVER["SERVER_NAME"]."");
			$mail->FromName = "Robot";
			$mail->Subject = _m('Регистрация на ').$_SERVER["SERVER_NAME"];
			$mail->Body    = $mess;
			$mail->AltBody = strip_tags($mess);
			if ($mail->Send())
			{
				$this->setMessage(sprintf(_m('На адрес %s отправленно сообщение со ссылкой для подтверждения регситрации.'), $data["email"]), false, true);
				$mail->ClearAddresses();
				return true;
			}
			$mail->ClearAddresses();
			$this->error("Ошибка работы почтового робота");
			return false;
			
		}
		
		
		protected function _resendActivationCode($email)
		{
			$data=Db::i()->selectRow("SELECT login, realname, user_id, email, actkey, `status` FROM ?_users WHERE email=?", trim($email));
			if (!$data) $this->error("Такой адрес в базе не зарегистрирован");
			elseif($data['status']!=0) $this->error("Этот аккаунт уже активирован");
			else return $this->_sendActivationCode($data);
			return false;
		}
		
		
		protected function _addLoginRules(&$login)
		{
			return $login->addRule('required', _m('Надо указать логин'), null, $this->validation)
			->and_($login->createRule('maxlength', _m('Логин не может быть длиннее 20 символов'), 20, $this->validation))
			->and_($login->createRule('callback', _m('Логин уже занят'), array($this, 'IsLoginExists')));
		}
		
		
		protected function _addEmailRules(&$email)
		{
			return $email->addRule('required', _m('Надо указать email'), null, $this->validation)
			->and_($email->createRule('maxlength', _m('Email не может быть длиннее 50 символов'), 50, $this->validation))
			->and_($email->createRule('regex', _m('Сдается нам, таких email-ов не бывает'),
									  '/\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/i'), $this->validation)
			->and_($email->createRule('callback', _m('Этот email уже используется.'), array($this, 'isEmailExists')));
		}
		
		
		protected function _celeanUnactivatedUsers()
		{
			Db::i()->query("DELETE FROM ?_users WHERE register_date<NOW()-INTERVAL 7 DAY AND `status`=0 AND user_id!=-1");
		}
		
		
		public function sendRegOpenId($open_id)
		{
			if ($open_id)
			{
				$oid=new OpenId();
				$oid->returnTo=$oid->getTrustRoot()
							.LabCMS::i()->url(false, 'reg_openid');
				//$oid->SendOpenId($_COOKIE['openid']);
				$oid->required=array('email', 'nickname');
				return $oid->SendOpenId($open_id);
			}
			return true;
		}
		
		
		protected function _genKey($int)
		{
			$key = '';
				$alpha = array("a","b","c","d","e","f","g","h","i","g","k","l","m","n","o","p","q","r","s","t",
				"u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","G","K","L","M","N","O","P","Q","R",
				"S","Y","U","V","W","X","Y","Z","1","2","3","4","5","6","7","8","9","0");
			for ($i=0;$i < $int;$i++)
			{
				$key .= $alpha[rand(0,count($alpha))];
			}
			return $key;
		}
		
		
		function IsLoginExists($login)
		{
			if(User::i()->isLoginExists($login)) return false;
			return true;
		}

		
		function IsEmailExists($email)
		{
			if (Db::i()->selectCell("SELECT COUNT(user_id) FROM ?_users
									WHERE email=? {AND user_id!=?}",
									trim($email), (User::i()->id>0)?User::i()->id:DBSIMPLE_SKIP)) return false;
			else return true;
		}
		
		
		protected function getCatcher()
		{
			return '<input type="text" name="login" value="" class="catch" />';
		}
		
		protected function setRedirect($redirect='', $time=0)
		{
			if (!$redirect) $redirect=$_SERVER['REQUEST_URI'];
			$this->assign('redirect', '<meta http-equiv="refresh" content="'.$time.';url='.htmlspecialchars($redirect).'" />');
		}
		
		protected function _render($form)
		{
			$renderer = HTML_QuickForm2_Renderer::factory('labsmarty');
			$html=$form->render($renderer)->toArray();
			if ($this->validation>1)
			{
				LabCMS::i()->skins[LabCMS::i()->getSkin()]['js']=LabCMS::i()->skins[LabCMS::i()->getSkin()]['js']+$renderer->getJavascriptBuilder()->getLibraries(false, false);
			}
			return $html;
		}
		
		protected function _setUserLogged($user_id)
		{
			$info=Db::i()->selectRow("SELECT user_id, group_id FROM ?_users WHERE user_id=?", $user_id);
			$_SESSION['user_id']=$info['user_id'];
			$_SESSION['group_id']=$info['group_id'];
			$_SESSION['user_info']=false;
		}
		
		public function assign($var, $val)
		{
			Tpl::i()->assign($var, $val);
		}
		
		public function setMessage($text, $html=false, $lang=false)
		{
			LabCMS::i()->setMessage($text, $html, $lang);
		}
		
		public function error($text)
		{
			LabCMS::i()->error(_m($text));
		}
		
		function getUserIdByOpenId($openid)
		{
			return Db::i()->selectCell("SELECT user_id FROM ?_openid WHERE openid=?", $openid);
		}
	}