<?php


require_once dirname(__FILE__) . '/' . 'Lib.php';
Lib::loadClass('V');
Lib::loadClass('UserProfile');


class User {

	public static function getLogin() {
		return V::get('ADM_ACCOUNT', '', $_SESSION);
	}

	public static function getName() {
		return V::get('ADM_ACCOUNT', '', $_SESSION);
	}

	public static function getID() {
		if (V::get('ADM_ID', 0, $_SESSION, 'int') <= 0) {
			self::_fetchMoreUserData();
		}
		return V::get('ADM_ID', '', $_SESSION);
	}

	public static function getType() {
		if (!empty($_SESSION['EMPLOYEE_TYPE'])) {
			self::_fetchMoreUserData();
		}
		return V::get('EMPLOYEE_TYPE', '', $_SESSION);
	}

	public static function getFullName() {
		return V::get('ADM_NAME', '', $_SESSION);
	}

	public static function getInicjaly() {
		if (!V::get('ADM_INICJALY_HANDLOWCA', '', $_SESSION)) {
			self::_fetchMoreUserData();
		}
		return $_SESSION['ADM_INICJALY_HANDLOWCA'];
	}

	public static function getDefaultAclGroup() {
		if (!V::get('DEFAULT_ACL_GROUP', '', $_SESSION)) {
			self::_fetchMoreUserData();
		}
		return $_SESSION['DEFAULT_ACL_GROUP'];
	}

	public static function _fetchMoreUserData() {
		$db = DB::getDB();
		$login = self::getLogin();
		if (empty($login)) return false;
		$sql = "select `ID`, `INICJALY_HANDLOWCA`, `EMPLOYEE_TYPE`
				, `DEFAULT_ACL_GROUP`
			from `ADMIN_USERS`
			where `ADM_ACCOUNT`='{$login}'
			limit 1
		";
		$res = $db->query($sql);
		if ($r = $db->fetch($res)) {
			$_SESSION['ADM_ID'] = $r->ID;
			$_SESSION['ADM_INICJALY_HANDLOWCA'] = $r->INICJALY_HANDLOWCA;
			$_SESSION['EMPLOYEE_TYPE'] = $r->EMPLOYEE_TYPE;
			$_SESSION['DEFAULT_ACL_GROUP'] = $r->DEFAULT_ACL_GROUP;
		}
	}

	public static function logged() {
		return (!empty($_SESSION['AUTHORIZE_USER']))? true : false;
	}

	public static function get( $key ) {
		return V::get($key, '', $_SESSION);
	}

	public static function getGroups() {
		$groups = User::_fetchGroups();
		return $groups;
	}

	public static function getGroupsIds() {
		$groups = User::_fetchGroups();
		return array_keys($groups);
	}

	public static function _fetchGroups() {
		static $_groups;
		if (!$_groups) {
			$user_id = User::getID();
			Lib::loadClass('UsersHelper');
			$_groups = UsersHelper::get_group_by_user($user_id);
		}
		return $_groups;
	}

	public static function loadProfile($force = false) {
		return UserProfile::load($force);
	}

	public static function saveProfile() {
		return UserProfile::save();
	}

	public static function getProfile($key) {
		return UserProfile::get($key);
	}

	public static function setProfile($key, $val) {
		UserProfile::set($key, $val);
	}

	public static function getProfileColumn($column_name, $key) {
		return UserProfile::getColumn($column_name, $key);
	}

	public static function setProfileColumn($column_name, $key, $value) {
		UserProfile::setColumn($column_name, $key, $value);
	}

	public static function removeProfileColumn($column_name, $key) {
		UserProfile::removeColumn($column_name, $key);
	}

	public static function isAdmin() {
		if (in_array(self::get('ADM_ADMIN_LEVEL'), array(0, 1))) {
			return true;
		}
		return false;
	}

