Location: PHPKode > projects > PSlash > pslash-0.70/html/user.php
<?

###############################################################################
# Copyright (C) 2000  Derek Leung
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# You may modify your copy or copies of this Program or any portion of it,
# but you must cause the modified files to carry prominent notices stating 
# that you changed the files and the date of any change.  And you are required 
# to keep a copy of this License along with this Program.
#
# You are not required to accept this License, since you have not signed it. 
# However, nothing else grants you permission to modify or distribute this 
# Program or its derivative works. These actions are prohibited by law if 
# you do not accept this License. Therefore, by modifying or distributing 
# this Program (or any work based on this Program), you indicate your 
# acceptance of this License to do so, and all its terms and conditions 
# for copying, distributing or modifying this Program or works based on it.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# See the GNU General Public License for more details.
# http://www.opensource.org/licenses/gpl-license.html
###############################################################################


require("mainfile.php");

global $myTopic,$config;
$myTopic = $config[def_theme];

function nav() {

// navigation menu
	global $config;

	?>
	<center>
	[ 
	<a href="user.php"><? echo translate("User Info"); ?></a> | 
	<a href="user.php?op=edituser"><? echo translate("Edit User Info"); ?></a> | 
	<a href="user.php?op=edithome"><? echo translate("Customize Homepage"); ?></a> | 
	<a href="user.php?op=editcomm"><? echo translate("Customize Comments"); ?></a> | 
	<? if ($config[email_forward] == true) {
		// only show if email forwarder service is enable
		echo "<a href=\"user.php?op=emailForward\">".translate("Email Forwarder")."</a> |"; 
	   } 
	?>
	<? if ($config[ip_mapping] == true) {
		// only show if ip mapping service is enable
		echo "<a href=\"user.php?op=domainMap\">".translate("Domain Mapping")."</a> |"; 
	   } 
	?>
	<? if ($config[url_forward] == true) {
		// only show if url forwarding service is enable
		echo "<a href=\"user.php?op=urlMap\">".translate("URL Forwarding")."</a> |"; 
	   } 
	?>
	<a href="user.php?op=logout"><? echo translate("Logout"); ?></a> ]</center><br>
	<?
}

function userCheck($uname, $email) {
	
// check username and email
	global $config;

	$uname2 = FixQuotes($uname);
	if (emailValid_Partial($email,3) != 0) {
		$stop = translate("Invalid email")."<br>";
	}
	if (strrpos($uname,' ') > 0) $stop = translate("Email addresses do not contain spaces.");
	if ((!$uname) || ($uname=="") ) $stop = translate("Invalid username!!")."<br>";
	if ($config[allow_special_name] == false) {

		// do not allow special char, filter it out.
		if ((!$uname) || ($uname=="") || (ereg("[^a-zA-Z0-9_-]",$uname))) $stop = translate("Invalid username!!  You can only use a combination of alphabet, numbers and underscore '_'.")."<br>";
	} else {

		// allow special char, but still no space in between username
		if ((!$uname) || ($uname=="") || (ereg("[ ]",$uname))) $stop = translate("Invalid username!!  You can not have space in between your username.")."<br>";
	}

	// username longer than 20 characters.  throw error mesg
	if (strlen($uname) > 20) $stop = translate("Name is too long. It must be less than 20 characters.");

	// reserve username
	if (eregi("^((root)|(anonymous)|(admin)|(moderator)|(operator)|(webmaster)|(administrator)|(postmaster)|(sitemaster)|(ftp)|(www)|(ns1)|([censored]))$",$uname)) $stop = translate("Name is reserved.");

	// username looks ok, check if it is in the database or not	
	if (!$stop) {
		if (mysql_num_rows(mysql_query("select uname from ps_users where uname='$uname2'")) > 0) $stop = translate("Username taken")."<br>";
		if (mysql_num_rows(mysql_query("select email from ps_users_info where email='$email'")) > 0) $stop = translate("Email address already registered")."<br>";
	}
	return($stop);
}

function makePass() {

// make a password
	$makepass="";	$syllables="er,in,tia,wol,fe,pre,vet,jo,nes,al,len,son,cha,ir,ler,bo,ok,tio,nar,sim,ple,bla,ten,toe,cho,co,lat,spe,ak,er,po,co,lor,pen,cil,li,ght,wh,at,the,he,ck,is,mam,bo,no,fi,ve,any,way,pol,iti,cs,ra,dio,sou,rce,sea,rch,pa,per,com,bo,sp,eak,st,fi,rst,gr,oup,boy,ea,gle,tr,ail,bi,ble,brb,pri,dee,kay,en,be,se";
	$syllable_array=explode(",", $syllables);
	srand((double)microtime()*1000000);
	for ($count=1;$count<=4;$count++) {
		if (rand()%10 == 1) {
			$makepass .= sprintf("%0.0f",(rand()%50)+1);
		} else {
			$makepass .= sprintf("%s",$syllable_array[rand()%62]);
		}
	}
	return($makepass);
}

function confirmNewUser($uname, $email) {

// confirm a new user before we actually add the user
	global  $myTopic,$config;
	
	$stop = "";
	$stop = userCheck($uname, $email);
	$uname2 =htmlspecialchars($uname);
	$email2 = htmlspecialchars($email);
	$uname2 = check_words(check_html($uname2,"nohtml"));
	$email2 = check_html($email2,"nohtml");

	//make sure the username is not the same as your [censor_replace_word]
	if ($uname2 == $config[CensorReplace]) {
		errorPage("Username is not valid!",$myTopic);
	}

	// show confirmation screen
	if ($stop == "") {
		
		ps_header("");
		echo "<br><br>";
		echo "<center><b>" . errorMsg("Password will be sent to the email address below.  Is this correct?  If it is correct, please click the finish button. Otherwise, please click Go Back.") . "</b></center><br>";
		echo "<table align=center border=0><tr><td>";
		echo "<b>" . translate("Username") . ":</b>";
		echo "</td><td>";
		echo $uname2 . "</td></tr><tr><td>";
		echo "<b>" . translate("Email") . ":</b>";
		echo "</td><td>";
		echo $email . "</td></tr><tr><td>"; ?>
		<form action="user.php" method="post">
			<input type="hidden" name="uname" value="<? echo"$uname2"; ?>">
			<input type="hidden" name="email" value="<? echo"$email2"; ?>">
			<input type="hidden" name="op" value="finish">
			<input type="submit" value=" <? echo translate("Finish"); ?> ">
		</form>
		</td>
		<td>
		<form action="user.php" method="post">
			<input type="submit" value=" <? echo translate("Go Back"); ?> ">
		</form>
		</td>
		</tr></table>
	<?
		
		ps_footer("");
	} else {
		errorPage($stop,$myTopic);
	}
}


