Location: PHPKode > projects > web-cp - Web Hosting Control Panel > webcp/web/functions.inc.phps
<?	/*
	// File:	functions.inc.php
	// Purpose:	web://cp Interface functions (API)
	// Author:	Felix <hide@address.com>
	*/

// Regular Expressions
// Shortcuts for often used regex, also makes the code cleaner

$rx['user']	= '^([[:alpha:]]([-_]?[[:alnum:]])*){1,16}[[:alnum:]]$';
$rx['name']	= '^([[:alnum:]]([[:space:]]?[-[:alnum:].,\'])*){3,50}$';
$rx['alias']	= '^([[:alnum:]]([-_.]?[[:alnum:]])*){1,25}$';
$rx['pass']	= '^([[:graph:]]){5,25}$';
$rx['dom']	= '^([[:alnum:]]([.]?[-[:alnum:]])*[[:alnum:]])\.([[:alpha:]]){2,25}$';
$rx['host']	= '^(([[:alpha:]](-?[[:alnum:]])*)[[:alnum:]]){1,25}$';
$rx['eml']	= '^([[:alnum:]]([-.]?[_[:alnum:]])*)@([[:alnum:]]([.]?[-[:alnum:]])*[[:alnum:]])\.([[:alpha:]]){2,25}$';
$rx['ip']	= '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$';
$rx['service']	= '^([[:alnum:]]([-_.]?[[:alnum:]])*){1,25}$';
$rx['num']	= '^([0-9]+)$';
$rx['word']	= '^([[:alpha:]]){1,255}$';
$rx['alnum']	= '^([[:alnum:]]){1,255}$';



// Function:	webcp_log()
// Utility:	Centralize all web://cp fatal errors, warnings, logging
// Usage:	webcp_log(ERROR_LEVEL,ID,EXTRA,LOG_MSG,REMOTE_IP,ECHO = 0)
// Examples:	webcp_log(1,$data['id'],$data['username'],"login failed",$REMOTE_ADDR);
//		webcp_log(2,$userdata['id'],$host.".".$domain,"domain modify",$REMOTE_ADDR);
// Definitions:	ERROR_LEVEL:	0: fatal  1: warning  2: logging 3: screen output only
//		ID:		User or domain id that generated the function call
//		EXTRA:		Extra usefull info about ^^
//		LOG_MSG:	Error/Message to log
//		REMOTE_IP:	Remote address or local name that triggered the function call
//		ECHO:		1 to echo, 0 to log only (optional, 0 by default)
//		$cfg['loglevel'] : 0 for none, 1 for fatal errors, 2 for +warning, 3 for +activity logging

function webcp_log($level, $id, $extra, $log_msg, $remote_ip, $echo = 0) {
	// Get Configurations
	GLOBAL $cfg;

	if ($echo) {
		if (php_sapi_name() == 'cli') {
			if ($level <= $cfg['loglevel'])
				fwrite(STDERR,"($extra) $log_msg\n");
			else
				fwrite(STDOUT,"$log_msg\n");
		}
		else {
			if ($level <= $cfg['loglevel'])
				echo "($extra) $log_msg\n";
			else
				echo "$log_msg\n";
		}
	}

	// DB system
	if (($cfg['loglevel'] != 0 ) AND (($cfg['log_system'] == 'db' ) || ($cfg['log_system'] == 'filedb' ))) {
		// 0: fatal 
		if ($level < $cfg['loglevel']) {
			mysql_query("INSERT INTO log SET error_level='".$level."', id='".$id."', extra='".$extra."', log_msg='".$log_msg."', remote_ip='".$remote_ip."'");
		}
	}

	// file system
	if (($cfg['loglevel'] != 0 ) AND (($cfg['log_system'] == 'file' ) OR ($cfg['log_system'] == 'filedb' ))) {

		// open file as r/w & point at the end of the file
		$logfile=fopen($cfg['logfile'], 'a+'); 

        // 0: fatal
        if ($level < $cfg['loglevel']) {
			fwrite($logfile,$level."|".$id."|".$extra."|".$log_msg."|".$remote_ip."|".date("YmdHis")."\n");
        }
		
		// close file
		fclose ($logfile);
	}
}

function randstring($length) {

	if(!ereg("^[0-9]+$", $length))
        return(-1);

	if($length < 1 || $length > 65536)
        return(-1);

	srand((double)microtime()*1000000);

	$string = '';

	while(strlen($string) != $length)  {
        $type = rand(1,3);
        if($type == 1) $string = $string . chr(rand(48,57));
        if($type == 2) $string = $string . chr(rand(65,90));
        if($type == 3) $string = $string . chr(rand(97,122));
	}

	return($string);
}

function file_size_info($filesize) { 
	$bytes = array('KB', 'KB', 'MB', 'GB', 'TB'); # values are always displayed  
	if ($filesize <= 1024) $filesize = 1; # in at least kilobytes. 
	for ($i = 0; $filesize > 1024; $i++) $filesize /= 1024; 
	$file_size_info['size'] = ceil($filesize); 
	$file_size_info['type'] = $bytes[$i]; 
	return $file_size_info; 
}

function returnFileSize($sizeInBytes,$precision=2){
	return ($sizeInBytes < 1024)?"$sizeInBytes bytes":round(($sizeInBytes / pow(1024,floor(log($sizeInBytes,1024)))),$precision)." ".substr(" KMGT",log($sizeInBytes,1024),1)."B";
}

function strip_array($data) {
	while (list($key, $val) = each($data)) {
		if(!is_array($val))
			$data[$key] = trim(stripslashes($val));
		else
			$data[$key] = strip_array($val);
	}
	reset($data);
	
	return $data;
}

function password_check($password) {
	$passarray[] = $password;
	$passarray[] = ereg_replace("[^a-zA-Z]","",$password);
	
    if (function_exists(pspell_check) && $pspell_config = pspell_config_create("en")) {
    	pspell_config_runtogether($pspell_config, true);
    	$pspell_link = pspell_new_config($pspell_config);
    	foreach ($passarray as $key) {
			if (pspell_check($pspell_link, $key)) {
				return false;
			}
		}
	}
	if (function_exists('crack_check') && $crack_dict = crack_opendict($cfg['cracklib_dict'])) {
		foreach ($passarray as $key) {
			if (!crack_check($crack_dict, $key)) {
				crack_closedict($crack_dict);
				return false;
			}
		}
		crack_closedict($crack_dict);
	}
	return true;
}

function ftp_file_type($file, $file_types) {
/* match filename against a regex and return the file type */

	// strip all but extension
	$ext = substr($file, (strrpos($file, '.')));
	$ext = str_replace('.', '',  $ext);

	// find file type
	foreach($file_types AS $key => $regex) {
		if (eregi('^('.$regex.')$', $ext)) {
			$type = $key;
		}
	}

	// if type not found return 'other'
	if (!isset($type)) $type = 'other';

	return $type;
}

function send_cookie($name, $value, $expires, $path, $domain, $secure = 0) {
/* same as php's setcookie() */

	global $cfg;

	if ($cfg['httpd_mode'] == 'apache') {
		setcookie($name, $value, $expires, $path, $domain, $secure);
	} else {
		/* expires must follow the format: Saturday, 06-Sep-2014 23:50:08 GMT */
		$expires = date("l, d-M-Y H:i:s \G\M\T", $expires);
		send_header("Set-Cookie: $name=$value; expires=$expires; path=$path; domain=$domain; $secure", false);
	}
}

function send_header($header, $replace = true) {
/* same as php's header() except doesn't support the
 * optional http_reponse_code parameter */

	global $cfg, $send_headers, $header_redirect;

	if ($cfg['httpd_mode'] == 'apache') {
		header($header, $replace);
	} else {
		if ($replace) {
			/* if replace is true (default) overwrite any alike headers */
			$header_name = explode(":", $header);
			$send_headers[strtolower($header_name[0])] = $header."\r\n";
		} else 	{
			/* otherwise give them a unique number */
			$send_headers[] = $header."\r\n";
		}
	}

	/* location headers are a special case, we have to let send_response()
	 * know to change the response status to redirect */
	if (stristr($header, 'Location:')) {
		$header_redirect = true;
	}
}

function convert_bytes($size, &$metric, $from = 'b', $to = '') {
/* used for byte conversion. $from should contain the unit
 * of measurement that $size is currently in. if $to is not
 * provided this function will return the largest unit of
 * measurement. The $metric variable will contain the final
 * unit of measurement used. */

	if (!is_numeric($size)) {
		return false;
	}

	/* amounts in bytes */
	$m['b'] = 1;			// Byte
	$m['kb'] = 1024;		// Kilobyte
	$m['mb'] = 1048576;		// Megabyte
	$m['gb'] = 1073741824;		// Gigabyte
	$m['tb'] = 1099511627776;	// Terabyte
	$m['pb'] = 1125899906842624; 	// Petabyte
	$m['eb'] = 1152921504606847000;	// Exabyte

	/* we work in bytes, so multiply size by the variable that corresponds to 'from' */
	if (!empty($m[$from])) {
		$size = $size * $m[$from];
	} else {
		return false;
	}

	if (isset($m[$to])) {
		$metric = $to;
	} else {
		/* 'to' was not provided, so just return the largest increment */
		$last = 'b';
		foreach ($m AS $key => $val) {
			if ($size < $val) {
				$metric = $last;
				break;
			}
			$last = $key;
		}
	}

	/* convert the size, which is in bytes now, to the requested metric */
	return round($size / $m[$metric], 2);
}

// Function:	service()
// Utility:	Request system services to stop,start,restart or server to reboot.
// Usage:	service(ACTION[,SERVICE,HOST])
// Examples:	service("restart","network","servername.com");
//				service("reboot","","servername.com");
// Definitions:	ACTION:	stop,start,restart [service], reboot
//		SERVICE:(optional)	Used with actions stop,start,restart: any registered program in the sysv init dir.
//		HOST:	(optional) Target Host, default to localhost

function service($action,$service,$host = 'localhost') {
	// Get Configurations configurations, Language file, regex, userdata
	GLOBAL $cfg, $T, $rx, $userdata, $REMOTE_ADDR;

	// Set error 'counter'
	$i = 1;

	//
	// Verify input $data
				
	// Action validity
	if (!eregi($rx['word'],$action))
		$error[$i++] = $T['err']['service']['action'];

	// Service validity
	if ((!eregi($rx['alnum'],$service)) && ($action != "reboot"))
		$error[$i++] = $T['err']['service']['service'];	

	// Action host
	if (!eregi($rx['service'],$host))
		$error[$i++] = $T['err']['service']['host'];
	
	// If tehre are any errors, stop; else commit action
	if (is_array($error)) return $error;
	else 
		commit($action,$service,$host);

	// Log it
	webcp_log(2,$userdata['id'],$userdata['username'],"service : $action $service",$REMOTE_ADDR);
}


// Function:	commit()
// Utility:	This is the link between web://cp interface and web.cp CGI daemon.  Request system updates, etc.
// Usage:	commit(ACTION[,EXTRA,HOST])
// Examples:	commit("scan");
//		commit("restart","network","servername.com");
// Definitions:	ACTION:	scan (system update), read (check flag presence), stop,start,restart [service], reboot, sanity(system<=>db check)
//		EXTRA:	(optional) Used with actions stop,start,restart: any registered program in the sysv init dir.
//		HOST:	(optional) Target Host, default to localhost

function commit($action,$extra = '',$host = 'localhost') {
	// Get Configurations
	GLOBAL $cfg;
	
	// web://cp file 'tag'
	$tag = $cfg['basedir']."/tag/.webcp";
	$tag2 = $cfg['basedir']."/sqltag/.webcp"; // remote notice by MySQL
	
	// Generate authenticity and 'freshness' seal
	$now = time();
	$seal = crypt($now,$cfg['key']);


	// Read tag and return value if it exists
	if ($action == "read") {
		// Only read flag if one exists
		if (file_exists($tag)) {
			$tmp = file($tag);
			
			// Split the flag into ['action'] and ['seal']
			$tmp = explode(":",$tmp[0]);
			$return['action'] = explode(" ",$tmp[0]);
			$return['seal'] = explode(" ",$tmp[1]);
			
			// If seal is valid, return the value
			$seal = crypt($return['seal'][0],$cfg['key']);
			if ($seal == $return['seal'][1])
				return $return;
			else
				webcp_log(0,0,"system","Error: invalid server update request (Invalid Tag Seal)",0);
			
		} // temp sqltag stuff
		elseif (file_exists($tag2)) {
			$tmp = file($tag2);
			
			// Split the flag into ['action'] and ['seal']
			$tmp = explode(":",$tmp[0]);
			$return['action'] = explode(" ",$tmp[0]);
			$return['seal'] = explode(" ",$tmp[1]);
			
			// return the value
			return $return;
		}
	}
	
	// Tell daemon to scan db for user & domain changes
	elseif ($action == "scan") {
		// Only set flag if none exists
		if (!file_exists($tag)) {
			$fp = fopen($tag,"w+");
			fwrite($fp,"scan database:$now $seal");
			fclose($fp);
		}
	}
	
	// Tell daemon to stop/start/restart registered sysv init service (httpd,sendmail,named,xinetd,etc)
	elseif ($action == "stop" OR $action == "start" OR $action == "restart" ) {
		// Check current flag to see if we can set a new one
		$flag = commit("read","",$host);
		
		// Only set flag if none exists or its a db scan
		if (!$flag OR $flag['action'][0] == "scan") {
			$fp = fopen($tag,"w+");
			fwrite($fp,"$action $extra:$now $seal");
			fclose($fp);
		}
	}
	
	// Tell daemon to reboot server
	elseif ($action == "reboot" ) {
		// Set flag in any case
		$fp = fopen($tag,"w+");
		fwrite($fp,"reboot system:$now $seal");
		fclose($fp);
	}
	
	// Tell daemon to edit config.php
 	elseif ($action == 'config') {
 		// Set flag in any case
 		$fp = fopen($tag, "w+");
 		fwrite($fp, "config $extra:$now $seal");
 		fclose($fp);
 	}

	// Tell daemon to run a backup
 	elseif ($action == 'backup') {
 		// Set flag in any case
 		$fp = fopen($tag, "w+");
 		fwrite($fp, "backup $extra:$now $seal");
 		fclose($fp);
 	}

	// Tell daemon to run a backup
 	elseif ($action == 'restore') {
 		// Set flag in any case
 		$fp = fopen($tag, "w+");
 		fwrite($fp, "restore $extra:$now $seal");
 		fclose($fp);
 	}

    // Tell daemon to setup webcp
    elseif ($action == 'setup') {
            // Set flag in any case
            $fp = fopen($tag,"w+");
            fwrite($fp, "setup $extra:$now $seal");
            fclose($fp);
    }

	// Remove Server Flag
	elseif ($action == "remove" ) {
		// Set flag in any case
		if (@is_file($tag)) 
			unlink($tag);
		// temp sqltag stuff
		if (@is_file($tag2)) 
			unlink($tag2);
	}
}



// Function:	dirlist()
// Utility:	List [recursively or not] directories or files, can use simple search patern 
// Usage:	dirlist(ROOT,TYPE[,SEARCH])
// Examples:	dirlist($personaldata['root'],"all");
//		dirlist($domaindata['path'],"dir",'.gif$');
// Definitions:	ROOT:	root dir to list
//		TYPE:	type of listing: all, dir, files
//		SEARCH:	search pattern: simple REGEX.
//		LIMIT:	how deep to list dirs, default unlimited
// Return:	array: directory structure.

