<?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 admin_users_actions
{
	public function deleteUsers($users)
	{
		$user=User::getUser();
		foreach ($users as $user_id) {
			$user->loadUserDataById($user_id);
			if ($user->isNotGuest() && !$user->isDeleted()) $user->delete();
		}
	}
	
	public function addUser($data)
	{
		if (User::i()->IsLoginExists($data['login']))
			return LabCMS::i()->error(_m('Такой логин уже используется'));

		if ($this->_isEmailExists($data['email']))
			return LabCMS::i()->error(_m('Такой email уже используется'));

		if ($data['new_pass']) $data['pass']=$data['new_pass'];
		unset($data['token'], $data['new_pass']);
		$user=User::getUser();
		return $user->add($data);
	}
	
	public function updateUser($user, $data)
	{
		if ($user->login!=$data['login']
			&& User::i()->IsLoginExists($data['login']))
			return LabCMS::i()->error(_m('Такой логин уже используется'));

		if ($user->email!=$data['email']
			&& $this->_isEmailExists($data['email']))
			return LabCMS::i()->error(_m('Такой email уже используется'));

		if ($data['new_pass']) $data['pass']=$data['new_pass'];
		unset($data['token'], $data['new_pass']);
		$user->update($data);
		return true;
	}
	
	public function deleteUserByRealId($id)
	{
		$users=Db::i()->selectCol("SELECT user_id FROM ?_users WHERE real_id=?", $id);
		if ($users) {
			$user=User::getUser();
			foreach ($users as $user_id) {
				$user->loadUserDataById($user_id);
				$user->delete();
			}
			return true;
		}
	}
	
	public function deleteUserByIP($ip)
	{
		$users=Db::i()->selectCol(
			"SELECT user_id FROM ?_users WHERE last_ip=?", inet_pton($ip)
		);
		if ($users) {
			$user=User::getUser();
			foreach ($users as $user_id) {
				$user->loadUserDataById($user_id);
				$user->delete();
			}
		}
	}
	
	public function markAsUnique($id)
	{
		$user=User::getUser();
		$user->loadUserDataById($id);
		if ($user->IsGuest()) return LabCMS::i()->error(_m('Пользователь не найден!'));
		if ($user->id!=$user->real_id) $user->update(array('real_id'=>$user->id));
		else {
			$users=Db::i()->selectCol(
				"SELECT user_id FROM ?_users WHERE real_id=? AND user_id!=?",
				$user->real_id, $user->id
			);

			if ($users) {
				$newRealId=0;
				foreach ($users as $user_id) {
					$user->loadUserDataById($user_id);
					if (!$newRealId && $user->IsNotGuest()) $newRealId=$user->id;
					$user->update(array('real_id'=>$newRealId));
				}
			}
		}
		return true;
	}
	
	protected function _isEmailExists($email)
	{
		if (empty($email)) return false;
		return Db::i()->selectCell("SELECT COUNT(user_id) FROM ?_users WHERE email=?", $email);
	}
}