function finishNewUser($uname, $email) {
	
// finish the new user and add to database
	global $config,$myTopic;
	
	$ip = getenv("REMOTE_ADDR");
	$settingArray = getCookie($config[setting_cookie_name]);
	$stop = userCheck($uname, $email);
	$uname2 = FixQuotes($uname);
	$email = FixQuotes($email);

	$makepass=makepass();

	if ($config[crypt_method] == 1) {
		$cryptpass=crypt($makepass);
	} else {
		$cryptpass = $makepass;
	}

	// lock the table and make sure no duplicate , then add
	$uid = "";
	mysql_query("LOCK TABLES ps_users, ps_users_info WRITE");

	// error checking
	if (mysql_num_rows(mysql_query("select uname from ps_users where uname='$uname2'")) > 0) {
		mysql_query("UNLOCK TABLES");
		errorPage("Username taken",$myTopic);
	}

	if (mysql_num_rows(mysql_query("select email from ps_users_info where email='$email'")) > 0) {
		mysql_query("UNLOCK TABLES");
		errorPage("Email address already registered",$myTopic);
	}
	
	// insert to tables
	$result = mysql_query("insert into ps_users (uname, pass, rights, status,regIP,serviceEnable,forwarderEnabled,regDate) values ('$uname2','$cryptpass','','member','$ip','false','false',now())");
	mysql_query("UNLOCK TABLES");
	if(!$result) {
		echo mysql_errno(). ": ".mysql_error(). "<br>";
	}
	
	
	

	// hmm..double check we did insert it before we do more inserting...
	$result = mysql_query("select uid from ps_users where uname='$uname2'");
	if(!$result) {
		mysql_query("delete from ps_users where uname='$uname2'");
		errorPage(sprintf("DateBase Error, %s", mysql_error() ),$myTopic);
	} else {
		$userinfo = mysql_fetch_array($result);
		$uid = $userinfo[uid];
	}
	
	// ok, we now do the rest of inserting into other tables
	if ($uid != "") {
		$result = mysql_query("insert into ps_users_info values ('$uid','','$email','','','')");
		$result = mysql_query("insert into ps_users_home values ('$uid',10,0,'','','$config[language]','800x600')");
		$result = mysql_query("insert into ps_users_comments values ('$uid','nested',0,4096)");
		$result = mysql_query("insert into ps_domain values ('$uid','','','true','')");
	}
		
	// Now we make the letter we are going to sent by email
	if($uid != "") {
		$message = translate("Welcome to") . " " . $config[sitename] . "!";
		$message .= "\n\n";
		$message .= sprintf (translate("You or someone else has used this email account (%s) to register an account at %s."), $email, $config[sitename]);
		$message .= "\n\n";
		$message .= translate("The following is the member's information:");
		$message .= "\n\n-";
		$message .= translate("Username");
		$message .= ": ";
		$message .= $uname;
		$message .= "\n-";
		$message .= translate("Password");
		$message .= ": ";
		$message .= $makepass;
		$message .= "\n\n";
		$message .= translate("You can change your password by going to the USER AREA after you login.");
		$message .= "\n\n\n";
		$message .= "----------------------------------\n";
		$message .= "Webmaster of " . $config[sitename];
		$subject  = sprintf( translate("User password for %s"), $uname );
		$from="\"$config[sitename]\" <$config[notifyEmail]>";

		// find the charset
		if ($settingArray[language] != "") {
			$charset = getCharset($settingArray[language]);
		} else {
			// default is english
			$charset = "iso-8859-1";
		}

		$headers .= "Content-Type: text/plain; charset=$charset\n"; // Mime type
		$headers .= "From: $from\nX-Mailer: PHP\n";

		if ($config[use_w3b] == true) {
			// Now we will add the data into WWWThreads database
			include("wwwthreads/config.inc.php");
			include("wwwthreads/theme.inc.php");
			
			$w3Status = "User";
			$temp = file ("$config[root_path]/usertitles");
			list($post,$temp2) = split("\t",$temp[0]);
			chop($temp2);
			$w3Title = addslashes($temp2); 
			$currtime = time();
			$w3Date = $currtime+($config[adjusttime]*3600);
			$w3Group = $config[newusergroup];
			$w3User = $uname2;
			$w3Email = $email;
			$w3Display  = addslashes($theme[postlist]);
			$w3View     = addslashes($theme[threaded]);
			$w3EReplies = addslashes("Off");
			$w3PFormat    = addslashes($theme[post_format]);
			$w3Color    = " ";
			$w3ip = getenv('REMOTE_ADDR');
			$w3ip = addslashes($w3ip);

			$query = "INSERT INTO w3t_Users (U_Username,U_Password,U_Email,U_Totalposts,U_Laston,U_Status,U_Sort,
				U_Display,U_View,U_PostsPer,U_EReplies,U_Post_Format,U_Registered,U_RegEmail,U_RegIP,U_Groups,U_Title,U_Color,U_Privates) 
				VALUES ('$w3User','$cryptpass','$w3Email','0','$w3Date','$w3Status','$theme[sort]','$w3Display','$w3View',
				'$theme[postsperpage]','$w3EReplies','$w3PFormat','$w3Date','$w3Email','$w3ip','$w3Group','$w3Title','$w3Color','1')"; 

			mysql_select_db($config['dbname']);
			$result = mysql_query($query);
			if(!$result) echo mysql_errno(). ": ".mysql_error(). " b <br>";
		}

		
		// now we add the user in phpBB database
		if ($config[use_phpBB] == true) {
			include("$config[phpBB_path]/extention.inc");
			include("$config[phpBB_path]/config.php");
			include("$config[phpBB_path]/functions.php");
			include("$config[phpBB_path]/auth.php");
			
			$regdate = date("M d, Y");
			$md5_passwd = md5($makepass);
			
			$sql = "INSERT INTO users (user_id, username, user_regdate, user_email, user_icq, user_password, user_occ, user_intrest, user_from, user_website, user_sig, user_aim, user_viewemail, user_yim, user_msnm) 
				VALUES ($uid, '$uname2', '$regdate', '$email', '', '$md5_passwd', '', '', '', '', '', '', '', '', '')";

			if(!$result = mysql_query($sql, $db)) {		
				die("An Error Occured while trying to add the information into the database. Please go back and try again. <BR>$sql<BR>$mysql_error()");
				exit;
			}
		}
		
		mail($email, $subject, $message, $headers);

		ps_header("");

		echo "<br><br><br>";
		echo translate("You are now registered. You should receive your password at the email account you provided shortly.");
		echo "<br><br><br><br><br><br>";
	}
	ps_footer("");
}


function userinfo($uname, $mesg) {

// show the user info
	global $myTopic,$config;
	
	$db_uname = fixquotes($uname);
	$result = mysql_query("select u.uname,u.newsPostNum,u.userTitle,u.commentPostNum,i.email, i.femail, i.bio, i.name, i.url from ps_users_info i, ps_users u where u.uname='$db_uname' and u.uid=i.uid");
	$userinfo = mysql_fetch_array($result);
	$userArray=getCookie($config[user_cookie_name]);
	
	ps_header("");

	// show the user title
	if ($userinfo[userTitle] == "") {
		$titleList = FILE("$config[root_path]/usertitles");
		foreach ($titleList as $userTitle) {
			list($num,$myTitle) = split("\t",$userTitle);
			if ($userinfo[newsPostNum] >= $num) {
				$newsTitle = trim($myTitle);
			}
			if ($userinfo[commentPostNum] >= $num) {
				$commTitle = trim($myTitle);
			}
		}	
	} else {
		$newsTitle = trim($userinfo[userTitle]);
		$commTitle = trim($userinfo[userTitle]);
	}

	if (strcasecmp($userArray[username],$uname) == 0) {

		// showing my own info
		nav();
		echo "<h3>" . translate("User Preferences");
		if ($mesg) {
			echo "<font color=red size=-1> ($mesg)</font>";
		}

		echo "</h3>";
		echo translate( "This is user info page." );
		echo " ".translate( "You can edit your information here." );
		echo " "."<hr size=1>";
		echo "<h3>" . translate("User Info") . "</h3>"; 
		echo "<b>".translate("Username").":</b> $userinfo[uname]<br>\n";
		echo "<b>".translate("Real Name").":</b> $userinfo[name]<br>\n"; 
		
		echo "<b>".translate("Homepage").":</b> <a href=\"$userinfo[url]\">$userinfo[url]</a><br>\n"; 
		if ($config[use_fake_email]) {
			echo "<b>".translate("Email").":</b> <a href=\"mailto:$userinfo[femail]\">$userinfo[femail]</a><br>\n"; 
		} else {
			echo "<b>".translate("Email").":</b> <a href=\"mailto:$userinfo[email]\">$userinfo[email]</a><br>\n"; 
		}
		echo "<b>".translate("Number of comments has posted").":</b> $userinfo[commentPostNum] ($commTitle)<br>\n"; 
		echo "<b>".translate("Number of news has posted").":</b> $userinfo[newsPostNum] ($newsTitle)<br>\n"; 
		echo "<br><b>".translate("User Bio").":</b><br>$userinfo[bio]<br>\n"; 
		
	} elseif (strcasecmp($uname,$userinfo[uname]) == 0) {

		// showing someone else info
		echo "<h3>" . translate("User Info") . "</h3>"; 
		echo "<b>".translate("Username").":</b> $userinfo[uname]<br>\n";
		echo "<b>".translate("Real Name").":</b> $userinfo[name]<br>\n"; 
		
		echo "<b>".translate("Homepage").":</b> <a href=\"$userinfo[url]\">$userinfo[url]</a><br>\n"; 
		if ($config[use_fake_email]) {
			echo "<b>".translate("Email").":</b> <a href=\"mailto:$userinfo[femail]\">$userinfo[femail]</a><br>\n"; 
		} else {
			echo "<b>".translate("Email").":</b> <a href=\"mailto:$userinfo[email]\">$userinfo[email]</a><br>\n"; 
		}
		echo "<b>".translate("Number of comments has posted").":</b> $userinfo[commentPostNum] ($commTitle)<br>\n"; 
		echo "<b>".translate("Number of news has posted").":</b> $userinfo[newsPostNum] ($newsTitle)<br>\n"; 
		
		echo "<br><b>".translate("User Bio").":</b><br>$userinfo[bio]<br>\n"; 
		
	} else {

		// can't find user, no info show
		echo sprintf (translate("No information available for %s"),$uname) ;
	}
	
	ps_footer("");
}