function dirlist($root, $type, $search='', $limit='none') {
	// Get Configurations
	GLOBAL $cfg;
	
	// Set find type
	if ($type == "dir") $type = "d";
   	elseif ($type == "file") $type = "f";
   	else unset($type);
   	
   	if ($type) exec($cfg['prog']['find']." '$root' -type $type",$dirstruct);
   	else exec($cfg['prog']['find']." '$dir'",$dirstruct);

	return $dirstruct;
}



// Function:	getstat()
// Utility:	Gets system stat: uptime, monitor status, memory, swap, cpu load.
// Usage:	getstat(TYPE)
// Examples:	getstat("uptime");
//		getstat("cpu");
// Definitions:	TYPE:	uptime, ram, swap, cpu, monitor
// Returns:	array: ['http'], ['total'], etc

function getstat($action) {
	// Get Configurations
	GLOBAL $cfg;
	
	// initialize
	unset($return);
	
	// Select what to do based on the action
	switch($action) {
		case 'ram':
			if($cfg["os"]=="linux"){
				$return['total'] = trim(`free -m |grep -i mem | cut -c15-18`);
				$return['used'] = trim(`free -m |grep -i mem | cut -c26-29`);
			}
			elseif($cfg["os"]=="freebsd"){
				$return['total'] = (int)(trim(`sysctl -n hw.physmem`)/pow(1024, 2));
				$return['used'] = (int)(trim(`vmstat | tail -n 1 | cut -c8-16`)/1024);
			}
			
			break;
		
		case 'swap':
			if($cfg["os"]=="linux"){
				$return['total'] = trim(`free -m |grep -i swap | cut -c15-18`);
				$return['used'] = trim(`free -m |grep -i swap | cut -c26-29`);
			}
			elseif($cfg["os"]=="freebsd"){
				// $swapinfo contains swap info for each disk
				exec("swapinfo | sed -e '1d'", $swapinfo);

				foreach($swapinfo as $disk){
					// find Used and Avail on this disk
					preg_match("/^(\S+\s+){2}(\S+)\s+(\S+)/", $disk, $matches);

					// Add to totals:
					$return["used"]+=$matches[2];
					$return["total"]+=$matches[3];
				}
				$return["used"]=(int)($return["used"]/1024);
				$return["total"]=(int)($return["total"]/1024);
			}
			break;
			
		case 'cpu':
		case 'uptime':
			// check for how long its been up and parse accordingly
			if($cfg["os"]=="linux"){
				$serverinfo = trim(`uptime | cut -c11-`);
			}
			elseif($cfg["os"]=="freebsd"){
				$serverinfo = trim(`uptime | cut -c10-`);
			}
			if (strstr($serverinfo,"day")) {
				$serverinfo = explode(",",$serverinfo);
				$return['uptime'] = trim(str_replace("up","",$serverinfo[0].", ".$serverinfo[1]));
				$return['cpu'] = (trim(str_replace("load average: ","",$serverinfo[3]))." : ".trim($serverinfo[4])." : ".trim($serverinfo[5]));
			}
			else {
			   $serverinfo = explode(",",$serverinfo);
			   $return['uptime'] = trim(str_replace("up","",$serverinfo[0]));
			   $return['cpu'] = (trim(str_replace("load average: ","",$serverinfo[2]))." : ".trim($serverinfo[3])." : ".trim($serverinfo[4]));
			}
			break;
		
		case 'monitor':
			// load config file and parse it for HOST	localhost
			$filename = $cfg['basedir']."/server/data/sysmon.dat";
			if (file_exists($filename)) {
				$return = file($filename);
				$return = implode("",$return);
				$return = unserialize($return);
			}
			else return $T['err']['getstat']['no monitor data'];
			break;
	}
	return ($return);
}



// Function:	fetchdata()
// Utility:	Quickly fetch data without using SQL statements; trim, remove slashes & parse as well
// Usage:	fetchdata(SELECT_COL,TYPE,WHERE)
// Examples:	fetchdata("*","user",$username);
//		fetchdata("host,domain","domain",$personaldata['id']);
//		fetchdata("users","total",$domainid);
// Return:	$data 		array var (SQL data fetched)  or nothing
// Definitions:	SELECT_COL:	Column name(s) to fetch (corresponding to the MySQL Tables)
//		TYPE:		user, domain, reseller, total, alloc
//		WHERE:		user: username, domain: ID, reseller: ID

function fetchdata($select_col,$type,$where) {
	// get configurations
	GLOBAL $cfg;
	
	// Initialize
	unset($tmp);
	// type is 'user'
	if ($type == "user") {
		$dbp = mysql_query("SELECT $select_col FROM users WHERE username='$where'");

		$data = mysql_fetch_array($dbp);
		if ($data) {
			reset($data);
			$j = 0;
			do {
				$key = key($data);
				if ($key != $j) {
					// if col_name == password, decode it
					if ($key == "password") {
						$dbp2 = mysql_query("SELECT DECODE(password,'".$cfg['key']."') AS password FROM users WHERE username='$where'");
						$data2 = mysql_fetch_array($dbp2);
						$data['password'] = trim(stripslashes($data2['password']));
					}
					else {
						// clean the data (no slashes, no leading spaces)
						$data[$key] = trim(stripslashes(current($data)));
					}
				}
				else ++$j;
			} while (next($data) OR isset($data[$j]));
		}
	}
	
	// type is 'domain'
	elseif ($type == "domain") {
		
		// fetch data from SQL db
		$dbp = mysql_query("SELECT $select_col FROM domains WHERE id='$where'");
		$data = mysql_fetch_array($dbp);
		
		// clean the data (no slashes, no leading spaces)
		if ($data) {
			reset($data);
			$j = 0;
			do {
				$key = key($data);
				if ($key != $j) {
					// if col_name == serverside or databases, unserialize it
					
					if ($key == "serverside") {
						$data[$key] = unserialize(current($data));
						$tmp = unserialize(current($data));
						print_r($tmp);
					}
					else {
						// clean the data (no slashes, no leading spaces)
						$data[$key] = trim(stripslashes(current($data)));
					}
				}
				else ++$j;
			} while (next($data) OR isset($data[$j]));
		}
	}
	
	// type is 'reseller'
	elseif ($type == "reseller") {
		
		// only get reseller ID (5 first numbers)
		$where = substr($where, 0, 5);
		
		// fetch data from SQL db
		$dbp = mysql_query("SELECT $select_col FROM resellers WHERE id='$where'");
		$data = mysql_fetch_array($dbp);
		
		if ($data) {
			reset($data);
			$j = 0;
			do {
				$key = key($data);
				if ($key != $j) {
					// if col_name == serverside, unserialize it
					if ($key == "serverside") {
						$data[$key] = unserialize(trim(stripslashes(current($data))));
					}
					else {
						// clean the data (no slashes, no leading spaces)
						$data[$key] = trim(stripslashes(current($data)));
					}
				}
				else ++$j;
			} while (next($data) OR isset($data[$j]));
		}
	}
	// type is 'database'
	elseif ($type == "database") {
		
		// fetch data from SQL db
		if (is_numeric($where))
			$dbp = mysql_query("SELECT $select_col FROM databases WHERE uid='$where'");
		
		else
			$dbp = mysql_query("SELECT $select_col FROM databases WHERE username='$where'");
		$data = mysql_fetch_array($dbp);
		
		if ($data) {
			reset($data);
			$j = 0;
			do {
				$key = key($data);
				if ($key != $j) {
					// if col_name == password, decode it
					if ($key == "password") {
						$dbp2 = mysql_query("SELECT DECODE('".addslashes($data['password'])."','".$cfg['key']."') AS password");
						$data2 = mysql_fetch_array($dbp2);
						$data['password'] = trim(stripslashes($data2['password']));
					}
					else {
						// clean the data (no slashes, no leading spaces)
						$data[$key] = trim(stripslashes(current($data)));
					}
				}
				else ++$j;
			} while (next($data) OR isset($data[$j]));
		}
	}
	
	// type is 'total'
	elseif ($type == "total") {

		if ($select_col == "users") {
			// if $where == 0, get all users
			if ($where == 0)
				$dbp = mysql_query("SELECT COUNT(*) AS $select_col FROM users");
			// if $where < 1000000000, get a reseller's users
			elseif ($where < 1000000000)
				$dbp = mysql_query("SELECT COUNT(*) AS $select_col FROM users WHERE id >= ".$where."10000 AND id <= ".$where."99999");
			// else get a domain's users
			else
				$dbp = mysql_query("SELECT COUNT(*) AS $select_col FROM users WHERE id='$where'");
		}
		if ($select_col == "transfer") {
			// if $where == 0, get all transfer
			if ($where == 0)
				$dbp = mysql_query("SELECT SUM(transfer_used) AS $select_col FROM domains");
			// else get a reseller's total transfer
			elseif ($where < 1000000000)
				$dbp = mysql_query("SELECT SUM(transfer_used) AS $select_col FROM domains WHERE id >= ".$where."10000 AND id <= ".$where."99999");
			// else get a domain's + sub & pointer total
			else
				$dbp = mysql_query("SELECT SUM(transfer_used) AS $select_col FROM domains WHERE id = ".$where." OR owner = ".$where);
			
		}
		if ($select_col == "hd") {
			// if $where == 0, get all hd space
			if ($where == 0)
				$dbp = mysql_query("SELECT SUM(hd_used) AS $select_col FROM domains");
			// else get a reseller's total hd space
			else
				$dbp = mysql_query("SELECT SUM(hd_used) AS $select_col FROM domains WHERE owner='$where'");
		}
		elseif ($select_col == "db") {
			// if $where == 0, get all databases
			if ($where == 0)
				$dbp = mysql_query("SELECT SUM(db) AS $select_col FROM domains WHERE type = 'domain'");
			// get a reseller's dbs
			elseif ($where < 1000000000)
				$dbp = mysql_query("SELECT SUM(db) AS $select_col FROM domains WHERE id >= ".$where."10000 AND id <= ".$where."99999");
			// else get a domain's databases
			else
				$dbp = mysql_query("SELECT SUM(db) AS $select_col FROM domains WHERE owner = '$where' AND type = 'domain'");
		}
		elseif ($select_col == "domains") {
			// only get reseller ID (5 first numbers)
			$where = substr($where, 0, 5);
			// if $where == 0, get all domains
			if ($where == 0)
				$dbp = mysql_query("SELECT COUNT(*) AS $select_col FROM domains WHERE type = 'domain'");
			// else get a reseller's domains
			else
				$dbp = mysql_query("SELECT COUNT(*) AS $select_col FROM domains WHERE owner = '$where' AND type = 'domain'");
		}
		elseif ($select_col == "subdomains") {
			// if $where == 0, get all subs
			if ($where == 0)
				$dbp = mysql_query("SELECT COUNT(*) AS $select_col FROM domains WHERE type = 'subdomain'");
			// if $where < 1000000000, get a reseller's subs
			elseif ($where < 1000000000)
				$dbp = mysql_query("SELECT COUNT(*) AS $select_col FROM domains WHERE id >= ".$where."10000 AND id <= ".$where."99999 AND type = 'subdomain'");
			// else get a domain's subs
			else
				$dbp = mysql_query("SELECT COUNT(*) AS $select_col FROM domains WHERE owner = '$where' AND type = 'subdomain'");
		}
		elseif ($select_col == "pointers") {
			// if $where == 0, get all pointers
			if ($where == 0)
				$dbp = mysql_query("SELECT COUNT(*) AS $select_col FROM domains WHERE type = 'pointer'");
			// if $where < 1000000000, get a reseller's pointers
			elseif ($where < 1000000000)
				$dbp = mysql_query("SELECT COUNT(*) AS $select_col FROM domains WHERE owner >= ".$where."10000 AND owner <= ".$where."99999 AND type = 'pointer'");
			// else get a domain's pointers
			else
				$dbp = mysql_query("SELECT COUNT(*) AS $select_col FROM domains WHERE owner = '$where' AND type = 'pointer'");
		}
		
		// fetch data from SQL db
		if ($dbp) {
			$data = mysql_fetch_array($dbp);
		}
		else $data = "";
	}
	
	// type is 'alloc'
	elseif ($type == "alloc") {
		switch($select_col) {
			case 'db':
			case 'users':
			case 'hd':
			case 'subdomains':
			case 'pointers':
			case 'transfer':
				$dbp = mysql_query("SELECT SUM($select_col) AS $select_col FROM domains WHERE owner='$where'");
				break;
			default:
				break;
		}
		
		// fetch data from SQL db
		if ($dbp) {
			$data = mysql_fetch_array($dbp);
		}
		else $data = "";
	}
	
	if (is_array($data)) {
		$ii = 0;
		while(isset($data[$ii]))
			unset($data[$ii++]);
	}
	
	// Return fetched data, or null if nothing
	return($data);
}

// Function: createBackup()
// Utility:	begin a backup
// Usage:	createBackup(URLLIST,DATABASES,FILES,EMAIL,LOCAL,REMOTE,FTPSERVER,USERNAME,PASSWORD,DIRECTORY)
// Examples: createBackup("");
// Return:	$error	array var or nothing
// Definitions:	URLLIST: array of domain names to backup
//				LOCAL: bool - make a local backup
//				REMOTE: bool - make a remote backup
//				FTPSERVER: where to place the data
//				USERNAME: username for FTP login
//				PASSWORD: password for FTP login
//				DIRECTORY: optional - remote directory for backup

function createBackup($urllist, $scheduled, $recurrance, $immediate, $databases, $files, $email, $local, $remote, $ftpserver, $username, $password, $directory) {

	GLOBAL $T, $userdata;
	
	if (($immediate != "on") && ($scheduled != "on")) {
		$error[0] = $T['err']['backup']['no backup time'];
		return $error;
	}
	
	if (($scheduled == "on") && ($recurrance == "")) {
		$error[0] = $T['err']['backup']['no schedule'];
		return $error;
	}
	
	if (($urllist == "") && ($databases != "on")) {
		$error[0] = $T['err']['backup']['no domains'];
		return $error;
	}
	
	if (($files != "on") && ($email != "on") && ($databases != "on")) {
		$error[0] = $T['err']['backup']['no backup content'];
		return $error;
	}

	if ($remote == "on") {

		$conn_id = ftp_connect($ftpserver);
		if (!$conn_id) { 
			$error[0] = $T['err']['backup']['ftp connect failed'];
			return $error;
		}
		
		$login_result = ftp_login($conn_id, $username, $password);
		if (!$login_result) {
			$error[0] = $T['err']['backup']['ftp login failed'];
			ftp_close($conn_id);
			return $error;
		}
		
		if ($directory != "") {
		
			$dir_result = ftp_chdir($conn_id, $directory);
			if (!$dir_result) {
				$error[0] = $T['err']['backup']['ftp cd failed'];
				ftp_close($conn_id);
				return $error;
			}
			
		}
		
		ftp_close($conn_id);
		
	}
	
	if (($local != "on") && ($remote != "on")) {
		$error[0] = $T['err']['backup']['no backup type'];
		return $error;
	}
	
	if ($immediate ==  "on") {
		commit("backup", "$databases|$files|$email|$local|$remote|$urllist|$ftpserver|$username|$password|$directory");
	}

	if ($scheduled == "on") {
		if ($databases == "on") {
			$databases = 1;
		} else {
			$databases = 0;
		}
		if ($files == "on") {
			$files = 1;
		} else {
			$files = 0;
		}
		if ($email == "on") {
			$email = 1;
		} else {
			$email = 0;
		}
		if ($local == "on") {
			$local = 1;
		} else {
			$local = 0;
		}
		if ($remote == "on") {
			$remote = 1;
		} else {
			$remote = 0;
		}
		$totalresult = true;
		$domains = explode("_", $urllist);
		for ($i=0; $i<sizeOf($domains); $i++) {
			$SQL = "INSERT INTO `backups`(`files`, `email`, `local`, `remote`, `domain`, `ftpserver`, `username`, `password`, `directory`, `recurrance`, `cpusername`) VALUES(";
			$SQL .= "$files, $email, $local, $remote, '".$domains[$i]."', '$ftpserver', '$username', ENCODE('$password','".$cfg['key']."'), '$directory', $recurrance, '".$userdata['username']."')";
			$result = mysql_query($SQL);
			$totalresult = ($totalresult && $result);
		}
		if ($databases == 1) {
			$SQL = "INSERT INTO `backups`(`databases`, `local`, `remote`, `ftpserver`, `username`, `password`, `directory`, `recurrance`, `cpusername`) VALUES(";
			$SQL .= "$databases,  $local, $remote, '$ftpserver', '$username', ENCODE('$password','".$cfg['key']."'), '$directory', $recurrance, '".$userdata['username']."')";
			$result = mysql_query($SQL);
			$totalresult = ($totalresult && $result);
		}
		if (!$totalresult) {
			$error[0] = $T['err']['backup']['sched fail'] . $SQL;
			return $error;
		}
	}

}

