<?php

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

if( !isAdmin() ){
	message('You must be an administrator to access this page.');
	return;
}

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

includeFile('admin/UserTools.php');

/* 
includeFile('search/all.php');
look for cases of

userGroups::

*/



class queryUsers extends userTools{
	var $classes;
	var $specialContent = array();
	
	function queryUsers(){
		global $dbInfo,$page,$pageOwner,$langA,$wbTables,$jsNum;
		// Get User Groups
		$this->userGroups = $this->getAllGroups();
		
		$page->autoForm = true;//needed because of delete!
		$page->formMethod = 'get';
		$page->css2 = true;

		$this->specialContent['suspended'] = true;
		$this->specialContent['disabled'] = true;

		switch($page->userCmd){
			case 'group':
				$this->changeGroup();
			break;
			
			case 'confirm delete':
			case 'delete':
				adminUsers::deleteAccount();
			return;
		}
		
		
		
		
		$userTable = $wbTables['users'];
		$this->classes[] = ' class="tableRowEven" ';
		$this->classes[] = ' class="tableRowOdd" ';
		$this->rowLimit = 10;
		$this->overWrite['cmd'] = false;
		$this->overWrite['newgroup'] = false;
		$this->overWrite['user_id'] = false;
		
		//$this->fieds[-display value-] = -database value-
		$this->fields[$langA['username']] = 'owner';
		$this->fields[$langA['entries']] = 'count';
		$this->fields[$langA['total_usage']] = 'total_usage';
		$this->fields[$langA['last_visit']] = $userTable.'.`visited`';
		$this->fields[$langA['last_modified']] = $userTable.'.`modified`';
		
		//$this->searchUrl = $page->formAction = '/Admin/'.$pageOwner['username'].'/UserSearch'; //needed because of delete!
		$this->searchUrl = '/Admin/'.$pageOwner['username'].'/UserSearch'; 
		
		
		///	New
		$this->query = 'SELECT SQL_CALC_FOUND_ROWS '.$userTable.'.`username` as `owner` ';
		$this->query .= ', '.$userTable.'.`visited` as `visited` ';
		$this->query .= ', '.$userTable.'.`modified` as `modified` ';
		$this->query .= ', '.$userTable.'.`created` as `created` ';
		$this->query .= ', '.$userTable.'.`total_usage` as `total_usage` ';
		$this->query .= ', '.$userTable.'.`max_usage` as `max_usage` ';
		$this->query .= ', '.$userTable.'.`ugroup_id` ';
		$this->query .= ', '.$userTable.'.`user_id` ';
		$this->query .= ', COUNT('.$wbTables['all_files'].'.`file_id`) as `count` ';
		$this->query .= ', COUNT(IF(FIND_IN_SET("notchecked", '.$wbTables['all_files'].'.`flags`), 1, NULL)) as `unchecked` ';
		$this->query .= ', '.$userTable.'.`flags` as `flags` ';
		$this->query .= 'FROM ';
		$this->query .= ' '.$userTable.' LEFT JOIN '.$wbTables['all_files'];
		$this->query .= ' ON '.$userTable.'.`user_id` = '.$wbTables['all_files'].'.`owner_id` ';
		$this->query .= ' WHERE 1 ';
		if( !empty($_GET['user']) ){
			$this->query .= ' AND '.$userTable.'.`username` LIKE "%'.wbDB::escape($_GET['user']).'%" ';
		}
		if( isset($_GET['group']) && is_numeric($_GET['group']) ){
			$this->query .= ' AND '.$userTable.'.`ugroup_id` = "'.wbDB::escape($_GET['group']).'" ';
		}
		
		$this->query .= ' GROUP BY `user_id` ';
		
		$this->orderBy();
		$this->browse($langA['user_statistics']);
		
		$page->regLink('User Groups','/Admin/'.$pageOwner['username'].'/UserGroups');
	}
	
	function orderBy(){
		global $langA;
		if( !isset($_GET['field']) ){
			$this->field = $langA['last_modified'];
		}
		parent::orderBy();
	}
	
	function mysqlFetch(&$result){
		return mysql_fetch_object($result);
	}