	public static function getRawData() {
		$ret = array();
		if (self::logged()) {
			$ret['id'] = self::getID();
			$ret['login'] = self::getName();
			$ret['name'] = self::get('ADM_NAME');
			$ret['admin_level'] = self::get('ADM_ADMIN_LEVEL');
			$ret['opis'] = self::get('ADM_ADMIN_DESC');
		}
		return $ret;
	}

	public static function getAcl() {
		static $_acl;
		if (!$_acl) {
			Lib::loadClass('UserAcl');
			$_acl = new UserAcl(self::getID(), $use_cache = true);
		}
		return $_acl;
	}

	public static function reloadAcl() {
		unset($_SESSION['TableAcl_cache']);
		unset($_SESSION['Typespecial_Cache']);
		unset($_SESSION['ADM_INICJALY_HANDLOWCA']);
		unset($_SESSION['EMPLOYEE_TYPE']);
		unset($_SESSION['DEFAULT_ACL_GROUP']);
		//TODO: not work: unset($_SESSION['CRM_PROCES_USERA_WYKONANE_TESTY-' . User::getID()]);
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none">ses (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($_SESSION);echo'</pre>';
		$userAcl = User::getAcl();
		$userAcl->fetchAllPerms(true);
	}

	public static function auth() {
		$task = V::get('LOGIN', '', $_REQUEST);

		$data = array();
		$data['errors'] = array();
		Lib::loadClass('Config');
		$data['ALLOW_GUEST_ACCOUNT'] = (int)Config::get('ALLOW_GUEST_ACCOUNT');

		switch ($task) {
			case 'LOGIN':
				if (!User::logged()) {
					$req_ADM_ACCOUNT = (isset($_REQUEST['ADM_ACCOUNT']))? $_REQUEST['ADM_ACCOUNT'] : '';
					$req_ADM_PASSWD = (isset($_REQUEST['ADM_PASSWD']))? $_REQUEST['ADM_PASSWD'] : '';
					if (empty($req_ADM_ACCOUNT) || empty($req_ADM_PASSWD)) {
						$data['errors'][] = "Proszę podać LOGIN i HASŁO!";
					} else {
						User::login($req_ADM_ACCOUNT, $req_ADM_PASSWD, $data['errors']);
					}
				}
				break;

			case 'LOGOUT':
				if (User::logged()) {

					session_destroy();
					unset($_SESSION['AUTHORIZE_USER']);
					unset($_SESSION['ADM_ACCOUNT']);

					Lib::loadClass('SE_Layout');
					SE_Layout::gora();
					SE_Layout::loadTemplate('logout', $data);
					SE_Layout::dol();
					exit;
				}
				break;

			case 'PERMS_RELOAD':
				User::reloadAcl();
				break;

			case 'PASSEDIT':
				if (User::logged()) {
					$data = array();

					if (!empty($_POST)) {
						if (empty($_POST['ADM_PASSWD_NEW']) || empty($_POST['ADM_PASSWD'])) {
							$data['msg'] = "Proszę podać stare i nowe hasło.";
						}
					}
					if (!empty($_POST['ADM_PASSWD_NEW']) && !empty($_POST['ADM_PASSWD'])) {
						$ret = User::changePasswd($_POST['ADM_PASSWD'], $_POST['ADM_PASSWD_NEW']);
						if ($ret) {
							$data['info'] = "Hasło zostało zmienione";
						} else {
							$data['error'] = "Nie udało się zmienić hasła";
						}
					}

					SE_Layout::gora();
					SE_Layout::loadTemplate('passedit', $data);
					SE_Layout::dol();
					exit;
				}
				break;

			case 'ANONYMOUS_LOGIN':
				if (!User::logged()) {
					if ($data['ALLOW_GUEST_ACCOUNT'] != 1) {
						$data['errors'][] = "Zablokowane logowaniwe na konto gościa!";
					}
					else {
						$anonim = User::getAnonymousAccount();
						if (!$anonim) {
							$data['errors'][] = "Konto gościa nie istnieje!";
						} else {
							User::login($anonim->ADM_ACCOUNT, $anonim->ADM_PASSWD, $data['errors']);
						}
					}
				}
				break;

			default:
				
		}

		if (!User::logged()) {
			Lib::loadClass('SE_Layout');
			SE_Layout::gora();
			SE_Layout::loadTemplate('login', $data);
			SE_Layout::dol();
			exit;
		}
	}