// Function: backupDirList()
// Utility:	delete a backup
// Usage:	backupDirList(DIRECTORY)
// Examples: backupDirList("/home/test.com/_backups");
// Return:	$dirarray	array var containing list of files
// Definitions:	DIRECTORY: directory to list
function backupDirList($directory) 
{

    // create an array to hold directory list
    $results = array();

    // create a handler for the directory
    $handler = opendir($directory);

    // keep going until all files in directory have been read
    while ($file = readdir($handler)) {

        // if $file isn't this directory or its parent, 
        // add it to the results array
        if ($file != '.' && $file != '..')
            $results[] = $file;
    }

    // tidy up: close the handler
    closedir($handler);

    // done!
    return $results;

}

// Function: deleteBackup()
// Utility:	delete a backup
// Usage:	deleteBackup(TYPE,BACKUPLIST)
// Examples: deleteBackup("local","1_2_3");
// Return:	$error	array var or nothing
// Definitions:	BACKUPLIST: List of backup id's to delete

function deleteBackup($type,$backuplist) {
	GLOBAL $T;
	switch ($type) {
		case "local":
			for ($i=0; $i<sizeOf($backuplist); $i++) {
				unlink($backuplist[$i]);
			}
			break;
		case "sched":
			for ($i=0; $i<sizeOf($backuplist); $i++) {
				$SQL = "DELETE FROM backups WHERE id = ".$backuplist[$i];
				mysql_query($SQL);
			}
			break;
	}
}

// Function: restoreBackup()
// Utility:	restore a backup
// Usage:	restoreBackup(TYPE,BACKUPLIST)
// Examples: restoreBackup("local","1_2_3");
// Return:	$error	array var or nothing
// Definitions:	BACKUPLIST: List of backup id's to delete

function restoreBackup($type,$backuplist) {
	GLOBAL $T;
	$backups = implode("|", $backuplist);
	switch ($type) {
		case "local":
			commit("restore", "$backups");
			break;
		case "remote":
			$error[0] = "Not Yet Implemented";
			return $error;
			break;
	}
}


// Function:	user()
// Utility:	Create, Delete, Modify, Suspend, Unsuspend users; make sure everything is ok & secure
// Usage:	user(ACTION,DATA)
// Examples:	user("create",$_POST);
//		user("delete",$username);
// Return:	$error		array var or nothing
// Definitions:	ACTION:		create, delete, modify, suspend, unsupend
//		DATA:		username, HTTP_POST_VARS, etc