	function displayPre(){
		global $langA;
		
		
		echo '<table width="100%" class="tableRows">';
		echo '<tr>';
		echo '<th style="white-space:nowrap">' . $langA['username'] . '</th>';
		echo '<th style="white-space:nowrap">' . $langA['entries'] . '</th>';
		echo '<th style="white-space:nowrap">' . $langA['total_usage'] . '</th>';
		echo '<th style="white-space:nowrap">' . $langA['last_visit'] . '</th>';
		echo '<th style="white-space:nowrap">' . $langA['last_modified'] . '</th>';
		echo '<th style="white-space:nowrap">' . $langA['created'] . '</th>';
		echo '</tr>';
		
	}
	
	function searchLinks(){
		global $langA;
		
		//user groups
		echo '<table class="WBeditArea1" cellpadding="7" style="margin:0 auto 0 auto">';
		echo '<tr>';
		echo '<td style="text-align:right;white-space:nowrap">';
		echo '<b>'.wbLinks::admin('UserGroups','User Groups').':</b> ';
		echo '</td>';
		echo '<td>';
		echo '<select name="group">';
		echo '<option value="false"></option>';
		foreach($this->userGroups as $group){
			if(isset($_GET['group']) && is_numeric($_GET['group']) && ($_GET['group'] == $group['ugroup_id'])){
				echo '<option value="'.$group['ugroup_id'].'" selected="selected">'.wbHtmlspecialchars($group['name']).'</option>';
			}else{
				echo '<option value="'.$group['ugroup_id'].'">'.wbHtmlspecialchars($group['name']).'</option>';
			}
		}
		echo '</select>';
		echo '</td>';
		echo '</tr>';
		
		
		//search
		$_GET += array('user'=>'');
		echo '<tr>';
		echo '<td style="text-align:right;white-space:nowrap">';
		echo '<b>';
		echo $langA['username'];
		echo ':</b>';
		echo '</td>';
		echo '<td>';
		echo '<input type="text" name="user" value="'.$_GET['user'].'" />';
		echo ' &nbsp; ';
		echo '<input type="submit" name="" value="'.$langA['search'].'" />';
		echo '</td></tr></table>';
	}
	
	function displayPost(&$prev,&$pages,&$next){
		global $langA;
		echo '</table>';
		
		
		echo '<p class="sm" style="text-align:center">';
		echo '<b>Entries:</b> (Number of Unchecked Entries) / (Number of Entries) ';
		echo '</p>';
		
		$this->searchLinks();
		
		parent::displayPost($prev,$pages,$next);
	}
	function displayNumbers(&$from,&$to,&$rowsFound,&$prev,&$next){
		global $langA;
		echo '<div style="text-align:right">&nbsp;';
		echo $rowsFound.' '.$langA['users_found'].'<br/>';
		echo '<span style="font-size:85%">';
		echo wbLang::text('showing_of_found',$from,$to);
		echo '<br/>'.$prev.' &nbsp; '.$next;
		echo '</span></div>';
	}
	function displayEmpty(){
		global $langA;
		echo $langA['EMPTY_SET'];
		return true;
	}
	