function main($user,$stop,$mesg) {

// the main menu for login or register new user
	global $myTopic,$config;
	
	$userArray = getCookie($config[user_cookie_name]);

	// you login as a register user? show welcome mesg
	if(sizeof($userArray) <= 0) {
		
		ps_header("");
		// show custom mesg
		if ($mesg) {
			echo "<h3><font color=red>".translate($mesg)."</font></h3>";
		} else {
			if ($stop) {

				// no good, not login correctly
				echo "<h3><font color=red>".translate("Incorrect login")."</font></h3>";
			} else {
				echo "<h3>".translate("Welcome"). " " . $mesg . "</h3>";
			}
		}

		// user did not login, display login screen
		?>
		<table cellpadding=8 cellspacing=0 border=0 width="100%">
			<tr>
				<td width="50%" valign="top">
					<b><? echo translate("Login"); ?>:</b><br>
					<form action="user.php" method="post">
						<table border=0>
							<tr>
								<td colspan="2">
								<?
								if ($config[anon_users]>0) {
									echo translate( "Logging in will allow you to post comments as yourself. If you don't login, you will only be able to post as anonymous");
								} else {
									echo translate( "Logging in will enable you to post comments.  You can not post messages or submit news without an account.");
								}
								?>
								</td>
							</tr>
							<tr>
								<td><? echo translate("Username"); ?></td>
								<td><input type="text" name="uname" size=20 maxlength=20></td>
							</tr>
							<tr>
								<td><? echo translate("Password"); ?></td>
								<td><input type="password" name="pass" size=20 maxlength=20></td>
							</tr>
							<tr>
								<td colspan="2"><input type="radio" name="op" value="mailpasswd"><font size=-1><? echo translate("I've forgotten my password, please mail it to me."); ?></font></td>
							</tr>
							<tr>
								<td colspan="2"><input type="radio" name="op" value="login" CHECKED><font size="-1"><? echo translate("Log me in."); ?></font></td>
							</tr>
							<tr>
								<td colspan="2"><input type="submit" value="<? echo translate("Submit"); ?>"></td>
							</tr>
						</table>
					</form>
				</td>
				<td width="50%" valign="top">
					<form action="user.php" method="post">
						<b><? echo translate("New User"); ?>:</b>
						<table border=0>
							<tr>
								<td colspan="2">
									<? echo "<font size=3 color=red><b>" . translate("Password will be sent to the email address you enter, so please make sure you enter a valid email address.") . "</b></font>"; ?>
								</td>
							</tr>
							<tr>
								<td>
									<? echo translate("username"); ?></td><td><input type="text" name="uname" size=20 maxlength=20>
								</td>
							</tr>
							<tr>
								<td><? echo translate("Email"); ?></td><td><input type="text" name="email" size=20 maxlength=60></td>
							</tr>
							<tr>
								<td colspan="2">
									<input type="hidden" name="op" value="new user"><input type="submit" value="<? echo translate("Register"); ?>">
								</td>
							</tr>
						</table>
					</form>
				</td>
			</tr>
		</table>

		<?
		ps_footer("");
	} else {

		// user login already, send him to userinfo page
		userinfo($userArray[username],$mesg);
	}
}



function mail_password($uname) {

// mail the password to user's email address if they forget
	global $myTopic,$config;
	
	$db_uname = fixquotes($uname);
	$result = mysql_query("select i.email, u.pass, u.uname from ps_users_info i, ps_users u where u.uname='$db_uname' and u.uid=i.uid");
	list($email,$pass,$u_uname) = mysql_fetch_row($result);

	// can't find the user, throw error
	if($email == "") {
		errorPage("Sorry, no corresponding user info was found",$myTopic);
	} else {
		$host_name = getenv("REMOTE_ADDR");
		$message  = sprintf( translate("Notice from %s,"), $config[sitename] );
		$message .= "\n\n";
		$message .= sprintf( translate("A web user from %s has just requested your password for the account %s sent to this email address."), $host_name, $uname );
		
		$newpass=makepass();
		$clearPass = $newpass;

		$message .= "  ";
		$message .= sprintf( translate("For security reason, we now change the new password to '%s'."), $newpass );
		
		$message .= "\n\n";
		$message .= translate("If you didn't ask for this, don't worry about it.");
		$message .= "  ";
		$message .= translate("You are the one who is reading this message, not \"them\".");
		$message .= "  ";
		$message .= translate("Please use the new password we provide above and login.  You can change your password after you login.");
		$message .= "\n\n";
		$message .= "---------------------------------\n";
		$message .= "Webmaster of " . $config[sitename];
		$subject  = sprintf( translate("User password for %s"), $uname );
		$from="\"$config[sitename]\" <$config[notifyEmail]>";
	
		mail($email, $subject, $message, "From: $from\nX-Mailer: PHP/" . phpversion());

		// Next step: add the new password to the database
		if ($config[crypt_method] == 1) {
			$newpass=crypt($newpass);
		} 
		
		$query="update ps_users set pass='$newpass' where uname='$db_uname'";
		mysql_query($query);

		// Next step: add the new password to wwwthreads database
		if ($config[use_w3b] == true) {
			include("wwwthreads/config.inc.php");
			$query = "update w3t_Users set U_Password = '$newpass' where U_Username='$db_uname'";
			mysql_select_db($config['dbname']);
			mysql_query($query);
		}

		// we update the password in phpBB database
		if ($config[use_phpBB] == true) {
			include("$config[phpBB_path]/extention.inc");
			include("$config[phpBB_path]/config.php");
			include("$config[phpBB_path]/functions.php");
			include("$config[phpBB_path]/auth.php");

			$md5_passwd = md5($clearPass);
			$query = "update users set user_password = '$md5_passwd' where username = '$db_uname'";
			mysql_query($query);
		}

		
		ps_header("");
		echo sprintf( translate("Password for <b>%s</b> mailed to <b>%s</b>."), $uname, $email)."<br><br>";
		echo translate("With this new password, you may login <a href=\"user.php\">here</a>.")."<br>";
		ps_footer("");
	}
}

function login($uname, $pass) {

// function for user login
	global $myTopic,$config;

	$clearPass = $pass;
	$db_uname = fixquotes($uname);
	$result = mysql_query("select u.uid, u.uname, u.pass, u.status, h.topics_displayed, h.storynum, h.ublockon, c.umode, c.uorder, c.commentmax, h.language, h.resolution from ps_users u, ps_users_home h, ps_users_comments c where u.uname='" . $db_uname . "' and u.uid=c.uid and u.uid=h.uid and h.uid=c.uid");

	// if retult return 0, database error
	if ($result ==0) {
	    echo "Error on SQL Query (User request)";
	    exit;
	} else {
		
		// find the user, lets do login
		if(mysql_num_rows($result)==1) {
			
			list($u_uid, $u_uname, $u_pass, $u_status,$h_topics_displayed, $h_storynum, $h_ublockon, $u_mode, $u_order,  $u_commentmax, $u_lang, $h_resol) = mysql_fetch_row($result);
		
			// record the user ip address when they login
			$ip = getenv("REMOTE_ADDR");
			$result2 = mysql_query("update ps_users set loginIP='$ip', loginTime=now() where uid=$u_uid");
			
			if ($config[crypt_method] == 1) {
				$pass=crypt($pass,substr($u_pass,0,2));
			}
		
			// password not right, kick him out
			if (strcmp($u_pass,$pass)) {
				Header("Location: user.php?stop=1");
				return;
			}

			// set cookie
			putCookie($config[user_cookie_name],"userid",$u_uid);
			putCookie($config[user_cookie_name],"username",$u_uname);
			putCookie($config[user_cookie_name],"passwd",$pass);
			putCookie($config[user_cookie_name],"status",$u_status,"sendCookie"); // send this cookie now, we have enough info

			putCookie($config[setting_cookie_name],"umode",$u_mode);
			putCookie($config[setting_cookie_name],"uorder",$u_order);
			putCookie($config[setting_cookie_name],"commentmax",$u_commentmax);
			putCookie($config[setting_cookie_name],"storynum",$h_storynum);
			putCookie($config[setting_cookie_name],"ublockon",$h_ublockon);
			putCookie($config[setting_cookie_name],"topics",$h_topics_displayed);
			putCookie($config[setting_cookie_name],"resolution",$h_resol);
			putCookie($config[setting_cookie_name],"language",$u_lang,"sendCookie"); // send this cookie now, we have enough info

		
			// using wwwthreads?  send wwwthreads cookie as well
			if ($config[use_w3b] == true) {
				setcookie("w3t_myname","$u_uname",time()+$config[cookieTTL],"/",$config[CookieURL]);
				setcookie("w3t_mypass","$pass",time()+$config[cookieTTL],"/",$config[CookieURL]);
				setcookie("w3t_language","$u_lang",time()+$config[cookieTTL],"/",$config[CookieURL]);
			}

			// using phpBB?  send phpBB cookies and login
			if ($config[use_phpBB] == true) {
				$username = strtolower($uname);
				include("$config[phpBB_path]/extention.inc");
				include("$config[phpBB_path]/config.php");
				include("$config[phpBB_path]/functions.php");
				include("$config[phpBB_path]/auth.php");
				
				$userdata = get_userdata($username, $db);
				$sessid = new_session($userdata[user_id], $ip, $sesscookietime, $db);	
				set_session_cookie($sessid, $sesscookietime, $sesscookiename, $cookiepath, $cookiedomain, $cookiesecure);
				
			}

			// everything is good, go to user info page
			Header("Location: user.php?op=userinfo&uname=$u_uname");
	   } else {

			// throw error, login incorrect
			Header("Location: user.php?stop=1");
	   }
	}
}