function user($action,$data) {
	// Get configurations, userdata, Language file, regex
	GLOBAL $userdata, $cfg, $T, $rx, $REMOTE_ADDR;
	
	// kill demo users (return error)
	if ($userdata['type'] == "demo") {
		$error[1] = $T['err']['demo user'];
		return $error;
	}
	
	// Set error 'counter'
	$i = 1;
	
	//
	// Create a new user entry in the database
	if ($action == "create") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[id]		*REQUIRED* domain group id that will hold the user
		// 
		// 
		// Expected Input Data (from POST)
		// ===============================
		// * Optional
		// data[name]		Full Name
		// data[username]	username
		// data[password]	password
		// data[root]		/path-to/user-root.  web://cp will add the start of the string (HOME).
		// data[type]		type of user: standard,virtual,email,ftp,database,demo
		// data[level]		Level: 1-5 (server, reseller, domain, personal, tools)
		// data[hd]		HD Quota
		// data[aliases]	* Default: none; e-mail aliases seperated by space, coma or new lines
		// data[catchall]	* Catch all mail non catched by another user first.  Once per domain.
		// data[shell]		* Default: off; on,off,ask
		// data[autoreply]	* E-Mail Auto-Responder message
		// data[forward]	* Addresses to forward to
		// data[lang]		* User Language. Default: #defaultlang
		// data[skin]		* Interface skin. Default: #defaultskin
		
		
		// Fetch some data to respect Quotas & verify some input validity		
		$dom_data = fetchdata("hd,users,shell,host","domain",$data['id']);
		$users = fetchdata("users","total",$data['id']);
				
		
		//
		// Verify input $data
				
		// Name validity
		if (!eregi($rx['name'],$data['name']))
			$error[$i++] = $T['err']['user']['name'];

		// Username validity
		if (eregi($rx['user'],$data['username'])) {
			$data['username'] = strtolower($data['username']);
			$dbp = mysql_query("SELECT username FROM users WHERE username = '".$data['username']."'");
			if (mysql_num_rows($dbp) OR stristr($cfg['badusers'],' '.$data['username'].' '))
				$error[$i++] = $T['err']['user']['used username'];
		} else 
			$error[$i++] = $T['err']['user']['username'];
		
		// Password
		if (!eregi($rx['pass'],$data['password'])) $error[$i++] = $T['err']['user']['password'];
		if ($cfg['strong_passwords'])
			if (!password_check($data['password'], $error)) $error[$i++] = $T['err']['user']['weakpassword'];
		// Escape ' and " for MySQL.
		$data['password'] = addslashes($data['password']);
		
		// User Root Validity
		if (!$data['root'])
			$data['root'] = $cfg['webdir']."/".$data['id'];
		else {
			$dir = ereg_replace("^/","",str_replace("../","",$data['root']));
			$dir = $cfg['webdir']."/".$data['id']."/".$dir;
			$dir = ereg_replace("/$","",$dir);
			if (strstr($dir,"%USER%")) {
				$tmp = explode("%USER%",$dir);
				if (!is_dir($tmp[0]))
					$error[$i++] = $T['err']['user']['root'].$tmp[0];
				$dir = $tmp[0].$data['username'].str_replace("/","",$tmp[1]);
			}
			else {
				if (!is_dir($dir))
					$error[$i++] = $T['err']['user']['root'].$dir;
			}
			$data['root'] = $dir;
		}
		
		
		// Aliases validity, unique
		$aliases = split("([[:space:]]+,?|[[:space:]]*,)",strtolower($data['aliases']));
		if (is_array($aliases) AND trim($data['aliases'])) {
			$rmalias = '';
			do {
				// is it valid?
				if (eregi($rx['alias'],current($aliases))) {
					// verify if its not used as a user already
					$dbp = mysql_query("SELECT username FROM users WHERE username = '".current($aliases)."' AND id = '".$data['id']."'");
					if (mysql_num_rows($dbp))
						$error[$i++] = $T['err']['user']['aliases'].current($aliases);
					
					// verify if its not used as an alias already
					$dbp = mysql_query("SELECT username FROM users WHERE aliases LIKE '% ".current($aliases)." %' AND id = '".$data['id']."'");
					if (mysql_num_rows($dbp))
						$error[$i++] = $T['err']['user']['aliases'].current($aliases);
						
					if (current($aliases) == $data['username'])
						$rmalias = current($aliases);
				}
				// not valid
				else
					$error[$i++] = $T['err']['user']['aliases'].current($aliases);
			} while(next($aliases));
			
			// Reset $data['aliases'] to a correct value.  The trailing spaces are needed for fast searching (step above)
			$data['aliases'] = " ".trim(implode(" ",$aliases))." ";
			if ($rmalias)
				str_replace(" $rmalias ", " ",$data['aliases']);
			$data['aliases'] = ereg_replace("[[:space:]]+"," ",$data['aliases']);
		}
		// there is no aliases, unset it.
		else
			unset($data['aliases']);
		
		// Check for catchall
		if ($data['catchall'] == "true") {
			$dbp = mysql_query("SELECT username FROM users WHERE catchall = 'true' AND id = '".$data['id']."'");
				if ($tmp = mysql_fetch_array($dbp))
					$error[$i++] = $T['err']['user']['catchall'].$tmp['username'];
		}
		else $data['catchall'] = "false";
		
		// Verify User type:  standard, virtual, email, ftp, database or demo
		switch($data['type']) {
			case 'standard':
			case 'database':
			case 'demo':
				break;
			case 'ftp':
				if ($cfg['ftpserver'] == "proftpd")
					break;
			case 'email':
				if ($cfg['mailserver'] == "virtualqmail")
					break;
			case 'virtual':
				if ($cfg['ftpserver'] == "proftpd" AND $cfg['mailserver'] == "virtualqmail")
					break;
			default:
				$error[$i++] = $T['err']['user']['type'];
		}
		
		// Verify User Level
		$data['level'] = intval($data['level']);
		if ($data['level'] < $userdata['level'])
			$error[$i++] = $T['err']['user']['level'];

		
		// Verify HD & Users availability
		$data['hd'] = intval($data['hd']);
		if ($dom_data['hd'] < $data['hd'])
			$error[$i++] = $T['err']['user']['hd'].$dom_data['hd'];
		if ($dom_data['users'] - $users['users'] <= 0)
			 $error[$i++] = $T['err']['user']['user'];
		
		// Verify Shell
		if ($data['shell'] == "on") {
			if ($dom_data['shell'] != "on")
				$error[$i++] = $T['err']['user']['shell'];
		}
		else $data['shell'] = "off";
		
		// Autoresponder Check 
		$data['autoreply'] = addslashes($data['autoreply']);
		
		// E-Mail Forwarding
		$forward = split("([[:space:]]+,?|[[:space:]]*,)",$data['forward']);
		if (is_array($forward) AND trim($data['forward'])) {
			do {
				// is it not valid?
				if (!eregi($rx['eml'],current($forward)) AND !eregi($rx['user'],current($forward)))
					$error[$i++] = $T['err']['user']['forward'].current($forward);
			} while(next($forward));
			
			// Reset $data['forward'] to a correct value.
			$data['forward'] = trim(implode(" ",$forward));
		}
		// there is no forwarding, unset it.
		else
			unset($data['forward']);
		
		// Set User's Language
		if (!ereg("^".$data['lang']."$",$cfg['lang']) AND
		    !ereg("^".$data['lang']."[:space:]*,",$cfg['lang']) AND
		    !ereg(",[:space:]*".$data['lang']."$",$cfg['lang']) AND
		    !ereg(",[:space:]*".$data['lang']."[:space:]*,",$cfg['lang']))
			$data['lang'] = $cfg['defaultlang'];
		
		// Set User's web://cp skin
		$data['skin'] = str_replace("/","",$data['skin']);
		if (!trim($data['skin']) OR !file_exists("skin/".$data['skin']))
			$data['skin'] = $cfg['defaultskin'];
		
			
		//
		// Insert into Database
		
		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			mysql_query("INSERT INTO users SET id='".$data['id']."', username='".$data['username']."', username1='".$data['username']."', name='".addslashes($data['name'])."', root='".$data['root']."',
				password=ENCODE('".$data['password']."','".$cfg['key']."'), type='".$data['type']."', level='".$data['level']."', hd='".$data['hd']."',
				aliases='".$data['aliases']."', shell='".$data['shell']."', autoreply='".$data['autoreply']."', forward='".$data['forward']."', catchall='".$data['catchall']."',
				lang='".$data['lang']."', skin='".$data['skin']."', action='create'");
			
			// create md5 signature and insert it.
			$hash = fetchdata("*","user",$data['username']);
			$hash['hash'] = $hash['time'] = $hash['ucount'] = '';
			$hash = crypt(md5(serialize($hash)), $cfg['key']);
			mysql_query("UPDATE users SET hash='$hash' WHERE username = '".$data['username']."'");
			
			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"user created: ".$data['username'],$REMOTE_ADDR);
			
			// Tell the system to commit the changes.
			commit("scan");
		}
		
	}
	// end 'create'
	///
	
	
	//
	// Update an user entry in the database
	if ($action == "update") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[uid]	*REQUIRED* username
		// data[id]	*REQUIRED* group ID#
		// 
		// 
		// Expected Input Data (from POST)
		// ===============================
		// ** ALL Optional
		// data[name]		Full Name
		// data[username]	new username
		// data[password]	new password
		// data[pass_confirm]	1 if confirmed -- needed for data[password]
		// data[root]		/path-to/user-root.  web://cp will add the start of the string (HOME).
		// data[level]		Level: 1-5 (server, reseller, domain, personal, tools)
		// data[hd]		HD Quota
		// data[shell]		on,off,ask
		// data[lang]		User Language.
		// data[skin]		Interface skin.
		// data[aliases]	E-mail aliases seperated by space, coma or new lines
		// data[autoreply]	E-Mail Auto-Responder message
		// data[forward]	Addresses to forward to seperated by space, coma or new lines
		// data[catchall]	Catch all mail non catched by another user first.  Once per domain.
		// data[ip_restrict]	IP restriction on the account.  Can match all or part of an IP Address.


		// Fetch some usefull data to verify input validity
		$personaldata = fetchdata("*","user",$data['uid']);
		$dom_data = fetchdata("hd,shell","domain",$personaldata['id']);
		
		// Check update count
		if ($personaldata['ucount'] >= $cfg['ucount'])
			$error[$i++] = $T['err']['update count'];
			
		// **** Remove Doubles ($data already in the db) & create SQL query as we check input
		$sql_query = "UPDATE users SET ";
		
		//
		// Verify input $data
		
		// Name validity
		if (trim($data['name']) AND $data['name'] != $personaldata['name']) {
			if (!eregi($rx['name'],$data['name']))
				$error[$i++] = $T['err']['user']['name'];
			
			$sql_query .= "name='".addslashes($data['name'])."', ";
		}
			
		// Username validity
		if (trim($data['username'])) $data['username'] = strtolower($data['username']); 
		if (trim($data['username']) AND $data['username'] != $personaldata['username'])	{
			if (eregi($rx['user'],$data['username'])) {
				$dbp = mysql_query("SELECT username FROM users WHERE username = '".$data['username']."'");
				if (mysql_num_rows($dbp))
					$error[$i++] = $T['err']['user']['used username'];
				
				// Check if no alias is set for that username
				$dbp = mysql_query("SELECT username FROM users WHERE aliases LIKE '% ".$data['username']." %' AND id = '".$personaldata['id']."'");
				if (mysql_num_rows($dbp))
					$error[$i++] = $T['err']['user']['aliases'].$data['username'];
			} else
				$error[$i++] = $T['err']['user']['username'];
			
			$sql_query .= "username='".$data['username']."', ";
		}
		
		// Password
		if (trim($data['password']) AND $data['password'] != $personaldata['password'])	{
			if ($data['pass_confirm']) {
				if (!eregi($rx['pass'],$data['password'])) $error[$i++] = $T['err']['user']['password'];
				if ($cfg['strong_passwords'])
					if (!password_check($data['password'])) $error[$i++] = $T['err']['user']['weakpassword'];
				// Escape ' and " for MySQL.
				$data['password'] = addslashes($data['password']);
				
				$sql_query .= "password=ENCODE('".$data['password']."','".$cfg['key']."'), ";
			}
		}
		
		// User Root Validity
		if (isset($data['root'])) {
			$dir = ereg_replace("^/","",str_replace("../","",$data['root']));
			$dir = $cfg['webdir']."/".$personaldata['id']."/".$dir;
			$data['root'] = ereg_replace("/$","",$dir);
			// we don't want roots with ' or " in them and it must exist
			if (strstr($data['root'],"\"") OR strstr($data['root'],"'") OR !@is_dir($data['root']))
				$error[$i++] = $T['err']['user']['root'].$data['root'];
			
			if ($data['root'] != $personaldata['root'])
				$sql_query .= "root='".$data['root']."', ";
		}
		
		// Verify User Level
		if (isset($data['level']) AND $data['level'] != $personaldata['level']) {
			$data['level'] = intval($data['level']);
			if ($data['level'] < $userdata['level'])
				$error[$i++] = $T['err']['user']['level'];
				
			$sql_query .= "level='".$data['level']."', ";
		}
		
		
		
		// Verify HD availability
		if (isset($data['hd']) AND $data['hd'] != $personaldata['hd']) {
			$data['hd'] = intval($data['hd']);
			if ($dom_data['hd'] < $data['hd'])
				$error[$i++] = $T['err']['user']['hd'].$dom_data['hd'];
				
			$sql_query .= "hd='".$data['hd']."', ";
		}
		
		// Verify Shell
		if (isset($data['shell']) AND $data['shell'] != $personaldata['shell']) {
			if ($data['shell'] == "on") {
				if ($dom_data['shell'] != "on") {
					$error[$i++] = $T['err']['user']['shell'];
					$data['shell'] = "off";
				}
			}
			else $data['shell'] = "off";
			
			$sql_query .= "shell='".$data['shell']."', ";
		}
		
		// Set User's Language
		if (isset($data['lang']) AND $data['lang'] != $personaldata['lang']) {
			if (!ereg($rx['word'],$data['lang']) OR !file_exists("lang/".$data['lang'].".phps"))
				$data['lang'] = $cfg['defaultlang'];
				
			$sql_query .= "lang='".$data['lang']."', ";
		}

		// Set User's web://cp skin
		if (isset($data['skin']) AND $data['skin'] != $personaldata['skin']) {
			if (!ereg($rx['alnum'],$data['skin']) OR !file_exists("skin/".$data['skin']))
				$data['skin'] = $cfg['defaultskin'];
			
			$sql_query .= "skin='".$data['skin']."', ";
		}
		
		// E-Mail Forwarding
		if (isset($data['forward'])) {
			$forward = trim(ereg_replace("[;,]"," ",$data['forward']));
			$forward = split("[[:space:]]+",$forward);
			if (is_array($forward) AND trim($data['forward'])) {
				do {
					// is it not valid?
					if (!eregi($rx['eml'],current($forward)) AND !eregi($rx['user'],current($forward)))
						$error[$i++] = $T['err']['user']['forward'].current($forward);
				} while(next($forward));
				
				// Reset $data['forward'] to a correct value.
				$data['forward'] = trim(implode(" ",$forward));
				
				if ($data['forward'] != $personaldata['forward'])
					$sql_query .= "forward='".$data['forward']."', ";
			}
			elseif ($data['forward'] != $personaldata['forward'])
				$sql_query .= "forward='', ";
		}
		
		// Aliases validity, unique
		if (isset($data['aliases'])) {
			$aliases = trim(ereg_replace("[;,]"," ",strtolower($data['aliases'])));
			$aliases = split("[[:space:]]+",$aliases);
			if (is_array($aliases) AND $data['aliases']) {
				$rmalias = '';
				do {
					// is it valid?
					if (eregi($rx['alias'],current($aliases))) {
						// verify if its not used as a user already
						$dbp = mysql_query("SELECT username FROM users WHERE username = '".current($aliases)."' AND id = '".$personaldata['id']."' AND username != '".$data['uid']."'");
						if (mysql_num_rows($dbp))
							$error[$i++] = $T['err']['user']['aliases'].current($aliases);
						
						// verify if its not used as an alias already
						$dbp = mysql_query("SELECT username FROM users WHERE aliases LIKE '% ".current($aliases)." %' AND id = '".$personaldata['id']."' AND username != '".$data['uid']."'");
						if (mysql_num_rows($dbp))
							$error[$i++] = $T['err']['user']['aliases'].current($aliases);
							
						if (current($aliases) == $personaldata['username'])
							$rmalias = current($aliases);
						
					}
					// not valid
					else
						$error[$i++] = $T['err']['user']['aliases'].current($aliases);
				} while(next($aliases));
				
				// Reset $data['aliases'] to a correct value.  The trailing spaces are needed for fast searching (step above)
				$data['aliases'] = " ".trim(implode(" ",$aliases))." ";
				if ($rmalias)
					str_replace(" $rmalias ", " ",$data['aliases']);
				$data['aliases'] = ereg_replace("[[:space:]]+"," ",$data['aliases']);
				
			}
			elseif ($data['aliases']) {
				if (!eregi($rx['alias'],$data['aliases']))
					$error[$i++] = $T['err']['user']['aliases'].$data['aliases'];
				else {
					// verify if its not used as a user already
					$dbp = mysql_query("SELECT username FROM users WHERE username = '".$data['aliases']."' AND id = '".$personaldata['id']."' AND username != '".$data['uid']."'");
					if (mysql_num_rows($dbp))
						$error[$i++] = $T['err']['user']['aliases'].$data['aliases'];
					
					// verify if its not used as an alias already
					$dbp = mysql_query("SELECT username FROM users WHERE aliases LIKE '% ".$data['aliases']." %' AND id = '".$personaldata['id']."' AND username != '".$data['uid']."'");
					if (mysql_num_rows($dbp))
						$error[$i++] = $T['err']['user']['aliases'].$data['aliases'];
				}
			}
			if ($data['aliases'] != $personaldata['aliases'])
				$sql_query .= "aliases='".$data['aliases']."', ";
		}
		
		// Catch-All
		if (isset($data['catchall']) AND $data['catchall'] != $personaldata['catchall']) {
			if ($data['catchall'] == "true") {
				$dbp = mysql_query("SELECT username FROM users WHERE catchall = 'true' AND id = '".$personaldata['id']."' AND username != '".$data['uid']."'");
					if ($tmp = mysql_fetch_array($dbp))
						$error[$i++] = $T['err']['user']['catchall'].$tmp['username'];
			
				$sql_query .= "catchall='true', ";
			}
			else
				$sql_query .= "catchall='false', ";
		}
		
		// Autoresponder Check 
		if (isset($data['autoreply']) AND $data['autoreply'] != $personaldata['autoreply']) {
			$data['autoreply'] = addslashes($data['autoreply']);
			$sql_query .= "autoreply='".$data['autoreply']."', ";
		}
		
		// IP Restriction Check 
		if (isset($data['ip_restrict']) AND $data['ip_restrict'] != $personaldata['ip_restrict']) {
			if (!ereg("^".$data['ip_restrict'],$REMOTE_ADDR))
				$error[$i++] = $T['err']['user']['ip_restrict'];

			$sql_query .= "ip_restrict='".$data['ip_restrict']."', ";
		}
		
		// Make sure we are not overwriting something:
		if ($personaldata['action'])
			$tmpaction = $personaldata['action'];
		else
			$tmpaction = 'update';
		
		//
		// Update Database
		
		if ($sql_query == "UPDATE users SET ") $error[$i++] = $T['err']['nothing to update'];
		else $sql_query .= "action='$tmpaction' WHERE username = '".$data['uid']."'";

		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			// Execute the db query
			mysql_query($sql_query);

			// create md5 signature and insert it.
			if (trim($data['username']))
				$userid = $data['username'];
			else
				$userid = $data['uid'];
			
			$hash = fetchdata("*","user",$userid);
			$hash['hash'] = $hash['time'] = $hash['ucount'] = '';
			$hash = crypt(md5(serialize($hash)), $cfg['key']);
			mysql_query("UPDATE users SET hash='$hash', ucount = ucount + 1 WHERE username = '$userid'");
			
			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"user updated: $userid",$REMOTE_ADDR);
			
			// Tell the system to commit the changes.
			commit("scan");
		}
	}
	// end 'update'
	///
	
	//
	// Suspend an user entry in the database
	elseif ($action == "suspend") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[id]		*REQUIRED* domain group id
		// 
		// 
		// Expected Input Data (from POST/GET)
		// ===============================
		// 
		// data[username]	username
		
		// Check update count
		if ($personaldata['ucount'] >= $cfg['ucount'])
			$error[$i++] = $T['err']['update count'];
			
		// Error if the user tries to suspend himself
		if ($data['username'] == $userdata['username'])
			$error[$i++] = $T['err']['user']['suspend myself'];
		
		// Username validity
		if (!eregi($rx['user'],$data['username']))
			$error[$i++] = $T['err']['user']['username'];
		
		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			// Execute the db query
			mysql_query("UPDATE users SET action='suspend' WHERE username = '".$data['username']."' AND id='".$data['id']."'");
			
			// create md5 signature and insert it.
			$hash = fetchdata("*","user",$data['username']);
			$hash['hash'] = $hash['time'] = $hash['ucount'] = '';
			$hash = crypt(md5(serialize($hash)), $cfg['key']);
			mysql_query("UPDATE users SET hash='$hash' WHERE username = '".$data['username']."' AND id='".$data['id']."'");
			
			// update ucount
			mysql_query("UPDATE domains SET ucount = ucount + 1 WHERE domain = '".$data['domain']."'");

			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"user suspended: ".$data['username'],$REMOTE_ADDR);
			
			// Tell the system to commit the changes.
			commit("scan");
		}
	}
	// end 'suspend'
	///
	
	//
	// Unsuspend an user entry in the database
	elseif ($action == "unsuspend") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[id]		*REQUIRED* domain group id
		// 
		// 
		// Expected Input Data (from POST/GET)
		// ===============================
		// 
		// data[username]	username

		// Username validity
		if (!eregi($rx['user'],$data['username']))
			$error[$i++] = $T['err']['user']['username'];
		
		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			// Execute the db query
			mysql_query("UPDATE users SET action='unsuspend',time='NOW()' WHERE username = '".$data['username']."' AND id='".$data['id']."'");
			
			// create md5 signature and insert it.
			$hash = fetchdata("*","user",$data['username']);
			$hash['hash'] = $hash['time'] = $hash['ucount'] = '';
			$hash = crypt(md5(serialize($hash)), $cfg['key']);
			mysql_query("UPDATE users SET hash='$hash' WHERE username = '".$data['username']."' AND id='".$data['id']."'");
			
			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"user unsuspended: ".$data['username'],$REMOTE_ADDR);
			
			// Tell the system to commit the changes.
			commit("scan");
		}
	}
	// end 'unsuspend'
	///
	
	//
	// Mark an user to be removed
	elseif ($action == "remove") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[id]		*REQUIRED* domain group id
		// 
		// 
		// Expected Input Data (from POST/GET)
		// ===============================
		// 
		// data[username]	username

		// Error if the user tries to remove himself
		if ($data['username'] == $userdata['username'])
			$error[$i++] = $T['err']['user']['remove myself'];
		
		// Username validity
		if (!eregi($rx['user'],$data['username']))
			$error[$i++] = $T['err']['user']['username'];
		
		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			// Execute the db query
			mysql_query("UPDATE users SET action='remove' WHERE username = '".$data['username']."' AND id='".$data['id']."'");
			
			// create md5 signature and insert it.
			$hash = fetchdata("*","user",$data['username']);
			$hash['hash'] = $hash['time'] = $hash['ucount'] = '';
			$hash = crypt(md5(serialize($hash)), $cfg['key']);
			mysql_query("UPDATE users SET hash='$hash' WHERE username = '".$data['username']."' AND id='".$data['id']."'");
			
			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"user suspended: ".$data['username'],$REMOTE_ADDR);
			
			// Tell the system to commit the changes.
			commit("scan");
		}
	}
}
		


// Function:	domain()
// Utility:	Create, Delete, Modify, Suspend, Unsuspend domainss; make sure everything is ok & secure
// Usage:	domain(ACTION,DATA,RETURN)
// Examples:	domain("create",$_POST);
//		domain("delete",$domain_id);
// Return:	$error		array var or nothing
// Definitions:	ACTION:		create, delete, modify, suspend, unsupend
//		DATA:		domain ID number, HTTP_POST_VARS, etc
// 		RETURN:		returns domain ID

