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

	class AKB_GROUP 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 'viewgroups':
					default:
						if ($_SESSION['user']->verify('group', 'edit')
						|| $_SESSION['user']->verify('group', 'delete')) {
							if (isset($_POST['bulkaction'])) {
								$this->BulkAction();
							}
							$this->ShowList();
						} else {
							$this->NoPermission();
						}
				}
			}
		}

		/**
		* 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;
			}
			$g = new API_GROUP();
			switch (strtolower($_POST['bulkaction'])) {
				case 'delete':
					if ($_SESSION['user']->verify('group', 'delete')) {
						if ($g->multiDelete($_POST['item'])) {
							$GLOBALS['Message'] = MessageBox(GetLang('GroupMultiDeleteOk'), MSG_SUCCESS);
						} else {
							$GLOBALS['Message'] = MessageBox(GetLang('GroupMultiDeleteFail'), MSG_ERROR);
						}
					} else {
						return false;
					}
				break;
			}
		}

		/**
		* ShowEditGroup
		* Show the edit a group page
		*
		* @return void
		*/
		function ShowEditGroup()
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('group', 'edit')) {
				$this->NoPermission();
				return;
			}

			// Show the update user form
			$GLOBALS["GroupTitle"] = GetLang("EditGroupTitle");
			$GLOBALS["GroupIntro"] = GetLang("EditGroupIntro");
			$GLOBALS["req"] = "&nbsp;&nbsp;";
			
			if (isset($_GET['groupid'])) {
				$groupid = (int) $_GET["groupid"];
				$group = new API_GROUP();
				$group->load($groupid);
				if ($group->loaded) {
					$GLOBALS["hiddenFields"] = sprintf("<input type='hidden' name='groupid' value='%d'>", $groupid);
					$GLOBALS["name"] = $group->name;

					$GLOBALS['Grid'] = $this->generatePermsGrid($group);

					if (is_array($group->applies['category'])) {
						$GLOBALS['AllSelected'] = '';
					} else {
						$GLOBALS['AllSelected'] = 'selected';
					}

					if ($group->contactable) {
						$GLOBALS['YesContactable'] = 'checked';
					} else {
						$GLOBALS['YesContactable'] = '';
					}
					
					if ((!isset($group->applies['feonly']) || ($group->applies['feonly'] == "0"))) {
						$GLOBALS['feonly0'] = "checked=\"checked\" ";
						$GLOBALS['GroupFE'] = "0";
					} else {
						$GLOBALS['feonly1'] = "checked=\"checked\" ";
						$GLOBALS['GroupFE'] = "1";
					}
					
					$GLOBALS['appliestooptions'] = $this->generateAppliesToOptions($groupid, 'category');

					$GLOBALS['FormAction'] = 'saveUpdatedGroup';
					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('group.form');
					$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
				} else {
					$this->ShowList();
				}
			} else {
				$this->ShowList();
			}
		}

		/**
		* DeleteGroup
		* Delete a group from the database
		*
		* @return void
		*/
		function DeleteGroup()
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('group', 'delete')) {
				$this->NoPermission();
				return;
			}

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

		/**
		* ShowNewGroup
		* Show the create a new group page
		*
		* @return void
		*/
		function ShowNewGroup()
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('group', 'edit')) {
				$this->NoPermission();
				return;
			}

			// Show the create new user screen
			$GLOBALS["GroupTitle"] = GetLang("AddGroupTitle");
			$GLOBALS["GroupIntro"] = GetLang("AddGroupIntro");
			$GLOBALS["req"] = "*";
			$GLOBALS['Backup'] = '';
			$GLOBALS['PermBackup'] = '';
			$GLOBALS['PermBackupEdit'] = '';
			$GLOBALS['PermBackupCreate'] = '';
			$GLOBALS['Database'] = '';
			$GLOBALS['PermDatabase'] = '';
			$GLOBALS['PermDatabaseCheck'] = '';
			$GLOBALS['hiddenFields'] = '';
			$GLOBALS['name'] = '';
			$GLOBALS['YesContactable'] = '';

			$GLOBALS["AddingUser"] = "1";
			$GLOBALS["FormAction"] = "saveNewGroup";

			$group = new API_GROUP();
			$GLOBALS['Grid'] = $this->generatePermsGrid($group);
			
			//Default to frontend only for new groups
			$GLOBALS['GroupFE'] = "1";
			$GLOBALS['feonly1'] = "checked=\"checked\" ";

			$GLOBALS['AllSelected']		= 'selected';

			$GLOBALS['appliestooptions'] = $this->generateAppliesToOptions(0, 'category');

			$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("group.form");
			$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
		}

		/**
		* CopyGroup
		*
		* Takes the currently setup group and copies.
		*
		* @return void
		*/
		function CopyGroup() {
			
			$GLOBALS['BreadcrumEntries'] = array(GetLang("Home") => "index.php", GetLang("GroupManageGroups") => "");
			if (isset($_POST['bulkaction'])) {
				if ($_SESSION['user']->verify('group', 'edit')
				|| $_SESSION['user']->verify('group', 'delete')) {
					$this->BulkAction();
					$this->ShowList();
					return true;
				}
			}
			
			$groupId = (int)$_GET['groupid'];
			$successObj = false;
			if ($groupId > 0) {
				$group = new API_GROUP();
				$group->load($groupId);
				$gFields = $group->writeFields();
				
				$exist = true;
				$gName = $group->name;
				while ($exist) {
					$gName = "Copy of ".$gName." ";
					$existQuery = "SELECT count(name) as tot from ".$group->table." WHERE name = '".$gName."'";
					$tot = $GLOBALS['AKB_DB']->FetchOne($existQuery);
					if ($tot == 0) {
						break;
					}
				}
				$gFields[0] = "'".$gName."' as " . $gFields[0];
				$copy_query = 'INSERT INTO '.$group->table.'
				('.implode(', ', $group->writeFields()).')
				SELECT '.implode(', ', $gFields).'
				FROM '.$group->table.'
				WHERE '.$group->pk.' = '.((int) $group->{$group->pk});
				
				if ($GLOBALS['AKB_DB']->Query($copy_query)) {
		$this->ShowList(GetLang("GroupCopySuccess"), MSG_SUCCESS);
				} else {
						$this->ShowList(GetLang("GroupCopyError"), MSG_ERROR);
				}
			}
		}
		
		/**
		* SaveUpdatedGroup
		* Save updates to an existing group to the database
		*
		* @return void
		*/
		function SaveUpdatedGroup()
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('group', 'edit')) {
				$this->NoPermission();
				return;
			}

			$group = new API_GROUP();
			$group->load($_POST['groupid']);

			$old_name = $group->name;

			// If the username hasn't changed or is still available
			if (strtolower($_POST['name']) == strtolower($old_name) || $this->_GroupnameAvailable($_POST['name'])) {
				// We have to set the perms array of the group before we call
				// save so that our permissions get saved
				foreach ($group->getDefaultPerm() as $area => $perms) {
					foreach ($perms as $perm => $val) {
						$str = 'perm_'.$area.'_'.$perm;
						$group->perms[$area][$perm] = (isset($_POST[$str]));
					}
				}
				
				//Save the group type
				$group->applies['feonly'] = ($_POST['feonly'] == "1") ? "1" : "0";
				
				// Setup our applies array for saving
				if (isset($_POST['appliesto']) && is_array($_POST['appliesto'])) {
					if (in_array(-1, $_POST['appliesto'])) {
						$group->applies['category'] = "all";
					} else {
						// Reset the perms
						$group->applies['category'] = array();
						foreach ($_POST['appliesto'] as $catid) {
							$group->applies['category'][] = $catid;
						}
					}
				} else {
					$group->resetApplies();
				}

				if (!isset($_POST['contactable'])) {
					$_POST['contactable'] = 0;
				}

				if ($group->save()) {
					// Everything is done
					$this->ShowList(sprintf(GetLang("GroupUpdatedOK"), htmlspecialchars($_POST['name'],ENT_QUOTES,$GLOBALS['charset'])), MSG_SUCCESS);
				} else {
					// Something went wrong
					$GLOBALS["Message"] = MessageBox(sprintf(GetLang("GroupError"), $GLOBALS['AKB_DB']->GetErrorMsg()), MSG_ERROR);
					$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("error");
					$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
				}
			} else {
				// The username is already taken
				$GLOBALS["Message"] = MessageBox(sprintf(GetLang("GroupnameTaken"), htmlspecialchars($_POST['name'],ENT_QUOTES,$GLOBALS['charset'])), MSG_ERROR);
				$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("error");
				$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
			}
		}

		/**
		* SaveNewGroup
		* Save a new group to the database
		*
		* @return void
		*/
		function SaveNewGroup()
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('group', 'edit')) {
				$this->NoPermission();
				return;
			}

			if ($this->_GroupnameAvailable($_POST['name'])) {
				$group = new API_GROUP();

				// We have to set the perms array of the group before we call
				// save so that our permissions get saved
				foreach ($group->getDefaultPerm() as $area => $perms) {
					foreach ($perms as $perm => $val) {
						$str = 'perm_'.$area.'_'.$perm;
						$group->perms[$area][$perm] = (isset($_POST[$str]));
					}
				}
				
				//Save the group type
				$group->applies['feonly'] = ($_POST['feonly'] == "1") ? "1" : "0";
				
				// Setup our applies array for saving
				if (isset($_POST['appliesto']) && is_array($_POST['appliesto'])) {
					if (in_array(-1, $_POST['appliesto'])) {
						$group->applies['category'] = "all";
					} else {
						// Reset the perms
						$group->applies['category'] = array();
						foreach ($_POST['appliesto'] as $catid) {
							$group->applies['category'][] = $catid;
						}
					}
				} else {
					$group->resetApplies();
				}

				if (!isset($_POST['contactable'])) {
					$_POST['contactable'] = 0;
				}

				if ($group->create()) {
					$group->find('name', $_POST['name']);

					// Everything is done
					$this->ShowList(sprintf(GetLang('GroupAddedOK'), htmlspecialchars($_POST['name'],ENT_QUOTES,$GLOBALS['charset'])), MSG_SUCCESS);
				} else {
					// Something went wrong
					$GLOBALS['Message'] = MessageBox(sprintf(GetLang('GroupError'), $GLOBALS['AKB_DB']->GetErrorMsg()), MSG_ERROR);
					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('error');
					$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
				}
			} else {
				$GLOBALS['Message'] = MessageBox(sprintf(GetLang('GroupnameTaken'), htmlspecialchars($_POST['name'],ENT_QUOTES,$GLOBALS['charset'])), MSG_ERROR);
				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('error');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
			}
		}

		/**
		* ShowList
		* Show the list of groups
		*
		* @param string $MsgDesc A message to display
		* @param int $MsgStatus the status of the message being displayed
		*
		* @return void
		*/
		function ShowList($MsgDesc = "", $MsgStatus = "")
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('group', 'edit')
			&& !$_SESSION['user']->verify('group', 'delete')) {
				$this->NoPermission();
				return;
			}
			
			$query = "SELECT COUNT(*)
			FROM ".$GLOBALS["tablePrefix"]."groups";
			$link = 'index.php?ToDo=viewGroups';

			$total = $GLOBALS['AKB_DB']->FetchOne($query);			

			$GLOBALS['Style'] = '';
			$GLOBALS['FormAction'] = 'index.php?ToDo=viewGroups';
			if ((int)$total == 0) {
				// There aren't any groups, show a message so they can create some
				$GLOBALS['Title'] = GetLang('ManageGroups');
				$GLOBALS['ButtonText'] = GetLang('CreateGroupAccount');
				$GLOBALS['ButtonClass'] = 'Field150';
				$GLOBALS['Message'] = MessageBox(GetLang('NoGroups'), MSG_SUCCESS);
				$GLOBALS['URL'] = 'index.php?ToDo=createGroup';

				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('messagewithbutton');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
			} else {
				if ($MsgDesc != '') {
					$GLOBALS['Message'] = MessageBox($MsgDesc, $MsgStatus);
				}

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

				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('group.manage');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
			}
		}
		
		function ShowGroupsListRemote() {
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('group', 'edit')
			&& !$_SESSION['user']->verify('group', 'delete')) {
				$this->NoPermission();
				return;
			}	
			
			//Get count
			$query = "SELECT COUNT(*)
			FROM ".$GLOBALS["tablePrefix"]."groups";

			$total = $GLOBALS['AKB_DB']->FetchOne($query);
			$numpages = ceil($total / AKB_GROUP_PER_PAGE);
			
			//Set pagination variables.
			$page = isset($_GET['page'])? (int) $_GET['page'] : 1;
			$start = ($page == 1) ? 0 : ($page * AKB_GROUP_PER_PAGE) - (AKB_GROUP_PER_PAGE-1) -1;			

			//Setup pagination
			$this->SetupPaginationLink("ShowGroupsListRemote","a","name");
			$this->SetupPagination($query,$page,AKB_GROUP_PER_PAGE);
			
			$sortVars = array("name","usercount");
			$sortArray = $this->SetupSortingParams($sortVars,"ShowGroupsListRemote",$page);
			
			$query = 
			"
			select gg.groupid, gg.name, gg.permissions, gg.application, gg.contactable, (
			SELECT  COUNT(m.groupid) as usercount
						FROM (".$GLOBALS['tablePrefix']."members m
						RIGHT JOIN ".$GLOBALS['tablePrefix']."groups g ON g.groupid = m.groupid)
			            WHERE g.groupid = gg.groupid
			            GROUP BY g.groupid, g.name
			) as usercount
			"
			." FROM ".$GLOBALS['tablePrefix']."groups gg"
			." ORDER BY ".$this->sortField." ".$this->sortDirection
			." " . $GLOBALS['AKB_DB']->AddLimit($start, AKB_GROUP_PER_PAGE)
			;
			
			$result = $GLOBALS['AKB_DB']->Query($query);
			
			$adminTable = new GroupManage_Table();
			$adminTable->rsData = $result;
			$adminTable->sortArray = $sortArray;
			
			echo $adminTable->ReturnTable();
		}

		/**
		* _GroupnameAvailable
		* Check if the group name is already taken or not
		*
		* @param string $name The name to check
		*
		* @return bool Is the group available ?
		*/
		function _GroupnameAvailable($name)
		{
			$group = new API_GROUP();
			$group->find('name', $name);

			return ($group->groupid == 0);
		}

		/**
		* generatePermsGrid
		* Generate the grid of possible permissions to display in the new and
		* edit group page
		*
		* @param obj $group An established group object.
		*
		* @return string The html of the grid
		*/
		function generatePermsGrid(&$group)
		{
			$grid = '';

			$groupid = $group->groupid;

			if ($group->groupid == 0) {
				$group->resetPerms();
			}

			if (!empty($group->perms)) {
				foreach ($group->getDefaultPerm() as $area => $perms) {
					$GLOBALS['area'] = $GLOBALS['AKB_LANG'][ucfirst($area)];
					$langStr = 'Perm'.ucfirst($area);
					$GLOBALS['areaLabel'] = $GLOBALS['AKB_LANG'][$langStr];

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('group.perms.header');
					$grid .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('group.perms.row');

					foreach (array_keys($perms) as $perm) {
						$langStr = 'Perm'.ucfirst($area).ucfirst($perm);
						$GLOBALS['label'] = $GLOBALS['AKB_LANG'][$langStr];
						$set = ((isset($group->perms[$area][$perm])
							&& $group->perms[$area][$perm]));

						$GLOBALS['checked'] = ($set || $groupid == 0) ? 'checked' : '';
						$GLOBALS['area'] = $area;
						$GLOBALS['perm'] = $perm;

						$grid .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
					}

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('group.perms.footer');
					$grid .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
				}
			}
			return $grid;
		}

		/**
		* generateAppliesToOptions
		* Generate html options for applying permissions to groups
		*
		* @param int $groupid The groupid the applicaton is for
		* @param string $where The area the application is to
		*
		* @return string The html of the options
		*/
		function generateAppliesToOptions($groupid, $where)
		{
			if ($where == '') {
				return '';
			}

			$options = '';
			$group = new API_GROUP();

			if ($groupid > 0) {
				$group->load($groupid);
			} else {
				$group->resetApplies();
			}
			
			if (!empty($group->applies)) {
				$options = $GLOBALS['AKB_CLASS_CATEGORY']->GetCategoryOptions($group->applies[$where], "<option %s value='%d'>%s</option>", 'selected', '- ', false);
			}
			
			return $options;
		}

		/**
		* getMemebers
		* Get a list of memebrs for a list of groups and put them in
		* $this->members
		*
		* @param array $groupids The ids of the groups to get the members of
		*
		* @return void
		*/
		function getMembers($groupids=array())
		{
			if (empty($groupids)) {
				$query = "SELECT *
				FROM ".$GLOBALS['tablePrefix']."members";
			} else {
				$query = "SELECT *
				FROM ".$GLOBALS['tablePrefix']."members
				WHERE groupid IN (".implode(',',$groupids).")";
			}

			$result = $GLOBALS['AKB_DB']->Query($query);
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$this->members[$row['groupid']][] = $row;
			}

		}

	}
	
	
	class GroupManage_Table extends AKB_AdminTable {
	
		function GroupManage_Table() {
			parent::AKB_AdminTable();
		
			$GLOBALS['TableIconImagePath'] = "images/group.gif";
			
			$this->prependDataTemplate['CHECKBOX'] = "admintable.cell.selector.check";
			$this->prependDataTemplate['ICON'] = "admintable.cell.selector.icon";
			
			$this->headingArray['name'] 		= GetLang("GroupName");
			$this->headingArray['usercount'] 	= GetLang("Users");
			$this->headingArray['action'] 		= GetLang("Action");
			
			$this->sizeArray		= array("60%","20%","20%");
			$this->prependDataID 	= "groupid";
			$this->tableIdent 		= "ShowGroupsListRemote";

			$this->addCallback("action","","");
			$this->addCallback("name","htmlspecialchars",array("__name__",ENT_QUOTES,$GLOBALS['charset']));

			if ($_SESSION['user']->verify('group', 'edit')) {
				$this->addTemplateOverride("action","group.cell.edit",array("__groupid__"));
			} else {
				$this->addTemplateOverride("action","group.cell.noedit");
			}			
		}
		
		function ReturnTable() {
			return parent::ReturnTable();
		}
	}

?>
