<?
########## Confixx(R) 3.0 Professional ############
####### Copyright SWsoft, Inc. 2004-2005 ##########
#### http://www.sw-soft.com - info@sw-soft.com ####


include_once( "page_functions.php" );
include_once( 'include/class.SQLString.php' );
if (!isset($functionschonmal))  {
$functionschonmal = 1;

 if( !function_exists( 'is_a' ) ) {
	 ## there is 'is_a'-function since ver. 4.2.0
	 function is_a( $loSrc, $lcClass ){  
		 if(is_object($loSrc)){
			 if ( get_class($loSrc) == $lcClass ) {
				 return TRUE;
			 }
			 return is_subclass_of( $loSrc, $lcClass ); 
		 }
		 return FALSE;
	 }
 }


function istleer($var)	  {
  if (!isset($var)) 
    return true; 
  else    {
    if ($var == "") 
      return true; 
    else 
      return false;
  }
}

function ltext($key, $params = "")
	{
	 global $lang_text;
	 $string = $lang_text[$key];
         if(is_array($params)) $prlength = count($params); else $prlength = 0;
	 for ($i=0; $i < $prlength; $i++)
		{
		 $string = str_replace('$VAR['.$i.']',$params[$i],$string);
		}
	 if (istleer($string)) $string = "<b><font color=\"red\">Unknown key: $key</font></b>";
	 return $string;
	}

function get_langs($pfad = "../languages/"){
  global $langfileversion;
  $handle = opendir($pfad);
  while ($ldir = readdir($handle))
    {
      if (!eregi("\.",$ldir)) ##filters '.' and '..'
	{
	  include($pfad.$ldir."/misc.inc.php");
	  if ($lang_version == $langfileversion)
	    {
	      $languages["short"][] = $lang_short;
	      $languages["nat"][] = $lang_name_nat;
	      $languages["int"][] = $lang_name_int;
				}
	}
    }
  closedir($handle);
  return $languages;
}

function licence_status ( $text, $date )
{
	$parts = explode("||", $text);
	if ( $parts[0] == "mlf" && $parts[1] == "scripts_licence_valid" )
		return ltext ( "ls_valid", array( $date ) );
	return mlf_text($text);
}

function mlf_text($text)
	{
	 $parts = explode("||", $text);
	 if ($parts[0] == "mlf")
		{
		 $varlist = "";
		 for ($i = 2; $i < count($parts); $i++)
			{
			 $varlist[] = htmlspecialchars($parts[$i]);
			}
		 return ltext($parts[1], $varlist);
		} else
		{
		 return $text;
		}
	}

function char_crunch($text)
	{
	 $tok = strtok($text, " ");
	 while ($tok)
		{
		 $newtext .= chunk_split($tok, 15, " ");
		 $tok = strtok(" ");
		}
	 return $newtext;
	}

function set_countdomains( $kunde )	{
	$loUser = new SQLString( $kunde );
	$id = safe_query2( "SELECT COUNT(domain) AS countdomains FROM domains WHERE kunde=?", $loUser);
	$werte = db_fetch_array( $id );
	$countdomains = $werte["countdomains"];
	safe_query2( "UPDATE kunden SET countdomains = $countdomains where kunde=?", $loUser);
}

function noMagic(&$string)
	{
	 $string = str_replace("\'", "'", $string);
	 $string = str_replace("\\\"", "\"", $string);
	 $string = str_replace("\\\\", "\\", $string);
	}

function getuid()
	{
	    return 0;	
	 #db_connect($GLOBALS["db_host"], $GLOBALS["db_user"], $GLOBALS["db_pass"]);
	 $id = db_query("select minuid, maxuid, flock from admin");
	 $werte = db_fetch_array($id);
	 $minuid = $werte["minuid"];
	 $maxuid = $werte["maxuid"];
	 $flock = $werte["flock"];
	 $flock2 = $flock;
	 $wait = 10;
	 while($flock2 != 0)
		{
		 $wait--;
		 sleep(1);
		 $id = db_query("select flock from admin");
		 $werte = db_fetch_array($id);
		 $flock2 = $werte["flock"];
		 if ($flock2 != $flock) $wait = 10;
		 if ($wait < 0)
			{
			 db_query("update admin set flock = 0");
			}
		}
	 $flock = time();
	 db_query("update admin set flock = $flock");
	 $uidstring = "";
	 $anzahl = 1;

	 $id = db_query("select uid from pop3");
	 while ($daten = db_fetch_array($id))
		{
		 $uidstring .= "[".$daten["uid"]."]";
		 $anzahl++;
		}

	 $id = db_query("select uid from ftp");
	 while ($daten = db_fetch_array($id))
		{
		 $uidstring .= "[".$daten["uid"]."]";
		 $anzahl++;
		}

	 $id = db_query("select uid from kunden");
	 while ($daten = db_fetch_array($id))
		{
		 $uidstring .= "[".$daten["uid"]."]";
		 $anzahl++;
		}

	 while ($anzahl > 0)
		{
		 $newtmpuid = $anzahl + $minuid;
		 $ereg = "\[".$newtmpuid."\]";
		 if (! ereg($ereg, $uidstring))
			{ 
			 $newuid = $newtmpuid;
			}
		 $anzahl--;
		}
	 if (($newuid > $maxuid) || ($newuid < $minuid))
		{
		 echo "<p><b>System error:</b> no free available UIDs found</p>";
		 exit();
		}
	 return $newuid;
	}

function freeuid()
	{
#	 db_connect($GLOBALS["db_host"], $GLOBALS["db_user"], $GLOBALS["db_pass"]);
	 db_query("update admin set flock = 0");
	}

function mkpasswd($pwlength) {
srand((double)microtime()*1000000);
$Zeichen = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$pawd = "";
while (strlen($pawd) < $pwlength)
	{
	 $pawd .= substr($Zeichen,(rand()%(strlen($Zeichen))),1);
	}
return $pawd;
}

function mksalt($pwlength) {
srand((double)microtime()*1000000);
$Zeichen = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$pawd = "";
while (strlen($pawd) < $pwlength)
	{
	 $pawd .= substr($Zeichen,(rand()%(strlen($Zeichen))),1);
	}
return $pawd;
}

function crypt_pw($plainpw) {
	global $disable_md5;
	$salt = mksalt(8);
	if ((CRYPT_MD5)					// CRYPT_MD5 = php_global_const
		&& ($disable_md5 == 0)) {	// $disable_md5 = confixx_global in settings.inc.php
		$salt = "\$1\$$salt\$";
	} else { // use STD_DES
		$salt = substr($salt,0,2);
	}
	return crypt($plainpw, $salt);
}

function valid_pw($plainpw) {
	if ((strlen($plainpw) < 6) || (strlen($plainpw) > 12)) {
		return 0;
	} else {
		return 1;
	}
}

function sinnv_kbwert($wert, $unbegrenzt = "-1") {
	$kb_expr = $GLOBALS["lang_format_kb_expr"]; // misc.inc.php must to be included 102400
	$mb_expr = $GLOBALS["lang_format_mb_expr"];
	$gb_expr = $GLOBALS["lang_format_gb_expr"];
	$sep_dec = $GLOBALS["lang_format_sep_dec"];
	$sep_kilo = $GLOBALS["lang_format_sep_kilo"];
	if ($wert <> -1)
	{
		if (($wert < 999) && ($wert <> 0))
		{
			$wert .= " ".$kb_expr;
		}
		elseif ($wert > 999)
		{
			$wert = $wert / 1024;
			if ($wert > 999)
			{
				$wert = $wert / 1024;
				$gb = "yes";
			}
			if (ereg("\.",$wert))
			{
				$wert = number_format($wert,2,$sep_dec,$sep_kilo);
			}
			else
			{
				$wert = number_format($wert,0,$sep_dec,$sep_kilo);
			}
			$sufix = preg_quote($sep_dec)."00";
			if (ereg($sufix,$wert))
			{
				$wert = substr($wert,0,strlen($wert) - 3);
			}
			if ($gb == "yes")
			{
				$wert .= " ".$gb_expr;
			}
			else
			{
				$wert .= " ".$mb_expr;
			}
		}
		else
		{
			$wert = "0 ".$kb_expr;
		}
	}
	else
	{
		$wert = $unbegrenzt;
	}
	return $wert;
}

function sinnv_intwert($wert, $unbegrenzt = "-1") {
$sep_dec = $GLOBALS["lang_format_sep_dec"]; // misc.inc.php must be included
$sep_kilo = $GLOBALS["lang_format_sep_kilo"];
if ($wert <> -1)
	{
	 return number_format($wert,0,$sep_dec,$sep_kilo);
	}
else
	{
	 return $unbegrenzt;
	}
}

function get_comment( $pop3 ) {
	if (!ereg("\@",$pop3)) {
		global $PHP_AUTH_USER;

		$id = safe_query2( "SELECT kommentar FROM pop3 WHERE account=? AND kunde=?", 
											 new SQLString($pop3), new SQLString($PHP_AUTH_USER));
		if (db_num_rows($id) > 0) {
			$werte = db_fetch_array($id);
			return $werte["kommentar"];
		} else {
		    return "";
		}
	} else {
	    return "";
	}
}

function sub_comment($comment, $maxlength) {
	if ($comment != "") {
		if (strlen($comment) > $maxlength) {
			$comment = substr($comment,0,($maxlength-3));
			$comment = trim($comment);
			return " (".$comment."..)";
		} else {
			return " (".$comment.")";
		}
	} else {
	    return "";
	}
}

## datenbankfunktionen
function db_connect()
{
	global $db_type, $db_user, $db_host, $db_pass, $db_db, $db_port;

	if (!isset($db_type)) {
		die("Database type is not defined.");

	}	elseif ( $db_type == 'mysql' ) {
		if (isset($GLOBALS['db_connection_id']) && $GLOBALS['db_connection_id'] ) {
	    mysql_close($GLOBALS['db_connection_id']);
		}  

		if ( $db_port ) {
			$server = $db_host.':'.$db_port;
		} else {
			$server = $db_host;
		}
		
		$GLOBALS['db_connection_id'] = mysql_connect($server, $db_user, $db_pass) 
	    or die("Verbindung zur Datenbank fehlgeschlagen!");
		
		return mysql_select_db($db_db);
	
	} elseif ( $db_type == 'Pg' ) {
		if (isset($GLOBALS['db_connection_id']) && $GLOBALS['db_connection_id']) {
	    pg_close($GLOBALS['db_connection_id']);
		}  
		$DSN = "host=$db_host user=$db_user password=$db_pass dbname=$db_db";
		if ( $db_port ) {
			$DSN .= " port=$db_port"; 
		}
		$GLOBALS['db_connection_id'] = pg_connect( $DSN ) 
	    or die("Verbindung zu Datenbank fehlgeschlagen!");

		return $GLOBALS['db_connection_id'];

	} elseif ( !$db_type ) {
		die('Database type is empty.');

	} else {
		die("Unsupported database type. ");
	}
}

function db_query( $query_string, $show_errors = true ) {
	global $db_type;
	global $DEBUG;

	if( is_object( $show_errors ) ) { ## typo: do_query -> safe_query2
		$laArgs = func_get_args();			
		return call_user_func_array( 'safe_query2', $laArgs );
	}

	if ($db_type == "mysql"){
		$GLOBALS["db_last_id"] = @mysql_query($query_string);
		if(!$GLOBALS["db_last_id"] && $show_errors){
			log_debug_message($message);
			echo mysql_error();
		}
		return $GLOBALS["db_last_id"];
	} else{
		$GLOBALS["db_last_id"] = pg_exec($GLOBALS["db_connection_id"], $query_string);
		if($GLOBALS["db_last_id"]){
			$iid=0+$GLOBALS["db_last_id"];
			$counter = "pgresindex".$iid;
			$GLOBALS[$counter]=0;
		}else{
			if($DEBUG){
				log_debug_message($message);
				echo "Error execute: $query_string<br>\n";
			}
		}
		return $GLOBALS["db_last_id"];
	}
}

function safe_query_error ( $show_errors, $message )
{
	if ($show_errors) {
		echo ($message);
		log_debug_message($message);
	}
	return $GLOBALS["db_last_id"];
}

// this files contains types used as an arguments of safe_query
// I included them here for not to include them in each file
include_once('class.SQLString.php');
include_once('class.SQLInteger.php');

function safe_query ( $query_string, $show_errors = true )
{
	global $db_type;
	$arguments = func_get_args();
	if(is_object($show_errors)){
		$show_errors = TRUE;
		array_splice( $arguments, 0, 1 );
	} else {
		array_splice( $arguments, 0, 2 );
	}
	$process = $query_string;
	$result = "";
	while( ( $index = strpos( $process, "?" ) ) !== FALSE )
	{
		$result .= substr( $process, 0, $index );
		$process = substr( $process, $index+1 );
		if( !count($arguments) )
			return safe_query_error( $show_errors, "Error in query: Zero number of arguments in safe query: $query_string");
		$type = array_shift($arguments);
		if( !is_object( $type ) )
			return safe_query_error( $show_errors, "Error in query: $type argument is not an object in safe query: $query_string");
		if( !$type->Validate() )
			return safe_query_error( $show_errors, "Error in query: one of safe query arguments is not valid: ".$type->GetError(). " : $query_string");
		$result .= $type->SQL();
	}
	$result .= $process;
	if( $db_type == "mysql" )
	{
		$GLOBALS["db_last_id"] = @mysql_query( $result );
		if( !$GLOBALS["db_last_id"] )
			return safe_query_error( $show_errors, "Error while executing query: $result : " . mysql_error() );
	}
	else
		$GLOBALS["db_last_id"] = pg_exec( $GLOBALS["db_connection_id"], $result );
	return $GLOBALS["db_last_id"];
}

/**
	the analogue of safe_query, but 
	1) will always show errors (if any)
	2) allows specifying him string/int values, not wrapper object

 	sample call: safe_query2("SELECT a FROM b WHERE c=? AND d=?", $var1, $var2);
 */
function safe_query2 ($query_string) {
	$arguments = func_get_args();
	$arguments2 = array();		// resulting array
	array_splice($arguments, 0, 1);	// drop out the first parameter
	for ($i=0, $n=count($arguments); $i<$n; ++$i) {
	    if (is_string($arguments[$i]))
			array_push($arguments2, new SQLString($arguments[$i]));
	    elseif (is_int($arguments[$i]))
			array_push($arguments2, new SQLInteger($arguments[$i]));
		elseif (is_object($arguments[$i]) && is_subclass_of($arguments[$i], 'SQLType'))
			array_push($arguments2, $arguments[$i]);	// already wrapped with object
	    else
			array_push($arguments2, new SQLString($arguments[$i]));
	}
	array_unshift($arguments2, $query_string, TRUE); // prepend list of vars by implied values
	return call_user_func_array('safe_query', $arguments2);
}

function db_fetch_array($id){
	global $db_type;
	if ($db_type == "mysql"){
		return mysql_fetch_array($id);
	} else{
		if (!$id){
			return false;
		}
		$iid=0+$id;
		$counter = "pgresindex".$iid;
		$rows = pg_numrows($id);
		if ($rows > $GLOBALS[$counter]){
			if ($array = pg_fetch_array($id, $GLOBALS[$counter])){
				$GLOBALS[$counter]++;
				return $array;
			} else{
				$GLOBALS[$counter] = 0;
			}
		} else{
			$GLOBALS[$counter] = 0;
		}
	}
}

function db_close($id = "kein Wert")
	{
	 if ($id == "kein Wert") $id = $GLOBALS["db_connection_id"];
	 global $db_type;
	 if ($db_type == "mysql")
		{
#		 return mysql_close($id);	# nicht noetig
		} else
		{
#		 return pg_close($id);
		}
	}

function db_error($id = "kein Wert")
	{
	 global $db_type;
	 if ($db_type == "mysql")
		{
	 	 if ($id == "kein Wert") $id = $GLOBALS["db_last_id"];
		 return mysql_error($id);
		} else
		{
	 	 if ($id == "kein Wert") $id = $GLOBALS["db_connection_id"];
		 return pg_errormessage($id);
		}
	}

function db_num_rows($id)
	{
	 global $db_type;
	 if ($db_type == "mysql")
		{
		 return mysql_num_rows($id);
		} else
		{
		  if($id){
		    return pg_numrows($id);
		  }else{
		    return false;
		  }
		}
	}

 function db_insert_id($sequenz_name, $field = ""){
   global $db_type;
   global $DEBUG;
   if ($db_type == "mysql"){
     return mysql_insert_id();
   } else{
     if($field){
       $sequenz_name.='_'.$field.'_seq';
     }
     $pg_id = pg_exec($GLOBALS["db_connection_id"], "SELECT last_value FROM $sequenz_name");
     if($pg_id){
       $ret=pg_result($pg_id, 0, 0);
     }else{
       if($DEBUG){
	 echo "Error get last ID from: '$sequenz_name'<br>\n";
       }
       $ret=false;
     }
     return $ret;
   }
 }

# converts unix timestamp to full TIMESTAMP type value 
# of the current DBMS (mysql/posgresql)
function db_timestamp($unix_timestamp)
{
	global $db_type;
	if ($db_type == "mysql") {
		return date('YmdHis', $unix_timestamp);		# mysql
	} else {
		return date('Ymd His', $unix_timestamp);	# postgresql (with space between date and time)
	}
}
## //

function domain_aendern($domain, $aktion, $kunde)	{

	if( preg_match('/^\*\./', $domain ) ){
		return;
	}

	$loDomain = new SQLString( $domain );
	$loUser = new SQLString( $kunde );

	$id = safe_query2( "SELECT * FROM domains WHERE domain=?", $loDomain);
	if (db_num_rows($id) > 0)	{
		if ( $aktion == "anlegen" ) {
			$id = safe_query2("select * from domainlog where domain=? and loeschen = 1", $loDomain );
			if (db_num_rows($id) > 0)	{
				safe_query2( "UPDATE domainlog SET kunde = ?, neu = 1 where domain = ?", $loUser, $loDomain );

			} else	{
				safe_query2( "INSERT INTO domainlog (kunde, neu, domain, loeschen) VALUES (?, 1, ?, 0)", $loUser, $loDomain );
				db_query( "UPDATE allgemein SET domains = 1");
			}

		} else	{
			$id = safe_query2("select * from domainlog where domain=? and neu = 1", $loDomain );
			if (db_num_rows($id) == 1 ) {
				safe_query2( "DELETE FROM domainlog WHERE domain = ? and neu = 1", $loDomain );
			} else	{ 
				safe_query2( "INSERT INTO domainlog (kunde, loeschen, domain, neu) VALUES (?, 1, ?, 0)", $loUser, $loDomain );
				db_query("update allgemein set domains = 1");
			}
		}
	}
 }

function fpalias_aendern($domain, $aktion, $kunde) {
	 ## frontpage aliase

	$loUser = new SQLString( $kunde );

	$fpid = safe_query2("SELECT frontpage, anbieter FROM kunden WHERE kunde = ?", $loUser);
	$fpwerte = db_fetch_array($fpid);
	$frontpage = $fpwerte["frontpage"];
	$anbieter = $fpwerte["anbieter"];
	$add = 0;
	$del = 0;
	if ($frontpage != 1) {
		return;
	}
	if( !preg_match('/^\*\./', $domain ) ) {
		$loDomain = new SQLString( $domain );
		$loRes = new SQLString( $anbieter );
	## nicht ssl domains
		$id = safe_query2( "SELECT * FROM domains WHERE domain = ? and pfad = '/' and cssl = 0", $loDomain );
		if (db_num_rows($id) > 0) {
			if ($aktion == "anlegen")	{ ## anlegen
				$id = safe_query2( "SELECT * FROM frontpagealias WHERE domain = ? and kunde = ? and loeschen = 1 and port=80",
													 $loDomain, $loUser );

				if (db_num_rows($id) == 0){
					safe_query2( "INSERT INTO frontpagealias (domain, kunde, anbieter, port, neu, loeschen) ".
											 "VALUES (?, ?, ?, 80, 1, 0)", $loDomain, $loUser, $loRes );
					$add++;
					
				} else {
					safe_query2("DELETE FROM frontpagealias WHERE domain = ? and kunde = ? and port=80",
											$loDomain, $loUser );
				}
				
			} else { ## loeschen
				$id = safe_query2("SELECT * FROM frontpagealias WHERE domain = ? and kunde = ? and neu = 1 and port = 80",
													$loDomain, $loUser );
				if (db_num_rows($id) == 0) {
					safe_query2( "INSERT INTO frontpagealias (domain, kunde, anbieter, port, neu, loeschen) ".
										 "VALUES (?, ?, ?, 80, 0, 1)", $loDomain, $loUser, $loRes );
					$del++;

				} else {
					safe_query2( "DELETE FROM frontpagealias WHERE domain = ? and kunde = ? and port = 80",
										$loDomain, $loUser );
				}
			}
		}
		 ## ssl domains

		$id = safe_query2("SELECT * FROM domains WHERE domain = ? AND pfad = '/' AND cssl = 1", $loDomain );
		if (db_num_rows($id) > 0)	{
			if ( $aktion == "anlegen" ) { ## anlegen
				$id = safe_query2( "SELECT * FROM frontpagealias WHERE domain = ? and kunde = ? and loeschen = 1 and port=443",
													 $loDomain, $loUser );
				if (db_num_rows($id) == 0) {
					safe_query2( "INSERT INTO frontpagealias (domain, kunde, anbieter, port, neu, loeschen) ".
											 " VALUES (?, ?, ?, 443, 1, 0)", $loDomain, $loUser, $loRes );
				$add++;

				} else {
					safe_query2( "DELETE FROM frontpagealias WHERE domain = ? and kunde = ? and port = 443",
											 $loDomain, $loUser );
				}
			
			} else { ## loeschen
				$id = safe_query2( "SELECT * FROM frontpagealias WHERE domain = ? and kunde = ? and neu = 1 and port = 443",
													 $loDomain, $loUser );
				if (db_num_rows($id) == 0) {
					safe_query2( "INSERT INTO frontpagealias (domain, kunde, anbieter, port, neu, loeschen) ".
											 "VALUES ( ?, ?, ?, 443, 0, 1)", $loDomain, $loUser, $loRes);
					$del++;
				} else {
					safe_query2( "DELETE FROM frontpagealias WHERE domain = ? and kunde = ? and port = 443",
											 $loDomain, $loUser );
				}
			}
		}
	}
	$set = '';
	if ( $add > 0 ) {
		$set = "fpaliasadd = 1";
	}
	if ( $del > 0 ) {
		if ( $set ) {
			$set .= ',';
		}
		$set .= "fpaliasdel = 1";
	}
	if( $set ){
		db_query( "UPDATE allgemein SET $set");
	}
}
	
	
function compare_confixx_version($newver)
{
	/*$tem = explode('-', $GLOBALS['version'], 2);
	$nem = explode('-', $newver, 2);
	if(!array_key_exists(1, $tem))
	{
		$tem[1]	= false;
	}

	if(!array_key_exists(1, $nem))
	{
		$nem[1]	= false;
	}
	
	$tvarr = explode('.', $tem[0]);
	$nvarr = explode('.', $nem[0]);
	
	$co = max(count($tvarr), count($nvarr));
	
	$tver = $nver = 0;
	
	for($i = 0; $i < $co; $i++)
	{
		$st = pow(100, ($co - $i - 1));
		$tver += $tvarr[$i] * $st;
		$nver += $nvarr[$i] * $st;
	}
	
	return ($nver > $tver && $tem[1] != $nem[1]);*/
	
	// only for 3.0.0 branch
	$newver = intval( str_replace('.', '', array_pop(array_reverse(explode("-", $newver))) ) );
	$curver = intval( str_replace('.', '', $GLOBALS['version'] ) );
	if( $curver < $newver ) return 1;

	return 0;	
}


function check_new_versions()
{
	$versions = false;
	$id = db_query('select id, version from updates where new = 1');
	if( db_num_rows($id) )
	{
		while ($werte = db_fetch_array($id))
		{
			if(compare_confixx_version($werte['version']))
			//if($werte['version'] != $GLOBALS['version'])
			{
				$versions[$werte['id']] = $werte['version'];
			}
		}	
	}
	return $versions;	
}


function newLocation($url){
  echo "<html>\n<head>\n";
  echo "\t<meta http-equiv=\"refresh\" content=\"1, URL=$url\">\n";
  echo "</head>\n<body>\n";
  echo "<a href=\"$url\">$url</a>\n";
  echo "</body>\n</html>\n";
}

function log_debug_message($msg) {
	$stderr = fopen('php://stderr', 'w');
	$today = date("D M j G:i:s T Y");   	
	fwrite($stderr,"[$today] confixx: $msg\n");
	fclose($stderr); 
}

#
# user's MySQL
#

function userdb_connect( $show_errors = true )
{
	global $mysql_user_user, $mysql_user_host, $mysql_user_pass, $mysql_user_port;

	if (isset($GLOBALS['mysql_connection_id']) && $GLOBALS['mysql_connection_id'] ) {
		mysql_close($GLOBALS['mysql_connection_id']);
	}  

	if ( $mysql_user_port ) {
		$server = $mysql_user_host.':'.$mysql_user_port;
	} else {
		$server = $mysql_user_host;
	}
		
	$GLOBALS['mysql_connection_id'] = mysql_connect( $server, 
																									 $mysql_user_user, 
																									 $mysql_user_pass );
	if ( !$GLOBALS['mysql_connection_id'] && $show_errors ) {
		$message = mysql_error();
		log_debug_message( $message );
		echo $message;
	}
		
	return mysql_select_db( 'mysql' );
}

function userdb_query ($query_string, $show_errors = true) {

	global $DEBUG;

	if ( $DEBUG ) {
		echo "user's mysql: $query_string<br>\n";
		$show_errors = true;
	}

	$GLOBALS['mysql_last_id'] = @mysql_query( $query_string, 
																						$GLOBALS['mysql_connection_id']
																						);

	if ( $DEBUG ) {
		echo "user's mysql: resurce id: ".$GLOBALS['mysql_last_id']."<br>\n";
	}
	if ( !$GLOBALS['mysql_last_id'] && $show_errors ) {
		$message = mysql_error();
#		log_debug_message( $message );
		echo $message;
	}
	return $GLOBALS['mysql_last_id'];

}

function userdb_close() {
	if (isset($GLOBALS['mysql_connection_id']) && $GLOBALS['mysql_connection_id'] ) {
		userdb_query( "FLUSH PRIVILEGES" );
		mysql_close($GLOBALS['mysql_connection_id']);
	}  
}

	
}




?>