function domain($action,$data,&$return) {
	// Get configurations, userdata, Language file, regex
	GLOBAL $userdata, $cfg, $T, $rx, $REMOTE_ADDR;
	
	// kill demo users (return error)
	if ($userdata['type'] == "demo") {
		$error[1] = $T['err']['demo user'];
		return $error;
	}

	// Set error 'counter'
	$i = 1;
	
	// Reset return val
	$return = '';
	
	//
	// Create a new domain entry in the database
	if ($action == "create") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[id]		*REQUIRED* reseller group id that will hold the domain [OR] domain id that hold a sub/pointer
		// data[type]		*REQUIRED* type of domain: domain,subdomain,pointer
		// 
		// 
		// Expected Input Data (from POST)
		// ===============================
		// * Optional
		// data[ip_addr]	IP Address, dedicated or shared.
		// data[path]		* Path to domain pointer
		// data[hostname]	Hostname (www)
		// data[domain]		Domain name (domain.com)
		// data[aliases]	* Hostname aliases; seperated by space, coma or new lines
		// data[catchall]	* Catch *.domain.com, removes all aliases, requires no sub-domains and will stop them.
		// data[nohost]		* Catch http://domain.com
		// data[redirect]	* Redirect *.domain.com or domain.com to [hostname].[domain] (to use with 2 opt. above)
		
		// data[email]		Domain Contact E-Mail Address
		// data[users]		* Number of users allowed
		// data[hd]		* HD Quota
		// data[subdomains]	* Number of subdomains allowed
		// data[pointers]	* Number of domain pointers allowed
		// data[transfer]	* Soft transfer limit (in GB)
		// data[databases]	* # Databases allowed.
		// data[bandwidth]	* Speed throttling with mod_bandwidth
		// data[serverside][x]	* Server Side languages. [x] is what's defined by $cfg['sslang'], cam be: on, off, na, ask
		// data[defaultroot]	* Default Domain's user root dir. Replaces %USER% by username
		// data[httpcustom]	* Custom Apache commands to be inserted at the end of the domain's config

		// Get some reseller data
		$id = substr($data['id'], 0, 5);
		$resellerdata = fetchdata("*","reseller",$id);
		$users = fetchdata("users","total",$id);
		$domains = fetchdata("domains","total",$id);
		$pointers = fetchdata("pointers","alloc",$id);
		$subdomains = fetchdata("subdomains","alloc",$id);
		$databases = fetchdata("databases","total",$id);
		$hd = fetchdata("hd","alloc",$id);
		
		// create unique 10 decimal ID, 5 from reseller, 5 random
		mt_srand((double)microtime()*1000000);
   		do
   			$num = mt_rand(10001,99999);
   		while (fetchdata("id","domain",$id.$num));
   		$num = $id.$num;
   		
		// IP Address validity
		if (eregi($rx['ip'],$data['ip_addr'])) {
			// check if it is in the reseller's ip pool
			if (!strstr(' '.$resellerdata['ip'].' ',' '.$data['ip_addr'].' '))
				$error[$i++] = $T['err']['domain']['ip address'];
		}
		else
			$error[$i++] = $T['err']['domain']['ip address'];
		// Set IP priority if this IP is unused
		$dbp = mysql_query("SELECT id FROM domains WHERE ip = '".$data['ip_addr']."'");
		if (!mysql_num_rows($dbp))
			$ippriority = 0;
		else
			$ippriority = 1;
		
		// Hostname validity
		$data['hostname'] = strtolower($data['hostname']);
		if (!ereg($rx['host'],$data['hostname']))
			$error[$i++] = $T['err']['domain']['hostname'];
		
		// Domain validity
		$data['domain'] = strtolower($data['domain']);
		if (!ereg($rx['dom'],$data['domain']))
			$error[$i++] = $T['err']['domain']['domain'];
		
		// E-Mail validity
		if (!eregi($rx['eml'],$data['email']))
			$error[$i++] = $T['err']['domain']['email'];
		
		// Check domain type & if its unique
		if ($data['type'] == "domain") {
			// Is this domain already taken?
			$dbp = mysql_query("SELECT id FROM domains WHERE domain = '".$data['domain']."'");
			if (mysql_num_rows($dbp))
				$error[$i++] = $T['err']['domain']['domain taken'];
		}
		elseif ($data['type'] == "subdomain") {
			if ($data['id'] < 1000000000)  
				$error[$i++] = $T['err']['domain']['invalid type'];
			// Is this subdomain already taken?
			$dbp = mysql_query("SELECT id FROM domains WHERE host = '".$data['hostname']."' AND domain = '".$data['domain']."'");
			if (mysql_num_rows($dbp))
				$error[$i++] = $T['err']['domain']['domain taken'];
		}
		elseif ($data['type'] == "pointer") {
			if ($data['id'] < 1000000000)  
				$error[$i++] = $T['err']['domain']['invalid type'];
			// Is this domain already taken?
			$dbp = mysql_query("SELECT id FROM domains WHERE host = '".$data['hostname']."' AND domain = '".$data['domain']."'");
			if (mysql_num_rows($dbp))
				$error[$i++] = $T['err']['domain']['domain taken'];
			else {
				// Cancel nohost, wildcard and redirect if there are more than one site under that domain
				$dbp = mysql_query("SELECT id,owner FROM domains WHERE domain = '".$data['domain']."'");
				if ($tmp = mysql_fetch_array($dbp)) {
					$data['catchall'] = "false";
					$data['nohost'] = "false";
					$data['redirect'] = "false";
					// Check if its under a domain we control
					if ($tmp['owner'] != $data['id'] AND $tmp['id'] != $data['id'])
						$error[$i++] = $T['err']['domain']['domain taken'];
				}
			}
		}
		else
			$error[$i++] = $T['err']['domain']['invalid type'];

		// Check update count
		$dbp = mysql_query("SELECT ucount FROM domains WHERE domain='".$data['domain']."'");
		$ucount = mysql_fetch_array($dbp);
		if ($ucount['ucount'] >= $cfg['ucount'])
			$error[$i++] = $T['err']['update count'];		

		// Check path if its a domain pointer
		if ($data['type'] == "pointer") {
			$data['path'] = ereg_replace("^/","",$data['path']);
			$data['path'] = ereg_replace("/$","",$data['path']);
			$dir = $cfg['webdir']."/".$data['id']."/".$data['path'];
			if (@!is_dir($dir))
				$error[$i++] = $T['err']['domain']['invalid path'];
			$data['path'] = $dir;
		}
		else $data['path'] = $cfg['webdir']."/$num";
		
		// Do we have a wildcard?
		if ($data['catchall'] == "true" AND $data['type'] != "subdomain") {
			// Remove other aliases	
			$data['aliases'] = "";
		}
		else $data['catchall'] = "false";
		
		// Check no host and domain redirect
		if ($data['nohost'] == "true") {
			if ($data['redirect'] != "true") $data['redirect'] = "false";
		}
		else {
			$data['nohost']= "false";
			$data['redirect'] = "false";
		}

		// Aliases validity, unique
		if ($data['aliases']) {
			$aliases = trim(ereg_replace("[;,]"," ",$data['aliases']));
			$aliases = split("[[:space:]]+",$aliases);
			if (is_array($aliases) AND trim($data['aliases'])) {
				do {
					// is it valid?
					if (eregi($rx['host'],current($aliases))) {
						// It must not be the same as our main host!
						if (current($aliases) == $data['hostname'])
							$error[$i++] = $T['err']['domain']['aliases'].current($aliases);
						
						// verify if its not used already
						$dbp = mysql_query("SELECT id FROM domains WHERE (host = '".current($aliases)."' OR aliases LIKE '% ".current($aliases)." %') AND domain = '".$data['domain']."'");
						if (mysql_num_rows($dbp))
							$error[$i++] = $T['err']['domain']['aliases'].current($aliases);
						
					}
					// not valid
					else
						$error[$i++] = $T['err']['domain']['aliases'].current($aliases);
				} while(next($aliases));
				
				// Reset $data['aliases'] to a correct value.  The trailing spaces are needed for fast searching (step above)
				$data['aliases'] = " ".trim(implode(" ",$aliases))." ";
				$data['aliases'] = ereg_replace("[[:space:]]+"," ",$data['aliases']);
			}
			// there is no aliases, unset it.
			else
				unset($data['aliases']);
		}
		
		// Check Server Sides (PHP, ASP, SSI, SSL, CGI/Perl, Python, etc.)
		// get list from config first.
		if (strstr($cfg['sslang'],",")) $sslang = explode(",",$cfg['sslang']);
		else $sslang[0] = $cfg['sslang'];
		
		$j = 0;
		unset($tmpdata);
		while ($sslang[$j]) {
			$tmp = $data['serverside'][trim($sslang[$j])];
			if ($tmp == "on" OR $tmp == "off" OR $tmp == "ask") {
				if ($resellerdata['serverside'][trim($sslang[$j])] == "on")
					$tmpdata[trim($sslang[$j])] = $tmp;
				else
					$tmpdata[trim($sslang[$j])] = "na";
			}
			else
				$tmpdata[trim($sslang[$j])] = "na";
			++$j;
		}
		$data['serverside'] = addslashes(serialize($tmpdata));
		
		// Verify Shell
		if ($data['shell'] == "on" OR $data['shell'] == "off" OR $data['shell'] == "ask") {
			if ($resellerdata['shell'] != "on")
				$data['shell'] = "off";
		}
		else $data['shell'] = "off";
				
		// Bandwidth check
		$data['bandwidth'] = intval($data['bandwidth']);
		
		// HTTP custom check: only for serveradmin+
		if ($data['httpcustom'] AND $userdata['level'] > 1) $data['httpcustom'] = "";
		else $data['httpcustom'] = addslashes($data['httpcustom']);
		
		// Check if enough domain, subdomains, pointers, users, hd space are availabe. Validate ['defaultroot'].
		if ($data['type'] == "domain") {
			// domain check
			$total = $resellerdata['domains'];
			$used = $domains['domains'];
			if (($total - $used) < 1) $error[$i++] = $T['err']['domain']['no domains'];

			// users
			$data['users'] = intval($data['users']);
			$total = $resellerdata['users'];
			$used = $users['users'];
			if (($total - $used) < $data['users']) $error[$i++] = $T['err']['domain']['no users'].intval($total - $used);
			if (!$data['users']) $error[$i++] = $T['err']['domain']['need user'];
			
			// subdomains
			$data['subdomains'] = intval($data['subdomains']);
			$total = $resellerdata['subdomains'];
			$used = $subdomains['subdomains'];
			if (($total - $used) < $data['subdomains']) $error[$i++] = $T['err']['domain']['no subdomains'].intval($total - $used);
			
			// pointers
			$data['pointers'] = intval($data['pointers']);
			$total = $resellerdata['pointers'];
			$used = $pointers['pointers'];
			if (($total - $used) < $data['pointers']) $error[$i++] = $T['err']['domain']['no pointers'].intval($total - $used);
			
			// hd space
			$data['hd'] = intval($data['hd']);
			$total = $resellerdata['hd'];
			$used = $hd['hd'];
			if (($total - $used) < $data['hd']) $error[$i++] = $T['err']['domain']['no hd'].intval($total - $used);
			if (!$data['hd']) $error[$i++] = $T['err']['domain']['need hd'].intval($total - $used);
			
			// transfer
			$data['transfer'] = intval($data['transfer']);
			$total = $resellerdata['transfer'];
			if ($total < $data['transfer']) $error[$i++] = $T['err']['domain']['no transfer'].$total;
			if (!$data['transfer']) $error[$i++] = $T['err']['domain']['need transfer'].intval($total - $used);
			
			// databases
			$data['databases'] = intval($data['databases']);
			$total = $resellerdata['db'];
			$used = $databases['databases'];
			if (($total - $used) < $data['databases']) $error[$i++] = $T['err']['domain']['no databases'].intval($total - $used);
			
			// default user root
			if ($data['defaultroot']) {
				unset($root);
				if (stristr($data['defaultroot'],"%USER%")) {
					$root = explode("%USER%",$data['defaultroot']);
					$defroot = $root[0];
					// make sure the user is created within /www/web or /www/data
					if (!strstr($defroot,"/".$data['hostname']."/".$cfg['webname']."/") AND !strstr($defroot,"/".$data['hostname']."/data/"))
						$error[$i++] = $T['err']['domain']['invalid user path'];
				}
				else 
					$defroot = $data['defaultroot'];
					
				$defroot = ereg_replace("^/","",$defroot);
				
				// construct real path
				$dir = $cfg['webdir']."/$num/".$defroot;
				
				if ($root)
					$data['defaultroot'] = $dir."%USER%".$root[1];
				else
					$data['defaultroot'] = $dir;
			}
					
			
			
		}
		else {
			$domdata = fetchdata("subdomains,pointers","domain",$data['id']);
			
			if ($data['type'] == 'subdomain') {
				$total = fetchdata("subdomains","total",$data['id']);
				if ($domdata['subdomains'] <= $total['subdomains'])
					$error[$i++] = $T['err']['domain']['no subdomain'];
			}
			if ($data['type'] == 'pointer') {
				$total = fetchdata("pointers","total",$data['id']);
				if ($domdata['pointers'] <= $total['pointers'])
					$error[$i++] = $T['err']['domain']['no pointer'];
			}
					
			$data['users'] = 0;
			$data['subdomains'] = 0;
			$data['databases'] = 0;
			$data['pointers'] = 0;
			$data['users'] = 0;
			$data['hd'] = 0;
			$data['transfer'] = 0;
			$data['defaultroot'] = "";
		}
		
		//
		// Insert into Database

		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			mysql_query("INSERT INTO domains SET id=$num, owner=".$data['id'].", priority=$ippriority, ip='".$data['ip_addr']."',host='".$data['hostname']."',
				host1='".$data['hostname']."', domain='".$data['domain']."', domain1='".$data['domain']."', aliases='".$data['aliases']."',
				catchall='".$data['catchall']."', nohost='".$data['nohost']."', redirect='".$data['redirect']."', path='".$data['path']."', 
				defaultroot='".$data['defaultroot']."', type='".$data['type']."', transfer='".$data['transfer']."', hd='".$data['hd']."', users='".$data['users']."',
				subdomains='".$data['subdomains']."', pointers='".$data['pointers']."', bandwidth='".$data['bandwidth']."',
				serverside='".$data['serverside']."', db='".$data['databases']."', shell='".$data['shell']."',
				email='".$data['email']."', httpcustom='".$data['httpcustom']."', action='create'");
			
			// create md5 signature and insert it.
			$hash = fetchdata("*","domain",$num);
			$hash['hash'] = $hash['time'] = $hash['ucount'] = '';
			$hash = crypt(md5(serialize($hash)), $cfg['key']);
			mysql_query("UPDATE domains SET hash='$hash' WHERE id = '$num'");

			// update ucount
			mysql_query("UPDATE domains SET ucount = ucount + 1 WHERE domain = '".$data['domain']."'");

			// Return ID in $return
			$return = $num;
			
			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"domain created: ".$data['hostname'].".".$data['domain'],$REMOTE_ADDR);
			
			// Tell the system to commit the changes.
			commit("scan");
		}
	}
	// end 'create'
	///
	
	//
	// Update a domain entry in the database
	elseif ($action == "update") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[id]		*REQUIRED* domain/sub/pointer id
		// 
		// 
		// Expected Input Data (from POST)
		// ===============================
		// All Optional
		// data[ip_addr]	IP Address, dedicated or shared.
		// data[path]		Path to domain pointer
		// data[hostname]	Hostname (www)
		// data[domain]		Domain name (domain.com)
		// data[aliases]	Hostname aliases; seperated by space, coma or new lines
		// data[catchall]	Catch *.domain.com, removes all aliases, requires no sub-domains and will stop them.
		// data[nohost]		Catch http://domain.com
		// data[redirect]	Redirect *.domain.com or domain.com to [hostname].[domain] (to use with 2 opt. above)
		// data[priority]	Domain IP Priority (first or not) true or false
		// data[email]		Domain Contact E-Mail Address
		// data[users]		Number of users allowed
		// data[hd]		HD Quota
		// data[subdomains]	Number of subdomains allowed
		// data[pointers]	Number of domain pointers allowed
		// data[transfer]	Soft transfer limit (in GB)
		// data[databases]	# Databases allowed.
		// data[bandwidth]	Speed throttling with mod_bandwidth
		// data[serverside][x]	Server Side languages. [x] is what's defined by $cfg['sslang'], cam be: on, off, na, ask
		// data[defaultroot]	Default Domain's user root dir. Replaces %USER% by username
		// data[ip_restrict]	IP restriction on the account.  Can match all or part of an IP Address.
		// data[httpcustom]	Custom Apache commands to be inserted at the end of the domain's config

		// Get some domain & reseller data
		$id = substr($data['id'], 0, 5);
		$resellerdata = fetchdata("*","reseller",$id);
		$domaindata = fetchdata("*","domain",$data['id']);
		
		// Get current reseller usage for validation
		$users = fetchdata("users","alloc",$id);
		$pointers = fetchdata("pointers","alloc",$id);
		$subdomains = fetchdata("subdomains","alloc",$id);
		$databases = fetchdata("databases","alloc",$id);
		$hd = fetchdata("hd","alloc",$id);
		
		// Check update count
		$dbp = mysql_query("SELECT ucount FROM domains WHERE domain='".$domaindata['domain']."'");
		$ucount = mysql_fetch_array($dbp);
		if ($ucount['ucount'] >= $cfg['ucount'])
			$error[$i++] = $T['err']['update count'];
		
		// **** Remove Doubles ($data already in the db) & create SQL query as we check input
		$sql_query = "UPDATE domains SET ";
		
		//
		// Verify input $data
		
		
		// IP Address validity
		if (trim($data['ip_addr']) AND $data['ip_addr'] != $domaindata['ip']) {
			if (eregi($rx['ip'],$data['ip_addr'])) {
				// check if it is in the reseller's ip pool
				if (!strstr(' '.$resellerdata['ip'].' ',' '.$data['ip_addr'].' '))
					$error[$i++] = $T['err']['domain']['ip address'];
			}
			else
				$error[$i++] = $T['err']['domain']['ip address'];
				
			$sql_query .= "ip='".$data['ip_addr']."', ";
		}
		
		// Hostname validity
		if (trim($data['hostname']) AND $data['hostname'] != $domaindata['host']) {
			$data['hostname'] = strtolower($data['hostname']);
			if (!ereg($rx['host'],$data['hostname']))
				$error[$i++] = $T['err']['domain']['hostname'];
			
			$sql_query .= "host='".$data['hostname']."', ";
		}
		
		// Domain validity
		if (trim($data['domain']) AND $data['domain'] != $domaindata['domain']) {
			$data['domain'] = strtolower($data['domain']);
			if (ereg($rx['dom'],$data['domain'])) {
				if ($domaindata['type'] == "domain") {
					// Is this domain already taken?
					$dbp = mysql_query("SELECT id FROM domains WHERE domain = '".$data['domain']."'");
					if (mysql_num_rows($dbp))
						$error[$i++] = $T['err']['domain']['domain taken'];
				}
				elseif ($domaindata['type'] == "pointer") {
					// Is this domain already taken?
					$dbp = mysql_query("SELECT id FROM domains WHERE host = '".$data['hostname']."' AND domain = '".$data['domain']."'");
					if (mysql_num_rows($dbp))
						$error[$i++] = $T['err']['domain']['domain taken'];
					else {
						// Cancel nohost, wildcard and redirect if there are more than one site under that domain
						$dbp = mysql_query("SELECT id,owner FROM domains WHERE domain = '".$data['domain']."'");
						if ($tmp = mysql_fetch_array($dbp)) {
							$data['catchall'] = "false";
							$data['nohost'] = "false";
							$data['redirect'] = "false";
							// Check if its under a domain we control
							if ($tmp['owner'] != $domaindata['owner'] AND $tmp['id'] != $domaindata['owner'])
								$error[$i++] = $T['err']['domain']['domain taken'];
						}
					}
				}
				else
					$data['domain'] = $domaindata['domain'];
					
			} else
				$error[$i++] = $T['err']['domain']['domain'];
			
			$sql_query .= "domain='".$data['domain']."', ";
		}
		
		// Domain Priority validity
		if (trim($data['priority'])) {
			if ($data['priority'] == "true") $data['priority'] = 0;
			else $data['priority'] = 1;
			
			if ($data['priority'] != $domaindata['priority']) {
				
				if ($data['priority'] == 0) {
					// Check if another domain has priority already, if so error.
					$dbp = mysql_query("SELECT host,domain FROM domains WHERE ip='".$data['ip_addr']."' AND priority=0");
					
					if ($tmp = mysql_fetch_array($dbp))
						$error[$i++] = $T['err']['domain']['priority'].$tmp['host'].'.'.$tmp['domain'];
				}
				$sql_query .= "priority='".$data['priority']."', ";
			}
		}
		
		// E-Mail contact validity
		if (trim($data['email']) AND $data['email'] != $domaindata['email']) {
			if (!eregi($rx['eml'],$data['email']))
				$error[$i++] = $T['err']['domain']['email'];
				
			$sql_query .= "email='".$data['email']."', ";
		}
		
		// Check path if its a domain pointer
		if (trim($data['path']) AND $data['path'] != $domaindata['path']) {
			if ($domaindata['type'] == "pointer") {
				$data['path'] = ereg_replace("^/","",$data['path']);
				$data['path'] = ereg_replace("/$","",$data['path']);
				$dir = $cfg['webdir']."/".$domaindata['owner']."/".$data['path'];
				if (@!is_dir($dir))
					$error[$i++] = $T['err']['domain']['invalid path'];
				$sql_query .= "path='".$dir."', ";
			}
		}

		
		// Do we have a wildcard?
		if (trim($data['catchall']) AND $data['catchall'] != $domaindata['catchall']) {
			if ($domaindata['type'] != "subdomain") {
				// Remove other aliases	
				$data['aliases'] = "";
				
				if ($data['catchall'] == "true" OR $data['catchall'] == "false")
					$sql_query .= "catchall='".$data['catchall']."', ";
			}
		}

		
		// Check no host and domain redirect
		if (trim($data['nohost']) AND $data['nohost'] != $domaindata['nohost']) {
			if ($data['nohost'] == "true" OR $data['nohost'] == "false")
				$sql_query .= "nohost='".$data['nohost']."', ";
		}
		if ($data['nohost'] == "false") $data['redirect'] = "false";
		if (trim($data['redirect']) AND $data['redirect'] != $domaindata['redirect']) {
			if ($data['redirect'] == "true" OR $data['redirect'] == "false")
				$sql_query .= "redirect='".$data['redirect']."', ";
		}
				
		
		// Aliases validity, unique
		if (isset($data['aliases']) AND $data['aliases'] != $domaindata['aliases']) {
			if ($data['aliases']) {
				$aliases = split("([[:space:]]+,?|[[:space:]]*,)",$data['aliases']);
				if (is_array($aliases)) {
					do {
						// is it valid?
						if (eregi($rx['host'],current($aliases))) {
							// It must not be the same as our main host!
							if (current($aliases) == $data['hostname'])
								$error[$i++] = $T['err']['domain']['aliases'].current($aliases);
							
							// verify if its not used already
							$dbp = mysql_query("SELECT id FROM domains WHERE (host = '".current($aliases)."' OR aliases LIKE '% ".current($aliases)." %') AND domain = '".$data['domain']."' AND id != '".$data['id']."'");
							if (mysql_num_rows($dbp))
								$error[$i++] = $T['err']['domain']['aliases'].current($aliases);
							
						}
						// not valid
						else
							$error[$i++] = $T['err']['domain']['aliases'].current($aliases);
					} while(next($aliases));
					
					// Reset $data['aliases'] to a correct value.  The trailing spaces are needed for fast searching (step above)
					// See if it needs an update
					$data['aliases'] = trim(implode(" ",$aliases));
					$data['aliases'] = ereg_replace("[[:space:]]+"," ",$data['aliases']);
				}
			}
			
			if ($data['aliases'] != $domaindata['aliases'])
				$sql_query .= "aliases=' ".$data['aliases']." ', ";
		}
		
		// Check Server Sides (PHP, ASP, SSI, SSL, CGI/Perl, Python, etc.)
		// get list from config first.
		if (strstr($cfg['sslang'],",")) $sslang = explode(",",$cfg['sslang']);
		else $sslang[0] = $cfg['sslang'];
		
		if ($data['serverside']) {
			$j = 0;
			unset($tmpdata);
			while ($sslang[$j]) {
				$tmp = $data['serverside'][trim($sslang[$j])];
				if (($tmp == "on" OR $tmp == "off") AND $resellerdata['serverside'][trim($sslang[$j])] == "on")
					$tmpdata[trim($sslang[$j])] = $tmp;
				else
					$tmpdata[trim($sslang[$j])] = "na";
				++$j;
			}
			$data['serverside'] = addslashes(serialize($tmpdata));
			
			// re-serialize domaindata['serverside'] to see if its different than our 'new' serverside
			$tmp = addslashes(serialize($domaindata['serverside']));
			
			if ($data['serverside'] != $tmp)
				$sql_query .= "serverside='".$data['serverside']."', ";
		}
		
		// Verify Shell
		if (trim($data['shell'])) {
			if ($data['shell'] == "on" OR $data['shell'] == "off" OR $data['shell'] == "ask") {
				if ($resellerdata['shell'] != "on")
					$data['shell'] = "off";
			}
			else $data['shell'] = "off";
			
			if ($data['shell'] != $domaindata['shell'])
				$sql_query .= "shell='".$data['shell']."', ";
		}	
		// Bandwidth check
		if (trim($data['bandwidth']) AND $data['bandwidth'] != $domaindata['bandwidth']) {
			$data['bandwidth'] = intval($data['bandwidth']);
			
			$sql_query .= "bandwidth='".$data['bandwidth']."', ";
		}
		
		
		// HTTP custom check: only for serveradmin+
		if ($data['httpcustom'] AND $userdata['level'] > 1)
			unset($data['httpcustom']);
		else
			$data['httpcustom'] = trim(addslashes($data['httpcustom']));
		if ($data['httpcustom'] != $domaindata['httpcustom']);
			$sql_query .= "httpcustom='".$data['httpcustom']."', ";
		
		// IP Restriction Check 
		if (isset($data['ip_restrict']) AND $data['ip_restrict'] != $domaindata['ip_restrict']) {
			if (!ereg("^".$data['ip_restrict'],$REMOTE_ADDR))
				$error[$i++] = $T['err']['domain']['ip_restrict'];

			$sql_query .= "ip_restrict='".$data['ip_restrict']."', ";
		}
		
		// Check if enough domain, subdomains, pointers, users, hd space are availabe. Validate ['defaultroot'].
		if ($domaindata['type'] == "domain") {
			// users
			if (isset($data['users']) AND $data['users'] != $domaindata['users']) {
				$data['users'] = intval($data['users']);
				$total = $resellerdata['users'];
				$used = $users['users'];
				$current = $domaindata['users'];
				if (($total - $used + $current) < $data['users'])
					 $error[$i++] = $T['err']['domain']['no users'].intval($total - $used);
				// Can't have 0 users
				if (!$data['users']) $error[$i++] = $T['err']['domain']['need user'];
				
				$sql_query .= "users=".$data['users'].", ";
			}
			
			// subdomains
			if (isset($data['subdomains']) AND $data['subdomains'] != $domaindata['subdomains']) {
				$data['subdomains'] = intval($data['subdomains']);
				$total = $resellerdata['subdomains'];
				$used = $subdomains['subdomains'];
				$current = $domaindata['subdomains'];
				if (($total - $used + $current) < $data['subdomains'])
					$error[$i++] = $T['err']['domain']['no subdomains'].intval($total - $used);
				
				$sql_query .= "subdomains=".$data['subdomains'].", ";
			}
			
			// pointers
			if (isset($data['pointers']) AND $data['pointers'] != $domaindata['pointers']) {
				$data['pointers'] = intval($data['pointers']);
				$total = $resellerdata['pointers'];
				$used = $pointers['pointers'];
				$current = $domaindata['pointers'];
				if (($total - $used + $current) < $data['pointers'])
					$error[$i++] = $T['err']['domain']['no pointers'].intval($total - $used);
				
				$sql_query .= "pointers='".$data['pointers']."', ";
			}
		
			// hd space
			if (isset($data['hd']) AND $data['hd'] != $domaindata['hd']) {
				$data['hd'] = intval($data['hd']);
				$total = $resellerdata['hd'];
				$used = $hd['hd'];
				$current = $domaindata['hd'];
				if (($total - $used + $current) < $data['hd'])
					$error[$i++] = $T['err']['domain']['no hd'].intval($total - $used);
				// Can't have 0 HD space
				if (!$data['hd']) $T['err']['domain']['need hd'].intval($total - $used);
				
				$sql_query .= "hd='".$data['hd']."', ";
			}
			
			// transfer
			if (isset($data['transfer']) AND $data['transfer'] != $domaindata['transfer']) {
				$data['transfer'] = intval($data['transfer']);
				$used = $data['transfer'];
				$total = $resellerdata['transfer'];
				if ($total < $used)
					$error[$i++] = $T['err']['domain']['no transfer'].$total;
				if (!$data['transfer']) $T['err']['domain']['need transfer'].intval($total - $used);
				
				$sql_query .= "transfer='".$data['transfer']."', ";
			}
			
			// databases
			if (isset($data['databases']) AND $data['databases'] != $domaindata['databases']) {
				$data['databases'] = intval($data['databases']);
				$total = $resellerdata['db'];
				$used = $databases['databases'];
				$current = $domaindata['db'];
				if (($total - $used + $current) < $data['databases'])
					$error[$i++] = $T['err']['domain']['no databases'].intval($total - $used);
				
				$sql_query .= "db='".$data['databases']."', ";
			}
			
			// default user root
			if (isset($data['defaultroot'])) {
				if (!trim($data['defaultroot']))
					$data['defaultroot'] = '/';
				
				unset($root);
				if (stristr($data['defaultroot'],"%USER%")) {
					$root = explode("%USER%",$data['defaultroot']);
					$defroot = $root[0];
					// make sure the user is created within /www/web or /www/data
					if (!strstr($defroot,"/".$data['hostname']."/".$cfg['webname']."/") AND !strstr($defroot,"/".$data['hostname']."/data/"))
						$error[$i++] = $T['err']['domain']['invalid user path'];
					
				}
				else 
					$defroot = $data['defaultroot'];
				
				$defroot = ereg_replace("^/","",$defroot);
				
				// construct real path & verify it
				$dir = $cfg['webdir']."/".$data['id']."/".$defroot;
				
				if (@!is_dir($dir))
					$error[$i++] = $T['err']['domain']['invalid user path'];
				else {
					if ($root)
						$data['defaultroot'] = $dir."%USER%".$root[1];
					else
						$data['defaultroot'] = $dir;
				}
				
				if ($data['defaultroot'] != $domaindata['defaultroot'])
					$sql_query .= "defaultroot='".$data['defaultroot']."', ";

			}
		}
		
		// Make sure we are not overwriting something:
		if ($domaindata['action'])
			$tmpaction = $domaindata['action'];
		else
			$tmpaction = 'update';
		
		//
		// Update Database
		
		if ($sql_query == "UPDATE domains SET ") $error[$i++] = $T['err']['nothing to update'];
		else $sql_query .= "action='$tmpaction' WHERE id = '".$data['id']."'";
		
		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			mysql_query($sql_query);
			
			// create md5 signature and insert it.
			$hash = fetchdata("*","domain",$data['id']);
			$hash['hash'] = $hash['time'] = $hash['ucount'] = '';
			$hash = crypt(md5(serialize($hash)), $cfg['key']);
			mysql_query("UPDATE domains SET hash='$hash' WHERE id = '".$data['id']."'");

			// update ucount
			mysql_query("UPDATE domains SET ucount = ucount + 1 WHERE domain = '".$data['domain']."'");

			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"domain updated: ".$data['hostname'].".".$data['domain']." [".$data['id']."]",$REMOTE_ADDR);
			
			// Tell the system to commit the changes.
			commit("scan");
		}
	}
	// end 'update'
	///
	
	//
	// Suspend a domain entry in the database
	elseif ($action == "suspend") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[owner]		*REQUIRED* reseller id
		// 
		// 
		// Expected Input Data (from POST/GET)
		// ===============================
		// 
		// data[id]		domain ID
		
		// Check update count
		$domain = fetchdata("domain","domain",$data['id']);
		$dbp = mysql_query("SELECT ucount FROM domains WHERE domain='".$domain['domain']."'");
		$ucount = mysql_fetch_array($dbp);
		if ($ucount['ucount'] >= $cfg['ucount'])
			$error[$i++] = $T['err']['update count'];
		
		// Error if the user tries to suspend his own domain
		if ($data['id'] == $userdata['id'])
			$error[$i++] = $T['err']['domain']['suspend myself'];
		
		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {	
			// Execute the db query
			mysql_query("UPDATE domains SET action='suspend' WHERE id = '".$data['id']."' AND owner='".$data['owner']."'");
			
			// create md5 signature and insert it.
			$hash = fetchdata("*","domain",$data['id']);
			$hash['hash'] = $hash['time'] = $hash['ucount'] = '';
			$hash = crypt(md5(serialize($hash)), $cfg['key']);
			mysql_query("UPDATE domains SET hash='$hash' WHERE id = '".$data['id']."' AND owner='".$data['owner']."'");
			
			// update ucount
			$domain = fetchdata("domain","domain",$data['id']);
			mysql_query("UPDATE domains SET ucount = ucount + 1 WHERE domain = '".$domain['domain']."'");

			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"domain suspended: ".$data['id'],$REMOTE_ADDR);
			
			// Tell the system to commit the changes.
			commit("scan");
		}
	}
	// end 'suspend'
	///
	
	//
	// Unsuspend a domain entry in the database
	elseif ($action == "unsuspend") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[owner]		*REQUIRED* reseller id
		// 
		// 
		// Expected Input Data (from POST/GET)
		// ===============================
		// 
		// data[id]		domain ID

		// Execute the db query
		mysql_query("UPDATE domains SET action='unsuspend' WHERE id = '".$data['id']."' AND owner='".$data['owner']."'");
		
		// create md5 signature and insert it.
		$hash = fetchdata("*","domain",$data['id']);
		$hash['hash'] = $hash['time'] = $hash['ucount'] = '';
		$hash = crypt(md5(serialize($hash)), $cfg['key']);
		mysql_query("UPDATE domains SET hash='$hash' WHERE id = '".$data['id']."' AND owner='".$data['owner']."'");

		// Log it
		webcp_log(2,$userdata['id'],$userdata['username'],"domain unsuspended: ".$data['id'],$REMOTE_ADDR);
		
		// Tell the system to commit the changes.
		commit("scan");
	}
	// end 'unsuspend'
	///
	
	//
	// Mark a domain to be removed
	elseif ($action == "remove") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[owner]		*REQUIRED* reseller id
		// 
		// 
		// Expected Input Data (from POST/GET)
		// ===============================
		// 
		// data[id]		domain ID
		
		// Error if the user tries to remove his own domain
		if ($data['id'] == $userdata['id'])
			$error[$i++] = $T['err']['domain']['remove myself'];
			
		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			// Execute the db query
			mysql_query("UPDATE domains SET action='remove' WHERE id = '".$data['id']."' AND owner='".$data['owner']."'");
			
			// create md5 signature and insert it.
			$hash = fetchdata("*","domain",$data['id']);
			$hash['hash'] = $hash['time'] = $hash['ucount'] = '';
			$hash = crypt(md5(serialize($hash)), $cfg['key']);
			mysql_query("UPDATE domains SET hash='$hash' WHERE id = '".$data['id']."' AND owner='".$data['owner']."'");
			
			// update ucount
			$domain = fetchdata("domain","domain",$data['id']);
			mysql_query("UPDATE domains SET ucount = ucount + 1 WHERE domain = '".$domain['domain']."'");

			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"domain removed: ".$data['id'],$REMOTE_ADDR);
			
			// Tell the system to commit the changes.
			commit("scan");
		}
	}
	// end 'remove'
	///
}



