Index: branches/rsr.v5.1.dev/web/punbb/login.php
===================================================================
--- branches/rsr.v5.1.dev/web/punbb/login.php	(revision 1)
+++ branches/rsr.v5.1.dev/web/punbb/login.php	(revision 3)
@@ -1,31 +1,14 @@
 <?php
-/***********************************************************************
-
-  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
-
-  This file is part of PunBB.
-
-  PunBB 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.
-
-  PunBB 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.  See the
-  GNU General Public License for more details.
-
-  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
-
-************************************************************************/
-
+
+/**
+ * Copyright (C) 2008-2011 FluxBB
+ * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
+ * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
+ */
 
 if (isset($_GET['action']))
 	define('PUN_QUIET_VISIT', 1);
 
-define('PUN_ROOT', './');
+define('PUN_ROOT', dirname(__FILE__).'/');
 require PUN_ROOT.'include/common.php';
 
@@ -38,30 +21,42 @@
 if (isset($_POST['form_sent']) && $action == 'in')
 {
-	$form_username = trim($_POST['req_username']);
-	$form_password = trim($_POST['req_password']);
-
-	$username_sql = ($db_type == 'mysql' || $db_type == 'mysqli') ? 'username=\''.$db->escape($form_username).'\'' : 'LOWER(username)=LOWER(\''.$db->escape($form_username).'\')';
-
-	$result = $db->query('SELECT id, group_id, password, save_pass FROM '.$db->prefix.'users WHERE '.$username_sql) or error('Impossible de retrouver les informations utilisateur', __FILE__, __LINE__, $db->error());
-	list($user_id, $group_id, $db_password_hash, $save_pass) = $db->fetch_row($result);
+	$form_username = pun_trim($_POST['req_username']);
+	$form_password = pun_trim($_POST['req_password']);
+	$save_pass = isset($_POST['save_pass']);
+
+	$username_sql = ($db_type == 'mysql' || $db_type == 'mysqli' || $db_type == 'mysql_innodb' || $db_type == 'mysqli_innodb') ? 'username=\''.$db->escape($form_username).'\'' : 'LOWER(username)=LOWER(\''.$db->escape($form_username).'\')';
+
+	$result = $db->query('SELECT * FROM '.$db->prefix.'users WHERE '.$username_sql) or error('Unable to fetch user info', __FILE__, __LINE__, $db->error());
+	$cur_user = $db->fetch_assoc($result);
 
 	$authorized = false;
 
-	if (!empty($db_password_hash))
-	{
-		$sha1_in_db = (strlen($db_password_hash) == 40) ? true : false;
-		$sha1_available = (function_exists('sha1') || function_exists('mhash')) ? true : false;
-
-		$form_password_hash = pun_hash($form_password);	// This could result in either an SHA-1 or an MD5 hash (depends on $sha1_available)
-
-		if ($sha1_in_db && $sha1_available && $db_password_hash == $form_password_hash)
-			$authorized = true;
-		else if (!$sha1_in_db && $db_password_hash == md5($form_password))
+	if (!empty($cur_user['password']))
+	{
+		$form_password_hash = pun_hash($form_password); // Will result in a SHA-1 hash
+
+		// If there is a salt in the database we have upgraded from 1.3-legacy though havent yet logged in
+		if (!empty($cur_user['salt']))
 		{
-			$authorized = true;
-
-			if ($sha1_available)	// There's an MD5 hash in the database, but SHA1 hashing is available, so we update the DB
-				$db->query('UPDATE '.$db->prefix.'users SET password=\''.$form_password_hash.'\' WHERE id='.$user_id) or error('Impossible de modifier le mot de passe', __FILE__, __LINE__, $db->error());
+			if (sha1($cur_user['salt'].sha1($form_password)) == $cur_user['password']) // 1.3 used sha1(salt.sha1(pass))
+			{
+				$authorized = true;
+
+				$db->query('UPDATE '.$db->prefix.'users SET password=\''.$form_password_hash.'\', salt=NULL WHERE id='.$cur_user['id']) or error('Unable to update user password', __FILE__, __LINE__, $db->error());
+			}
 		}
+		// If the length isn't 40 then the password isn't using sha1, so it must be md5 from 1.2
+		else if (strlen($cur_user['password']) != 40)
+		{
+			if (md5($form_password) == $cur_user['password'])
+			{
+				$authorized = true;
+
+				$db->query('UPDATE '.$db->prefix.'users SET password=\''.$form_password_hash.'\' WHERE id='.$cur_user['id']) or error('Unable to update user password', __FILE__, __LINE__, $db->error());
+			}
+		}
+		// Otherwise we should have a normal sha1 password
+		else
+			$authorized = ($cur_user['password'] == $form_password_hash);
 	}
 
@@ -70,14 +65,25 @@
 
 	// Update the status if this is the first time the user logged in
-	if ($group_id == PUN_UNVERIFIED)
-		$db->query('UPDATE '.$db->prefix.'users SET group_id='.$pun_config['o_default_user_group'].' WHERE id='.$user_id) or error('Uimpossible de modifier le statut utilisateur', __FILE__, __LINE__, $db->error());
+	if ($cur_user['group_id'] == PUN_UNVERIFIED)
+	{
+		$db->query('UPDATE '.$db->prefix.'users SET group_id='.$pun_config['o_default_user_group'].' WHERE id='.$cur_user['id']) or error('Unable to update user status', __FILE__, __LINE__, $db->error());
+
+		// Regenerate the users info cache
+		if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
+			require PUN_ROOT.'include/cache.php';
+
+		generate_users_info_cache();
+	}
 
 	// Remove this users guest entry from the online list
-	$db->query('DELETE FROM '.$db->prefix.'online WHERE ident=\''.$db->escape(get_remote_address()).'\'') or error('Impossible de supprimer de la liste des utilisateur en ligne', __FILE__, __LINE__, $db->error());
-
-	$expire = ($save_pass == '1') ? time() + 31536000 : 0;
-	pun_setcookie($user_id, $form_password_hash, $expire);
-
-	redirect($_POST['redirect_url'], $lang_login['Login redirect']);
+	$db->query('DELETE FROM '.$db->prefix.'online WHERE ident=\''.$db->escape(get_remote_address()).'\'') or error('Unable to delete from online list', __FILE__, __LINE__, $db->error());
+
+	$expire = ($save_pass == '1') ? time() + 1209600 : time() + $pun_config['o_timeout_visit'];
+	pun_setcookie($cur_user['id'], $form_password_hash, $expire);
+
+	// Reset tracked topics
+	set_tracked_topics(null);
+
+	redirect(htmlspecialchars($_POST['redirect_url']), $lang_login['Login redirect']);
 }
 
@@ -85,5 +91,5 @@
 else if ($action == 'out')
 {
-	if ($pun_user['is_guest'] || !isset($_GET['id']) || $_GET['id'] != $pun_user['id'])
+	if ($pun_user['is_guest'] || !isset($_GET['id']) || $_GET['id'] != $pun_user['id'] || !isset($_GET['csrf_token']) || $_GET['csrf_token'] != pun_hash($pun_user['id'].pun_hash(get_remote_address())))
 	{
 		header('Location: index.php');
@@ -91,12 +97,12 @@
 	}
 
-	// Remove user from "users online" list.
-	$db->query('DELETE FROM '.$db->prefix.'online WHERE user_id='.$pun_user['id']) or error('Impossible de supprimer de la liste des utilisateur en ligne', __FILE__, __LINE__, $db->error());
+	// Remove user from "users online" list
+	$db->query('DELETE FROM '.$db->prefix.'online WHERE user_id='.$pun_user['id']) or error('Unable to delete from online list', __FILE__, __LINE__, $db->error());
 
 	// Update last_visit (make sure there's something to update it with)
 	if (isset($pun_user['logged']))
-		$db->query('UPDATE '.$db->prefix.'users SET last_visit='.$pun_user['logged'].' WHERE id='.$pun_user['id']) or error('Impossible de modifier les donnÃ©es de visite de l\'utilisateur', __FILE__, __LINE__, $db->error());
-
-	pun_setcookie(1, random_pass(8), time() + 31536000);
+		$db->query('UPDATE '.$db->prefix.'users SET last_visit='.$pun_user['logged'].' WHERE id='.$pun_user['id']) or error('Unable to update user visit data', __FILE__, __LINE__, $db->error());
+
+	pun_setcookie(1, pun_hash(uniqid(rand(), true)), time() + 31536000);
 
 	redirect('index.php', $lang_login['Logout redirect']);
@@ -111,56 +117,90 @@
 	if (isset($_POST['form_sent']))
 	{
+		// Start with a clean slate
+		$errors = array();
+
 		require PUN_ROOT.'include/email.php';
 
-		// Validate the email-address
+		// Validate the email address
 		$email = strtolower(trim($_POST['req_email']));
 		if (!is_valid_email($email))
-			message($lang_common['Invalid e-mail']);
-
-		$result = $db->query('SELECT id, username FROM '.$db->prefix.'users WHERE email=\''.$db->escape($email).'\'') or error('Impossible de retrouver les informations utilisateur', __FILE__, __LINE__, $db->error());
-
-		if ($db->num_rows($result))
+			$errors[] = $lang_common['Invalid email'];
+
+		// Did everything go according to plan?
+		if (empty($errors))
 		{
-			// Load the "activate password" template
-			$mail_tpl = trim(file_get_contents(PUN_ROOT.'lang/'.$pun_user['language'].'/mail_templates/activate_password.tpl'));
-
-			// The first row contains the subject
-			$first_crlf = strpos($mail_tpl, "\n");
-			$mail_subject = trim(substr($mail_tpl, 8, $first_crlf-8));
-			$mail_message = trim(substr($mail_tpl, $first_crlf));
-
-			// Do the generic replacements first (they apply to all e-mails sent out here)
-			$mail_message = str_replace('<base_url>', $pun_config['o_base_url'].'/', $mail_message);
-			$mail_message = str_replace('<board_mailer>', $pun_config['o_board_title'].' '.$lang_common['Mailer'], $mail_message);
-
-			// Loop through users we found
-			while ($cur_hit = $db->fetch_assoc($result))
+			$result = $db->query('SELECT id, username, last_email_sent FROM '.$db->prefix.'users WHERE email=\''.$db->escape($email).'\'') or error('Unable to fetch user info', __FILE__, __LINE__, $db->error());
+
+			if ($db->num_rows($result))
 			{
-				// Generate a new password and a new password activation code
-				$new_password = random_pass(8);
-				$new_password_key = random_pass(8);
-
-				$db->query('UPDATE '.$db->prefix.'users SET activate_string=\''.pun_hash($new_password).'\', activate_key=\''.$new_password_key.'\' WHERE id='.$cur_hit['id']) or error('Impossible de modifier les donnÃ©es d\'activation', __FILE__, __LINE__, $db->error());
-
-				// Do the user specific replacements to the template
-				$cur_mail_message = str_replace('<username>', $cur_hit['username'], $mail_message);
-				$cur_mail_message = str_replace('<activation_url>', $pun_config['o_base_url'].'/profile.php?id='.$cur_hit['id'].'&action=change_pass&key='.$new_password_key, $cur_mail_message);
-				$cur_mail_message = str_replace('<new_password>', $new_password, $cur_mail_message);
-
-				pun_mail($email, $mail_subject, $cur_mail_message);
-			}
-
-			message($lang_login['Forget mail'].' <a href="mailto:'.$pun_config['o_admin_email'].'">'.$pun_config['o_admin_email'].'</a>.');
+				// Load the "activate password" template
+				$mail_tpl = trim(file_get_contents(PUN_ROOT.'lang/'.$pun_user['language'].'/mail_templates/activate_password.tpl'));
+
+				// The first row contains the subject
+				$first_crlf = strpos($mail_tpl, "\n");
+				$mail_subject = trim(substr($mail_tpl, 8, $first_crlf-8));
+				$mail_message = trim(substr($mail_tpl, $first_crlf));
+
+				// Do the generic replacements first (they apply to all emails sent out here)
+				$mail_message = str_replace('<base_url>', get_base_url().'/', $mail_message);
+				$mail_message = str_replace('<board_mailer>', $pun_config['o_board_title'], $mail_message);
+
+				// Loop through users we found
+				while ($cur_hit = $db->fetch_assoc($result))
+				{
+					if ($cur_hit['last_email_sent'] != '' && (time() - $cur_hit['last_email_sent']) < 3600 && (time() - $cur_hit['last_email_sent']) >= 0)
+						message($lang_login['Email flood'], true);
+
+					// Generate a new password and a new password activation code
+					$new_password = random_pass(8);
+					$new_password_key = random_pass(8);
+
+					$db->query('UPDATE '.$db->prefix.'users SET activate_string=\''.pun_hash($new_password).'\', activate_key=\''.$new_password_key.'\', last_email_sent = '.time().' WHERE id='.$cur_hit['id']) or error('Unable to update activation data', __FILE__, __LINE__, $db->error());
+
+					// Do the user specific replacements to the template
+					$cur_mail_message = str_replace('<username>', $cur_hit['username'], $mail_message);
+					$cur_mail_message = str_replace('<activation_url>', get_base_url().'/profile.php?id='.$cur_hit['id'].'&action=change_pass&key='.$new_password_key, $cur_mail_message);
+					$cur_mail_message = str_replace('<new_password>', $new_password, $cur_mail_message);
+
+					pun_mail($email, $mail_subject, $cur_mail_message);
+				}
+
+				message($lang_login['Forget mail'].' <a href="mailto:'.$pun_config['o_admin_email'].'">'.$pun_config['o_admin_email'].'</a>.', true);
+			}
+			else
+				$errors[] = $lang_login['No email match'].' '.htmlspecialchars($email).'.';
+			}
 		}
-		else
-			message($lang_login['No e-mail match'].' '.htmlspecialchars($email).'.');
-	}
-
-
-	$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / '.$lang_login['Request pass'];
-	$required_fields = array('req_email' => $lang_common['E-mail']);
+
+	$page_title = array(pun_htmlspecialchars($pun_config['o_board_title']), $lang_login['Request pass']);
+	$required_fields = array('req_email' => $lang_common['Email']);
 	$focus_element = array('request_pass', 'req_email');