function logout() {

// logout function
	global $myTopic,$config;

	$userArray = getCookie($config[user_cookie_name]);
	$db_uname = fixquotes($userArray[username]);
	
	// logout wwwthreads
	if ($config[use_w3b] == true) {
		setcookie("w3t_myname","","","/",$config[CookieURL]);
		setcookie("w3t_mypass","","","/",$config[CookieURL]);
		setcookie("w3t_language","","","/",$config[CookieURL]);
	}

	// using phpBB?  Logout
	if ($config[use_phpBB] == true) {
		$result = mysql_query("select uid from ps_users where uname = '$db_uname'");
		list($uid) = mysql_fetch_row($result);
		include("$config[phpBB_path]/extention.inc");
		include("$config[phpBB_path]/config.php");
		include("$config[phpBB_path]/functions.php");
		include("$config[phpBB_path]/auth.php");

		if ($user_logged_in) {
			end_user_session($uid, $db);
			setcookie($cookiename,'','',$cookiepath,$cookiedomain,$cookiesecure);
			setcookie("LastVisit",'','',$cookiepath,$cookiedomain,$cookiesecure);
			setcookie("LastVisitTemp",'','',$cookiepath,$cookiedomain,$cookiesecure);
		}
	}

	// clean cookie for pslash, yea, I put this last because some of the above function might still want to access these cookies.
	cleanCookie($config[user_cookie_name]);
	cleanCookie($config[setting_cookie_name]);

	
	ps_header("");
	?>
	<h3><? echo translate("You are now logged out"); ?></h3>
	<? echo translate("You are now logged out"); ?><br><br>
	<a href="index.php"><? echo translate("Go home"); ?></a>
	<?
	ps_footer("");
}


function edituser() {

// edit a user info
	global $myTopic,$config;
	
	$userArray = getCookie($config[user_cookie_name]);
	if (sizeof($userArray) <= 0) {
		errorPage("You are not authorized to edit!",$myTopic);
	}

	list($name, $email, $femail, $url, $bio) = mysql_fetch_row(mysql_query("select name, email, femail, url, bio from ps_users_info where uid='$userArray[userid]'"));

	// now we show the form
	
	ps_header("");
	nav();
	?>
	<h3><? echo translate("Edit Account Information"); ?></h3>

	<form action="user.php" method="post" name="edituser">
		<? echo "<b>".translate("Real Name")."</b> ".translate("(Optional, it gives people a hint who you really are)"); ?><br>
		<input type="text" name="name" value="<? echo"$name"; ?>" size=30 maxlength=60><br><br>
		<?
		if ($config[use_fake_email]) {
			echo "<b>".translate("Real Email Address")."</b> ".translate("(Required but it will not be showed publicly.)")."<br>";
			echo "$email <a href=\"user.php?op=changeEmail\"><b>[" . translate("Change Email Address") . "]</b></a><br><br>";
			echo "<b>".translate("Public Email")."</b> ".translate("(Optional and it will be displayed publicly.)")."<br>";
			echo "<input type=\"text\" name=\"femail\" value=\"$femail\" size=30 maxlength=60><br><br>";
		} else {
			echo "<b>".translate("Email")."</b> ".translate("(Required but it will not be showed publicly.)")."<br><br>";
			echo "$email<br><br>";
		}
		
		if ($config[email_forward] == true) {
			list($serviceEnable,$forwarder) = mysql_fetch_row(mysql_query("select serviceEnable,forwarder from ps_users where uid=$userArray[userid]"));

			// if email forwarder service enable, display it
			if ($serviceEnable == "true" && $forwarder == "") {

				// no email forwarder assigned yet, show the input box
				echo "<b>".translate("Email Forwarder")."</b><font color=red> ".translate("(You can only assign the email forwarder ONCE, you can NOT change it again. So, make sure you come up with a name you like before you assign it)"); ?></font><br>
				<input type="text" name="forwarder" value="<?=$forwarder?>" size=15 maxlength=15><b><?=$config[email_domain]?></b><br><br> <?
			} else if ($serviceEnable == "true" && $forwarder != "") {

				// email forwarder assigned already, just show the email address
				echo "<b>".translate("Email Forwarder")."</b><br>";
				echo "$forwarder".$config[email_domain]."<br><br>";
			}
		}
		?>
		<? echo "<b>".translate("Homepage")."</b> ".translate("(Optional, use http:// in front of your link)"); ?><br>
		<input type="text" name="url" value="http://<? echo str_replace("http://", "", $url); ?>" size=30 maxlength=100><br><br>
		<? echo "<b>".translate("Bio")."</b> ".translate("(Optional, 255 char limit)"); ?><br>
		<textarea wrap=virtual cols=40 rows=5 name=bio><? echo"$bio"; ?></TEXTAREA>
		<br><br>
		<? echo "<b>".translate("Password")."</b> ".translate("(Enter new password twice to change)"); ?><br>
		<input type="password" name="pass" size=10 maxlength=20> <input type="password" name="vpass" size=10 maxlength=20>
		<br><br>
		<input type="hidden" name="uname" value="<? echo"$userArray[username]"; ?>">
		<input type="hidden" name="uid" value="<? echo"$userArray[userid]"; ?>">
		<input type="hidden" name="op" value="Save User">
		<input type="submit" value="<? echo translate("Save User"); ?>">
	</form>
	<?
	ps_footer("");
}

function saveuser($uid, $name, $uname, $email, $femail, $url, $pass, $vpass, $bio, $forwarder) {

// function to save a user info
	global $myTopic,$config;
	
	$userArray = getCookie($config[user_cookie_name]);
	$db_uname = fixquotes($uname);
	$minpass = $config[minpass];
	list($checkpass) = mysql_fetch_row(mysql_query("select pass from ps_users where uid='$uid'"));

	// kick out if the password do not match
	if (strcmp($userArray[passwd],$checkpass) != 0 || ($userArray[userid] != $uid) ) {
		errorPage("Authentication error.  You can not update this account.  Please logout and log back in.",$myTopic);
	}
	
	// check input password match
	if ((isset($pass)) && ("$pass" != "$vpass")) {
		errorPage("The verification password is not the same as the first password",$myTopic);
	} elseif (($pass != "") && (strlen($pass) < $minpass)) {

		// check if the password have minimum length
		errorPage(sprintf("Sorry, your password must be at least %s charachters long",$minpass),$myTopic);
	} else {

		// looks good, update it
		if ($bio) $bio = FixQuotes(check_html($bio));
		if ($url == "http://") {

		   #it means no input for homepage
		   $url = "";
		}
		
		// do we enable the email forwarder service?
		if ($config[email_forward] == true) {
			$forwarder = fixquotes($forwarder);
			$forwarder = check_words($forwarder);
			$forwarder = strtolower($forwarder);
			if ($forwarder != "") {

				// check if forwarder format ok
				if (!preg_match("/^[a-zA-Z][a-zA-Z0-9_]+$/i",$forwarder)) {
					errorPage("Your email forwarder name has to be a combination of alphabet, numbers and underscore \"_\".  Moreover, the first character has to be an alphabet and no space in between.  Other characters are invalid!",$myTopic);
				}
				if (strlen($forwarder) > 20) {
					errorPage("Your email forwarder is too long!",$myTopic);	
				}
				$rs = mysql_query("select forwarder,forwarderEnabled from ps_users where uid=$userArray[userid]");
				list($myForwarder,$forwarderEnabled) = mysql_fetch_row($rs);
				mysql_free_result($rs);

				if ($myForwarder != $forwarder) {
					if ($forwarderEnabled == "true") {

						// forwarder enabled already, can not assign again
						errorPage("You can not change your forwarder again!",$myTopic);
					}
					$rs = mysql_query("select forwarder from ps_users where forwarder='$forwarder'");
					if (mysql_num_rows($rs) > 0) {

						// forwarder taken, throw error
						errorPage("This email forwarder name is taken, please choose another one.",$myTopic);
					}
					mysql_free_result($rs);

					// make forwarder on qmail
					mysql_query("update ps_users set forwarder='$forwarder', forwarderEnabled='true' where uid=$userArray[userid]");
					list($email) = mysql_fetch_row(mysql_query("select email from ps_users_info where uid=$userArray[userid]"));
		
					// make sure the email is valid before we write to the file...just to be safe.
					if (emailValid_Partial($email,3) != 0) {
						errorPage("Your email in database is not a valid email address, please change your primary email address!",$myTopic);
					}
					$fileName = ".qmail-" . $forwarder;
					$fullPath = $config[data_path] . "/" . $fileName;
					$str = "&" . $email;
					$fp = fopen($fullPath,"w");
					$len = strlen($str);
					fwrite($fp,$str,$len);
					fclose($fp);
					$forwarderUpdated = "true";
				}
			}
		}

		mysql_query("update ps_users_info set name='$name', femail='$femail', url='$url', bio='$bio' where uid=$uid");

		// need to update password?
		$clearPass = $pass;
		if ($pass != "") {
			if ($config[crypt_method] == 1) {
				$pass=crypt($pass);
			}
			mysql_query("update ps_users set pass='$pass' where uid='$uid'");
			
			$result = mysql_query("select u.uid, u.uname, u.pass, h.topics_displayed, h.storynum, h.ublockon, u.status  from ps_users u, ps_users_home h where u.uname='$db_uname' and u.uid=h.uid");

			// post the cookie
			if(mysql_num_rows($result)==1) {
				list($u_uid, $u_uname, $u_pass, $h_topics_displayed, $h_storynum, $h_ublockon, $u_status) = mysql_fetch_row($result);
				putCookie($config[user_cookie_name],"userid",$u_uid);
				putCookie($config[user_cookie_name],"username",$u_uname);
				putCookie($config[user_cookie_name],"passwd",$pass);
				putCookie($config[user_cookie_name],"status",$u_status,"sendCookie");  // send this cookie now, we have enough info
	
				// we update the password in wwwthread database
				if ($config[use_w3b] == true) {
					include("wwwthreads/config.inc.php");
					$query = "update w3t_Users set U_Password = '$pass' where U_Username='$db_uname'";
					mysql_select_db($config['dbname']);
					mysql_query($query);
					setcookie("w3t_myname","$uname",time()+$config[cookieTTL],"/",$config[ip_mapping_domain]);
					setcookie("w3t_mypass","$pass",time()+$config[cookieTTL],"/",$config[ip_mapping_domain]);
				}

				// we update the password in phpBB database
				if ($config[use_phpBB] == true) {
					include("$config[phpBB_path]/extention.inc");
					include("$config[phpBB_path]/config.php");
					include("$config[phpBB_path]/functions.php");
					include("$config[phpBB_path]/auth.php");

					$md5_passwd = md5($clearPass);
					$query = "update users set user_password = '$md5_passwd' where username = '$db_uname'";
					mysql_query($query);
				}
			} else {
				errorPage("Something is wrong.  Your record is not in the database!",$myTopic);
			}
		}
		
		$mesg = translate("Data+is+updated.");

		// we just update the forwarder, take them to the email forwarder page
		if ($forwarderUpdated ==  "true") {
			header("Location: user.php?op=emailForward");
			exit;
		}

		// else we go to the user info page
		Header("Location: user.php?mesg=$mesg"); 
	}
}

