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


/*

	IP addresses are not be allowed to get Full/Owner or Admin access 

*/

global $pageOwner,$dbObject,$jsNum,$langA,$wbConfig;
$page->displayTitle = $langA['user_permissions'];
$page->regLink($langA['permissions'],'/Special/'.$pageOwner['username'].'/Permissions');
$page->regLink($langA['friends'],'/Special/'.$pageOwner['username'].'/Friends');
$page->regLink('?',$langA['user_permissions'].'?en=User_Permissions');
$page->scripts[] = '/include/js/workgroup.js?'.$jsNum;

if( empty( $_POST['guest']) && !empty($_GET['guest']) ){
	$_POST['guest'] = $_GET['guest'];
}elseif(empty($_POST['guest']) ){
	$_POST['guest'] = '';
}

if( !isOwner(true,false) ) return false;

includeFile('search/all.php');

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//


	class workgroup extends query{
		var $group;
		
		function workGroup(){
			global $page, $pageOwner,$langA,$wbTables;
			
			$page->css2 = true;
			$this->classes[] = 'class="tableRowOdd" ';
			$this->classes[] = 'class="tableRowEven" ';
			$this->searchUrl = '/Special/'.$pageOwner['username'].'/Permissions';
			
			//so that we don't get multiple tabs
			$this->overWrite['guest'] = false;
			$this->overWrite['cmd'] = false;
			$page->autoForm = true;
			
			$this->query = 'SELECT SQL_CALC_FOUND_ROWS ';
			$this->query .= ' `guest` , `userlevel` ';
			$this->query .= 'FROM '.$wbTables['workgroup'].' WHERE `owner` = "'.$pageOwner['username'].'" ORDER BY `userlevel` DESC, `guest`';
			$this->browse($langA['permissions']);
			
			//	tell users to finalize user permissions when a username is passed with $_GET
			if( isset($_GET['guest']) ){
				message('SET_PERMISSIONS',$_GET['guest']);
			}			
		}
		
		function mysqlFetch(&$result){
			return mysql_fetch_assoc($result);
		}
		
		function displayPre(){
			global $langA,$pageOwner;
	
			echo '<table id="update" border="0" style="margin-left:auto;margin-right:auto"><tr><td><b>';
			echo $langA['username_or_ip'];
			echo '</b>';
			echo '</td><td><b>';
			echo $langA['status'];
			echo '</b></td></tr><tr><td>';
			echo '<input type="text" name="guest" size="30" value="'. wbHtmlspecialchars($_POST['guest']) .'" />';
			echo '</td><td>';
			echo ' <select name="level">';
			echo '<option value="'.$langA['workgroup']. '" selected="selected">'.$langA['workgroup'].'</option>';
			echo '<option value="'.$langA['full_owner'].'">'.$langA['full_owner'].'</option>';
			echo '<option value="'.$langA['banned'].'">'.$langA['ban'].'</option>';
			echo '</select>';
			echo ' <input type="submit" name="cmd" value="'.$langA['update_permissions'].'" />';
			echo '</td></tr><tr><td>';
			echo $langA['EX_USERNAMES'];
			echo '</td></tr></table>';
				 
			echo '<table cellspacing="0" width="100%" class="tableRows"><tr>';
			echo '<th>'.$langA['user'].'</th>';
			echo '<th>'.$langA['status'].'</th>';
			echo '<th colspan="2">'.$langA['view_users'].'</th>';
			echo '<th>'.$langA['options'].'</th>';
			echo '</tr>';
		}
		function displayEmpty(){
			global $langA;
			return true;
		}
		function displayPost(&$prev,&$pages,&$next){
			echo '</table>';
			parent::displayPost($prev,$pages,$next);
		}
		
		function abbrevOutput($row,$i){
			global $langA;
			
			echo '<tr '.$this->classes[($i%2)].'>';
			echo '<td>'.toDisplay($row['guest']).'</td>';
			echo '<td>'.translateLevel($row['userlevel']).'</td>';
			
			$temp = wbStr_replace('.','',$row['guest']);
			if( !is_numeric($temp) ){
				
				echo '<td class="sm">'.wbLinks::user($row['guest'],$langA['homepage']).'</td>';
				echo '<td class="sm">'.wbLinks::special('ControlPanel','control_panel','',$row['guest']).'</td>';
			}else{
				echo '<td> </td><td> </td>';
			}
			
			echo '<td class="sm">';
			echo '<a href="javascript:void(0)" onclick="changeUser(\''.$row['guest'].'\',\''.translateLevel($row['userlevel']).'\');return false;">';
				echo '<img src="'.wbLinks::getDir('/imgs/icons/pencil.gif').'" title="'.$langA['change'].'" alt="'.$langA['change'].'" />';
				echo '</a> ';
			
			
			echo ' &nbsp; ';
			$label = '<img src="'.wbLinks::getDir('/imgs/icons/delete.gif').'" height="16" width="16" alt="'.$langA['delete'].'" title="'.$langA['delete'].'" />';
			echo wbLinks::special('Permissions?cmd['.urlencode($row['guest']).']=delete"',$label);

			
			echo '</td>';
			echo '</tr>';
		}
	}

