<?php
defined('WikyBlog') or die("Not an entry point...");


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//		Show Rows
//

includeFile('admin/UserTools.php');
	
class userGroups extends userTools{
	
	var $specialContent;
	
	function userGroups(){
		global $page,$wbTables,$pageOwner;
		
		$page->autoForm = true;
		$page->css2 = true;
		$this->classes[] = ' class="tableRowEven" ';
		$this->classes[] = ' class="tableRowOdd" ';
		$this->specialContent['suspended'] = true;
		$this->specialContent['disabled'] = true;
		
		$contentUri = $page->regLink('User Groups','/Admin/'.$pageOwner['username'].'/UserGroups');
		$page->regLink('user_statistics','/Admin/'.$pageOwner['username'].'/UserSearch');
		
		
		ob_start();
		
		$show = true;
		switch($page->userCmd){
			case 'update':
				if( $this->updateGroup() ){
					break;
				}
			case 'edit':
				$this->editGroup();
				$show = false;
			break;
			
			case 'save':
				if( $this->saveGroup() ){
					break;
				}
			case 'new':
				$this->newGroup();
				$show = false;
			break;
			
			case 'move':
				if( $this->moveGroup() ){
					break;
				}
			case 'delete':
				$this->deleteGroup();
				$show = false;
			break;
		}
		if( $show ){
			$this->showGroups();
		}
		
		$page->contentB[$contentUri] = wb::get_clean();
	}
	
	//
	//	Delete
	//
	function deleteGroup(){
		global $page,$wbTables,$langA;
		if( isset($_POST['from']) ){
			$from = $_POST['from'];
		}else{
			$from = $_GET['from'];
		}
		if( !is_numeric($from) ){
			message('INVALID_REQUEST');
			return false;
		}
		$groupInfo =  $this->getGroupInfo($from);
		if( $groupInfo === false ){
			message('INVALID_REQUEST');
			return;
		}
		
		echo '<table class="WBeditArea1" style="margin:1em auto 1em auto" cellpadding="7">';
		echo '<tr>';
			echo '<th>';
			echo 'Move Users From';
			echo '</th>';
			echo '<th>';
			echo 'To This Group';
			echo '</th>';
			echo '</tr>';
		
		echo '<tr>';
			echo '<td>';
			echo wbHtmlspecialchars($groupInfo['name']);
			echo '<input type="hidden" name="from" value="'.$groupInfo['ugroup_id'].'" />';
			echo '</td>';
			echo '<td>';
			$allGroups = $this->getAllGroups();
			echo '<select name="newgroup">';
			foreach($allGroups as $group){
				if( $group['ugroup_id'] == $groupInfo['ugroup_id'] ){
					continue;
				}
				echo '<option value="'.$group['ugroup_id'].'">'.wbHtmlspecialchars($group['name']).'</option>';
			}
			echo '</select>';
			echo '</td>';
			echo '</tr>';
			
		echo '<tr>';
			echo '<td>';
			echo '</td>';
			echo '<td>';
			echo '<input type="submit" name="cmd" value="Move" />';
			echo ' &nbsp; ';
			echo '<input type="submit" name="" value="'.$langA['cancel'].'" />';
			echo '</td>';
			echo '</tr>';		
		echo '</table>';
	}
	
	function moveGroup(){
		global $page,$wbTables,$langA;
		if( !is_numeric($_POST['from']) ){
			message('INVALID_REQUEST');
			return false;
		}
		if( !is_numeric($_POST['newgroup']) ){
			message('INVALID_REQUEST');
			return false;
		}
		
		$newGroup =  $this->getGroupInfo($_POST['newgroup']);
		if( $newGroup === false ){
			message('INVALID_REQUEST');
			return false;
		}
		
		if( !$this->checkGroup($newGroup,$_POST['from']) ){
			return false;
		}
		
		//update users
		$set = ', `max_usage` = "'.wbDB::escape($newGroup['max_usage']).'" ';
		$set .= ', `max_history` = "'.wbDB::escape($newGroup['max_history']).'" ';
		$set .= ', `ugroup_id` = "'.wbDB::escape($newGroup['ugroup_id']).'" ';
		$set .= ', `restricted` = "'.wbDB::escape($newGroup['restricted']).'" ';
		$where = ' `ugroup_id` = "'.wbDB::escape($_POST['from']).'" ';
		if( !$this->UpdateUserFlags($where,$newGroup['flags'],$set) ){
			return false;
		}		
		
		$query = ' DELETE FROM '.$wbTables['config_ugroups'];
		$query .= ' WHERE `ugroup_id` = "'.wbDB::escape($_POST['from']).'" ';
		$result = wbDB::runQuery($query);
		message('User group deleted and users moved.');
		return true;
	}
	
	
	//
	//	`flags`
	//
	

