<?php

	class AKB_AUTH
	{
		/**
		* AKB_AUTH
		*
		* Constructor
		*
		* @return void
		*/
		function AKB_AUTH()
		{
			// If the user object isnt setup or is the wrong object remake it
			if (!isset($_SESSION['user'])) {
				$_SESSION['user'] = new API_USER();
			} else if (strtolower(get_class($_SESSION['user'])) != 'api_user') {
				$_SESSION['user'] = new API_USER();
			}
		}

		/**
		* LogOut
		*
		* Kill the session auth variable and redirect the user to the login page
		*
		* @return void
		*/
		function LogOut()
		{
			unset($_SESSION['user']);

			// Set the cookies to a time in the past
			setcookie($GLOBALS['cookiePrefix'].'RememberMe', '', time() - 3600*24*365);
			setcookie($GLOBALS['cookiePrefix'].'RememberUser', '', time() - 3600*24*365);
			setcookie($GLOBALS['cookiePrefix'].'RememberPass', '', time() - 3600*24*365);

			if (isset($_COOKIE[session_name()])) {
				setcookie(session_name(), '', time()-42000, '/');
			}

			session_destroy();

			?>
				<script type="text/javascript" language="javascript">
					document.location.href='index.php';
				</script>
			<?php
				die();
		}

		/**
		* IsLoggedIn
		*
		* Check if a user is logged in or not
		* Additionally we need to check if they have access to be in the admin.
		*
		* @return boolean
		*/
		function IsLoggedIn() {
			$isLoggedIn = (isset($_SESSION['user']) && $_SESSION['user']->userid > 0);
			return (($isLoggedIn) && (AKB_AUTH::HasAdminAccess()));
		}

		/**
		* HasAdminAccess
		*
		* Check if the group the user is in has access to the backend of the system.
		*
		* @return boolean
		*/
		function HasAdminAccess($groupid=0) {
			if ((!isset($_SESSION['user'])) || (strtolower(get_class($_SESSION['user'])) != "api_user")) {
				return false;
			}

			//Special case for admin users.
			if ($_SESSION['user']->userid == 1) {
				return true;
			}

			$groups = $_SESSION['user']->groups;

			if (!$groups) {
				return false;
			}

			$hasAccess = false;
			foreach ($groups as $groupObj) {
				if ((!isset($groupObj->applies['feonly'])) || ((isset($groupObj->applies['feonly'])) && ($groupObj->applies['feonly'] == 0))) {
					$hasAccess = true;
					break;
				}
			}

			return $hasAccess;
		}

		/**
		* GetUserType
		* Determine if the user is AKB or LDAP user
		*
		* @return string
		*/
		function GetUserType ($var) {
			if ($var == '@LDAP') {
				return 'LDAP';
			} elseif (strlen($var) == 32 && preg_match('/[0-9a-f]+/', $var)) {
				return 'DB';
			} else {
				return '';
			}
		}

		/**
		* ProcessLogin
		* Take the credentials from an attempt and try to verify them
		*
		* @return void
		*/
		function ProcessLogin()
		{
			if(!$this->UserLoginCheck(GetIPAdd(), $GLOBALS['bannedRetried'], $GLOBALS['bannedPeriod'])) {
				unset($_SESSION['user']);
				$this->DoLogin(true);
				die();
			}
			$loginName = $_POST['username'];
			$loginPass = $_POST['password'];
			$remember = isset($_POST['remember']);

			if ($remember) {
				setcookie($GLOBALS['cookiePrefix'].'RememberMe',   true, time() + 3600*24*365);
				setcookie($GLOBALS['cookiePrefix'].'RememberUser', $loginName, time() + 3600*24*365);
				$cookiesLoginPass = md5($loginPass);
				if (strlen($loginPass) == 32) {
					$cookiesLoginPass = $loginPass;
				}
				setcookie($GLOBALS['cookiePrefix'].'RememberPass', $cookiesLoginPass, time() + 3600*24*365);
			}

			if (isset($_SESSION['user'])) {
				//Regenerate the session id before we begin
				//session_regenerate_id(true);

				// Try and find a user with the same credentials
				$_SESSION['user']->find('username', $loginName);

				$userId = ($_SESSION['user']->checkPass($loginPass)) ? $_SESSION['user']->userid : 0;


				// If this user is not in db or this user is LDAP user
				if (!$userId || API_LDAP::isLdapUser($_SESSION['user']->pass)) {
					// If LDAP authentication is enabled authentication && we have our LDAP Class initialized
					if (isset($GLOBALS['AKB_LDAP']) && $GLOBALS['AKB_LDAP']->getErrorMsg() == null) {
						$userId = API_LDAP::authenticate($loginName, $loginPass, $userId);
					}
				}


				//The user has to at least be in one group that has admin access
				$feonly = false;
				if ($userId > 1) {
					$feonly = true;
					if ((isset($_SESSION['user']->groups)) && (is_array($_SESSION['user']->groups))) {
						foreach ($_SESSION['user']->groups as $groupObj) {
							if (!$groupObj->isFrontendOnly()) {
								$feonly = false;
							}
						}
					}
				}

				if (($userId) && (!$feonly)) {
					// reset the login ip checking
					$this->UserLoginReset(GetIPAdd());

					$_SESSION['user']->sessionid = session_id();
					$_SESSION['user']->updateField('sessionid', $_SESSION['user']->sessionid);
					header('Location: '.@$_SESSION['AttemptedAccessUrl']);
					// Everything was OK and the user has been logged in successfully
					?>
						<script type="text/javascript" language="javascript">
							document.location.href='index.php';
						</script>
					<?php
						die();
				} else {
					unset($_SESSION['user']);
					$this->UserLoginLog(GetIPAdd());
					sleep(5);
					$this->DoLogin(true);
					die();
				}
			} else {
				$this->DoLogin(true);
				die();
			}
		}

		function UserLoginLog($ipaddress) {
			if (!isset($GLOBALS['enabledLoginSecurity']) || !$GLOBALS['enabledLoginSecurity']) {
				return true;
			}

			if ($ipaddress != '') {
			$query = sprintf("SELECT attemptnum FROM %suserlogin WHERE ipaddress = '%s' ", $GLOBALS['tablePrefix'], $ipaddress);
			$result = $GLOBALS['AKB_DB']->Query($query);

				// if the ipaddress exist?
				if($row = $GLOBALS['AKB_DB']->Fetch($result)) {
					// increase the attempted number
					$query = sprintf("UPDATE %suserlogin SET attemptnum = '%d', tslogin = '%s' WHERE ipaddress = '%s' ", $GLOBALS['tablePrefix'], (int)$row['attemptnum']+1, date("Y-m-d H:i:s"), $ipaddress);
					$GLOBALS['AKB_DB']->Query($query);
				} else {
					// else insert a new one
					$query = sprintf("INSERT INTO %suserlogin VALUES ('%s', '%d', '%s')", $GLOBALS['tablePrefix'], $ipaddress, 1, date("Y-m-d H:i:s"));
					$GLOBALS['AKB_DB']->Query($query);
				}
				return true;
			}
			return false;
		}

		function UserLoginReset($ipaddress) {
			if (!isset($GLOBALS['enabledLoginSecurity']) || !$GLOBALS['enabledLoginSecurity']) {
				return true;
			}

			// delete all the records from the $ipaddress
			$query = sprintf("DELETE FROM %suserlogin WHERE ipaddress = '%s' ", $GLOBALS['tablePrefix'], $ipaddress);
			return $GLOBALS['AKB_DB']->Query($query);
		}

		function UserLoginCheck($ipaddress, $attemptnum, $min = 5) {
			if (!isset($GLOBALS['enabledLoginSecurity']) || !$GLOBALS['enabledLoginSecurity']) {
				return true;
			}
			$now = date("Y-m-d H:i:s", mktime(date("H"), date("i")-$min, date("s"), date("m")  , date("d"), date("Y")));
			$query = sprintf("SELECT attemptnum, tslogin FROM %suserlogin WHERE ipaddress = '%s' AND attemptnum >= '%d' AND tslogin >= '%s'", $GLOBALS['tablePrefix'], $ipaddress, (int)$attemptnum, $now);
			$result = $GLOBALS['AKB_DB']->Query($query);


			// if attemptnum is same or greater than $attemptnum AND the ipaddress is matched.
			if(!$row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$query = sprintf("SELECT attemptnum FROM %suserlogin WHERE ipaddress = '%s' AND attemptnum >= '%d' AND tslogin < '%s'", $GLOBALS['tablePrefix'], $ipaddress, (int)$attemptnum, $now);
				$result = $GLOBALS['AKB_DB']->Query($query);
				if($row = $GLOBALS['AKB_DB']->Fetch($result)) {
					$this->UserLoginReset(GetIPAdd());
				}
				return true;
			}
			$GLOBALS['loginBlocked'] = 1;
			$blockStartedTs = $row['tslogin'];
			$GLOBALS['ExactMinutesRemain'] = ceil((strtotime($row['tslogin'])-mktime(date("H"), date("i")-$min, date("s"), date("m")  , date("d"), date("Y")))/60);
			return false;
		}

		/**
		* ProcessLogin
		* Take the credentials from an attempt and try to verify them
		*
		* @return void
		*/
		function ProcessXmlLogin()
		{
			if(!$this->UserLoginCheck(GetIPAdd(), $GLOBALS['bannedRetried'], $GLOBALS['bannedPeriod'])) {
				unset($_SESSION['user']);
				return false;
			}

			if (isset($GLOBALS['xmlRequest']->kbuserlogin->username) && isset($GLOBALS['xmlRequest']->kbuserlogin->password)) {
				$loginName = strval($GLOBALS['xmlRequest']->kbuserlogin->username);
				$loginPass = strval($GLOBALS['xmlRequest']->kbuserlogin->password);

				if (isset($_SESSION['user'])) {
					//Regenerate the session id before we begin
					//session_regenerate_id(true);

					// Try and find a user with the same credentials
					$_SESSION['user']->find('username', $loginName);
					$userId = ($_SESSION['user']->checkPass($loginPass)) ? $_SESSION['user']->userid : 0;


					// If this user is not in db or this user is LDAP user
					if (!$userId || API_LDAP::isLdapUser($_SESSION['user']->pass)) {
						// If LDAP authentication is enabled authentication && we have our LDAP Class initialized
						if (isset($GLOBALS['AKB_LDAP'])) {
							$userId = API_LDAP::authenticate($loginName, $loginPass, $userId);
						}
					}


					//The user has to at least be in one group that has admin access
					$feonly = false;
					if ($userId > 1) {
						$feonly = true;
						if ((isset($_SESSION['user']->groups)) && (is_array($_SESSION['user']->groups))) {
							foreach ($_SESSION['user']->groups as $groupObj) {
								if (!$groupObj->isFrontendOnly()) {
									$feonly = false;
								}
							}
						}
					}

					if (($userId) && (!$feonly)) {
						// reset the login ip checking
						$this->UserLoginReset(GetIPAdd());

						$_SESSION['user']->sessionid = session_id();
						$_SESSION['user']->updateField('sessionid', $_SESSION['user']->sessionid);
						return true;
					} else {
						unset($_SESSION['user']);
						$this->UserLoginLog(GetIPAdd());
						sleep(5);
						return false;
					}
				} else {
					return false;
				}
			}
			return false;
		}

		/**
		* DoLogin
		* Display the credentials page
		*
		* @param bool $BadLogin Was this page loaded after a bad login attempt?
		*/
		function DoLogin($BadLogin=false)
		{
			if ($BadLogin) {
				$GLOBALS['Message'] =  GetLang('BadLogin');
			} else {
				$GLOBALS['Message'] = GetLang("LoginIntro");
			}

			if (isset($_GET['loggedout'])) {
				$GLOBALS['Message'] =  MessageBox(GetLang('LoggedOut'), MSG_WARNING);
			} elseif (isset($_GET['sessionloggedout'])) {
				$GLOBALS['Message'] =  MessageBox(GetLang('SessionLoggedOutMessage'), MSG_WARNING);
			} else if (isset($GLOBALS['loginBlocked'])) {
				$minRemain = $GLOBALS['bannedPeriod'];
				if (isset($GLOBALS['ExactMinutesRemain'])) {
					$minRemain = $GLOBALS['ExactMinutesRemain'];
				}
				$GLOBALS['Message'] =  '<span style="color:red;">'.sprintf(GetLang('UserLoginBlockedMessage'), $GLOBALS['bannedRetried'], $minRemain) . '</span>';
			}


			if (isset($_COOKIE[$GLOBALS['cookiePrefix'].'RememberMe'])) {
				$GLOBALS['RememberMe'] = 'CHECKED';
			} else {
				$GLOBALS['RememberMe'] = '';
			}

			if (!isset($_POST['username']) && isset($_COOKIE[$GLOBALS['cookiePrefix'].'RememberMe']) && isset($_COOKIE[$GLOBALS['cookiePrefix'].'RememberUser']) && isset($_COOKIE[$GLOBALS['cookiePrefix'].'RememberUser'])) {
				$_POST['username'] = $_COOKIE[$GLOBALS['cookiePrefix'].'RememberUser'];
				$_POST['password'] = $_COOKIE[$GLOBALS['cookiePrefix'].'RememberPass'];
				$this->ProcessLogin();
				die();
			}

			if (!isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI'] == '') {
				$_SERVER['REQUEST_URI'] = $_SERVER["SCRIPT_NAME"] .'?'.
				$_SERVER['QUERY_STRING'];
			}

			$_SESSION['AttemptedAccessUrl'] = $_SERVER['REQUEST_URI'];

			$GLOBALS['SubmitAction'] = 'processLogin';
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('credentials.form');

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

		/**
		* SetupHomePageLinks
		* Setup some global variables for the admin home page
		*
		* @return void
		*/
		function SetupHomePageLinks()
		{
			$GLOBALS['GbHomeQuickLinks'] = '';
			$GLOBALS['GbHomeGettingStarted'] = '';
			if (isset($_COOKIE[$GLOBALS['cookiePrefix'].'HomeLinks']) && $_COOKIE[$GLOBALS['cookiePrefix'].'HomeLinks'] != '') {
				$GLOBALS['Gb'.$_COOKIE[$GLOBALS['cookiePrefix'].'HomeLinks']] = 'none';
			} else {
				$GLOBALS['GbHomeQuickLinks'] = 'none';
			}
			$this->GetQuestionsSummary();
			$this->GetCommentsSummary();

			// Get the most popular question
			$query = sprintf('select questionid, title from %squestions where score > 0 order by score desc ' . $GLOBALS['AKB_DB']->AddLimit(-1, 1), $GLOBALS['tablePrefix']);
			$result = $GLOBALS['AKB_DB']->Query($query);

			if ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['Text'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['PopularQuestionLink'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');
			} else {
				$GLOBALS['PopularQuestionLink'] = GetLang('NA');
			}

			// Get the most popular category
			$query = sprintf('select categoryid, name from %scategories where visits > 0 order by visits desc ' . $GLOBALS['AKB_DB']->AddLimit(-1, 1), $GLOBALS['tablePrefix']);
			$result = $GLOBALS['AKB_DB']->Query($query);

			if ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['Href'] = GetUrl('question', $row['categoryid']);
				$GLOBALS['Text'] = htmlspecialchars($row['name'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['PopularCategoryLink'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');
			} else {
				$GLOBALS['PopularCategoryLink'] = GetLang('NA');
			}

			// Get the most popular author
			$arrUsers = array();
			$query = sprintf('SELECT userid, SUM(score) as score FROM %squestions GROUP BY userid', $GLOBALS['tablePrefix']);
			$result = $GLOBALS['AKB_DB']->Query($query);

			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				if (!isset($arrUsers[$row['userid']])) {
					$arrUsers[$row['userid']] = $row['score'];
				}
			}

			if (!empty($arrUsers)) {
				asort($arrUsers);

				foreach ($arrUsers as $k=>$v) {
					$userId = $k;
				}

				// Get the users details
				$query = sprintf("select * from %susers where userid='%d'", $GLOBALS['tablePrefix'], $userId);
				$result = $GLOBALS['AKB_DB']->Query($query);

				if ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
					if (trim($row['firstname']) != '' && trim($row['lastname']) != '') {
						$GLOBALS['PopularAuthorLink'] = sprintf("%s %s", $row['firstname'], $row['lastname']);
					} else {
						$GLOBALS['PopularAuthorLink'] = $row['username'];
					}
				} else {
					$GLOBALS['PopularAuthorLink'] = GetLang('NA');
				}
			} else {
				$GLOBALS['PopularAuthorLink'] = GetLang('NA');
			}

			/*
			* Important Notices
			*/
			// setup the notices
			$noticesArray = array();
			$GLOBALS['ShowNotice'] = 'none';
			$GLOBALS['NoticesLists'] = '';

			// setup pending article notice
			if (validUrl()) {
				// Get the number of pending article that need to be approved by this user.
				require_once("includes/classes/class.question.php");
				if (isset($_SESSION['search'])) {
					unset($_SESSION['search']);
				}
				$GLOBALS['AKB_QUESTION'] = new AKB_QUESTION();
				$GLOBALS['AKB_QUESTION'] -> BuildListQueries(true, false);
				$totalPendingArticles = $GLOBALS['AKB_DB']->FetchOne($GLOBALS['AKB_QUESTION']->countQuery);
				if ($totalPendingArticles > 0) {
					if ($totalPendingArticles == 1) {
						$noticeLang = 'OnePendingArticleNotice';
						$GLOBALS['Text'] = GetLang('OnePendingArticle');
					} else {
						$noticeLang = 'MorePendingArticleNotice';
						$GLOBALS['Text'] = GetLang('MorePendingArticles');
					}

					$GLOBALS['Href'] = $GLOBALS['pathToKB'].'/admin/index.php?ToDo=viewWorkflowQuestions';
					$link = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkCurrentWindow');
					$noticesArray[] = sprintf(GetLang($noticeLang), $totalPendingArticles, $link);
				}
			}

			foreach ($noticesArray as $notice) {
				$GLOBALS['Item'] = $notice;
				$GLOBALS['NoticesLists'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
			}
			if ($GLOBALS['NoticesLists'] != '') {
				$GLOBALS['ShowNotice'] = '';
			}

			/*
			* Statistics
			*/
			$GLOBALS['ShowGraph'] = '';
			$GLOBALS['ShowWholeGraph'] = '';
			require_once("includes/charts/charts.php");
			require_once("includes/classes/class.stats.php");
			$GLOBALS['AKB_STATS'] = new AKB_STATS();
			if(isset($_POST["Calendar"])) {
				$cal = $GLOBALS['AKB_STATS']->CalculateCalendarRestrictions($_POST["Calendar"]);
				$GLOBALS["CurrentDate"] = $_POST["Calendar"]["DateType"];
			}
			else {
				$cal = $GLOBALS['AKB_STATS']->CalculateCalendarRestrictions();
				$GLOBALS["CurrentDate"] = "Last30Days";
			}

			$GLOBALS['CustomDisplay'] = 'none';
			if ($GLOBALS["CurrentDate"] == 'Custom') {
				$GLOBALS['CustomDisplay'] = '';
			}
			$GLOBALS["CalendarDateTypeOptions"] = $GLOBALS['AKB_STATS']->_GetCalendarDateTypesAsOptions($GLOBALS["CurrentDate"], false);

			// Set the global variables for the select boxes
			$from_stamp = $cal["start"];
			$to_stamp = $cal["end"];

			$from_days = $from_stamp / 86400;
			$to_days = $to_stamp / 86400;
			$num_days = floor($to_days - $from_days)+1;

			$from_day = date("d", $from_stamp);
			$from_month = date("m", $from_stamp);
			$from_year = date("Y", $from_stamp);

			$to_day = date("d", $to_stamp);
			$to_month = date("m", $to_stamp);
			$to_year = date("Y", $to_stamp);


			$GLOBALS["ArticlePerUserFromDays"] = $GLOBALS['AKB_STATS']->_GetDayOptions($from_day);
			$GLOBALS["ArticlePerUserFromMonths"] = $GLOBALS['AKB_STATS']->_GetMonthOptions($from_month);
			$GLOBALS["ArticlePerUserFromYears"] = $GLOBALS['AKB_STATS']->_GetYearOptions($from_year);

			$GLOBALS["ArticlePerUserToDays"] = $GLOBALS['AKB_STATS']->_GetDayOptions($to_day);
			$GLOBALS["ArticlePerUserToMonths"] = $GLOBALS['AKB_STATS']->_GetMonthOptions($to_month);
			$GLOBALS["ArticlePerUserToYears"] = $GLOBALS['AKB_STATS']->_GetYearOptions($to_year);

			$_SESSION['ArticlePerUserFromStamp'] = $from_stamp;
			$_SESSION['ArticlePerUserToStamp'] = $to_stamp;
			$GLOBALS['AKB_STATS']->GetArticlePerUser('d', 1, 'postingcount', 215);
			if ($_SESSION['user']->verify('stats', 'viewuser')) {
				if (($GLOBALS['TotalAuthors'] <= 0 && !isset($_POST['Calendar'])) || $GLOBALS['TotalAuthors'] > 20 ) {
					$GLOBALS['ShowGraph'] = 'none';
				} elseif ($GLOBALS['TotalAuthors'] <= 0 && isset($_POST['Calendar'])) {
					$GLOBALS['ShowGraph'] = 'none';
					$GLOBALS['GraphMessage'] = '<div style="padding:5px;">'.MessageBox(GetLang('StatNoArticlesPosted'), MSG_INFORMATION).'</div>';
				} else {
					$GLOBALS['GraphMessage'] = '<div style="padding:5px;text-align:center;font-weight:bold;font-size:11px;font-family:Tahoma;">'.GetLang('NumOfArticlesPostedByUser').'</div>';
				}
			}
			else {
				$GLOBALS['DateRange'] = 'none';
				$GLOBALS['ShowGraph'] = 'none';
				$GLOBALS['GraphMessage'] = '<div style="padding:20px;padding-top:0;">'.MessageBox(GetLang('StatNoPermUsers'), MSG_INFORMATION).'</div>';
			}

			/*
			* Question
			*/
			if ($_SESSION['user']->verify('question', 'edit')
			|| $_SESSION['user']->verify('question', 'delete')
			|| $_SESSION['user']->verify('question', 'approve')) {
				$GLOBALS['ManageQuestionsLink'] = sprintf("<a href='index.php?ToDo=viewQuestions'>%s</a>", GetLang('ManageQuestions'));
			} else {
				$GLOBALS['ManageQuestionsLink'] = sprintf('<span class="Disabled">%s</span>', GetLang('ManageQuestions'));
			}

			if ($_SESSION['user']->verify('question', 'edit')) {
				$GLOBALS['CreateQuestionLink'] = sprintf("<a href='index.php?ToDo=createQuestion'>%s</a>", GetLang('CreateQuestion'));
			} else {
				$GLOBALS['CreateQuestionLink'] = sprintf('<span class="Disabled">%s</span>', GetLang('CreateQuestion'));
			}

			if ($_SESSION['user']->verify('question', 'review') && $GLOBALS['NumSubmittedQuestions'] > 0) {
				$GLOBALS['ReviewSubmittedQuestionsLink'] = sprintf("<a href='index.php?ToDo=reviewSubmittedQuestions'>%s</a>", GetLang('ManageSubmittedQuestions'));
				$GLOBALS['ReviewSubmittedQuestionsLink1'] = sprintf("<a href='index.php?ToDo=reviewSubmittedQuestions'>%s</a> (%d)", GetLang('ReviewSubmittedQuestions'), $GLOBALS['NumSubmittedQuestions']);
			} else {
				$GLOBALS['ReviewSubmittedQuestionsLink'] = sprintf('<span class="Disabled">%s</span>', GetLang('ManageSubmittedQuestions'));
				$GLOBALS['ReviewSubmittedQuestionsLink1'] = GetLang('NoSubmittedQuestions1');
			}

			/*
			* Category
			*/
			if ($_SESSION['user']->verify('category', 'edit')
			|| $_SESSION['user']->verify('category', 'delete')) {
				$GLOBALS['ManageCategoriesLink'] = sprintf("<a href='index.php?ToDo=viewCategories'>%s</a>", GetLang('ManageCategories'));
			} else {
				$GLOBALS['ManageCategoriesLink'] = sprintf('<span class="Disabled">%s</span>', GetLang('ManageCategories'));
			}
			if ($_SESSION['user']->verify('category', 'edit')) {
				$GLOBALS['CreateCategoryLink'] = sprintf("<a href='index.php?ToDo=createCategory'>%s</a>", GetLang('CreateCategory'));
			} else {
				$GLOBALS['CreateCategoryLink'] = sprintf('<span class="Disabled">%s</span>', GetLang('CreateCategory'));
			}
			/*
			* User
			*/
			if ($_SESSION['user']->verify('user', 'edit')
			|| $_SESSION['user']->verify('user', 'delete')) {
				$GLOBALS['ManageUsersLink'] = sprintf("<a href='index.php?ToDo=viewUsers'>%s</a>", GetLang('ManageUsers'));
			} else {
				$GLOBALS['ManageUsersLink'] = sprintf('<span class="Disabled">%s</span>', GetLang('ManageUsers'));
			}
			if ($_SESSION['user']->verify('user', 'edit')) {
				$GLOBALS['CreateUserLink'] = sprintf("<a href='index.php?ToDo=createUser'>%s</a>", GetLang('CreateUser'));
			} else {
				$GLOBALS['CreateUserLink'] = sprintf('<span class="Disabled">%s</span>', GetLang('CreateUser'));
			}

			/*
			* Comment
			*/
			if ($_SESSION['user']->verify('comment', 'edit')
			|| $_SESSION['user']->verify('comment', 'delete')) {
				$GLOBALS['ManageCommentsLink'] = sprintf("<a href='index.php?ToDo=viewComments'>%s</a>", GetLang('ManageComments'));
				$GLOBALS['ReviewPendingCommentsLink1'] = sprintf("<a href='index.php?ToDo=viewComments'>%s</a> (%d)", GetLang('ReviewPendingComments'), $GLOBALS['NumPendingComments']);
			} else {
				$GLOBALS['ManageCommentsLink'] = sprintf('<span class="Disabled">%s</span>', GetLang('ManageComments'));
				$GLOBALS['ReviewPendingCommentsLink1'] = GetLang('NoPendingComments');
			}

			/*
			* Groups
			*/
			if ($_SESSION['user']->verify('group', 'edit')
			|| $_SESSION['user']->verify('group', 'delete')) {
				$GLOBALS['ManageGroupsLink'] = sprintf("<a href='index.php?ToDo=viewGroups'>%s</a>", GetLang('ManageGroups'));
			} else {
				$GLOBALS['ManageGroupsLink'] = sprintf('<span class="Disabled">%s</span>', GetLang('ManageGroups'));
			}

			if ($_SESSION['user']->verify('group', 'edit')) {
				$GLOBALS['CreateGroupLink'] = sprintf("<a href='index.php?ToDo=createGroup'>%s</a>", GetLang('CreateGroup'));
			} else {
				$GLOBALS['CreateGroupLink'] = sprintf('<span class="Disabled">%s</span>', GetLang('CreateGroup'));
			}

			/*
			* Statistics
			*/
			$GLOBALS['ManageStatisticsLink'] = sprintf("<a href='index.php?ToDo=viewStatsQuestions'>%s</a>", GetLang('ManageStatistics'));

		}

		/**
		* GetQuestionsSummary
		* Get a summary of the questions, their visibility, and if they were
		* submitted by a user or not
		*
		* @return void
		*/
		function GetQuestionsSummary()
		{
			$GLOBALS['NumVisibleQuestions'] = 0;
			$GLOBALS['NumHiddenQuestions'] = 0;
			$GLOBALS['NumQuestions'] = 0;

			// Get the normal questions summary
			$query = 'SELECT visible, count(*) as num
			FROM '.$GLOBALS['tablePrefix'].'questions
			GROUP by visible';

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

			while ($row = $GLOBALS['AKB_DB']->Fetch($results)) {
				switch ($row['visible']) {
					case '0':
						$GLOBALS['NumHiddenQuestions'] = $row['num'];
						$GLOBALS['NumQuestions'] += $row['num'];
					break;
					case '1':
						$GLOBALS['NumVisibleQuestions'] = $row['num'];
						$GLOBALS['NumQuestions'] += $row['num'];
					break;
				}
			}

			// Get the submitted questions summary
			$query = 'SELECT COUNT(*)
			FROM '.$GLOBALS['tablePrefix'].'submittedquestions';

			$GLOBALS['NumSubmittedQuestions'] = $GLOBALS['AKB_DB']->FetchOne($query);
			$GLOBALS['NumQuestions'] += $GLOBALS['NumSubmittedQuestions'];

			$GLOBALS['NumQuestions'] = number_format($GLOBALS['NumQuestions']);
			$GLOBALS['NumHiddenQuestions'] = number_format($GLOBALS['NumHiddenQuestions']);
			$GLOBALS['NumVisibleQuestions'] = number_format($GLOBALS['NumVisibleQuestions']);
		}

		/**
		* GetCommentsSummary
		*
		* Get a summary of comments
		*
		* @return void
		*/
		function GetCommentsSummary()
		{
			$GLOBALS['NumApprovedComments'] = 0;
			$GLOBALS['NumDisapprovedComments'] = 0;
			$GLOBALS['NumPendingComments'] = 0;
			$GLOBALS['NumComments'] = 0;

			// Get the normal questions summary
			$query = 'SELECT status, count(*) AS num
			FROM '.$GLOBALS['tablePrefix'].'comments
			GROUP BY status';

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

			while ($row = $GLOBALS['AKB_DB']->Fetch($results)) {
				switch ($row['status']) {
					case 'pending':
						$GLOBALS['NumPendingComments'] = $row['num'];
						$GLOBALS['NumComments'] += $row['num'];
					break;
					case 'approved':
						$GLOBALS['NumApprovedComments'] = $row['num'];
						$GLOBALS['NumComments'] += $row['num'];
					break;
					case 'disapproved':
						$GLOBALS['NumDisapprovedComments'] = $row['num'];
						$GLOBALS['NumComments'] += $row['num'];
					break;
				}
			}

			$GLOBALS['NumApprovedComments'] = number_format($GLOBALS['NumApprovedComments']);
			$GLOBALS['NumDisapprovedComments'] = number_format($GLOBALS['NumDisapprovedComments']);
			$GLOBALS['NumPendingComments'] = number_format($GLOBALS['NumPendingComments']);
			$GLOBALS['NumComments'] = number_format($GLOBALS['NumComments']);
		}

		/**
		* IsSuperAdmin
		*
		* Check if the current user has super admin access
		*
		* @return boolean
		*/
		function IsSuperAdmin() {
			if ((!isset($_SESSION['user'])) || (strtolower(get_class($_SESSION['user'])) != "api_user")) {
				return false;
			}

			if ($_SESSION['user']->userid == 1) {
				return true;
			}
			return false;
		}

		/**
		* HasApprovalAccess
		*
		* Check if the group the user is in has access to the backend of the system.
		*
		* @param array $categories An array of category ids
		*
		* @return boolean
		*/
		function HasApprovalAccess($categories, $editMode = true, $checkCat = false) {
			if ((!isset($_SESSION['user'])) || (strtolower(get_class($_SESSION['user'])) != "api_user")) {
				return false;
			}

			//Special case for admin users.
			if ($_SESSION['user']->userid == 1) {
				return true;
			}

			if (is_array($_SESSION['user']->groups) && !empty($_SESSION['user']->groups)) {
				foreach ($_SESSION['user']->groups as $group) {
					if (isset($group->applies['category'])) {
						if ((isset($group->perms['category']['approve']) && $group->perms['category']['approve'] && ((is_array($group->applies['category']) && array_intersect($categories, $group->applies['category'])) || $group->applies['category'] == 'all')) && $group->applies['feonly'] != '1') {
							return true;
						}
					}
				}
			}

			if ($checkCat || 1) {
				// check if all the categories need any permission?
				// if not then return true.
				$catIds = "'" . implode("','", $categories) . "'";
				$query = sprintf("SELECT COUNT(categoryid) as num from %scategories where categoryid IN (%s) AND (approvaltype = '%d'", $GLOBALS['tablePrefix'], $catIds, CATEGORIES_NO_APPROVAL);
				if ($editMode) {
					$query .= sprintf(" OR approvaltype = '%d' ", CATEGORIES_ONCE_APPROVAL);
				}
				$query .= " ) ";
				$restriction = $GLOBALS['AKB_DB']->FetchOne($query);
				if ($restriction > 0) {
					return true;
				}
			}
			return false;
		}
	}

?>