// Function:	reseller()
// Utility:	Create, Delete, Modify, Suspend, Unsuspend resellers; make sure everything is ok & secure
// Usage:	reseller(ACTION,DATA,RETURN)
// Examples:	reseller("create",$_POST);
//		reseller("delete",$rid);
// Return:	$error		array var or nothing
// Definitions:	ACTION:		create, delete, modify, suspend, unsupend
//		DATA:		reseller id, HTTP_POST_VARS, etc
//		RETURN:		returns reseller ID

function reseller($action,$data,&$return) {
	// Get configurations, userdata, Language file, regex
	GLOBAL $userdata, $cfg, $T, $rx, $REMOTE_ADDR;
	
	// kill demo users (return error)
	if ($userdata['type'] == "demo") {
		$error[1] = $T['err']['demo user'];
		return $error;
	}
	
	// Set error 'counter'
	$i = 1;
	
	// Reset return val
	$return = '';
	
	//
	// Create a new reseller entry in the database
	if ($action == "create") {
		// Expected Input Data (from POST)
		// ===============================
		// * Optional
		// data[name]		Reseller Name
		// data[email]		Contact E-Mail
		// data[ip]		IP Addresse(s) : single, multiple seperated by space or coma
		// data[domains]	Number of domains.  Can't be 0
		// data[subdomains]	* Number of subdomains.  Can be 0
		// data[pointers]	* Number of domain pointers.  Can be 0
		// data[hd]		HD Quota.  Can't be 0
		// data[users]		Number of users.  Can't be 0
		// data[transfer]	Transfer Soft Quota.  Can't be 0
		// data[shell]		on,off
		// data[bandwidth]	* Bandwidth (mod_bandwidth).  Can be 0
		// data[serverside]	* Serverside http options (php, asp, ssi, ssl, etc)
		// data[databases]	* Number of databases.  Can be 0
		// data[skin]		* User Interface skin. free choice: 'any' or specify a skin name

		//
		// Verify input $data
		
		// Generate new reseller ID number
		mt_srand((double)microtime()*1000000);
   		do
   			$num = mt_rand(10001,99999);
   		while (fetchdata("id","reseller",$num));
     		
		// Name validity
		if (!eregi($rx['name'],$data['name']))
			$error[$i++] = $T['err']['reseller']['name'];
		
		// E-Mail validity
		if (!eregi($rx['eml'],$data['email']))
			$error[$i++] = $T['err']['reseller']['email'];
		
		// Handle IP Addresses
		$ip = split("([[:space:]]+,?|[[:space:]]*,)",$data['ip']);
		if (is_array($ip))
			$data['ip'] = implode(" ",$ip);
		$data['ip'] = ' '.trim($data['ip']).' ';
		
		// Num Domains
		$data['domains'] = intval($data['domains']);
		if (!$data['domains'])
			$error[$i++] = $T['err']['reseller']['need domains'];
		
		// Num Users
		$data['users'] = intval($data['users']);
		if (!$data['users'])
			$error[$i++] = $T['err']['reseller']['need users'];
			
		// Num Domain Pointers
		$data['pointers'] = intval($data['pointers']);
		
		// Num Subdomains
		$data['subdomains'] = intval($data['subdomains']);
		
		// Num Databases
		$data['databases'] = intval($data['databases']);
		
		// HD Quota
		$data['hd'] = intval($data['hd']);
		if (!$data['hd'])
			$error[$i++] = $T['err']['reseller']['need hd'];
			
		// Transfer Quota
		$data['transfer'] = intval($data['transfer']);
		if (!$data['transfer'])
			$error[$i++] = $T['err']['reseller']['need transfer'];
			
		// Bandwidth
		array_key_exists("bandwidth", $data) && $data['bandwidth'] = intval($data['bandwidth']);
		
		// Check Shell
		if ($data['shell'] != 'on')
			$data['shell'] = 'off';
		
		// Check Skin
		if (!array_key_exists("skin", $data) OR !file_exists("skin/".$data['skin']))
			$data['skin'] = "any";
		
		// Check Server Sides (PHP, ASP, SSI, SSL, CGI/Perl, Python, etc.)
		// get list from config first.
		if (strstr($cfg['sslang'],",")) $sslang = explode(",",$cfg['sslang']);
		else $sslang[0] = $cfg['sslang'];
		
		// Check serverside
		$j = 0;
		unset($tmpdata);
		while (isset($sslang[$j])) {
			if ($data['serverside'][trim($sslang[$j])] == "on")
				$tmpdata[trim($sslang[$j])] = "on";
			else
				$tmpdata[trim($sslang[$j])] = "off";
			++$j;
		}
		$data['serverside'] = addslashes(serialize($tmpdata));
		
		// Insert into database
		if (is_array($error)) return $error;
		else {
			mysql_query("INSERT INTO resellers SET id='$num', name='".addslashes($data['name'])."', email='".$data['email']."', ip='".$data['ip']."', domains='".$data['domains']."',
				subdomains='".$data['subdomains']."', pointers='".$data['pointers']."', users='".$data['users']."', hd='".$data['hd']."',
				transfer='".$data['transfer']."', bandwidth='".$data['bandwidth']."', serverside='".$data['serverside']."', db='".$data['databases']."', 
				shell='".$data['shell']."', skin='".$data['skin']."', lastchange=NOW()");
			
			// Return ID in $return
			$return = $num;
			
			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"reseller created: ".$data['name'],$REMOTE_ADDR);
		}
	}
	
	//
	// Update a reseller entry in the database
	elseif ($action == "update") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[id]		*REQUIRED* reseller id
		// 
		// 
		// Expected Input Data (from POST)
		// ===============================
		// * All Optional
		// data[name]		Reseller Name
		// data[email]		Contact E-Mail
		// data[ip]		IP Addresse(s) : single, multiple seperated by space or coma
		// data[domains]	Number of domains.  Can't be 0
		// data[subdomains]	Number of subdomains.  Can be 0
		// data[pointers]	Number of domain pointers.  Can be 0
		// data[hd]		HD Quota.  Can't be 0
		// data[users]		Number of users.  Can't be 0
		// data[transfer]	Transfer Soft Quota.  Can't be 0
		// data[shell]		on,off
		// data[bandwidth]	Bandwidth (mod_bandwidth).  Can be 0
		// data[serverside]	Serverside http options (php, asp, ssi, ssl, etc)
		// data[databases]	Number of databases.  Can be 0
		// data[skin]		User Interface skin. free choice: 'any' or specify a skin name

		// Fetch current resellerdata
		$resellerdata = fetchdata("*","reseller",$data['id']);
		
		// **** Remove Doubles ($data already in the db) & create SQL query as we check input
		$sql_query = "UPDATE resellers SET ";
		
		//
		// Verify input $data
		
		
		// Name validity
		if (isset($data['name']) AND $data['name'] != $resellerdata['name']) {
			if (!eregi($rx['name'],$data['name']))
				$error[$i++] = $T['err']['reseller']['name'];
			
			$sql_query .= "name='".addslashes($data['name'])."', ";
		}
		
		// E-Mail validity
		if (isset($data['email']) AND $data['email'] != $resellerdata['email']) {
			if (!eregi($rx['eml'],$data['email']))
				$error[$i++] = $T['err']['reseller']['email'];
			
			$sql_query .= "email='".$data['email']."', ";
		}
		// Handle IP Addresses
		if (isset($data['ip']) AND $data['ip'] != $resellerdata['ip']) {
			$ip = split("([[:space:]]+,?|[[:space:]]*,)",$data['ip']);
			if (is_array($ip))
				$data['ip'] = implode(" ",$ip);
			$data['ip'] = ' '.trim($data['ip']).' ';
			
			$sql_query .= "ip='".$data['ip']."', ";
		}
		
		// Num Domains
		if (isset($data['domains']) AND $data['domains'] != $resellerdata['domains']) {
			$data['domains'] = intval($data['domains']);
			if (!$data['domains'])
				$error[$i++] = $T['err']['reseller']['need domains'];
			
			$sql_query .= "domains='".$data['domains']."', ";
		}
		
		// Num Users
		if (isset($data['users']) AND $data['users'] != $resellerdata['users']) {
			$data['users'] = intval($data['users']);
			if (!$data['users'])
				$error[$i++] = $T['err']['reseller']['need users'];
			
			$sql_query .= "users='".$data['users']."', ";
		}
		
		// Num Domain Pointers
		if (isset($data['pointers']) AND $data['pointers'] != $resellerdata['pointers']) {
			$data['pointers'] = intval($data['pointers']);
			$sql_query .= "pointers='".$data['pointers']."', ";
		}
		
		// Num Subdomains
		if (isset($data['subdomains']) AND $data['subdomains'] != $resellerdata['subdomains']) {
			$data['subdomains'] = intval($data['subdomains']);
			$sql_query .= "subdomains='".$data['subdomains']."', ";
		}
		
		// Num Databases
		if (isset($data['databases']) AND $data['databases'] != $resellerdata['db']) {
			$data['databases'] = intval($data['databases']);
			$sql_query .= "db='".$data['databases']."', ";
		}
		
		// HD Quota
		if (isset($data['hd']) AND $data['hd'] != $resellerdata['hd']) {
			$data['hd'] = intval($data['hd']);
			if (!$data['hd'])
				$error[$i++] = $T['err']['reseller']['need hd'];
			
			$sql_query .= "hd='".$data['hd']."', ";
		}
			
		// Transfer Quota
		if (isset($data['transfer']) AND $data['transfer'] != $resellerdata['transfer']) {
			$data['transfer'] = intval($data['transfer']);
			if (!$data['transfer'])
				$error[$i++] = $T['err']['reseller']['need transfer'];
			
			$sql_query .= "transfer='".$data['transfer']."', ";
		}
		
		// Bandwidth
		if (isset($data['ip']) AND $data['ip'] != $resellerdata['ip']) {
			$data['bandwidth'] = intval($data['bandwidth']);
			$sql_query .= "ip='".$data['ip']."', ";
		}
		
		// Check Shell
		if (isset($data['shell']) AND $data['shell'] != $resellerdata['shell']) {
			if ($data['shell'] != 'on')
				$data['shell'] = 'off';
			
			$sql_query .= "shell='".$data['shell']."', ";
		}
		
		// Check Skin
		if (isset($data['skin']) AND $data['skin'] != $resellerdata['skin']) {
			if (!trim($data['skin']) OR !file_exists("skin/".$data['skin']))
				$data['skin'] = "any";
			
			$sql_query .= "skin='".$data['skin']."', ";
		}
		
		// Check Server Sides (PHP, ASP, SSI, SSL, CGI/Perl, Python, etc.)
		// get list from config first.
		if (strstr($cfg['sslang'],",")) $sslang = explode(",",$cfg['sslang']);
		else $sslang[0] = $cfg['sslang'];
		
		// Check serverside
		if ($data['serverside']) {
			$j = 0;
			unset($tmpdata);
			while ($sslang[$j]) {
				if ($data['serverside'][trim($sslang[$j])] == "on")
					$tmpdata[trim($sslang[$j])] = "on";
				else
					$tmpdata[trim($sslang[$j])] = "off";
				++$j;
			}
			$data['serverside'] = addslashes(serialize($tmpdata));
			
			// re-serialize domaindata['serverside'] to see if its different than our 'new' serverside
			$tmp = addslashes(serialize($resellerdata['serverside']));
			
			if ($data['serverside'] != $tmp)
				$sql_query .= "serverside='".$data['serverside']."', ";
		}
		
		// Check if there is anything to update
		if ($sql_query == "UPDATE resellers SET ") $error[$i++] = $T['err']['nothing to update'];
		else $sql_query .= "lastchange=NOW() WHERE id = '".$data['id']."'";
		
		// Insert into database
		if (is_array($error)) return $error;
		else {
			mysql_query($sql_query);
		
			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"reseller updated: ".$data['name'],$REMOTE_ADDR);
		}
	}
	
	//
	// Suspend a reseller (suspend its domains which in turn suspend their users)
	elseif ($action == "suspend") {
		// Expected Input Data (from POST/GET)
		// ===============================
		// 
		// data[id]		reseller ID
		//
		
		// Error if the user tries to suspend his own reseller
		if ($data['id'] == substr($userdata['id'], 0, 5))
			$error[$i++] = $T['err']['reseller']['suspend myself'];
		
		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			// fetch domain IDs under this reseller and suspend them
			$dbp = mysql_query("SELECT id,owner FROM domains WHERE owner = '".$data['id']."'");
			while ($ddata = mysql_fetch_array($dbp))
				domain("suspend",$ddata,$return);
			
			// Insert into database
			mysql_query("UPDATE resellers SET hold='true' WHERE id = '".$data['id']."'");
			
			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"reseller suspended: ".$data['id'],$REMOTE_ADDR);
		}
	}
		
	
	//
	// Unsuspend a reseller (unsuspend its domains which in turn unsuspend their users)
	elseif ($action == "unsuspend") {
		// Expected Input Data (from POST/GET)
		// ===============================
		// 
		// data[id]		reseller ID
		//
		
		// fetch domain IDs under this reseller and suspend them
		$dbp = mysql_query("SELECT id,owner FROM domains WHERE owner = '".$data['id']."'");
		while ($ddata = mysql_fetch_array($dbp))
			domain("unsuspend",$ddata,$return);
		
		// Insert into database
		mysql_query("UPDATE resellers SET hold='false' WHERE id = '".$data['id']."'");

		// Log it
		webcp_log(2,$userdata['id'],$userdata['username'],"reseller reactivated: ".$data['id'],$REMOTE_ADDR);

	}
	
	//
	// Remove a reseller (remove its domains which in turn remove their users)
	elseif ($action == "remove") {
		// Expected Input Data (from POST/GET)
		// ===============================
		// 
		// data[id]		reseller ID
		//
		
		// Error if the user tries to suspend his own reseller
		if ($data['id'] == substr($userdata['id'], 0, 5))
			$error[$i++] = $T['err']['reseller']['remove myself'];
		
		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			// fetch domain IDs under this reseller and set them to be removed
			$dbp = mysql_query("SELECT id,owner FROM domains WHERE owner = '".$data['id']."'");
			while ($ddata = mysql_fetch_array($dbp))
				domain("remove",$ddata,$return);
			
			// Remove from database
			mysql_query("DELETE FROM resellers WHERE id = '".$data['id']."'");
	
			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"reseller removed: ".$data['id'],$REMOTE_ADDR);
		}
	}
}
		