	function abbrevOutput(&$row,$i){
		global $langA, $wbConfig,$pageOwner;
		
		echo '<tr'.$this->classes[($i%2)].'>';
		
		//username
		echo '<td onmouseover="if(!WB)return;WB.SIO(this,\'inline\')" onmouseout="if(!WB)return;WB.HI(this)">';
			//echo wbLinks::user($row->owner);
			echo wbLinks::local('/'.$row->owner.'/'.$GLOBALS['wbDefaultTitle'],$row->owner);

			echo ' &nbsp; ';
			
			
			
			if( strpos($this->currUri,'?') ){
				$uri = $this->currUri.'&';
			}else{
				$uri = $this->currUri.'?';
			}
			
			//echo '<span class="sm" style="display:none">';
			echo '<dl style="margin:0;display:none" class="sm">';
				echo '<dt>';
				
				echo '<b>'.$langA['related_links'].'</b> ';
				echo '</dt>';
				echo '<dd style="white-space:nowrap">';
				
				//$link = '/Admin/'.$pageOwner['username'].'/UserSearch?cmd['.wbHtmlspecialchars($row->owner).']=options';
				//echo wbLinks::local($link,'options');
				
				echo wbLinks::local('/Special/'.$row->owner.'/ControlPanel','cpanel');
				
				//echo wbLinks::special('ControlPanel','cpanel','',$row->owner);
				if( $row->count > 0 ){
					echo ' &nbsp; ';
					echo wbLinks::local('/Special/'.$row->owner.'/ChangeLog','change_log');
					//echo wbLinks::special('ChangeLog','change_log','',$row->owner);
				}
				echo ' &nbsp; ';
				echo wbLinks::local('/Special/'.$row->owner.'/AccountDetails','details');
				//echo wbLinks::special('AccountDetails','details','',$row->owner);
				
				if( !adminUsers::isAdmin($row->owner) ){
					echo ' &nbsp; ';
					echo wbLinks::local($uri.'cmd=delete&user_id='.$row->user_id,'delete');
				}
				
				echo '</dd>';
				
				echo '<dt>';
				echo '<b>'.$langA['user_group'].'</b> ';
				echo '</dt>';
				echo '<dd>';
				//group
				foreach($this->userGroups as $id => $group){
					echo '<span style="white-space:nowrap">';
					if( $id == $row->ugroup_id ){
						echo '<em>'.wbHtmlspecialchars($group['name']).'</em>';
					}else{
						echo wbLinks::local($uri.'cmd=group&newgroup='.$id.'&user_id='.$row->user_id,wbHtmlspecialchars($group['name']));
					}
					echo ' &nbsp; ';
					echo '</span>';
				}
				echo '</dd>';
				echo '<dl>';
				//echo '</span>';
			echo '</td>';
			
			
		//entries
		if( ($row->count > 0) ){
			$perc = round(($row->unchecked/$row->count)*100);
		}else{
			$perc = 0;
		}
		if( $perc > 20 ){
			echo '<td class="sm" style="color:red !important;font-weight:bold !important;white-space:nowrap">';
		}else{
			echo '<td class="sm" style="white-space:nowrap">';
		}
			echo number_format($row->unchecked);
			echo ' / ';
			echo number_format($row->count);
			echo ' &nbsp; ';
			echo '(';
			echo $perc.'%';
			echo ')';
			echo '</td>';
			
		echo '<td class="sm">';
			echo $this->convert($row->total_usage);
			if( $row->max_usage > 0 ){
				if( function_exists('bcdiv') ){
					$perc = bcdiv($row->total_usage, $row->max_usage,2);
				}else{
					$perc = (float)$row->total_usage/ (float)$row->max_usage;
				}
				echo ' &nbsp; ('.round($perc*100).'%)';
			}
			echo '</td>';

		
		echo '<td class="sm">';
			echo $this->timeDiff($row->visited);
			echo '</td>';
		
		echo '<td class="sm">';
			echo $this->timeDiff($row->modified);
			echo '</td>';
			
		echo '<td class="sm">';
			if( (int)$row->created > 0 ){
				echo $this->timeDiff($row->created);
			}else{
				echo '-unknown-';
			}
			echo '</td>';
		echo '</tr>';		
	}
	
	
	
	function timeDiff(&$mod){
		global $langA;
		
		$unixMod = dbFromDate($mod,'unix');

		
		$div[$langA['hours']] = 3600;	//sec -> hours
		$div[$langA['days']] = 24;	//hours -> days
		$div[$langA['months']] = 30;	//days -> months
		$div[$langA['years']] = 12;	//months -> years
		
		$diff = time() - $unixMod;
		//$diff = mktime() - $unixMod;
		if( $diff < 3600 ){
			return $langA['within_the_hour'];
		}
		foreach( $div as $time => $val ){
			$diff = $diff/$val;
			if( $diff < 1){
				return $result.' '.$langA['ago'];
			}
			$result = number_format($diff) .' '.$time;
		}
		return $result.' '.$langA['ago'];
	}

	
	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];
	}
	
	
	
	
	
	//
	//	Changing Groups
	//
	function changeGroup(){
		global $wbTables,$page;
		
		if( !is_numeric($_GET['newgroup']) ){
			message('INVALID_REQUEST');
			return;
		}
		if( !is_numeric($_GET['user_id']) ){
			message('INVALID_REQUEST');
			return;
		}
		$groupInfo =  $this->getGroupInfo($_GET['newgroup']);
		if( $groupInfo === false){
			message('INVALID_REQUEST');
			return;
		}
		
		if( !$this->checkUser($groupInfo,$_GET['user_id']) ){
			return;
		}
		
		$set = ', `max_usage` = "'.wbDB::escape($groupInfo['max_usage']).'" ';
		$set .= ', `max_history` = "'.wbDB::escape($groupInfo['max_history']).'" ';
		$set .= ' , `ugroup_id` = "'.$groupInfo['ugroup_id'].'" ';
		$set .= ', `restricted` = "'.wbDB::escape($groupInfo['restricted']).'" ';
		$where = ' `user_id` = "'.wbDB::escape($_GET['user_id']).'" ';
		if( !$this->UpdateUserFlags($where,$groupInfo['flags'],$set) ){
			message('OOPS');
			return false;
		}
		
		message('updated');
	}

		
	
	//similar to checkGroup() in UserGroups.php
	function checkUser(&$groupInfo,$id){
		global $wbAdminUser, $wbTables;
		
		if( $this->adminCompatible($groupInfo) ){
			return true;
		}
		
		//is it the adminUser
		$query = 'SELECT 1 FROM '.$wbTables['users'];
		$query .= ' WHERE ';
		$query .= ' `username` = "'.wbDB::escape($wbAdminUser).'" ';
		$query .= ' AND `user_id` = "'.wbDB::escape($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 flags.');
			return false;
		}
		return true;
	}


	
}

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



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