function edithome() {

// edit user homepage setting
	global $myTopic,$config;
	
	$userArray = getCookie($config[user_cookie_name]);
	if (sizeof($userArray) <= 0) {
		errorMsg("You are not authorized to edit!",$myTopic);
	}
	$settingArray = getCookie($config[setting_cookie_name]);
	
	list($storynum, $ublockon, $ublock, $topics_displayed,$resolution) = mysql_fetch_row(mysql_query("select storynum, ublockon, ublock, topics_displayed,resolution from ps_users_home where uid='$userArray[userid]'"));

	// show the form
	
	ps_header("");
	nav();
	?>
	<h3><? echo translate("Edit Your Homepage Setting"); ?></h3>
	<form action="user.php" method="post" name="edithome">
		<b><? echo translate("Language you want to use"); ?> </b><br>

		<select name="language">
			<option value="<? echo $settingArray[language] ?>"> <? if ($settingArray[language] == "big5") echo "Traditional Chinese"; else echo "English"; ?>
			<? if ($settingArray[language] != "big5") echo "<option value=\"big5\">Traditional Chinese"; ?>
			<? if ($settingArray[language] != "english") echo "<option value=\"english\">English"; ?>
		</select><p>

		<b><? echo translate("Resolution you want to use"); ?> </b><br>

		<select name="resolution">
			<option value="800x600" <? if ($resolution == "800x600") echo "selected";?> >800x600
			<option value="1024x768" <? if ($resolution == "1024x768") echo "selected";?> >1024x768
			<option value="1280x1024" <? if ($resolution == "1280x1024") echo "selected";?> >1280x1024
		</select><p>

		<br>
		<b><? echo translate("Max number of stories to display"); ?></b><br>
		<input type="text" name="storynum" size=3 maxlength=3 value=<? echo"$storynum"; ?>>
		<font size="-1"><? echo sprintf(translate("(max 127, default is %s)"),$config[limitnews]); ?></font><br>
		<?
		$topics_disabled = explode( " ", $topics_displayed );
		?>
		<br><br>
		<b><? echo translate("Topics") ?> :</b>
		<br><font size="-1"><? echo translate("(check the topics you're not interested in. They will be disabled)"); ?></font><br><?
		
		// display a list of the topics that can be disable
		$result = mysql_query("select tid, topic, icon, icon_url, alt, required from ps_topics where displayTopic='true'");
		if(mysql_num_rows($result) > 0) { ?>
			<table border="0"><?
				while(list($tid, $topic, $icon, $icon_url, $chng_alt, $required) = mysql_fetch_row($result)) { ?>
					<tr>
						<td>
							<? 
							if ($required!="Y") { ?>
								<INPUT type=checkbox value="<? echo $tid ?>" name="chng_topics_disabled[<? echo $tid ?>]" 
								<? if (in_array($tid,$topics_disabled)) { echo "checked"; } ?>><? 
							} else { 
								echo "<li>"; 
							} # topic required, can't be disabled 
							?>&nbsp;
						</td>
						<td>
							<? echo $topic ?>
						</td>
					</tr> <? 
				} ?>
			</table> <?
		}  ?>

		<br><br>
		<INPUT type=checkbox name=ublockon <? if ($ublockon==1) { echo "checked"; } ?>>
		<B><? echo translate("Activate User Block"); ?></B>
		<br><font size="-1"><? echo translate("(check the box and whatever you enter below will appear on the main page)"); ?></font><br>
		<textarea wrap=virtual cols=40 rows=5 name=ublock><? echo"$ublock"; ?></textarea>
		<br><br>
		<input type="hidden" name="uname" value="<? echo"$userArray[username]"; ?>">
		<input type="hidden" name="uid" value="<? echo"$userArray[userid]"; ?>">
		<input type="hidden" name="op" value="Save Home">
		<input type="submit" value="<? echo translate("Save Home"); ?>">
	</form>
	<?
	ps_footer("");
}


function savehome($uid, $uname, $storynum, $ublockon, $ublock,$language, $chng_topics_displayed,$resolution ) {

// save the homepage setting
	global $myTopic,$config;
	
	$userArray= getCookie($config[user_cookie_name]);
	$settingArray = getCookie($config[setting_cookie_name]);
	$db_uname = fixquotes($uname);

	list($checkpass) = mysql_fetch_row(mysql_query("select pass from ps_users where uid='$uid'"));
	if (strcmp($userArray[passwd],$checkpass) != 0 || ($userArray[userid] != $uid) ) {
		errorPage("Authentication error.  You can not update this account.  Please logout and log back in.",$myTopic);
	}
	
	// did tbe user set his own block?
	if(isset($ublockon)) $ublockon=1; else $ublockon=0;	
	$ublock = FixQuotes($ublock);
	mysql_query("update ps_users_home set storynum='$storynum', ublockon='$ublockon', ublock='$ublock', topics_displayed='$chng_topics_displayed', language='$language', resolution='$resolution' where uid=$uid");

	putCookie($config[setting_cookie_name],"umode",$settingArray[umode]);
	putCookie($config[setting_cookie_name],"uorder",$settingArray[uorder]);
	putCookie($config[setting_cookie_name],"commentmax",$settingArray[commentmax]);
	putCookie($config[setting_cookie_name],"storynum",$storynum);
	putCookie($config[setting_cookie_name],"ublockon",$ublockon);
	putCookie($config[setting_cookie_name],"topics",$chng_topics_displayed);
	putCookie($config[setting_cookie_name],"resolution",$resolution);
	putCookie($config[setting_cookie_name],"language",$language,"sendCookie"); // send this cookie now, we have enough info

	// wwwthreads update language
	if ($config[use_w3b] == true) {
		$myLang = getWWWThreadsLang($language);
		setcookie("w3t_language","$myLang",time()+$config[cookieTTL],"/",$config[ip_mapping_domain]);
	}

	// phpBB update language
	if ($config[use_phpBB] == true) {
		include("$config[phpBB_path]/extention.inc");
		include("$config[phpBB_path]/config.php");
		include("$config[phpBB_path]/functions.php");
		include("$config[phpBB_path]/auth.php");
		$myLang = getPhpBBLang($language);
		$query = "update users set user_lang = '$myLang' where username = '$db_uname'";
		
		mysql_query($query);
	}
	
	$mesg = translate("Data+is+updated.");
	Header("Location: user.php?mesg=$mesg");
}