	//similar to checkUser() in Users.php
	function checkGroup(&$groupInfo,$ugroup_id){
		global $wbAdminUser, $wbTables;
		
		
		if( $this->adminCompatible($groupInfo) ){
			return true;
		}
		
		
		if( $ugroup_id === false ){
			message('<b>Notice:</b> The admin user account cannot be assigned these settings.');
			return false;
		}
			
		//is the administrator here
		$query = 'SELECT 1 FROM '.$wbTables['users'];
		$query .= ' WHERE ';
		$query .= ' `username` = "'.wbDB::escape($wbAdminUser).'" ';
		$query .= ' AND `ugroup_id` = "'.wbDB::escape($ugroup_id).'" ';
		$query .= ' LIMIT 1 OFFSET 0 ';
		$result = wbDB::runQuery($query);
		if( mysql_num_rows($result) > 0 ){
			message('<b>Notice:</b> The admin user account cannot be assigned these settings.');
			return false;
		}
		return true;
	}

	
	// can't just assign.. because there are flags that aren't affected by group options: "pending"
	//
	/* static */
	function flagQuery( $useFlags ){
		$useFlags = explode(',',$useFlags);
		$useFlags = array_diff($useFlags,array(''));
		
		$withPending = $useFlags;
		$withPending[] = 'pending';
		
		return ' IF( FIND_IN_SET( "pending", `flags`), "'.implode(',',$withPending).'", "'.implode(',',$useFlags).'" ) ';
		
		
		// losing mysql connection when the query affects a lot of rows
		
		// $flagQuery = ' IF(`flags` IS NULL,"",`flags` ) ';
		// //$flagQuery = ' IFNULL(`flags`,"") '; //losing connection with database when using this method
		
		// //first, remove all possible flags
		// foreach($this->flags as $flag){
		// 	$flagQuery = ' REPLACE( '.$flagQuery.', "'.$flag.'","")';
		// }
		
		// //then add current flags
		// $useFlags = explode(',',$useFlags);
		// foreach($useFlags as $flag){
		// 	if( empty($flag) ){
		// 		continue;
		// 	}
		// 	$flagQuery = ' CONCAT("'.$flag.',",'.$flagQuery.') '; 
		// }
		
		// $flagQuery = ' REPLACE( '.$flagQuery.', ",,", ",") ';
		// return ' TRIM("," FROM '.$flagQuery.' )';
	}
	

	
	
	//
	//	New Group
	//	
	
	function saveGroup(){
		global $page,$wbTables,$langA;
		
		if( !$this->checkPostValues() ){
			return false;
		}

		if( empty($_POST['name']) ){
			message('Name must be set');
			return false;
		}
		
		
		
		//get groups
		$query = 'INSERT INTO ';
		$query .= $wbTables['config_ugroups'];
		$query .= ' SET ';
		$query .= ' `name` = "'.wbDB::escape($_POST['name']).'" ';
		$query .= ', `max_usage` = "'.wbDB::escape($_POST['max_usage']).'" ';
		$query .= ', `max_history` = "'.wbDB::escape($_POST['max_history']).'" ';
		$query .= ', `flags` = "'.wbDB::escape($_POST['flags']).'" ';
		$result = wbDB::runQuery($query);
		message('User Group added.');
		return true;
		
	}
	
	function newGroup(){
		global $langA;
		if( isset($_POST['max_history']) ){
			$newInfo = $_POST;
			
		}else{
			$row = $this->getDefaultInfo();
			$newInfo['max_history'] = $row['max_history'];
			$newInfo['max_usage'] = $row['max_usage'];
		}
		echo '<input type="hidden" name="cmd" value="save" />';
		$this->groupForm($newInfo);
	}
	