+	define ('PUN_ACTIVE_PAGE', 'login');
 	require PUN_ROOT.'header.php';
 
+// If there are errors, we display them
+if (!empty($errors))
+{
+
+?>
+<div id="posterror" class="block">
+	<h2><span><?php echo $lang_login['New password errors'] ?></span></h2>
+	<div class="box">
+		<div class="inbox error-info">
+			<p><?php echo $lang_login['New passworderrors info'] ?></p>
+			<ul class="error-list">
+<?php
+
+	foreach ($errors as $cur_error)
+		echo "\t\t\t\t".'<li><strong>'.$cur_error.'</strong></li>'."\n";
+?>
+			</ul>
+		</div>
+	</div>
+</div>
+
+<?php
+
+}
 ?>
 <div class="blockform">
@@ -173,10 +213,10 @@
 					<div class="infldset">
 						<input type="hidden" name="form_sent" value="1" />
-						<input id="req_email" type="text" name="req_email" size="50" maxlength="50" />
+						<label class="required"><strong><?php echo $lang_common['Email'] ?> <span><?php echo $lang_common['Required'] ?></span></strong><br /><input id="req_email" type="text" name="req_email" size="50" maxlength="80" /><br /></label>
 						<p><?php echo $lang_login['Request pass info'] ?></p>
 					</div>
 				</fieldset>
 			</div>