function editcomm() {

// edit the comments setting
	global $myTopic,$config;
	
	$userArray = getCookie($config[user_cookie_name]);
	if (sizeof($userArray) <= 0) {
		errorPage("You are not authorized to edit!",$myTopic);
	}

	list($umode, $uorder, $commentmax) = mysql_fetch_row(mysql_query("select umode, uorder, commentmax from ps_users_comments where uid='$userArray[userid]'"));

	// show the form
	
	ps_header("");
	nav();
	?>
	<h3><? echo translate("Comment Preferences"); ?></h3>
	<form action="user.php" method="post">
		<b><? echo translate("Display Mode"); ?></b>
		<select name=umode>
			<option value="nocomments" <? if ($umode == 'nocomments') { echo "selected"; } ?>><? echo translate("No Comments"); ?>
			<option value="nested" <? if ($umode == 'nested') { echo "selected"; } ?>><? echo translate("Nested"); ?>
			<option value="flat" <? if ($umode == 'flat') { echo "selected"; } ?>><? echo translate("Flat"); ?>
			<option value="threaded" <? if (!isset($umode) || ($umode=="") || $umode=='threaded') { echo "selected"; } ?>><? echo translate("Threaded"); ?>
		</select>
		<br><br>
		<b><? echo translate("Sort Order"); ?></b>
		<select name=uorder>
			<option value="0" <? if (!$uorder) { echo "selected"; } ?>><? echo translate("Oldest First"); ?>
			<option value="1" <? if ($uorder==1) { echo "selected"; } ?>><? echo translate("Newest First"); ?>
		</select>
		<br><br>

		<b><? echo translate("Max Comment Length"); ?></b>
		<font size="-1"><? echo translate("(Truncates long comments, and adds a \"Read More\" link. Set really big to disable)"); ?></font><br>
		<input type="text" name="commentmax" value="<? echo $commentmax ?>" size=11 maxlength=11> <? echo translate("bytes"); ?> 
		<font size="-1"><? echo translate("(1024 bytes = 1K)"); ?></font>
		<br><br>
		<input type="hidden" name="uname" value="<? echo"$userArray[username]"; ?>">
		<input type="hidden" name="uid" value="<? echo"$userArray[userid]"; ?>">
		<input type="hidden" name="op" value="Save Comm">
		<input type="submit" value="<? echo translate("Save Comm"); ?>">
	</form>
	<?
	ps_footer("");
}

function savecomm($uid, $uname, $umode, $uorder, $comment_max) {

// save the comments setting
	global $myTopic,$config;
	
	$userArray = getCookie($config[user_cookie_name]);
	$settingArray = getCookie($config[setting_cookie_name]);
	list($checkpass) = mysql_fetch_row(mysql_query("select pass from ps_users where uid='$uid'"));
	if (strcmp($userArray[passwd],$checkpass) != 0 || ($userArray[userid] != $uid) ) {
		errorPage("Authentication error.  You can not update this account.  Please logout and log back in.",$myTopic);
	}
	
	putCookie($config[setting_cookie_name],"umode",$umode);
	putCookie($config[setting_cookie_name],"uorder",$uorder);
	putCookie($config[setting_cookie_name],"commentmax",$comment_max);
	putCookie($config[setting_cookie_name],"storynum",$settingArray[storynum]);
	putCookie($config[setting_cookie_name],"ublockon",$settingArray[ublockon]);
	putCookie($config[setting_cookie_name],"topics",$settingArray[topics]);
	putCookie($config[setting_cookie_name],"language",$settingArray[language],"sendCookie"); // send this cookie now, we have enough info
	
	mysql_query("update ps_users_comments set umode='$umode', uorder='$uorder', commentmax=$comment_max where uid=$uid");
	$mesg = translate("Data is updated.");
	Header("Location: user.php?mesg=$mesg");
}


function emailForward() {

// email forwarder service
	global $config,$myTopic;

	$userArray = getCookie($config[user_cookie_name]);
	if (sizeof($userArray) <= 0) {
		errorPage("You are not authorized to edit!",$myTopic);
	}
	
	// check to see if this service is enable
	if ($config[email_forward] == false) {
		errorPage("$config[no_forwarder_reason]",$myTopic);
	}
	
	$result = mysql_query("select serviceEnable,forwarder from ps_users where uid=$userArray[userid]");
	list($serviceEnable,$forwarder) = mysql_fetch_row($result);

	// service enable, we now describe the function
	if ($serviceEnable == "false" && $config[askQuestion]==true) {
		
		ps_header("");
		nav();
		echo "<h3>" . translate("Email Forwarder") . "</h3>";
		echo translate("$config[forward_desc]");
		echo "<br><br>";
		echo "<b>" . translate("$config[forward_desc2]") . "</b>";
		echo "<br><br>";
		echo "<center><font size=+1><a href=\"user.php?op=serviceCheck&serviceType=email\">".translate("Click here to Enable our service!")."</a></font><center>";
		
		echo "<br><br><br><br>";
		ps_footer("");
	} else {
		list($email) = mysql_fetch_row(mysql_query("select email from ps_users_info where uid=$userArray[userid]"));
		
		ps_header("");
		nav();
		echo "<h3>" . translate("Email Forwarder") . "</h3>";
		echo "<br>";
		if ($forwarder == "") {

			// no forwarder assigned yet, tell the user how to assign one
			echo translate("Service is enabled.  Please add your email forwarder in ");
			echo "<a href=\"$config[root_url]/user.php?op=edituser\"><b>" . translate("User Info") . "</b></a>.  ";
			echo "<font color=red>&nbsp" . translate("Remember, You can only assign the email forwarder ONCE. After you add your email forwarder it, you can NOT change the email forwarder again.  So please make sure you come up with a name you like before you assign.") . "</font>&nbsp;&nbsp;";
			echo sprintf(translate("Any email send to your new email forwarder will forward to your real email address (%s)."),$email);
		} else {

			// email forwarder assigned already.
			echo translate("Service is enabled.") . " ";
			echo sprintf(translate("Any email send to your email forwarder (<b>%s%s</b>) will forward to your real email address (<b>%s</b>).  If you just add your email forwarder, it will take 5 minutes before it is active."),$forwarder,$config[email_domain],$email);
		}
		$str = $userArray[username] ;
		echo "<br><br><br><br>";
		ps_footer("");
	}
}


function serviceCheck($serviceType) {

// ask question before enable service
	global $config,$myTopic;

	if ($config[askQuestion] == true) {
		$userArray = getCookie($config[user_cookie_name]);
		if (sizeof($userArray) <= 0) {
			errorPage("You are not authorized to edit!",$myTopic);
		}

		
		ps_header("");
		echo "<h3>".translate("Enable Service") . "</h3>";
		echo "<center>".translate("We provide services to Hong Kong Online gamers.  Please answer the questions below to activate the service.")."</center><br><br>";
		
		$result = mysql_query("select qid from ps_question");
		$count = 0;
		while (list($qid) = mysql_fetch_row($result)) {
			$qArray[$count] = $qid ;
			$count++;
		}
		mysql_free_result($result); 
		shuffle($qArray);
		$rand_array = array_rand($qArray,5);

		echo "<table border=1>";
		
		echo "<form action=\"user.php\" method=\"post\">";
		
		foreach ($rand_array as $key) {
			$key = $key +1;
			$result=mysql_query("select question from ps_question where qid=$key");
			while (list($question) = mysql_fetch_row($result)) {
				echo "<tr><td rowspan=5>$question</td></tr>";
				$result2 = mysql_query("select ansid from ps_answer where qid=$key");
				$count = 0;
				while (list($ansid) = mysql_fetch_row($result2)) {
					$aArray[$count] = $ansid;
					$count++;
				}
				mysql_free_result($result2);
				$ans_array = array_rand($aArray,4);
				foreach ($ans_array as $myAns) {
					$result3 = mysql_query("Select answer from ps_answer where ansid=$aArray[$myAns]");
					list($answer) = mysql_fetch_row($result3);
					echo "<tr><td><input type=\"radio\" name=\"question[$key]\" value=\"$aArray[$myAns]\"> $answer</td></tr>\n";
				}
				mysql_free_result($result3);
			}
		}
		
		echo "<input type=\"hidden\" name=\"op\" value=\"serviceCheckAction\">";
		echo "<input type=\"hidden\" name=\"serviceType\" value=\"$serviceType\">";
		echo "<tr><td><input type=\"submit\" value=\"Enable me!\"</td><td>&nbsp;</td></tr>";
		echo "</form>";
		echo "</table>";
		ps_footer("");
	} else {
		errorPage("Access Deny!",$myTopic);
	}
}