// Function:	database()
// Utility:	Create, Delete, Modify, Suspend, Unsuspend databases; make sure everything is ok & secure
// Usage:	database(ACTION,DATA)
// Examples:	database("create",$_POST);
//		database("delete",$rid);
// Return:	$error		array var or nothing
// Definitions:	ACTION:		create, delete, modify, suspend, unsupend
//		DATA:		database name, HTTP_POST_VARS, etc

function database($action,$data,&$return) {
	// Get configurations, userdata, Language file, regex
	GLOBAL $userdata, $cfg, $T, $rx, $REMOTE_ADDR;
	
	// kill demo users (return error)
	if ($userdata['type'] == "demo") {
		$error[1] = $T['err']['demo user'];
		return $error;
	}
	
	// Set error 'counter'
	$i = 1;
	
	// Reset return val
	$return = '';
	
	//
	// Create a new database entry in the database
	if ($action == "create") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[id]		*REQUIRED* domain id
		//
		// Expected Input Data (from POST)
		// ===============================
		// * Optional
		// data[name]		Database Name
		// data[username]	Database username
		// data[password]	Database password
		// data[access]		Database Access: localhost|any
		// data[type]		Database Type: mysql|postgresql
		
		// Check for the number of databases in use
		$domaindata = fetchdata("db","domain",$data['id']);
		$databases = fetchdata("databases","total",$data['id']);
		
		// Get current domain's user list
		$dbp = mysql_query("SELECT username FROM users WHERE id=".$data['id']." ORDER BY username");
		
		while ($tmp = mysql_fetch_array($dbp)) {
			$utmp = substr($tmp['username'],0,16);
			if ($userlist[$j-1] != $utmp)
				$userlist[$j++] = $utmp;
		}
		
		// Deal with MySQL or PostgreSQL only
		if ($data['type'] != 'mysql' AND $data['type'] != 'postgresql')
			$error[$i++] = $T['err']['db']['invalid type'];
		
		// Verify username validity
		if (!eregi($rx['user'],$data['username']) OR strlen($data['username']) > 16)
			$error[$i++] = $T['err']['db']['username'];
		$j = 0;
		$uvalid = false;
		while($userlist[$j]) {
			if ($userlist[$j] == $data['username']) {
				$uvalid = true;
				break;
			}
			++$j;
		}
		if (!$uvalid)
			$error[$i++] = $T['err']['db']['username'];
		// Make sure usernames are unique amongst the DB types
		$dbp = mysql_query("SELECT DISTINCT(type) AS type, DECODE('password'','".$cfg['key']."') AS password FROM databases WHERE username = '".$data['username']."'");
		$tmp = mysql_fetch_array($dbp);
		if ($tmp['type'] != $data['type'] OR mysql_num_rows($dbp) > 1)
			$error[$i++] = $T['err']['db']['username'];
		elseif (mysql_num_rows($dbp))
			$data['password'] = $tmp['password'];
		
		// Verify password
		if (!eregi($rx['pass'],$data['password']) AND !$userset)
			$error[$i++] = $T['err']['db']['password'];
		
		// Check Access
		if ($data['access'] != 'localhost')
			$data['access'] = '%';
		else
			$data['access'] = 'localhost';
		
		// Check database name
		if (!eregi($rx['user'],$data['name']) OR strlen($data['name']) > 64)
			$error[$i++] = $T['err']['db']['name'];
			
		// Check for if there are free databases left:
		$total = $domaindata['db'];
		$used = $ddatabases['databases'];
		if (($total - $used) < 1) $error[$i++] = $T['err']['db']['no db'];
		
		// Name is free?
		$dnp = mysql_query("SELECT name FROM databases WHERE name='".$data['name']."' AND type='".$data['type']."'");
		if (mysql_num_rows($dbp))
			$error[$i++] = $T['err']['db']['name taken'];
		// Do one more check for MySQL
		if ($data['type'] == 'mysql') {
			if (@mysql_select_db($data['name'])) {
				mysql_select_db($cfg['name']);
				$error[$i++] = $T['err']['db']['name taken'];
			}
			
			// check if db user already exist
			mysql_select_db('mysql');
			$dbp = mysql_query("SELECT User FROM user WHERE User='".$data['username']."'");
			if (mysql_num_rows($dbp))
				$userset = true;
			else
				$userset = false;
		}
		// Deal with PostgreSQL
		elseif ($data['type'] == 'postgresql') {
			
			// Name is free?
			$psql = @pg_connect("host=".$cfg['pgsql_host']." user=".$cfg['pgsql_user']." password=".$cfg['pgsql_pass']." dbname=".$data['name']);
			if (!@pg_connection_reset($psql)) {
				mysql_select_db($cfg['name']);
				$error[$i++] = $T['err']['db']['name taken'];
			}
			@pg_close($psql);
			
			// check if db user already exist
			$psql = pg_connect("host=".$cfg['pgsql_host']." user=".$cfg['pgsql_user']." password=".$cfg['pgsql_pass']." dbname=".$cfg['pgsql_db']);
			if (!@pg_query($psql,"ALTER USER ".$data['username']))
				$userset = true;
			else
				$userset = false;
			pg_close($psql);
		}

		
		
		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			if ($data['type'] == 'mysql') {
				// Create database (and user if appropriate)
				mysql_query("CREATE DATABASE ".$data['dbname']);
				mysql_select_db('mysql');
				if (!$userset)
					mysql_query("INSERT INTO user SET Host='".$data['access']."', User='".$data['username']."', password=PASSWORD('".$data['password']."')");
				mysql_query("INSERT INTO db SET Host='".$data['access']."', Db='".$data['name']."', User='".$data['username']."', Select_priv='Y',
						Insert_priv='Y', Update_priv='Y', Delete_priv='Y', Create_priv='Y' ,Drop_priv='Y', Grant_priv='N', 
						References_priv='Y', Index_priv='Y', Alter_priv='Y'");
				mysql_query("FLUSH PRIVILEGES");
				mysql_select_db($cfg['dbname']);
			}
			elseif ($data['type'] == 'postgresql') {
				// Create database (and user if appropriate)
				$psql = pg_connect("host=".$cfg['pgsql_host']." user=".$cfg['pgsql_user']." password=".$cfg['pgsql_pass']." dbname=".$cfg['pgsql_db']);
				if (!$userset)
					pg_query($psql,"CREATE USER \"".$data['username']."\" WITH ENCRYPTED PASSWORD '".$data['password']."' CREATEDB");
				pg_close($psql);
				$psql = pg_connect("user=".$data['username']." password=".$data['password']." dbname=".$cfg['pgsql_db']);
				pg_query($psql,"CREATE DATABASE \"".$data['name']."\"");
				pg_close($psql);
				$psql = pg_connect("host=".$cfg['pgsql_host']." user=".$cfg['pgsql_user']." password=".$cfg['pgsql_pass']." dbname=".$cfg['pgsql_db']);
				pg_query($psql,"ALTER USER \"".$data['username']."\" NOCREATEDB");
				pg_close($psql);
			}
			
			
			// Add into database
			mysql_query("INSERT INTO databases SET name='".$data['name']."', id=".$data['id'].", username='".$data['username']."', password=ENCODE('".$data['password']."','".$cfg['key']."'), access='".$data['access']."', type='".$data['type']."'");
	
			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"database created: ".$data['name'],$REMOTE_ADDR);
		}
	}
	
	//
	// Modify a database
	elseif ($action == "modify") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[id]		*REQUIRED* domain id
		//
		// Expected Input Data (from POST)
		// ===============================
		// ** Both groups are optional
		// data[uid]		Database Unique ID (uid)
		// data[access]		Database Access: localhost|any
		// -- OR --
		// data[username]	Database username
		// data[password]	Database password
		
		// Get dbdata
		if (is_numeric($data['uid']))
			$dbdata = fetchdata("*","database",$data['uid']);
		else
			$dbdata = fetchdata("*","database",$data['username']);
		
		// Get current domain's user list
		$dbp = mysql_query("SELECT username FROM users WHERE id=".$data['id']." ORDER BY username");
		while ($tmp = mysql_fetch_array($dbp)) {
			$utmp = substr($tmp['username'],0,16);
			if ($userlist[$j-1] != $utmp)
				$userlist[$j++] = $utmp;
		}
		
		// begin sql query
		$sql_query = "UPDATE databases SET ";
		
		// update user password
		if ($data['password'] AND $data['username']) {
			// Verify username
			if ($data['username']) {
				if (!eregi($rx['user'],$data['username']) OR strlen($data['username']) > 16)
					$error[$i++] = $T['err']['db']['username'];
				$j = 0;
				$uvalid = false;
				while($userlist[$j]) {
					if ($userlist[$j] == $data['username']) {
						$uvalid = true;
						break;
					}
					++$j;
				}
				if (!$uvalid)
					$error[$i++] = $T['err']['db']['username'];
			}
			// Verify password
			if (!eregi($rx['pass'],$data['password']) AND !$userset)
				$error[$i++] = $T['err']['db']['password'];
			
			if ($data['password'] != $dbdata['password'])
				$sql_query .= "password = ENCODE('".$data['password']."','".$cfg['key']."'), ";
			
		}
		
		// Verify Access
		if ($data['access'] AND $data['uid']) {
			if ($data['access'] != 'localhost')
				$data['access'] = '%';
			else
				$data['access'] = 'localhost';
			if ($dbdata['access'] != $data['access'])
				$sql_query .= "access='".$data['access']."', ";
		}
		
		// Check if there is anything to update
		if ($sql_query == "UPDATE databases SET ")
			$error[$i++] = $T['err']['nothing to update'];
		elseif (is_numeric($data['uid']))
			$sql_query .= "lastchange=NOW() WHERE uid = '".$data['uid']."' AND id = '".$data['id']."'";
		elseif ($data['username'])
			$sql_query .= "lastchange=NOW() WHERE username = '".$data['username']."' AND id = '".$data['id']."'";
		
		// If any error occured before, return it now
		if (is_array($error)) return $error;
		else {
			if (is_numeric($data['uid'])) {
				if ($dbdata['type'] == 'mysql') {
					// Create database (and user if appropriate)
					mysql_select_db('mysql');
					mysql_query("UPDATE user SET Host='".$data['access']."' WHERE User='".$dbdata['username']."')");
					mysql_query("UPDATE db SET Host='".$data['access']."', WHERE Db='".$dbdata['name']."' AND User='".$dbdata['username']."'");
					mysql_query("FLUSH PRIVILEGES");
					mysql_select_db($cfg['dbname']);
				}
			}
			elseif ($data['username']) {
				if ($dbdata['type'] == 'mysql') {
					// Create database (and user if appropriate)
					mysql_select_db('mysql');
					mysql_query("UPDATE user SET password=PASSWORD('".$data['password']."') WHERE User='".$dbdata['username']."')");
					mysql_query("FLUSH PRIVILEGES");
					mysql_select_db($cfg['dbname']);
				}
				elseif ($dbdata['type'] == 'postgresql') {
					// Create database (and user if appropriate)
					$psql = pg_connect("host=".$cfg['pgsql_host']." user=".$cfg['pgsql_user']." password=".$cfg['pgsql_pass']." dbname=".$cfg['pgsql_db']);
					pg_query($psql,"ALTER USER \"".$dbdata['username']."\" WITH ENCRYPTED PASSWORD '".$data['password']."'");
					pg_close($psql);
				}
			}
			
			// Add into database
			mysql_query($sql_query);
	
			// Log it
			webcp_log(2,$userdata['id'],$userdata['username'],"database updated: ".$dbdata['name']." (".$dbdata['username'].")",$REMOTE_ADDR);
		}
		
	}
	
	//
	// Suspend a database
	elseif ($action == "suspend") {
	}
	
	//
	// Unsuspend a database
	elseif ($action == "unsuspend") {
		
	}
	
	//
	// Remove a database
	elseif ($action == "remove") {
		// Expected Input Data (assumed SAFE, should be hardcoded)
		// ===============================
		// 
		// data[id]		*REQUIRED* domain id
		//
		// Expected Input Data (from POST)
		// ===============================
		// data[uid]		Database UID
		$data['uid'] = intval($data['uid']);
		$dbdata = fetchdata("*","database",$data['username']);
		/*
		if ($dbdata['uid'] == $data['id']) {
			if ($dbdata['type'] == 'mysql') {
				*********************************************
				// Create database (and user if appropriate)
				mysql_query("DROP DATABASE IF EXISTS ".$user);
				mysql_select_db("mysql");
				mysql_query("DELETE FROM user WHERE User='".$user."'");
				mysql_query("DELETE FROM db WHERE User='".$user."'");
				mysql_query("FLUSH PRIVILEGES");
				mysql_select_db($dbname);
				***********************
				mysql_select_db('mysql');
				mysql_query("UPDATE user SET password=PASSWORD('".$data['password']."') WHERE User='".$dbdata['username']."')");
				mysql_query("FLUSH PRIVILEGES");
				mysql_select_db($cfg['dbname']);
			}
			elseif ($dbdata['type'] == 'postgresql') {
				*********************************************
				$dbp = pg_Connect("user=".$user." password=".$personaldata['password']." dbname=".$pgsql_db);
				pg_exec($dbp,'DROP DATABASE "'.$user.'"');
				pg_close($dbp);
				$dbp = pg_Connect("user=".$pgsql_user." password=".$pgsql_pass." dbname=".$pgsql_db);
				pg_exec($dbp,'DROP USER "'.$user.'"');
				pg_close($dbp);
				**********************
				// Create database (and user if appropriate)
				$psql = pg_connect("host=".$cfg['pgsql_host']." user=".$cfg['pgsql_user']." password=".$cfg['pgsql_pass']." dbname=".$cfg['pgsql_db']);
				pg_query($psql,"ALTER USER \"".$dbdata['username']."\" WITH ENCRYPTED PASSWORD '".$data['password']."'");
				pg_close($psql);
			}
		} */
	}
}
		
?>
Return current item: web-cp - Web Hosting Control Panel