	//
	// Edit Group
	//
	
	function editGroup(){
		global $langA;
		if( isset($_POST['ugroup_id']) ){
			$groupInfo =  $_POST;
		}else{
			$groupInfo =  $this->getGroupInfo($_GET['id']);
		}
		if( $groupInfo === false ){
			message('INVALID_REQUEST');
			return;
		}
		echo '<input type="hidden" name="cmd" value="update" />';
		echo '<input type="hidden" name="ugroup_id" value="'.$groupInfo['ugroup_id'].'" />';
		$this->groupForm($groupInfo);
	}
	
	function updateGroup(){
		global $page,$wbTables,$langA;
		
		
		if( !$this->checkPostValues() ){
			return false;
		}
		
		if( !is_numeric($_POST['ugroup_id']) ){
			message('INVALID_REQUEST');
			return false;
		}
		
		if( ($_POST['ugroup_id'] > 0) && empty($_POST['name']) ){
			message('Name cannot be empty');
			return false;
		}
		
		if( !$this->checkGroup($_POST,$_POST['ugroup_id']) ){
			return false;
		}
		
		$set = ', `max_usage` = "'.wbDB::escape($_POST['max_usage']).'" ';
		$set .= ', `max_history` = "'.wbDB::escape($_POST['max_history']).'" ';
		$set .= ', `restricted` = "'.wbDB::escape($_POST['restricted']).'" ';
		$where = ' `ugroup_id` = "'.wbDB::escape($_POST['ugroup_id']).'" ';
		if( !$this->UpdateUserFlags($where,$_POST['flags'],$set) ){
			return false;
		}
		
		
		if( $_POST['ugroup_id'] > 0 ){
			
			$query = 'UPDATE ';
			$query .= $wbTables['config_ugroups'];
			$query .= ' SET ';
			$query .= $wbTables['config_ugroups'].'.`name` = "'.wbDB::escape($_POST['name']).'" ';
			$query .= ', '.$wbTables['config_ugroups'].'.`max_usage` = "'.wbDB::escape($_POST['max_usage']).'" ';
			$query .= ', '.$wbTables['config_ugroups'].'.`max_history` = "'.wbDB::escape($_POST['max_history']).'" ';
			$query .= ', `flags` = "'.wbDB::escape($_POST['flags']).'" ';
			$query .= ' WHERE ';
			$query .= $wbTables['config_ugroups'].'.`ugroup_id` = "'.wbDB::escape($_POST['ugroup_id']).'" ';
			$result = wbDB::runQuery($query);
			if( !$result ){
				message('OOPS');
				return false;
			}
			
		}else{
			
			//default user limits
			includeFile('tool/Variables.php');
			$array['defaultUser:max_usage'] = $_POST['max_usage'];
			$array['defaultUser:abs_max_history'] = $_POST['max_history'];
			$array['defaultUser:flags'] = $_POST['flags'];
			wbVariables::saveArray($array);
		}
		
		message('User Group updated.');
		return true;
	}
	
	function postToFlags(){
		$flags = array();
		if( isset($_POST['nofollow']) ){
			$flags[] = 'nofollow';
		}
		if( isset($_POST['disabled']) ){
			$flags[] = 'disabled';
		}
		if( isset($_POST['suspended']) ){
			$flags[] = 'suspended';
		}
		return implode(',',$flags);
	}
	
	function setSpaceRestrictions(){
		global $dbInfo;
		$spaces = array_keys($dbInfo);
		$spaces = array_diff($spaces,array('special','admin'));
		
		$result = array();
		if( isset($_POST['restrictions']) ){
			foreach($_POST['restrictions'] as $space){
				if( in_array($space,$spaces) ){
					$result[] = $space;
				}
			}
		}
		return implode(',',$result);
	}
		