	public static function kandydatLogin($kandydatId, &$errors = array()) {
		$user = self::kandydatLoginByDB($kandydatId, $errors);
		if ($user) {
			$_SESSION['ADM_ID'] = $user->ID;
			$_SESSION['AUTHORIZE_USER'] = $user->ADM_ACCOUNT;
			$_SESSION['ADM_ACCOUNT'] = $user->ADM_ACCOUNT;
			//$_SESSION['ADM_AREA'] = $user->ADM_AREA;
			$_SESSION['ADM_NAME'] = $user->ADM_NAME;
			$_SESSION['ADM_TECH_WORKER'] = $user->ADM_TECH_WORKER;
			$_SESSION['ADM_COMPANY'] = $user->ADM_COMPANY;
			$_SESSION['ADM_ADMIN_LEVEL'] = $user->ADM_ADMIN_LEVEL;
			$_SESSION['ADM_PHONE'] = $user->ADM_PHONE;
			$_SESSION['ADM_ADMIN_EXPIRE'] = $user->ADM_ADMIN_EXPIRE;
			$_SESSION['ADM_ADMIN_DESC'] = $user->ADM_ADMIN_DESC;
			$_SESSION['EMPLOYEE_TYPE'] = $user->EMPLOYEE_TYPE;

			// save user pass in encrypted form
			Lib::loadClass('Crypt');
			$_SESSION['ADM_PASS_HASH'] = Crypt::encrypt($pass);
			$_SESSION['EMAIL_IMAP_IMPORT_PASSWD_HASH'] = Crypt::encrypt($user->EMAIL_IMAP_IMPORT_PASSWD);
			$_SESSION['EMAIL_IMAP_IMPORT_HOST'] = $user->EMAIL_IMAP_IMPORT_HOST;
			$_SESSION['EMAIL_IMAP_IMPORT_USERNAME'] = $user->EMAIL_IMAP_IMPORT_USERNAME;
			//$keyFromHash = Crypt::decrypt($_SESSION['ADM_PASS_HASH']);

			$userAcl = User::getAcl();
			$userAcl->fetchAllPerms();

			return true;
		}

		return false;
	}

	public static function login($login, $pass, &$errors) {
		Lib::loadClass('LDAP');
		$ldap = LDAP::getInstance();

		if ($ldap != null && $ldap->isConnected()) {
			$user = self::loginByLDAP($login, $pass, $errors);
		} else {
			$user = self::loginByDB($login, $pass, $errors);
		}
		if ($user) {
			$_SESSION['ADM_ID'] = $user->ID;
			$_SESSION['AUTHORIZE_USER'] = $user->ADM_ACCOUNT;
			$_SESSION['ADM_ACCOUNT'] = $user->ADM_ACCOUNT;
			//$_SESSION['ADM_AREA'] = $user->ADM_AREA;
			$_SESSION['ADM_NAME'] = $user->ADM_NAME;
			$_SESSION['ADM_TECH_WORKER'] = $user->ADM_TECH_WORKER;
			$_SESSION['ADM_COMPANY'] = $user->ADM_COMPANY;
			$_SESSION['ADM_ADMIN_LEVEL'] = $user->ADM_ADMIN_LEVEL;
			$_SESSION['ADM_PHONE'] = $user->ADM_PHONE;
			$_SESSION['ADM_ADMIN_EXPIRE'] = $user->ADM_ADMIN_EXPIRE;
			$_SESSION['ADM_ADMIN_DESC'] = $user->ADM_ADMIN_DESC;
			$_SESSION['EMPLOYEE_TYPE'] = $user->EMPLOYEE_TYPE;

			// save user pass in encrypted form
			Lib::loadClass('Crypt');
			$_SESSION['ADM_PASS_HASH'] = Crypt::encrypt($pass);
			$_SESSION['EMAIL_IMAP_IMPORT_PASSWD_HASH'] = Crypt::encrypt($user->EMAIL_IMAP_IMPORT_PASSWD);
			$_SESSION['EMAIL_IMAP_IMPORT_HOST'] = $user->EMAIL_IMAP_IMPORT_HOST;
			$_SESSION['EMAIL_IMAP_IMPORT_USERNAME'] = $user->EMAIL_IMAP_IMPORT_USERNAME;
			//$keyFromHash = Crypt::decrypt($_SESSION['ADM_PASS_HASH']);

			$userAcl = User::getAcl();
			$userAcl->fetchAllPerms();

			return true;
		}

		return false;
	}