function serviceCheckAction($question,$serviceType) {

// check for question asked
	global $config,$myTopic;
	
	if ($config[askQuestion] == true) {
		if (!$question) {
			errorPage("Missing Field!",$myTopic);
		}

		$userArray = getCookie($config[user_cookie_name]);
		if (sizeof($userArray) <= 0) {
			errorPage("You are not authorized to edit!",$myTopic);
		}
		
		$wrong = "false";
		$count =0;
		while (list($quest,$ans) = each ($question)) {
			list($correctID) = mysql_fetch_row(mysql_query("select correctid from ps_question where qid=$quest"));
			if ($correctID != $ans) {
				$wrong = "true";
				$count++;
			}
		}
		
		if ($wrong == "true") {
			errorPage("Wrong answer,  Do it again.",$myTopic);
		} else {
			mysql_query("update ps_users set serviceEnable='true' where uid=$userArray[userid]");
			$mesg = translate("Service+is+enabled!");
			if ($serviceType == "email") {
				header("Location: user.php?op=emailForward");
			} else {
				header("Location: user.php?op=domainMap");
			}
		}		
	} else {
		errorPage("Access Deny!",$myTopic);
	}
}


function domainMap($mesg) {

// Domain Mapping service
	global $config,$myTopic;
	
	$userArray = getCookie($config[user_cookie_name]);
	if (sizeof($userArray) <= 0) {
		errorPage("You are not authorized to edit!",$myTopic);
	}
	
	// check to see if this service is enable
	if ($config[ip_mapping] == false) {
		errorPage("This function is not enabled!",$myTopic);
	}
	
	$result = mysql_query("select serviceEnable from ps_users where uid=$userArray[userid]");
	list($serviceEnable) = mysql_fetch_row($result);
	if ($serviceEnable == "false" && $config[askQuestion] == true) {
		$ip = getenv("REMOTE_ADDR");
		
		ps_header("");
		nav();
		echo "<h3>" . translate("Domain Mapping") ;
		echo "</h3>";
		echo translate("$config[ip_desc]");
		echo "<br><br>";
		echo translate("$config[ip_desc2]");
		echo "<br><br>";
		echo "<center><font size=+1><a href=\"user.php?op=serviceCheck&serviceType=domain\">".translate("Click here to Enable our service!")."</a></font><center>";
		echo "<br><br><br><br>";
		ps_footer("");
	} else {
		
		ps_header("");
		nav();
		$result = mysql_query("select domain from ps_domain where uid=$userArray[userid]");
		list($domain) = mysql_fetch_row($result);
		echo "<h3>" . translate("Domain Mapping") ;
		echo "</h3>";
		echo "<form action=\"user.php\" method=\"post\">";
		echo "<table>";
		echo "<tr>";
		echo "<td><b>" . translate("Domain Name:") . "</b></td>";
		echo "<td><input type=text name=domain value=\"$domain\">".translate("$config[ip_mapping_domain]")."</td>";
		echo "</tr>";
		echo "<tr>";
		echo "<td>&nbsp;</td>";
		echo "</tr>";
		$mesg = base64_decode($mesg);
		if ($mesg != "") {
			echo "<tr>";
			echo "<td colspan=2><font color=red> (" . $mesg . ")</font></td>";
			echo "</tr>";
		}
		echo "<tr><td colspan=2>" . sprintf(translate("$config[ip_desc3]"),$ip)  . "</td></tr>";
		echo "<tr><td>&nbsp;</td></tr>";
		echo "<tr><td><input type=\"submit\" value=\"Update IP\"></td></tr>";
		echo "<input type=\"hidden\" name=\"op\" value=\"updateDomain\">";
		echo "</table>";
		echo "</form>";
		ps_footer("");
	}
}


function updateDomain($domain) {
	
// update the domain of a user
	global $config,$myTopic;
	
	$userArray = getCookie($config[user_cookie_name]);
	if (sizeof($userArray) <= 0) {
		errorPage("You are not authorized to edit!",$myTopic);
	}
	
	// check to see if this service is enable
	if ($config[ip_mapping] == false) {
		errorPage("This function is not enabled!",$myTopic);
	}
	
	if (strlen($domain) > 30) {
		errorPage("Your domain is too long!",$myTopic);
	}

	if ($domain != "") {
		$domain = trim($domain);
		$len = strlen($domain);

		// domain name can not start with a dash
		if ($domain[0] == "-") {
			errorPage("Your domain name has to be a combination of alphabet, numbers and dash \"-\". Moreover, the first character has to be an alphabet and no space in between.  Other characters are invalid!",$myTopic);	
		}

		// domain name can not end with a dash
		if ($domain[$len-1] == "-") {
			errorPage("Your domain name has to be a combination of alphabet, numbers and dash \"-\". Moreover, the first character has to be an alphabet and no space in between.  Other characters are invalid!",$myTopic);
		}

		// check if it is a valid domain name
		if (!preg_match("/^[a-zA-Z0-9][a-zA-Z0-9-]*$/i",$domain)) {
			errorPage("Your domain name has to be a combination of alphabet, numbers and dash \"-\". Moreover, the first character has to be an alphabet and no space in between.  Other characters are invalid!",$myTopic);
		}

		$domain = fixquotes($domain);
		$domain = check_words($domain);
		$domain = strtolower($domain);

		// reserved domain prefix
		if ($domain == "ftp" || $domain == "www" || $domain == "ns1" || $domain == "webmaster" || $domain == "postmaster") {
			errorPage("Someone is using this domain name already, please choose another one.",$myTopic);
		}

		// check to see if the domain is in used or not
		$result = mysql_query("select domain from ps_domain where domain='$domain' and uid<>$userArray[userid]");
		if (mysql_num_rows($result) > 0) {
			errorPage("Someone is using this domain name already, please choose another one.",$myTopic);
		}

		// do the log
		list($oldDomain) = mysql_fetch_row(mysql_query("select domain from ps_domain where uid=$userArray[userid]"));
		if ($oldDomain != "") {
			mysql_query("insert into ps_domain_log values ($userArray[userid],'$oldDomain')");
		}
		$ip = getenv("REMOTE_ADDR");

		// now we update it
		mysql_query("update ps_domain set currentIP='$ip', domain='$domain', domainUpdated='false' where uid=$userArray[userid]");
		$mesg = "Your IP address <b>$ip</b> is now mapped to domain name <b>$domain".$config[ip_mapping_domain]."</b>.";
		$mesg = base64_encode($mesg);
		header("Location: user.php?op=domainMap&mesg=$mesg");
	}
}


function changeEmail($mesg) {

// function to change a user primary email address
	global $myTopic,$config;
	
	$userArray = getCookie($config[user_cookie_name]);
	if (sizeof($userArray) <= 0) {
		errorPage("You are not authorized to edit!",$myTopic);
	}
	
	// grap the email currently in the database
	$result = mysql_query("select email from ps_users_info where uid=$userArray[userid]");
	list($dbEmail) = mysql_fetch_row($result);

	// show the form
	
	ps_header("");
	nav();
	echo "<h3>" . translate("Change Email Address") ;
	echo "</h3>";
	echo translate("Since your Real Email Address is required in our service, if you need to change your Real Email Address, we will <b>reset your password</b> and send the new password to your new email address to make sure you have access to the new email account.  <font color=red>So, please make sure you have access to your new email address before you change the old one.</font>");
	echo "<br><br>";
	echo "<form action=\"user.php\" method=\"post\">";
	echo "<b>Real Email Address:</b> <input type=text name=email value=\"$dbEmail\">";
	if ($mesg != "") {
		echo "  <font color=red>($mesg)</font>";
	}
	echo "<br><br>";
	echo "<input type=hidden name=op value=\"updateEmail\">";
	echo translate("Please only click the Change Email button once, it will take a while.  Please be patience.");
	echo "<br>";
	echo "<input type=submit value=\"".translate("Change Email")."\">";
	echo "</form>";
	ps_footer("");
}