-			<p><input type="submit" name="request_pass" value="<?php echo $lang_common['Submit'] ?>" /><a href="javascript:history.go(-1)"><?php echo $lang_common['Go back'] ?></a></p>
+			<p class="buttons"><input type="submit" name="request_pass" value="<?php echo $lang_common['Submit'] ?>" /><?php if (empty($errors)): ?> <a href="javascript:history.go(-1)"><?php echo $lang_common['Go back'] ?></a><?php endif; ?></p>
 		</form>
 	</div>
@@ -192,9 +232,35 @@
 
 // Try to determine if the data in HTTP_REFERER is valid (if not, we redirect to index.php after login)
-$redirect_url = (isset($_SERVER['HTTP_REFERER']) && preg_match('#^'.preg_quote($pun_config['o_base_url']).'/(.*?)\.php#i', $_SERVER['HTTP_REFERER'])) ? htmlspecialchars($_SERVER['HTTP_REFERER']) : 'index.php';
-
-$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / '.$lang_common['Login'];
+if (!empty($_SERVER['HTTP_REFERER']))
+{
+	$referrer = parse_url($_SERVER['HTTP_REFERER']);
+	// Remove www subdomain if it exists
+	if (strpos($referrer['host'], 'www.') === 0)
+		$referrer['host'] = substr($referrer['host'], 4);
+
+	// Make sure the path component exists
+	if (!isset($referrer['path']))
+		$referrer['path'] = '';
+
+	$valid = parse_url(get_base_url());
+	// Remove www subdomain if it exists
+	if (strpos($valid['host'], 'www.') === 0)
+		$valid['host'] = substr($valid['host'], 4);
+
+	// Make sure the path component exists
+	if (!isset($valid['path']))
+		$valid['path'] = '';
+
+	if ($referrer['host'] == $valid['host'] && preg_match('%^'.preg_quote($valid['path'], '%').'/(.*?)\.php%i', $referrer['path']))
+		$redirect_url = $_SERVER['HTTP_REFERER'];
+}
+
+if (!isset($redirect_url))
+	$redirect_url = 'index.php';
+
+$page_title = array(pun_htmlspecialchars($pun_config['o_board_title']), $lang_common['Login']);
 $required_fields = array('req_username' => $lang_common['Username'], 'req_password' => $lang_common['Password']);
 $focus_element = array('login', 'req_username');