	public static function loginByLDAP($login, $pass, &$errors) {
		$ldapUser = array();

		$DBG = false;

		Lib::loadClass('LDAP');
		$ldap = LDAP::getInstance();

		if (!$ldap->isConnected()) {
			$errors[] = 'Error: Could not connect to LDAP server!';
			return false;
		}

		$filter = (false !== strpos($login, '@'))? "(mail={$login})" : "(uid={$login})";
		//$filter = "cn=*";// show all ldap accounts
		$justthese = array();//array("uid", "givenName", "mail", "*");
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">ldap_search (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('ldaprdn'=>$ldap->getBaseDN(), 'filter'=>$filter, 'justthese'=>$justthese));echo'</pre>';}
		$res = $ldap->search($filter, 'cn=users', $justthese);
		if ($ldap->count_entries($res) > 0) {
			$entry = $ldap->first_entry($res);
			if ($entry) {
				$ldapUser['user_dn'] = $ldap->get_dn($entry);

				$val = $ldap->get_values($entry, 'uid');
				$ldapUser['uid'] = $val[0];
				$val = $ldap->get_values($entry, 'mail');
				$ldapUser['mail'] = $val[0];
				$val = $ldap->get_values($entry, 'cn');
				$ldapUser['cn'] = $val[0];
			} else {
				$errors[] = 'Login nie istnieje';
				return false;
			}
			if($DBG){// test
				echo'<pre style="overflow:auto;border:1px solid green;">';
				// print number of entries found
				echo "Number of entries found: " . $ldap->count_entries($res) . "\n";
				while ( $entry ) {
					$dn = $ldap->get_dn($entry);
					echo "<b>$dn</b>\n";
					$attrs = $ldap->get_attributes($entry);
					for ( $i=0; $i < $attrs['count']; $i++) {
						echo "$attrs[$i]: ";
						for ( $j=0; $j < $attrs[$attrs[$i]]['count']; $j++ ) {
							echo $attrs[$attrs[$i]][$j] . " ";
						}
						echo "\n";
					}
					echo "\n";
					$entry = $ldap->next_entry($entry);
				}
				$ldap->free_result($res);
				echo'</pre>';
			}// test
		}

		if (!$ldapUser['user_dn']) {
			$errors[] = 'Error: login nie istnieje w bazie LDAP!';
			return false;
		}

		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">LDAP user (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ldapUser);echo'</pre>';}
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">ldap_bind (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('ldaprdn'=>$ldapUser['user_dn'], 'pass'=>'***'));echo'</pre>';}
		$ldapbind = $ldap->bind($ldapUser['user_dn'], $pass, $errorMsg);
		if (!$ldapbind) {
			$errors[] = 'Error: LDAP authorization failed!' . '<p>' . $errorMsg . '</p>';
			return false;
		}

		$user = new stdClass();
		$user->AUTHORIZE_USER = $ldapUser['uid'];
		$user->ADM_ACCOUNT = $ldapUser['uid'];
		$user->ADM_NAME = $ldapUser['cn'];

		$user->OTHER_INFO = $ldapUser['mail'];

		// get ID, ... from DB
		$db = DB::getDB();
		$sql = "SELECT u.*
			from `ADMIN_USERS` as u
			where
				u.`ADM_ACCOUNT`='{$user->ADM_ACCOUNT}'
				and u.`A_STATUS` in('WAITING','NORMAL')
		";
		//	LIMIT 0, 1;
		$res = $db->query($sql);
		if (!$res) {
			die("Error SQL login!");
		}
		$num_rows = $db->num_rows($res);
		if ($num_rows == 0) {
			$errors[] = 'Error: brak uzytkownika w bazie danych!';
			return false;
		}
		else if ($num_rows == 1) {
			if ($r = $db->fetch($res)) {
				$user->ID = $r->ID;
				$user->ADM_TECH_WORKER = $r->ADM_TECH_WORKER;
				$user->ADM_COMPANY = $r->ADM_COMPANY;
				$user->ADM_ADMIN_LEVEL = $r->ADM_ADMIN_LEVEL;
				$user->ADM_PHONE = $r->ADM_PHONE;
				$user->ADM_ADMIN_EXPIRE = $r->ADM_ADMIN_EXPIRE;
				$user->ADM_ADMIN_DESC = $r->ADM_ADMIN_DESC;
				$user->EMAIL_IMAP_IMPORT_PASSWD = $r->EMAIL_IMAP_IMPORT_PASSWD;
				$user->EMAIL_IMAP_IMPORT_HOST = $r->EMAIL_IMAP_IMPORT_HOST;
				$user->EMAIL_IMAP_IMPORT_USERNAME = $r->EMAIL_IMAP_IMPORT_USERNAME;
				$user->EMPLOYEE_TYPE = $r->EMPLOYEE_TYPE;
				return $user;
			}
		}
		return $user;
	}