function updateEmail($email) {

// update a user's primary email address
	global $myTopic,$config;
	
	$userArray = getCookie($config[user_cookie_name]);
	$db_uname = fixquotes($userArray[username]);

	if (sizeof($userArray) <= 0) {
		errorPage("You are not authorized to edit!",$myTopic);
	}
	
	// check if the new email address is valid or not
	$email = trim($email);
	$tmp =emailValid_Full($email);
	if ($tmp[0] != TRUE) {
		errorPage("Invalid Email Address!",$myTopic);
	}

	// check to see if the email address is in use or not
	$result =  mysql_query("select email from ps_users_info where email='$email' and uid<>$userArray[userid]");
	if (mysql_num_rows($result) > 0) {
		errorPage("Someone use this email register already!",$myTopic);
	}
		
	// we will send a email to the user's new email account, make the email
	$message  = sprintf( translate("Notice from %s,"), $config[sitename] );
	$message .= "\n\n";
	$message .= sprintf( translate("User %s at %s has just changed his email address."), $userArray[username],$config[sitename] );
	
	$newpass=makepass();
	$clearPass = $newpass;

	$message .= "  ";
	$message .= sprintf( translate("For security reason, we now change the new password to '%s'."), $newpass );
	
	$message .= "\n";
	
	$message .= translate("Please use the new password we provide above and login.  You can change your password at Edit User Info in User Area after you login.");
	$message .= "\n\n";
	$message .= "---------------------------------\n";
	$message .= "Webmaster of " . $config[sitename];
	$subject  = sprintf( translate("User password for %s"), $uname );
	$from="\"$config[sitename]\" <$config[notifyEmail]>";
	
	// send the email
	mail($email, $subject, $message, "From: $from\nX-Mailer: PHP/" . phpversion());

	// Next step: add the new password to the database
	if ($config[crypt_method] == 1) {
		$newpass=crypt($newpass);
	}
	$query="update ps_users set pass='$newpass' where uid=$userArray[userid]";
	mysql_query($query);
	if ($config[debug] == true) {
		mysql_query("insert into ps_email_log values ($userArray[userid],'$email')");
	}
	mysql_query("update ps_users_info set email='$email' where uid=$userArray[userid]");
	

	// we now update the email forwarder if any.
	if ($config[email_forward] == true) {
		list($forwarder) = mysql_fetch_row(mysql_query("select forwarder from ps_users where uid=$userArray[userid]"));
		if ($forwarder != "") {
			$fileName = ".qmail-" . $forwarder;
			$fullPath = $config[data_path] . "/" . $fileName;
			$str = "&" . $email;
			$fp = fopen($fullPath,"w");
			$len = strlen($str);
			fwrite($fp,$str,$len);
			fclose($fp);
		}
	}

	// we update the password in wwwthread database
	if ($config[use_w3b] == true) {
		include("wwwthreads/config.inc.php");
		$query = "update w3t_Users set U_Password = '$newpass' where U_Username='$db_uname'";
		mysql_select_db($config['dbname']);
		mysql_query($query);
		include("config.php");
	}

	// we update the password in phpBB database
	if ($config[use_phpBB] == true) {
		include("$config[phpBB_path]/extention.inc");
		include("$config[phpBB_path]/config.php");
		include("$config[phpBB_path]/functions.php");
		include("$config[phpBB_path]/auth.php");

		$md5_passwd = md5($clearPass);
		$query = "update users set user_password = '$md5_passwd' where username = '$db_uname'";
		mysql_query($query);

		// logout phpBB
		if ($user_logged_in) {
			end_user_session($uid, $db);
			setcookie($cookiename,'','',$cookiepath,$cookiedomain,$cookiesecure);
			setcookie("LastVisit",'','',$cookiepath,$cookiedomain,$cookiesecure);
			setcookie("LastVisitTemp",'','',$cookiepath,$cookiedomain,$cookiesecure);
		}
	}

	// log the user out
	cleanCookie($config[user_cookie_name]);
	cleanCookie($config[setting_cookie_name]);

	// logout wwwthreads
	if ($config[use_w3b] == true) {
		setcookie("w3t_myname","","","/",$config[ip_mapping_domain]);
		setcookie("w3t_mypass","","","/",$config[ip_mapping_domain]);
		setcookie("w3t_language","","","/",$config[ip_mapping_domain]);
	}
	
	ps_header("");
	nav();
	echo "<h3>" . translate("You are now logout") . "</h3>";
	echo translate("Your email is changed.  Please check your email at your new email account and get your new password.  You can change your password at Edit User Info in User Area after you login.");
	echo "<br><br><br><br><br><br>";
	ps_footer("");
}


function urlMap($mesg) {

// URL mapping
	global $config,$myTopic;
	
	$userArray = getCookie($config[user_cookie_name]);
	if (sizeof($userArray) <= 0) {
		errorPage("You are not authorized to edit!",$myTopic);
	}
	
	// check to see if this service is enable
	if ($config[url_forward] == false ) {
		errorPage("This function is not enabled!",$myTopic);
	}
	
	$result = mysql_query("select serviceEnable from ps_users where uid=$userArray[userid]");
	list($serviceEnable) = mysql_fetch_row($result);
	if ($serviceEnable == "false" && $config[askQuestion]==true) {
		// the service is not activated yet, tell them to activate
		$ip = getenv("REMOTE_ADDR");
		
		ps_header("");
		nav();
		echo "<h3>" . translate("Domain Mapping") ;
		echo "</h3>";
		echo sprintf(translate("$config[url_desc]"),$config[url_mapping_domain]);
		echo "<br><br>";
		echo "<center><font size=+1><a href=\"user.php?op=serviceCheck&serviceType=url\">".translate("Click here to Enable our service!")."</a></font><center>";
		echo "<br><br><br><br>";
		ps_footer("");
	} else {

		// service activated, show the form for updating
		
		ps_header("");
		nav();
		$result = mysql_query("select url from ps_domain where uid=$userArray[userid]");
		list($url) = mysql_fetch_row($result);
		echo "<h3>" . translate("URL Forwarding") ;
		echo "</h3>";
		echo "<form action=\"user.php\" method=\"post\">";
		echo "<table><tr><td><b>" . translate("Your homepage address:") . "</b></td><td><input type=text name=url value=\"$url\" maxlength=\"50\" size=\"50\"> <font size=-1>(".translate("make sure your URL is start with http://").")</font></td></tr>";
		echo "<tr><td>&nbsp;</td></tr>";

		$mesg = base64_decode($mesg);
		if ($mesg != "") {
			echo "<tr><td colspan=2><font color=red> (" . $mesg . ")</font></td></tr>";
		}
		echo "<tr><td colspan=2>" . sprintf(translate("Type in your homepage address.  And any users type in <b>http://%s%s</b> will be forward to your homepage address."),$userArray[username],$config[url_mapping_domain])  . "</td></tr>";
		echo "<tr><td>&nbsp;</td></tr>";
		echo "<tr><td><input type=\"submit\" value=\"Update URL\"></td></tr>";
		echo "<input type=\"hidden\" name=\"op\" value=\"updateURL\">";
		echo "</table></form>";
		ps_footer("");
	}
}

function updateURL($url) {
	
// update the URL mapping
	global $config,$myTopic;
	
	$userArray = getCookie($config[user_cookie_name]);
	if (sizeof($userArray) <= 0) {
		errorPage("You are not authorized to edit!",$myTopic);
	}

	if (strlen($url) > 70) {
		errorPage("Your URL is too long!",$myTopic);
	}
	
	// check to see if this service is enable
	if ($config[url_forward] == false) {
		errorPage("This function is not enabled!",$myTopic);
	}
	
	$url = fixquotes($url);
	$url = check_words($url);
		
	mysql_query("update ps_domain set url='$url' where uid=$userArray[userid]");
	$mesg = sprintf(translate("URL <b>%s</b> is now mapped to domain name <b>%s%s</b>."),$url,$userArray[username],$config[url_mapping_domain]);
	$mesg = base64_encode($mesg);
	header("Location: user.php?op=urlMap&mesg=$mesg");
}



switch($op) {

	case "logout":
		logout();
		break;

	case "lost_pass":
		lost_pass();
		break;

	case "new user":
		confirmNewUser($uname, $email);
		break;

	case "finish":
		finishNewUser($uname, $email);
		break;

	case "mailpasswd":
		mail_password($uname);
		break;

	case "userinfo":
		userinfo($uname, $mesg);
		break;

	case "login":
		login($uname, $pass);
		break;

	case "edituser":
		edituser();
		break;

	case "Save User":
		saveuser($uid, $name, $uname, $email, $femail, $url, $pass, $vpass, $bio, $forwarder);
		break;

	case "edithome":
		edithome();
		break;

	case "Save Home":
		if (IsSet($chng_topics_disabled) ) {
			savehome($uid, $uname, $storynum, $ublockon, $ublock,$language, implode(' ',$chng_topics_disabled),$resolution);
		} else {
			savehome($uid, $uname, $storynum, $ublockon, $ublock, $language,'',$resolution);
		}
		break;

	case "editcomm":
		editcomm();
		break;

	case "Save Comm":
		savecomm($uid, $uname, $umode, $uorder, $commentmax);
		break;

	case "emailForward":
		emailForward();
		break;

	case "serviceCheck":
		serviceCheck($serviceType);
		break;

	case "serviceCheckAction":
		serviceCheckAction($question,$serviceType);
		break;

	case "domainMap":
		domainMap($mesg);
		break;

	case "updateDomain":
		updateDomain($domain);
		break;

	case "changeEmail":
		changeEmail($mesg);
		break;

	case "updateEmail":
		updateEmail($email);
		break;

	case "urlMap":
		urlMap($mesg);
		break;

	case "updateURL":
		updateURL($url);
		break;

	default:
		main($user,$stop,$mesg);
		break;
}
?>
Return current item: PSlash