+define('PUN_ACTIVE_PAGE', 'login');
 require PUN_ROOT.'header.php';
 
@@ -207,16 +273,20 @@
 				<fieldset>
 					<legend><?php echo $lang_login['Login legend'] ?></legend>
-						<div class="infldset">
-							<input type="hidden" name="form_sent" value="1" />
-							<input type="hidden" name="redirect_url" value="<?php echo $redirect_url ?>" />
-							<label class="conl"><strong><?php echo $lang_common['Username'] ?></strong><br /><input type="text" name="req_username" size="25" maxlength="25" tabindex="1" /><br /></label>
-							<label class="conl"><strong><?php echo $lang_common['Password'] ?></strong><br /><input type="password" name="req_password" size="16" maxlength="16" tabindex="2" /><br /></label>
-							<p class="clearb"><?php echo $lang_login['Login info'] ?></p>
-							<p><a href="register.php" tabindex="4"><?php echo $lang_login['Not registered'] ?></a>&#160;&#160;
-							<a href="login.php?action=forget" tabindex="5"><?php echo $lang_login['Forgotten pass'] ?></a></p>
+					<div class="infldset">
+						<input type="hidden" name="form_sent" value="1" />
+						<input type="hidden" name="redirect_url" value="<?php echo pun_htmlspecialchars($redirect_url) ?>" />
+						<label class="conl required"><strong><?php echo $lang_common['Username'] ?> <span><?php echo $lang_common['Required'] ?></span></strong><br /><input type="text" name="req_username" size="25" maxlength="25" tabindex="1" /><br /></label>
+						<label class="conl required"><strong><?php echo $lang_common['Password'] ?> <span><?php echo $lang_common['Required'] ?></span></strong><br /><input type="password" name="req_password" size="25" tabindex="2" /><br /></label>
+
+						<div class="rbox clearb">
+							<label><input type="checkbox" name="save_pass" value="1" tabindex="3" /><?php echo $lang_login['Remember me'] ?><br /></label>
 						</div>
+
+						<p class="clearb"><?php echo $lang_login['Login info'] ?></p>
+						<p class="actions"><span><a href="register.php" tabindex="5"><?php echo $lang_login['Not registered'] ?></a></span> <span><a href="login.php?action=forget" tabindex="6"><?php echo $lang_login['Forgotten pass'] ?></a></span></p>
+					</div>
 				</fieldset>
 			</div>
-			<p><input type="submit" name="login" value="<?php echo $lang_common['Login'] ?>" tabindex="3" /></p>
+			<p class="buttons"><input type="submit" name="login" value="<?php echo $lang_common['Login'] ?>" tabindex="4" /></p>
 		</form>
 	</div>