	public static function loginByDB($login, $pass, &$errors) {
		$db = DB::getDB();
		$login = $db->_($login);
		$pass = $db->_($pass);
		$sql = "SELECT u.*
			from `ADMIN_USERS` as u
			where
				u.`ADM_ACCOUNT`='{$login}'
				and ( u.`ADM_PASSWD`='{$pass}' or u.`ADM_PASSWD`=md5('{$pass}') )
				and u.`A_STATUS` in('WAITING','NORMAL')
			LIMIT 0, 1;
		";
		$res = $db->query($sql);
		if (!$res) {
			die("Error SQL login!");
		}
		$num_rows = $db->num_rows($res);
		if ($num_rows == 0) {
			$errors[] =  "Podales zlego uzytkownika lub/i haslo()";
		}
		else if ($num_rows == 1) {
			if ($r = $db->fetch($res)) {
				$user = new stdClass();
				$user->ID = $r->ID;
				$user->ADM_TECH_WORKER = $r->ADM_TECH_WORKER;
				$user->ADM_COMPANY = $r->ADM_COMPANY;
				$user->AUTHORIZE_USER = $r->ADM_ACCOUNT;
				$user->ADM_ACCOUNT = $r->ADM_ACCOUNT;
				$user->ADM_NAME = $r->ADM_NAME;
				$user->ADM_ADMIN_LEVEL = $r->ADM_ADMIN_LEVEL;
				$user->ADM_PHONE = $r->ADM_PHONE;
				$user->ADM_ADMIN_EXPIRE = $r->ADM_ADMIN_EXPIRE;
				$user->ADM_ADMIN_DESC = $r->ADM_ADMIN_DESC;
				$user->EMAIL_IMAP_IMPORT_PASSWD = $r->EMAIL_IMAP_IMPORT_PASSWD;
				$user->EMAIL_IMAP_IMPORT_HOST = $r->EMAIL_IMAP_IMPORT_HOST;
				$user->EMAIL_IMAP_IMPORT_USERNAME = $r->EMAIL_IMAP_IMPORT_USERNAME;
				$user->EMPLOYEE_TYPE = $r->EMPLOYEE_TYPE;
				//$user->ADM_AREA = "$r->ADM_AREA";
				//$_SESSION['ADM_PASSWD'] = $pass;
				return $user;
			}
		}
		return false;
	}