//
//
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//

	function translateLevel($arg){
		global $page,$pageOwner,$langA;
		global $wbConfig;
	
		
		if(is_numeric($arg) ){
		
			switch((int)$arg){		
				case 5:
				case 4:
				case 3:
				return $langA['full_owner'];
				
				case 2:
				return $langA['workgroup'];
				
				case -1:
				return $langA['banned'];
				
				default:
					trigger_error('Unknown User Level: '.$arg);
				return $langA['undefined'];
			}
		}
		
		switch($arg){
			
			case $langA['full_owner'];
			return 3; //4 is only set by session.php
			
			
			case $langA['workgroup'];
			return 2;
			
			case $langA['banned'];
			default:
			return -1;
		}
		return;
	}
		
	
	//	Add User to database
	//
	//	can I do this with a single insert select?
	//
	function updatePermissions(){
		global $pageOwner,$wbTables;
	
		////////	0)	Check POST
			if( empty($_POST['guest']) ){
				message('ENTER_USERNAME');
				return;
			}
			
			$level = translateLevel($_POST['level']);
		
			
		////////	1)	IP or User
			$numDots = substr_count($_POST['guest'],'.');
			$ipTest = str_replace(array('.','%'),'',$_POST['guest']);
			if( ($numDots > 0) && is_numeric($ipTest) ){
				
				$isUsername = false;
				if( (int)$level >= 3 ){
					message('IP_WRONG_LEVEL');
					return;
				}
				$insertIParr = array();
				$pieces = explode('.',$_POST['guest']);
				//message(showArray($pieces));
				for($i = 0;$i <= 3;$i++){
					if( isset($pieces[$i]) ){
						$insertIParr[] = $pieces[$i];
					}else{
						$insertIParr[] = '%';
					}
				}
				$insertName = $messageName = implode('.',$insertIParr);
				
				//delete old
				$query = 'DELETE FROM '.$wbTables['workgroup'];
				$query .= 'WHERE `owner` = "'.wbDB::escape($pageOwner['username']).'" ';
				$query .= ' AND `guest` = "'.wbDB::escape($insertName).'" ';
				wbDB::runQuery($query);
				
				//add new
				$query = 'REPLACE INTO '.$wbTables['workgroup'].' ( `owner` , `guest`, `userlevel`, `type` ) VALUES (';
				$query .= ' "'. wbDB::escape($pageOwner['username']).'"';
				$query .= ', "'.wbDB::escape($insertName).'"';
				$query .= ', '.$level;
				$query .= ', "ip"';
				$query .= ')';
				
				
			}else{
				
				$insertName = toStorage($_POST['guest']);
				$messageName = $_POST['guest'];
				
				$isUsername = true;
				if( toStorage($insertName,true) == toStorage($pageOwner['username'],true) ){
					message('ALREADY_OWNER',$pageOwner['username']);
					return;
				}
				
				//delete old
				$query = 'DELETE FROM '.$wbTables['workgroup'];
				$query .= 'WHERE `owner` = "'.wbDB::escape($pageOwner['username']).'" ';
				$query .= ' AND `guest` = "'.wbDB::escape($insertName).'" ';
				wbDB::runQuery($query);
			
				//add new
				$query = 'REPLACE INTO '.$wbTables['workgroup'].' ( `owner` , `guest`, `userlevel`, `type` ) SELECT ';
				$query .= ' "'. wbDB::escape($pageOwner['username']).'"';
				$query .= ', `username` ';
				$query .= ', '.$level;
				$query .= ', "username" ';
				$query .= ' FROM '.$wbTables['users'];
				$query .= ' WHERE `username` = "'.wbDB::escape($insertName).'" ';
			}
			
			
			//message($query);
			$num = wbDB::runQuery($query,true);
			if( $num === 0 ){
				if($isUsername){
					message('NOT_A_USER',$messageName);
				}else{
					message('IP_NOT_ADDED',$messageName);
				}
			}elseif( $num === 2 ){
				message('UPDATED_PERMISSIONS',$messageName);
			}elseif( $num === 1){
				message('UPDATED_PERMISSIONS',$messageName);
				//message('ADDED_PERMISSIONS',$messageName);
			}else{
				trigger_error('User Permission Script did not work');
			}
			
			return;
	}
	
	
	
	function removeFromGroup(){
		global $pageOwner,$page,$wbTables;
		
		$_POST['guest'] = $page->cmdArg[0];
		
		
		$query = 'DELETE FROM '.$wbTables['workgroup'].' ';
		$query .= ' WHERE owner = "'.$pageOwner['username'].'" ';	
		$query .= ' AND guest = "'.toStorage($page->cmdArg[0]).'" ';
		$query .= ' LIMIT 1';
		$num = wbDB::runQuery($query,true);
		if( $num == 0 ){
			message('USER_NOT_REMOVED',$page->cmdArg[0]);
		}else{
			message('USER_REMOVED',$page->cmdArg[0]);
		}
		
	}
	
//
//
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//

	
	switch( $page->userCmd ){
		
		case 'delete':
		case 'removefromgroup':
		case wbStrtolower($langA['delete']);
			removeFromGroup();
		break;
		
		case wbStrtolower($langA['update_permissions']);
			updatePermissions();
		break;
		
	}
	new workgroup();