	function checkPostValues(){
		
		//Flags
		$_POST['flags'] = $this->postToFlags();
		
		$_POST['restricted'] = $this->setSpaceRestrictions();
		
		
		if( !is_numeric($_POST['max_history']) ){
			message('Maximum history must be a number');
			return false;
		}
		
		if( !is_numeric($_POST['max_usage']) ){
			message('Maximum usage must be a number');
			return false;
		}
		
		$bigInt = 18446744073709551615; //database limitation
		if( (float)$_POST['max_usage'] > $bigInt ){
			message('Maximum usage must be less than 18446744073709551615 bytes.');
			return false;
		}
		
		$medInt = 16777215;
		if( (float)$_POST['max_history'] > $medInt ){
			message('Maximum history must be less than 16777215.');
			return false;
		}
		
		
		return true;
	}
	
	
	//
	//
	//	
	
	
	function groupForm(&$groupInfo){
		global $page,$wbTables,$langA,$dbInfo;
		
		$groupInfo += array('name'=>'','flags'=>'','restricted'=>'');
		
		$restrictedSpaces = explode(',',$groupInfo['restricted']);
		$restrictedSpaces = array_diff($restrictedSpaces,array(''));
		
		$spaces = array_keys($dbInfo);
		$spaces = array_diff($spaces,array('special','admin'));
		
		
		echo '<table class="WBeditArea1" style="margin:1em auto 1em auto" cellpadding="7">';
		
		echo '<tr>';
			echo '<th>';
			echo 'Name';
			echo '</th>';
			echo '<td>';
			if( isset($groupInfo['ugroup_id']) && ($groupInfo['ugroup_id'] == 0) ){
				echo wbHtmlspecialchars($groupInfo['name']);
			}else{
				echo '<input type="text" name="name" value="'.wbHtmlspecialchars($groupInfo['name']).'" />';
			}
			echo '</td>';
			echo '</tr>';
			
		echo '<tr>';
			echo '<th>';
			echo 'Max Usage';
			echo '</th>';
			echo '<td>';
			echo '<input type="text" name="max_usage" value="'.wbHtmlspecialchars($groupInfo['max_usage']).'" /> '.$langA['bytes'];
			echo '<br/>';
			echo $this->convert($groupInfo['max_usage']);
			echo '</td>';
			echo '</tr>';
			
		echo '<tr>';
			echo '<th>';
			echo 'Max History Rows';
			echo '</th>';
			echo '<td>';
			echo '<input type="text" name="max_history" value="'.wbHtmlspecialchars($groupInfo['max_history']).'" />';
			echo '</td>';
			echo '</tr>';

		
		$size = min(5,count($spaces));
		echo '<tr>';
			echo '<th>';
			echo 'Namespace Restriction: ';
			echo '</th>';
			echo '<td>';
			echo '<select name="restrictions[]" multiple="multiple" size="'.$size.'">';
			foreach($spaces as $space){
				if( in_array($space,$restrictedSpaces) ){
					echo '<option value="'.$space.'" selected="selected">'.$langA[$space].'</option>';
				}else{
					echo '<option value="'.$space.'">'.$langA[$space].'</option>';
				}
			}
			echo '</select>';
			echo '</td>';
			echo '</tr>';			
			
		echo '<tr>';
			echo '<th>';
			echo $langA['NOFOLLOW'];
			echo '</th>';
			echo '<td>';
			if( strpos($groupInfo['flags'],'nofollow') === false ){
				echo ' <input type="checkbox" name="nofollow" value="nofollow" />';
			}else{
				echo ' <input type="checkbox" name="nofollow" value="nofollow" checked="checked" />';
			}
			echo '</td>';
			echo '</tr>';
			
		echo '<tr>';
			echo '<th>';
			echo $langA['DISABLE_ACCOUNT'];
			echo '</th>';
			echo '<td>';
			if( strpos($groupInfo['flags'],'disabled') === false ){
				echo ' <input type="checkbox" name="disabled" value="disabled" />';
			}else{
				echo ' <input type="checkbox" name="disabled" value="disabled" checked="checked" />';
			}
			echo '</td>';
			echo '</tr>';
			
		echo '<tr>';
			echo '<th>';
			echo $langA['SUSPEND_ACCOUNT'];
			echo '</th>';
			echo '<td>';
			if( strpos($groupInfo['flags'],'suspended') === false ){
				echo ' <input type="checkbox" name="suspended" value="suspended" />';
			}else{
				echo ' <input type="checkbox" name="suspended" value="suspended" checked="checked"/>';
			}
			echo '</td>';
			echo '</tr>';

		
		echo '<tr>';
			echo '<th>';
			echo '</th>';
			echo '<td>';
			echo '<input type="submit" name="" value="'.wbHtmlspecialchars($langA['save']).'" />';
			echo ' &nbsp; ';
			echo '<input type="submit" name="cmd" value="'.wbHtmlspecialchars($langA['cancel']).'" />';
			echo '</td>';
			echo '</tr>';
		
			
		
		echo '</table>';
		echo '<div class="sm" style="text-align:center">';
		//echo 'Set limits to zero for unlimited access.';
		echo 'Values of zero are treated as unlimited.';
		echo '</div>';
	}


	

	
	