	public static function kandydatLoginByDB($kandydatId, &$errors) {
		$db = DB::getDB();
		$kandydatId = (int)$kandydatId;
		$sql = "SELECT u.*
			from `ADMIN_USERS` as u
			where
				u.`ID`='{$kandydatId}'
				and u.`A_STATUS` in('WAITING','NORMAL')
			LIMIT 0, 1;
		";
		$res = $db->query($sql);
		if (!$res) {
			die("Error SQL login!");
		}
		$num_rows = $db->num_rows($res);
		if ($num_rows == 0) {
			$errors[] =  "Podales zlego uzytkownika lub/i haslo()";
		}
		else if ($num_rows == 1) {
			if ($r = $db->fetch($res)) {
				$user = new stdClass();
				$user->ID = $r->ID;
				$user->ADM_TECH_WORKER = $r->ADM_TECH_WORKER;
				$user->ADM_COMPANY = $r->ADM_COMPANY;
				$user->AUTHORIZE_USER = $r->ADM_ACCOUNT;
				$user->ADM_ACCOUNT = $r->ADM_ACCOUNT;
				$user->ADM_NAME = $r->ADM_NAME;
				$user->ADM_ADMIN_LEVEL = $r->ADM_ADMIN_LEVEL;
				$user->ADM_PHONE = $r->ADM_PHONE;
				$user->ADM_ADMIN_EXPIRE = $r->ADM_ADMIN_EXPIRE;
				$user->ADM_ADMIN_DESC = $r->ADM_ADMIN_DESC;
				$user->EMAIL_IMAP_IMPORT_PASSWD = $r->EMAIL_IMAP_IMPORT_PASSWD;
				$user->EMAIL_IMAP_IMPORT_HOST = $r->EMAIL_IMAP_IMPORT_HOST;
				$user->EMAIL_IMAP_IMPORT_USERNAME = $r->EMAIL_IMAP_IMPORT_USERNAME;
				$user->EMPLOYEE_TYPE = $r->EMPLOYEE_TYPE;
				//$user->ADM_AREA = "$r->ADM_AREA";
				//$_SESSION['ADM_PASSWD'] = $pass;
				return $user;
			}
		}
		return false;
	}

	public static function changePasswd($oldPass, $newPass) {
		$db = DB::getDB();
		$newPass = $db->_($newPass);
		$oldPass = $db->_($oldPass);
		$username = $db->_(self::getName());
		$sql = "update `ADMIN_USERS` set
				`ADM_PASSWD`=md5('{$newPass}')
			where
				`ADM_ACCOUNT`='{$username}' and
				(`ADM_PASSWD`='{$oldPass}' or `ADM_PASSWD`=md5('{$oldPass}'))
			limit 1;
		";
		$db->query($sql);
		return ($db->affected_rows() > 0);
	}

