<?php
	require_once(dirname(__FILE__).'/../../../lib/api/class.user.php');
	require_once(dirname(__FILE__).'/class.adminview.php');

	if (!class_exists('AKB_HELPER')) {
		include_once(dirname(__FILE__).'/class.helper.php');
	}

	class AKB_USER extends AdminView
	{
		/**
		* HandlePage
		*
		* Handles page routing based on the current ToDo get string
		* @return void
		*/
		function HandlePage()
		{
			$GLOBALS['Message'] = '';

			if (isset($_GET['ToDo'])) {
				switch (strtolower($_GET['ToDo'])) {
					case 'viewusers':
					default:
						if (isset($_POST['bulkaction'])) {
							$this->BulkAction();
						}
						$this->ShowUserList();
				}
			}
		}

		/**
		* BulkAction
		*
		* The handler for performing an action to multiple items
		* @return void
		*/
		function BulkAction()
		{
			if (!isset($_POST['bulkaction'])) {
				return false;
			}

			if (!isset($_POST['item']) || !is_array($_POST['item'])) {
				return false;
			}

			if (empty($_POST['item'])) {
				return false;
			}

			switch (strtolower($_POST['bulkaction'])) {
				case 'delete':
					if ($_SESSION['user']->verify('user', 'delete')) {
						if ($_SESSION['user']->multiDelete($_POST['item'])) {
							$users = implode("', '", array_keys($_POST['item']));

							// When we delete a user, try and remap questions they
							// owned to the user that deletes them
							$query = "UPDATE ".$GLOBALS['tablePrefix']."questions
							SET userid=".$_SESSION['user']->userid."
							WHERE userid IN ('".$users."')";

							$result = $GLOBALS['AKB_DB']->Query($query);

							$GLOBALS['Message'] = MessageBox(GetLang('UserMultiDeleteOk'), MSG_SUCCESS);
						} else {
							$GLOBALS['Message'] = MessageBox(GetLang('UserMultiDeleteFail'), MSG_ERROR);
						}
					} else {
						return false;
					}
				break;
				case 'ldap':
					if ($_SESSION['user']->verify('user', 'edit')) {
						if ($_SESSION['user']->multiUpdateUserType($_POST['item'])) {
							$GLOBALS['Message'] = MessageBox(GetLang('UserMultiUpdateUserTypeOk'), MSG_SUCCESS);
						} else {
							$GLOBALS['Message'] = MessageBox(GetLang('UserMultiUpdateUserTypeFail'), MSG_ERROR);
						}
					}
				break;
			}
		}

		/**
		* ShowEditUser
		* Show the form for updating an exisiting user
		*
		* @param bool $restricted Is this interface restricted ? (i.e. The
		* My Account section of the site ?)
		*
		* @return void
		*/
		function ShowEditUser($restricted=false, $message='')
		{
			if (!$restricted && !$_SESSION['user']->verify('user', 'edit')) {
				$this->NoPermission();
				return;
			} elseif ($restricted && $_GET['userid'] != $_SESSION['user']->userid) {
				$this->NoPermission();
				return;
			}

			// Show the update user form
			if ($_GET['userid'] != $_SESSION['user']->userid) {
				$GLOBALS['UserTitle'] = GetLang('EditUserTitle');
				$GLOBALS['UserIntro'] = GetLang('EditUserIntro');
			} else {
				$GLOBALS['UserTitle'] = GetLang('MyAccountTitle');
				$GLOBALS['UserIntro'] = GetLang('MyAccountIntro');
			}
			$GLOBALS['req'] = '&nbsp;&nbsp;';
			$GLOBALS['Message'] = $message;
			$GLOBALS['Active_0'] = '';
			$GLOBALS['Active_1'] = '';
			$GLOBALS['Admin_0'] = '';
			$GLOBALS['Admin_1'] = '';
			$GLOBALS['AddingUser'] = '';

			// Disable options if they are in the my account section
			if ($restricted && $_SESSION['user']->userid > 1) {
				$GLOBALS['HidePanels'][] = 'UserStatus';
				$GLOBALS['HidePanels'][] = 'UserGroups';
			}

			if (isset($_GET['userid'])) {
				// The super admin has full access - there is no reason to show
				// these options
				if ($_GET['userid'] == 1) {
					$GLOBALS['HidePanels'][] = 'UserStatus';
					$GLOBALS['HidePanels'][] = 'UserGroups';
				}

				$userid = (int) $_GET["userid"];
				$user = new API_USER();
				$group = new API_GROUP();

				$user_groups = array();

				// Only the admin user can edit the admin user
				if ($userid == 1 && $_SESSION['user']->userid != 1) {
					$this->ShowUserList();
					return;
				}

				if ($user->load($userid)) {

					$GLOBALS['hiddenFields']	= sprintf("<input type='hidden' name='userid' value='%d'>", $userid);
					$GLOBALS['Username']		= $user->username;
					$GLOBALS['UserPass']		= '';
					$GLOBALS['UserFirstName']	= $user->firstname;
					$GLOBALS['UserLastName']	= $user->lastname;
					$GLOBALS['UserEmail']		= $user->email;

					if (!$_SESSION['user']->verify('user', 'edit')) {
						$GLOBALS['HidePanels'][] = 'UserStatus';
						$GLOBALS['HidePanels'][] = 'UserGroups';
					}
					
					// initialise the username panel, the username panel is editable by default
					$GLOBALS['UsernamePanel'] = $GLOBALS['AKB_CLASS_TEMPLATE']->_GetPanelContent('UserUsernameEditable');
					$GLOBALS['PasswordPanel'] = $GLOBALS['AKB_CLASS_TEMPLATE']->_GetPanelContent('UserPasswordEditable');
					
					// if the LDAP option is enabled & this selected is ldap user,
					// unable the username for this user account to be edited.
					if (isset($GLOBALS['ldapEnabled']) && $GLOBALS['ldapEnabled'] && $user->isLdapUser()) {
						$GLOBALS['UsernamePanel'] = $GLOBALS['AKB_CLASS_TEMPLATE']->_GetPanelContent('UserUsernameNonEditable');
						$GLOBALS['PasswordPanel'] = $GLOBALS['AKB_CLASS_TEMPLATE']->_GetPanelContent('UserPasswordNonEditable');
					}
			
					if ($user->status == 0) {
						$GLOBALS['Active_0'] = 'SELECTED';
					} else {
						$GLOBALS['Active_1'] = 'SELECTED';
					}

					$GLOBALS['groups'] = '';
					$groups = $group->getList();
					$GLOBALS['groupListSize'] = 10;

					if (is_array($user->groups) && !empty($user->groups)) {
						foreach ($user->groups as $g) {
							$user_groups[] = $g->groupid;
						}
					}

					foreach ($groups as $id => $name) {
						$GLOBALS['groups'] .= '<option value="'.$id.'"';
						$GLOBALS['groups'] .= (in_array($id, $user_groups)) ? ' selected ' : '';
						$GLOBALS['groups'] .= '>'. htmlspecialchars($name, ENT_QUOTES, $GLOBALS['charset']);
						$GLOBALS['groups'] .= "</option>\n";
					}

					$GLOBALS['FormAction'] = 'saveUpdatedUser';
					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('user.form');
					$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
				} else {
					$this->ShowUserList();
				}
			} else {
				$this->ShowUserList();
			}
		}

		/**
		* DeleteUser
		* Delete a user from the database and display the confirmation
		*
		* @return void
		*/
		function DeleteUser()
		{
			if (!$_SESSION['user']->verify('user', 'delete')) {
				$this->NoPermission();
				return;
			}

			// Remove a user from the database
			if (isset($_GET["userid"]) && is_numeric($_GET["userid"])) {
				// We use the user object in the session since it will prevent
				// us from accidently deleting ourselves
				if ($_SESSION['user']->delete($_GET['userid'])) {
					$this->ShowUserList(GetLang('UserDeletedSuccessfully'), MSG_SUCCESS);
				} else {
					// Something went wrong when deleting the user
					$this->ShowUserList(sprintf(GetLang('UserDeleteFailed'), $GLOBALS['AKB_DB']->GetErrorMsg(), MSG_ERROR));
				}
			} else {
				$this->ShowUserList();
			}
		}

		/**
		* UpdateUserStatus
		* Update the status of a user in the database
		*
		* @return void
		*/
		function UpdateUserStatus()
		{
			if (!$_SESSION['user']->verify('user', 'edit')) {
				$this->NoPermission();
				return;
			}

			// Update the status of a user account
			if (isset($_GET['userid']) && isset($_GET['status']) && $_GET['userid'] > 1) {
				$user = new API_USER();
				$user->load($_GET['userid']);
				
				// Perform the LDAP operation to save ldap details.
				if (isset($GLOBALS['AKB_LDAP'])	&& API_LDAP::isLdapUser($user->pass)) {
					if (isset($GLOBALS['ldapAllowUserUpdateDetails']) && $GLOBALS['ldapAllowUserUpdateDetails']) {
						API_LDAP::updateUserDetails($user->username, $_GET);
					}
				}
				$user->updateField('status', (int) $_GET['status']);
			}
			$this->ShowUserList();
		}

		/**
		* ShowNewUser
		* Show the interface for creating a new user
		*
		* @return void
		*/
		function ShowNewUser()
		{
			if (!$_SESSION['user']->verify('user', 'edit')) {
				$this->NoPermission();
				return;
			}

			$user = new API_USER();
			if (!AKB_HELPER::valid_username($user->NumUsers()+1)) {
				$GLOBALS['Message'] = MessageBox(sprintf(GetLang('UserLimitReached'), AKB_HELPER::valid_username(0,true)), MSG_ERROR);
				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('error');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
				return;
			}

			// Show the create new user screen
			$GLOBALS['UserTitle'] = GetLang('AddUserTitle');
			$GLOBALS['UserIntro'] = GetLang('AddUserIntro');
			$GLOBALS['req'] = '*';
			$GLOBALS['hiddenFields'] = '';
			$GLOBALS['Username'] = (isset($_POST['username'])) ? $_POST['username'] : '';
			$GLOBALS['restricted'] = '';
			$GLOBALS['UserPass'] = '';
			$GLOBALS['UserFirstName'] = (isset($_POST['firstname'])) ? $_POST['firstname'] : '';
			$GLOBALS['UserLastName'] = (isset($_POST['lastname'])) ? $_POST['lastname'] : '';
			$GLOBALS['UserEmail'] = (isset($_POST['email'])) ? $_POST['email'] : '';
			$GLOBALS['Active_0'] = (isset($_POST['status']) && $_POST['status'] == '0') ? 'SELECTED' : '';
			$GLOBALS['Active_1'] = ($GLOBALS['Active_0'] != 'SELECTED') ? 'SELECTED' : '';

			// initialise the username panel, the username panel is editable by default
			$GLOBALS['UsernamePanel'] = $GLOBALS['AKB_CLASS_TEMPLATE']->_GetPanelContent('UserUsernameEditable');
			$GLOBALS['PasswordPanel'] = $GLOBALS['AKB_CLASS_TEMPLATE']->_GetPanelContent('UserPasswordEditable');

			$GLOBALS['groups'] = '';

			$group = new API_GROUP();
			$groups = $group->getList();
			$GLOBALS['groupListSize'] = 10;
			foreach ($groups as $id => $name) {
				$GLOBALS['groups'] .= '<option value="'.$id.'">';
				$GLOBALS['groups'] .= htmlspecialchars($name, ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['groups'] .= "</option>\n";
			}

			$GLOBALS['AddingUser'] = '1';
			$GLOBALS['FormAction'] = 'saveNewUser';
			$GLOBALS['Admin_1'] = 'SELECTED';
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('user.form');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* SaveUpdatedUser
		* Save the changes made to a user to the database
		*
		* @param bool $restricted Is this user restricted to only editing some
		* fields of the user ?
		*
		* @return void
		*/
		function SaveUpdatedUser($restricted=false)
		{
			if (!$restricted && !$_SESSION['user']->verify('user', 'edit')) {
				$this->NoPermission();
				return;
			} elseif ($restricted && $_POST['userid'] != $_SESSION['user']->userid) {
				$this->NoPermission();
				return;
			}

			$user = new API_USER();
			$user->load($_POST['userid']);

			$_POST['password'] = $_POST['password1'];

			if ($restricted) {
				// If we are in the my account section, the user is limited
				// to only being able to updated certain fields
				$restricted_fields = array (
					'username',
					'status',
				);

				foreach ($restricted_fields as $k) {
					$_POST[$k] = $user->$k;
				}
				foreach ($user->groups as $group) {
					$_POST['groups'][] = $group->groupid;
				}

			} else {
				// We have to copy it into the variable the api expects it to be in
				// We had to change the name to defeat password managers
				$_POST['username'] = $_POST['login'];
			}

			$old_username = $user->username;

			$group = new API_GROUP();
			$all_groups = $group->getList();
			foreach (array_keys($all_groups) as $groupid) {
				if (isset($_POST['groups']) && in_array($groupid, $_POST['groups'])) {
					$user->join($groupid);
				} else {
					$user->part($groupid);
				}
			}

			// If the username hasn't changed or is still available
			if (strtolower($_POST['username']) == strtolower($old_username) || AKB_USER::_UsernameAvailable($_POST['username'])) {
				if ($user->save()) {
					// Everything is done
					if (!$restricted) {
						$this->ShowUserList(sprintf(GetLang('UserUpdatedOK'), htmlspecialchars($_POST['username'], ENT_QUOTES, $GLOBALS['charset'])), MSG_SUCCESS);
					} else {
						$_GET['userid'] = $_POST['userid'];
						$msg = MessageBox(sprintf(GetLang('UserUpdatedOK'), htmlspecialchars($_POST['username'], ENT_QUOTES, $GLOBALS['charset'])), MSG_SUCCESS);
						$this->ShowEditUser(true, $msg);
					}
				} else {
					// Something went wrong
					if ($GLOBALS['AKB_DB']->GetErrorMsg() != '') {
						$error = $GLOBALS['AKB_DB']->GetErrorMessage();
					} else if ($user->error != '') {
						$error = $user->error;
					} else {
						$error = GetLang('UnknownError');
					}

					$GLOBALS['Message'] = MessageBox(sprintf(GetLang('UserError'), $error), MSG_ERROR);
					$this->ShowNewUser();
				}
			} else {
				// The username is already taken
				$GLOBALS['Message'] = MessageBox(sprintf(GetLang('UsernameTaken'), $_POST['username']), MSG_ERROR);
				$this->ShowNewUser();
			}
		}

		/**
		* CopyUser
		*
		* Takes the currently setup user and copies.
		*
		* @return void
		*/
		function CopyUser() {
			$GLOBALS['BreadcrumEntries'] = array(GetLang("Home") => "index.php", GetLang("UserManageUsers") => "");
			if (isset($_POST['bulkaction'])) {
				if ($_SESSION['user']->verify('user', 'delete')) {
					$this->BulkAction();
					$this->ShowUserList();
					return true;
				}
				$this->ShowUserList();
				return false;
			}
			
			$userId = (int)$_GET['userid'];
			$successObj = false;

			if ($userId > 0) {
				
				$qObj = new API_USER();
				if (!AKB_HELPER::valid_username($qObj->NumUsers()+1)) {
					$GLOBALS['Message'] = MessageBox(sprintf(GetLang('UserLimitReached'), AKB_HELPER::valid_username(0,true)), MSG_ERROR);
					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('error');
					$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
					return;
				}
				
				
				$qObj->load($userId);
				$gFields = $qObj->writeFields();
				
				$exist = true;
				$uName = $qObj->username;
				while ($exist) {
					$uName = "Copy of ".$uName." ";
					$existQuery = "SELECT count(username) as tot from ".$qObj->table." WHERE username = '".$uName."'";
					$tot = $GLOBALS['AKB_DB']->FetchOne($existQuery);
					if ($tot == 0) {
						break;
					}
				}
				$gFields[0] = "'".$uName."' as " . $gFields[0];
				$copy_query = 'INSERT INTO '.$qObj->table.'
				('.implode(', ', $qObj->writeFields()).')
				SELECT '.implode(', ', $gFields).'
				FROM '.$qObj->table.'
				WHERE '.$qObj->pk.' = '.((int) $qObj->{$qObj->pk});
				
				$result = $GLOBALS['AKB_DB']->Query($copy_query);
				if ($result) {
					// load source user's group
					$copiedUser = new API_USER();
					$copiedUser -> find('userid', $GLOBALS['AKB_DB']->LastId($qObj->table . '_seq'));
					
					// update the tokenkey
					$query = sprintf("update %s set tokencode = '%s' where userid = '%d'", $qObj->table, generateTokenCode($uName), $copiedUser->userid);
					$GLOBALS['AKB_DB']->Query($query);
					
					if ($qObj -> loadPerms()) {
						foreach ($qObj -> groups as $eachGroup) {
							$copiedUser->join($eachGroup->groupid);
						}
					}
					$this->ShowUserList(GetLang("UserCopySuccess"), MSG_SUCCESS);
					return true;
				} 
			}
			$this->ShowUserList(GetLang("UserCopyError"), MSG_ERROR);
			return false;
		}
		
		/**
		* SaveNewUser
		* Create a new user in the database
		*
		* @return void
		*/
		function SaveNewUser()
		{
			if (!$_SESSION['user']->verify('user', 'edit')) {
				$this->NoPermission();
				return;
			}

			$_POST['username'] = $_POST['login'];
			$_POST['password'] = $_POST['password1'];

			if ($this->_UsernameAvailable($_POST['username'])) {
				$user = new API_USER();
				if ($user->create()) {
					$user->find('username', $_POST['username']);

					$group = new API_GROUP();
					$all_groups = $group->getList();
					foreach (array_keys($all_groups) as $groupid) {
						if (in_array($groupid, $_POST['groups'])) {
							$user->join($groupid);
						}
					}

					// Everything is done
					$this->ShowUserList(sprintf(GetLang('UserAddedOK'), $_POST['username']), MSG_SUCCESS);
				} else {
					// Something went wrong
					if ($GLOBALS['AKB_DB']->GetErrorMsg() != '') {
						$error = $GLOBALS['AKB_DB']->GetErrorMessage();
					} else if ($user->error != '') {
						$error = $user->error;
					} else {
						$error = GetLang('UnknownError');
					}

					// Something went wrong
					$GLOBALS['Message'] = MessageBox(sprintf(GetLang('UserError'), $error), MSG_ERROR);
					$this->ShowNewUser();
				}
			} else {
				// The username is already taken
				$GLOBALS['Message'] = MessageBox(sprintf(GetLang('UsernameTaken'), $_POST['username']), MSG_ERROR);
				$this->ShowNewUser();
			}
		}

		/**
		* ShowUserList
		* Show the list of users for the manage interface
		*
		* @param string $MsgDesc The text of a message to display
		* @param bool $MsgStatus The type of message it is
		*
		* @return void
		*/
		function ShowUserList($MsgDesc = '', $MsgStatus = '')
		{
			if (!$_SESSION['user']->verify('user', 'edit')
			&& !$_SESSION['user']->verify('user', 'delete')) {
				$this->NoPermission();
				return;
			}

			if ($_SESSION['user']->verify('user', 'edit')) {
				$GLOBALS['ShowCreateButton'] = 'inline';
			} else {
				$GLOBALS['ShowCreateButton'] = 'none';
			}

			if ($_SESSION['user']->verify('user', 'delete')) {
				$GLOBALS['ShowDeleteButton'] = 'inline';
			} else {
				$GLOBALS['ShowDeleteButton'] = 'none';
			}

			// if user has the permission to edit user and if this is enterprise version of IKM 
			// and the ldap feature is enabled.
			if ($_SESSION['user']->verify('user', 'edit') && isset($GLOBALS['AKB_LDAP']) && isset($GLOBALS['ldapEnabled']) && $GLOBALS['ldapEnabled']) {
				$GLOBALS['ShowUpdateUserTypeButton'] = 'inline';
			} else {
				$GLOBALS['ShowUpdateUserTypeButton'] = 'none';
			}

			// Show a list of users to edit/delete
			$GLOBALS['UserGrid'] = '';
			$sortField = isset($_GET['sortField']) ?
				$GLOBALS['AKB_DB']->Quote($_GET['sortField']) : 'userName';
			$sortOrder = isset($_GET['sortOrder']) ?
				$GLOBALS['AKB_DB']->Quote($_GET['sortOrder']) : 'asc';

			// {{{ Setup our paging
			// What page are we on ?
			$page = isset($_GET['page'])? (int) $_GET['page'] : 1;

			// What is our offset in the results for the start ?
			$start = ($page == 1) ? 0 : ($page * AKB_USER_PER_PAGE) - (AKB_USER_PER_PAGE-1) -1;

			// How many search terms do we have in total ?
			if (isset($_GET['letter'])) {
				
				$fromStartWith = $_GET["letter"];
				$toStartWith = $_GET["letter"];
				$startWithHelper = explode('-', $_GET["letter"]);
				if (sizeof($startWithHelper) > 1) {
					$fromStartWith = $startWithHelper[0];
					$toStartWith = $startWithHelper[1];
				}
				
				$query = "SELECT COUNT(*)
				FROM ".$GLOBALS['tablePrefix']."users "
				. " WHERE ".$GLOBALS['AKB_DB']->SubString('username', 1, 1)." between '".$GLOBALS['AKB_DB']->Quote($fromStartWith)."' AND '".$GLOBALS['AKB_DB']->Quote($toStartWith)."'"
				. " OR ".$GLOBALS['AKB_DB']->SubString('firstname', 1, 1)." between '".$GLOBALS['AKB_DB']->Quote($fromStartWith)."' AND '".$GLOBALS['AKB_DB']->Quote($toStartWith)."'";
				$link = 'index.php?ToDo=viewUsers&letter='.$_GET['letter'];
			} else {
				$query = 'SELECT COUNT(*)
				FROM '.$GLOBALS['tablePrefix'].'users';
				$link = 'index.php?ToDo=viewUsers';
			}
			$total = $GLOBALS['AKB_DB']->FetchOne($query);
			$numpages = ceil($total / AKB_USER_PER_PAGE);

			$GLOBALS['Nav'] = BuildNav($link, $numpages, $page);
			// }}}

			// {{{ Build the alpha list (A-Z box list)
			$GLOBALS['FormAction'] = $GLOBALS['pathToKB'].'/admin/index.php?ToDo=viewUsers';
			$GLOBALS["AlphaList"] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListHeader');
			$letters = GetAlphaList();
			$GLOBALS["Item"] = 'users with first name';
			foreach ($letters as $letter) {
				$GLOBALS['Letter'] = $letter;
				$GLOBALS['TermClickLetter'] = sprintf(GetLang("TermClickLetter"), strtolower(GetLang('Users')), $letter);
				if (isset($_GET['letter']) && $letter == $_GET['letter']) {
					$GLOBALS['AlphaList'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListRowCurrent');
				} else {
					$GLOBALS['AlphaList'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListRow');
				}
			}
			$GLOBALS['AlphaList'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListFooter');
			// }}

			if (isset($_GET['letter'])) {
				
				$fromStartWith = $_GET["letter"];
				$toStartWith = $_GET["letter"];
				$startWithHelper = explode('-', $_GET["letter"]);
				if (sizeof($startWithHelper) > 1) {
					$fromStartWith = $startWithHelper[0];
					$toStartWith = $startWithHelper[1];
				}
				
				$query = "SELECT *
					FROM ".$GLOBALS['tablePrefix']."users "
					. " WHERE ".$GLOBALS['AKB_DB']->SubString('username', 1, 1)." between '".$GLOBALS['AKB_DB']->Quote($fromStartWith)."' AND '".$GLOBALS['AKB_DB']->Quote($toStartWith)."'"
					. " OR ".$GLOBALS['AKB_DB']->SubString('firstname', 1, 1)." between '".$GLOBALS['AKB_DB']->Quote($fromStartWith)."' AND '".$GLOBALS['AKB_DB']->Quote($toStartWith)."'"

					. " ORDER BY $sortField $sortOrder
					".$GLOBALS['AKB_DB']->AddLimit($start, AKB_USER_PER_PAGE);
			} else {
				$query = "SELECT *
				FROM ".$GLOBALS['tablePrefix']."users
				ORDER BY $sortField $sortOrder
				".$GLOBALS['AKB_DB']->AddLimit($start, AKB_USER_PER_PAGE);
			}

			$userResult = $GLOBALS['AKB_DB']->Query($query);

			if ($MsgDesc != '') {
				$GLOBALS['Message'] = MessageBox($MsgDesc, $MsgStatus);
			}

			if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
				$GLOBALS['NameSortUpLink'] = 'index.php?ToDo=viewUsers&amp;sortField=firstname&amp;sortOrder=asc';
				$GLOBALS['NameSortDownLink'] = 'index.php?ToDo=viewUsers&amp;sortField=firstname&amp;sortOrder=desc';

				$GLOBALS['UserSortUpLink'] = 'index.php?ToDo=viewUsers&amp;sortField=username&amp;sortOrder=asc';
				$GLOBALS['UserSortDownLink'] = 'index.php?ToDo=viewUsers&amp;sortField=username&amp;sortOrder=desc';

				$GLOBALS['UserTypeSortUpLink'] = 'index.php?ToDo=viewUsers&amp;sortField=pass&amp;sortOrder=asc';
				$GLOBALS['UserTypeSortDownLink'] = 'index.php?ToDo=viewUsers&amp;sortField=pass&amp;sortOrder=desc';

				$GLOBALS['EmailSortUpLink'] = 'index.php?ToDo=viewUsers&amp;sortField=email&amp;sortOrder=asc';
				$GLOBALS['EmailSortDownLink'] = 'index.php?ToDo=viewUsers&amp;sortField=email&amp;sortOrder=desc';

				$GLOBALS['StatusSortUpLink'] = 'index.php?ToDo=viewUsers&amp;sortField=status&amp;sortOrder=asc';
				$GLOBALS['StatusSortDownLink'] = 'index.php?ToDo=viewUsers&amp;sortField=status&amp;sortOrder=desc';

				while ($userRow = $GLOBALS['AKB_DB']->Fetch($userResult)) {
					$uObj = new API_USER();
					$uObj -> load($userRow['userid']);
					$uObj -> loadPerms();
					$userGroup = array();
					foreach ($uObj ->groups as $eachGroup) {
						$userGroup[] = $eachGroup->name;
					}
					$GLOBALS['UserGroupString'] = GetLang('NA');
					if (sizeof($userGroup)) {
						$GLOBALS['UserGroupString'] = implode(', ', $userGroup);
					}
					
					$GLOBALS['UserId'] = $userRow['userid'];
					$GLOBALS['Username'] = htmlspecialchars($userRow['username'], ENT_QUOTES, $GLOBALS['charset']);

					if ($userRow['userid'] == 1) {
						$GLOBALS['Username'] .= GetLang('SuperAdminInBrackets');
					}

					$GLOBALS['Fullname'] = htmlspecialchars(sprintf('%s %s', $userRow['firstname'], $userRow['lastname']),ENT_QUOTES,$GLOBALS['charset']);

					if (trim($userRow['email']) == '') {
						$GLOBALS['Email'] = GetLang('NA');
					} elseif (trim($GLOBALS['Fullname']) == '') {
						$GLOBALS['Email'] = sprintf('<a href="mailto:%s">%s</a>', $userRow['email'], $userRow['email']);
					} else {
						$GLOBALS['Email'] = sprintf('<a href="mailto:%s">%s</a>', $userRow['email'], $GLOBALS['Fullname']);
					}

					if (trim($GLOBALS['Fullname']) == '') {
						$GLOBALS['Fullname'] = GetLang('NA');
					}
					
					if ($userRow['userid'] == 1) {
						if ($userRow['status'] == 0) {
							$GLOBALS['Status'] = sprintf('<img border="0" src="images/cross.gif" alt="cross"">', GetLang('UserActivate'), $userRow['userid']);
						} else {
							$GLOBALS['Status'] = sprintf('<img border="0" src="images/tick.gif" alt="tick">', GetLang('UserDeactivate'), $userRow['userid']);
						}
					} else {
						if ($userRow['status'] == 0) {
							$GLOBALS['Status'] = sprintf('<a title="%s" href="index.php?ToDo=updateUserStatus&amp;userid=%d&amp;status=1"><img border="0" src="images/cross.gif" alt="cross"></a>', GetLang('UserActivate'), $userRow['userid']);
						} else {
							$GLOBALS['Status'] = sprintf('<a title="%s" href="index.php?ToDo=updateUserStatus&amp;userid=%d&amp;status=0"><img border="0" src="images/tick.gif" alt="tick"></a>', GetLang('UserDeactivate'), $userRow['userid']);
						}
					}
					
					// user type determination
					$GLOBALS['UserType'] = GetLang('LocalUser');
					if ($userRow['pass'] == '@LDAP') {
						$GLOBALS['UserType'] = GetLang('LdapUser');
					}

					if ($_SESSION['user']->verify('user', 'edit')) {
						$GLOBALS['EditLink'] =  '<a href="index.php?ToDo=editUser&amp;userid='.$userRow['userid'].'" class="bodylink">'.GetLang('Edit').'</a>';
						if ($userRow['userid'] != 1 && $userRow['pass'] != '@LDAP') {
							$GLOBALS['CopyLink'] =  ' <a href="index.php?ToDo=copyUser&amp;userid='.$userRow['userid'].'" class="bodylink">'.GetLang('Copy').'</a>';
						} else {
							$GLOBALS['CopyLink'] = ' <span class="Disabled">'.GetLang('Copy').'</span>';
						}
					} else {
						$GLOBALS['EditLink'] = '<span class="Disabled">'.GetLang('Edit').'</span>';
						$GLOBALS['CopyLink'] = ' <span class="Disabled">'.GetLang('Copy').'</span>';
					}


					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('user.row');
					$GLOBALS['UserGrid'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
				}

				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('user.manage');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
			} else {
				$valid_letters = GetAlphaList();
				if (isset($_GET['letter']) && in_array($_GET['letter'], $valid_letters)) {
					// There aren't any users, show a message so they can create some
					$GLOBALS['Title'] = GetLang('ManageUsers');
					$GLOBALS['ButtonText'] = GetLang('CreateUserAccount');
					$GLOBALS['ButtonClass'] = 'Field150';
					$GLOBALS['Message'] = MessageBox(sprintf(GetLang('UserNoneWithThatLetter'), $_GET['letter']), MSG_WARNING);
					$GLOBALS['URL'] = 'index.php?ToDo=createUser';

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('messagewithbutton');
					$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
				} else {
					// There aren't any users, show a message so they can create some
					$GLOBALS['Title'] = GetLang('ManageUsers');
					$GLOBALS['ButtonText'] = GetLang('CreateUserAccount');
					$GLOBALS['ButtonClass'] = 'Field150';
					$GLOBALS['Message'] = MessageBox(GetLang('NoUsers'), MSG_SUCCESS);
					$GLOBALS['URL'] = 'index.php?ToDo=createUser';

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('messagewithbutton');
					$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
				}
			}
		}

		/**
		* _UsernameAvailable
		* Check if the given username is already in use by another user
		*
		* @param string $username The username to check
		*
		* @return bool Is the username available ?
		*/
		function _UsernameAvailable($username)
		{
			$user = new API_USER();
			$user->find('username', $username);

			return ($user->userid == 0);
		}
		
		/**
		* Get a list of users and return them as an array
		*
		* @return Array The array containing the users
		*/
		function _GetUserListAsArray()
		{
			$query = sprintf('SELECT * FROM %susers ORDER BY username ASC', $GLOBALS['tablePrefix']);
			$result = $GLOBALS['AKB_DB']->Query($query);
			$users = array();

			while($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				array_push($users, $row);
			}

			return $users;
		}
	}

?>