<?

/*
FlexCMS (http://www.flexcms.com)
Flexible, Powerful, Affordable.

Contents of this file are protected by the copyright
notice found at http://www.flexcms.com/flex/pages/copyright.html,
and its usage is subject to the terms of the licensing agreement 
available at http://www.flexcms.com/flex/pages/license.html
*/



	// ========================================================================================
	// process login form
	// ========================================================================================

	$PageTitle = $MsgText[0][192];
	$BrowserTitle = $MsgText[0][192];
	$LocationBar = '<a href="'.$IndexURL.'">'.$MsgText[0][1].'</a> > '.$MsgText[0][192];
	
	
	ReadFormArguments();
	Global $FormArguments;
	


	if ($FormArguments['Username'] != '' && $FormArguments['Password'] != '') {
	
		//$FormArguments['Username'] = strtolower($FormArguments['Username']);

		DBConnect();
	
		//query the database and validate the input from the login page
		//assign $result to do a lookup up in the database flexcms users table
		//where the username is equal to the database field username, validates password
		$query = "select * from `".$Settings['DBPrefix']."core-Users` where Username='".$FormArguments['Username']."' LIMIT 1";
		$result = mysql_query($query) or die (mysql_error());
		$row = mysql_fetch_array($result);
		
		// if any rows are returned, the username exists
		if (mysql_num_rows($result) != 0 && $FormArguments['Username'] == $row['Username']) {
			
	
			// encrypt the password, correcting for the fact that php only encrypts the first eight characters
			$EncryptedUsername = crypt($FormArguments['Username'],substr($FormArguments['Username'],0,2));
			$EncryptedUsername = substr($EncryptedUsername,0,8);
			$LoopCount = ceil(strlen($FormArguments['Password'])/8);
			for ($i = 1; $i <= $LoopCount; $i++) {
				$FinalPassword .= crypt(substr($FormArguments['Password'],($i*8)-8,8),substr($FormArguments['Password'],0,2));
			}
			$FormArguments['Password'] = $EncryptedUsername.$FinalPassword;
			
					
			
			
			if ($row['Password'] == $FormArguments['Password'] && ($row['Verified'] == 'y' || $Settings['VerifyEmails'] != 'y')) {
			
					if ($row['LastFailedLogin']+10 > GetTimestamp()) {
						sleep($row['LastFailedLogin'] + 10 - GetTimestamp());
					}
					
					
					$query = "update `".$Settings['DBPrefix']."core-Users` set SessionLength='10', LastFailedLogin='0', ResetCode='', ShoppingCartContents='".$HTTP_COOKIE_VARS[$CookieName.'Cart']."' where Username='".$FormArguments['Username']."' LIMIT 1";
					$result = mysql_query($query) or die (mysql_error());
					
					
					$IPAddress = $HTTP_SERVER_VARS["REMOTE_ADDR"];
					
					$query = "delete from `".$Settings['DBPrefix']."core-RecentActivity` where User='".$FormArguments['Username']."'";
					$result = mysql_query($query) or die (mysql_error());
					
					$query = "update `".$Settings['DBPrefix']."core-RecentActivity` set User='".$row['Username']."', Name='".addslashes($row['DisplayName'])."', LastLocation='/login', UserOrGuest='u' where User='".$IPAddress."' LIMIT 1";
					$result = mysql_query($query) or die (mysql_error());
					
					
					if ($Settings['di'] == 'y') {
						@unlink('./install.php');
						@unlink('./v'.$Settings['iv'].'.data');
						@unlink('./v'.$Settings['iv'].'.map');
						@unlink('./v'.$Settings['iv'].'.sql');
						
						$query = "update `".$Settings['DBPrefix']."core-Settings` set Value='n' where Name='di' limit 1";
						$result = mysql_query($query) or die (mysql_error());					
					}
					
					
					
					
				
					ob_start();
				
						$CookieData = $FormArguments['Username'] . '==' . $FormArguments['Password'];
						
						
						if ($FormArguments['StayLoggedIn'] == 'y') {
							setcookie ($CookieName, $CookieData, (GetTimestamp()+(60*60*24*365)), '/');
						}
						else {
							setcookie ($CookieName, $CookieData, 0, '/');
						}
						
						setcookie($CookieName.'Cart',false, 0, '/');
						
						
						if ($FormArguments['ReturnTo'] == '') {
							if ($Settings['DestAfterLogin'] != '') {
								header('Location: ' . $MainURL . '/' . $Settings['DestAfterLogin']);
							}
							else {
								header('Location: ' . $IndexURL);
							}
						}
						else {
							if (substr($FormArguments['ReturnTo'], 0, 3) != '+++') {						
								header('Location: ' . $MainURL . '/' . str_replace('+++','/',$FormArguments['ReturnTo']) . '.html');
							}
							else {
								header('Location: ' . $MainURL . str_replace('+++','/',$FormArguments['ReturnTo']) . '.html');
							}
						}
						
					ob_end_flush();
				
			}
			else if ($row['Password'] == $FormArguments['Password']) {
				// password correct but not yet verified
				
				$PageTitle = $MsgText[0][501];
				$PageContents = $MsgText[0][660];
				
				
				$Message = $MsgText[0][143]."\n\n".$MsgText[0][656]."\n\n".$MainURL."/register-verify/".$row['Email']."/".$row['ConfirmationCode']."\n\n\n\n".$MsgText[0][142].','."\n".$Settings['SiteName']."\n".$IndexURL;
				mail($row['Email'], $MsgText[0][143], $Message, 'From: "'.$Settings['SiteName'].'" <'.$Settings['ContactEmail'].'>','-f'.$Settings['ContactEmail']);
				
			}
			else{
				$query = "update `".$Settings['DBPrefix']."core-Users` set LastFailedLogin='".GetTimestamp()."' where Username='".$FormArguments['Username']."' LIMIT 1";
				$result = mysql_query($query) or die (mysql_error());
				
				if ($row['LastFailedLogin']+10 > GetTimestamp()) {
					sleep($row['LastFailedLogin'] + 10 - GetTimestamp());
				}
				
			 	$PageTitle = $MsgText[0][501];
				$PageContents = $MsgText[0][502].'<br><br><a href="'.$MainURL.'/login/'.$FormArguments['ReturnTo'].'">'.$MsgText[0][503].'</a><br><br><a href="'.$MainURL.'/lost_password.html">'.$MsgText[0][500].'</a>';
			}
		}
		// no rows returned, username doesn't exist
		else {
			sleep(5);
			
			$PageTitle = $MsgText[0][501];
			$PageContents = $MsgText[0][504].'<br><br><a href="'.$MainURL.'/login/'.$FormArguments['ReturnTo'].'">'.$MsgText[0][503].'</a><br><br><a href="'.$MainURL.'/lost_password.html">'.$MsgText[0][500].'</a>';
		}
	}
	// username and/or password empty
	else {
		sleep(5);
		
		$PageTitle = $MsgText[0][501];
		$PageContents = $MsgText[0][505].'<br><br><a href="'.$MainURL.'/login/'.$FormArguments['ReturnTo'].'">'.$MsgText[0][503].'</a><br><br><a href="'.$MainURL.'/lost_password.html">'.$MsgText[0][500].'</a>';	
	}
	

	// ========================================================================================




?>