	/**
	 * Check user access.
	 * @param string $name
	 *   'menu' - access to view menu
	 * 
	 * @from [4101] ADM_ADMIN_LEVEL
	 *   Poziom uprawnień - każdy powinien mieć poziom o numerze 3
	 *   kierownicy powinni mieć 2
	 *   a administratorzy 0
	 *   kandydaci poziom 6.
	 *   Poziom 1 umożliwia edycje procesów i zasobów
	 *   poziom 2 umożliwia ocenę testów
	 *   poziom 3 umożliwia widzenie systemu jakości.
	 */
	public static function hasAccess($name) {
		switch ($name) {
			case 'menu': {
				if (User::get('ADM_ADMIN_LEVEL') < 6) {
					return true;
				}
				else {
					Lib::loadClass('Config');
					$ALLOW_GUEST_ACCOUNT = (int)Config::get('ALLOW_GUEST_ACCOUNT');
					if ($ALLOW_GUEST_ACCOUNT && User::getLogin() == 'anonymous') {
						return true;
					}
				}
				break;
			}
			case 'dbg': {
				return (0 == User::get('ADM_ADMIN_LEVEL'));
				break;
			}
			case 'procesy': {
				if (User::get('ADM_ADMIN_LEVEL') < 4) return true;
				break;
			}
			case 'procesy_admin': {
				if (User::get('ADM_ADMIN_LEVEL') < 2) return true;
				break;
			}
			case 'testy': {
				if (User::get('ADM_ADMIN_LEVEL') <= 6) return true;
				break;
			}
			case 'testy_wyniki': {
				if (User::get('ADM_ADMIN_LEVEL') < 3) return true;
				break;
			}
			case 'testy_wyniki_edit': {
				if (User::get('ADM_ADMIN_LEVEL') < 3) return true;
				break;
			}
			case 'testy_wyniki_read': {
				if (User::get('ADM_ADMIN_LEVEL') < 3) return true;
				break;
			}
			default:
				
		}
		return false;
	}

	public static function getAnonymousAccount() {
		$db = DB::getDB();
		if (!$db) die("Error DB connection!");
		$sql = "select u.*
			from `ADMIN_USERS` as u
			where
				u.`ADM_ACCOUNT`='anonymous'
				and u.`EMPLOYEE_TYPE`='Anonymous'
				and u.`A_STATUS` in('NORMAL')
			order by u.`ID` asc
			limit 1
		";
		$res = $db->query($sql);
		if (!$res) die("Error SQL login!");

		$num_rows = $db->num_rows($res);
		if ($r = $db->fetch($res)) {
			//$_SESSION['ADM_PASSWD'] = $pass;
			$user = new stdClass();
			$user->ID = "$r->ID";
			$user->AUTHORIZE_USER = "$r->ADM_ACCOUNT";
			$user->ADM_ACCOUNT = "$r->ADM_ACCOUNT";
			$user->ADM_PASSWD = "$r->ADM_PASSWD";
			//$user->ADM_AREA = "$r->ADM_AREA";
			$user->ADM_NAME = "$r->ADM_NAME";
			$user->ADM_TECH_WORKER = "$r->ADM_TECH_WORKER";
			$user->ADM_COMPANY = "$r->ADM_COMPANY";
			$user->ADM_ADMIN_LEVEL = "$r->ADM_ADMIN_LEVEL";
			$user->ADM_PHONE = "$r->ADM_PHONE";
			$user->ADM_ADMIN_EXPIRE = "$r->ADM_ADMIN_EXPIRE";
			$user->ADM_ADMIN_DESC = "$r->ADM_ADMIN_DESC";
			return $user;
		}
		return false;
	}

	public static function getLdapGroups() {
		$ldapGroups = User::_fetchLdapGroups();
		return $ldapGroups;
	}

	public static function getLdapGroupsNames() {
		$ldapGroupsNames = array();
		$ldapGroups = User::_fetchLdapGroups();
		foreach ($ldapGroups as $kID => $vLDAPGroup) {
			$ldapGroupsNames[$kID] = $vLDAPGroup->cn;
		}
		return $ldapGroupsNames;
	}

	public static function getLdapGroupsIds() {
		$ldapGroups = User::_fetchLdapGroups();
		$gidNumbers = array();
		if (!empty($ldapGroups)) {
			foreach ($ldapGroups as $vLdapGroup) {
				$gidNumbers[] = $vLdapGroup->gidNumber;
			}
		}
		return $gidNumbers;
	}

	public static function _fetchLdapGroups() {
		static $_groups;
		if (!$_groups) {
			$login = User::getLogin();
			Lib::loadClass('UsersLdapHelper');
			$_groups = UsersLdapHelper::getUserGroups($login, 3);
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">getLDAPGroupByUserName (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($_groups);echo'</pre>';
		}
		return $_groups;
	}

}