	//
	//	Showing Groups
	//
	function showGroups(){
		global $page,$wbTables,$langA;
		
		echo '<table class="tableRows">';
		echo '<tr>';
		echo '<th>Group Name</th>';
		echo '<th>Number of Users</th>';
		echo '<th>Maximum Disk Usage</th>';
		echo '<th>Maximum History Rows</th>';
		echo '<th>Flags</th>';
		echo '<th>Restricted From</th>';
		echo '<th>'.$langA['options'].'</th>';
		echo '</tr>';
		
		$groups = $this->getAllGroups(true);
		foreach($groups as $group){
			$this->showGroupRow($group);
		}
		
		//add 
		echo '<tr>';
			echo '<td>';
			echo '</td>';
			echo '<td>';
			echo '</td>';
			echo '<td>';
			echo '</td>';
			echo '<td>';
			echo '</td>';
			echo '<td>';
			echo '</td>';
			echo '<td>';
			echo '</td>';
			echo '<td>';
			echo wbLinks::admin('UserGroups?cmd=new','add_group');
			echo '</td>';
			
		echo '</table>';
	}
	
	function showGroupRow(&$row){
		static $i = 1;
		echo '<tr '.$this->classes[$i%2].'>';
		echo '<td>';
		echo wbLinks::admin('UserSearch?group='.$row['ugroup_id'],wbHtmlspecialchars($row['name']));
		echo '</td>';
		echo '<td>';
		echo $row['user_count'];
		echo '</td>';
		echo '<td>';
		echo $this->convert($row['max_usage']);
		echo '</td>';
		echo '<td>';
		echo $row['max_history'];
		echo '</td>';
		
		echo '<td class="sm">';
		
		
		
		$flags = $this->cleanFlags($row['flags']);
		$flags = explode(',',$flags);
		foreach($flags as $n => $flag){
			if( empty($flag)){
				unset($flags[$n]);
				continue;
			}
			
			if( isset($this->specialContent[$flag])){
				$flags[$n] = wbLinks::local('/'.$GLOBALS['wbAdminUser'].'/Template:'.$flag,$flag);
			}
		}
		echo implode(', ',$flags);		
		
		echo '</td>';
		echo '<td class="sm">';
		echo str_replace(',',', ',$row['restricted']);
		echo '</td>';
		echo '<td>';
		echo wbLinks::admin('UserGroups?cmd=edit&id='.$row['ugroup_id'],'edit');
		if( $row['ugroup_id'] != 0 ){
			echo ' &nbsp; ';
			echo wbLinks::admin('UserGroups?cmd=delete&from='.$row['ugroup_id'],'delete');
		}
		echo '</td>';
		echo '</tr>';
		$i++;
	}

//
//	Defined in Users.php
//	
	function convert( $bytes ){
		global $langA;
		$bytes = floatval($bytes);
		$types = array();
		
		if( $bytes == 0 ){
			return $langA['unlimited'];
		}
		
		$types[0] = $langA['bytes'];
		$types[1] = $langA['kb'];
		$types[2] = $langA['mb'];
		$types[3] = $langA['gb'];
		
		
		$i = 0;
		while( ($bytes > 1500) && ($i < 3) ){
			$bytes /= 1024;
			$i++;
		}
		if( $i == 0 ){
			return number_format($bytes).' '.$langA['bytes'];
		}
		return number_format($bytes,2).' '.$types[$i];
	}
	
}

global $initiateFileClass;
if( $initiateFileClass ){
	new userGroups();
}