class adminUsers{
	//
	//	utility functions
	//
	
	//check the account name against admin values
	function isAdmin($name){
		if( strcasecmp(wbDB::escape($name),$GLOBALS['wbAdminUser']) === 0 ){
			return true;
		}
		if( strcasecmp(wbDB::escape($name),$GLOBALS['wbConfig']['pUser']) === 0 ){
			return true;
		}
		return false;
	}
	
	
	///////////////////////////////////////////////////////////////////
	//
	//	Deleting Account
	//
	//
	
	
	function deleteAccount(){
		global $dbInfo,$page,$rootDir,$langA,$pageOwner,$wbConfig,$wbTables,$dbObject;
		$txtArray = array();
		$bool = true;
		
		if( !is_numeric($_GET['user_id']) ){
			message('INVALID_REQUEST');
			return;
		}
		
		//get username
		$query = 'SELECT `username` FROM '.$wbTables['users'];
		$query .= 'WHERE `user_id` = "'.$_GET['user_id'].'" ';
		$query .= ' LIMIT 1 OFFSET 0 ';
		$result = wbDB::runQuery($query);
		if( mysql_num_rows($result) < 1 ){
			message('INVALID_REQUEST');
			return;
		}
		$row = mysql_fetch_assoc($result);
		$account = $row['username'];
		$_GET += array('confirm'=>0);
		$label = $langA['user'].': '.$account;
		$contentUri = $page->regLink($label,'/Admin/'.$pageOwner['username'].'/UserSearch?cmd=delete&user_id='.$_GET['user_id']);
		$page->autoForm = true;
		
		
		ob_start();
		
		//dont delete certain accounts
		if( adminUsers::isAdmin($account) ){
			echo $langA['NOT_MAIN_ACCT'];
			return;
		}	
		
		$userDir = $rootDir.'/userfiles/'.$account;
		$templateDir = $rootDir.'/templates/'.$account;
		
		////	Confirm
			$time = substr(time(),-6);
			$diff = ($time - $_GET['confirm']);
			$timeLimit = 10;
				
			$mess = '<input type="hidden" name="confirm" value="'.wbHtmlspecialchars($time).'" />';
			$mess .= '<input type="hidden" name="user_id" value="'.wbHtmlspecialchars($_GET['user_id']).'" />';
			$mess .= wbLang::text('CONFIRM_DELETE_USER',$account);
			$mess .= '<ul>'.$langA['CONFIRM_DELETE_USER2'];
			$mess .= '<li>'.$langA['userfiles_directory'].$userDir.'</li>';
			$mess .= '<li>'.$langA['template_directory'].$templateDir.'</li>';
			$mess .= '<li>'.$langA['database_entries'].'</li>';
			$mess .= '</ul>';
			$mess .= '<p><input type="submit" name="cmd" value="'.$langA['confirm_delete'].'" /></p>';
			
			
			if( $page->userCmd !== wbStrtolower($langA['confirm_delete'])){
				$page->contentB[$contentUri] = $mess;
				wb::get_clean();
				return;
			}
			
			if( $diff > $timeLimit){
				message('TIMEOUT',$diff);
				$page->contentB[$contentUri] = $mess;
				wb::get_clean();
				return;
			}
			
			
			// $userTable = $wbTables['users'].'';
			// $tableList = $wbTables['all_history'].', '.$wbTables['all_files'].', '.$userTable;
			// $join = $userTable.'.`username` = "'.$account.'" AND ';
			// $join .= $wbTables['all_files'].'.`owner_id` = '.$userTable.'.`user_id` AND '.$wbTables['all_files'].'.`file_id` = '.$wbTables['all_history'].'.`file_id` ';
			// $queriesWorked = true;
			
			
		////	Deleting Files
			$userTable = $wbTables['users'];
			$tableList = $wbTables['all_files'].', '.$userTable;
			$join = $userTable.'.`username` = "'.$account.'" AND ';
			$join .= $wbTables['all_files'].'.`owner_id` = '.$userTable.'.`user_id` ';
			$queriesWorked = true;
			
			$tables = array();
			$tables[] = $wbTables['all_history'];
			$tables[] = $wbTables['all_search'];
		
			foreach($dbInfo as $space){
				if( !isset($space['dbTable']) ){
					continue;
				}
				$tables[] = $space['dbTable'];
			}
			
			foreach($tables as $table){
				$query = ' DELETE ';
				$query .= $wbTables['all_files'].', '.$table;
				$query .= ' FROM ';
				$query .= $tableList.', '.$table;
				$query .= ' WHERE ';
				$query .= $join.' AND '.$wbTables['all_files'].'.`file_id` = '.$table.'.`file_id` ';
				$num = wbDB::runQuery($query,true);
				if( $num == -1){
					$queriesWorked = false;
				}
			}
			
			//user table
				$query = 'DELETE ';
				$query .= $userTable;
				$query .= ' FROM ';
				$query .= $userTable;
				$query .= ' WHERE ';
				$query .= $userTable.'.`username` = "'.$account.'" ';
				$num = wbDB::runQuery($query,true);
				if( $num == -1){
					$queriesWorked = false;
				}
			
			
			if( !$queriesWorked ){
				$bool = false;
				$txtArray[] = wbLang::text('NOT_DELETED_DATABASE_ENTRIES');
			}else{
				$txtArray[] = wbLang::text('DELETED_DATABASE_ENTRIES');
			}
			
		////	Deleting Folders
			$result = adminUsers::removeDir($userDir);
			if( $result === true ){
				$txtArray[] = $langA['DELETED_USERFILES'];
			}else{
				$bool = false;
				$txtArray[] = $langA['NOT_DELETED_USERFILES'].$result;
			}
			
			$result = adminUsers::removeDir($templateDir);
			if( $result === true){
				$txtArray[] = $langA['DELETED_TEMPLATES'];
			}else{
				$bool = false;
				$txtArray[] = $langA['NOT_DELETED_TEMPLATES'].$result;
			}
			
		////	Finish
			$content =& $page->contentB[$contentUri];
			if( $bool ){
				$content .= '<h3>'.wbLang::text('USER_DELETED',$account).'</h3>';
			}else{
				$content .= '<h3>'.wbLang::text('USER_NOT_DELETED',$account).'</h3>';
			}
		
			$content .= '<ul>';
			foreach($txtArray as $txt){
				$content .= '<li>'.$txt.'</li>';
			}
			$content .= '</ul>';
			$content .= wb::get_clean();
	}


	function removeDir($dir,$return='bool'){
		
		wbData::loadFileFunctions();
		
		$paths = array();
		if( !is_dir($dir) ){
			return true;
		}
		
		if( $dh = opendir($dir) ){
			while (($file = readdir($dh)) !== false) {
				if($file == '..' || $file == '.'){
					continue;
				}
				$fullPath = $dir.'/'.$file;
				
				if( is_dir($fullPath) ){
					$array = adminUsers::removeDir($fullPath,'array');
					$paths = array_merge($paths, (array)$array);
					
				}elseif( is_file($fullPath) ){
					if( !@wbUnlink($fullPath) ){
						array_unshift($paths,$fullPath);
					}
				}else{
					$paths[] = $fullPath;
					//echo 'Not a file or dir: ';
				}
			}
		}
		
		closedir($dh);
		$bool = @wbRmdir($dir);
		if( !$bool){
			array_unshift($paths,$dir);
		}
		if( $return === 'array'){
			return $paths;
		}
		
		if( count($paths) > 0 ){
			includeFile('tool/error.php');
			return showArray($paths);
		}
		return true;
		
	}

	
}
