<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Revised: 2/7/2012	ELL
// Added table prefix handling.
// Revised: 7/2/2012	ELL
// Adapted for website user page restrictions as well.
// Revised: 11/16/2012	ELL
// Added insertion of salt into password before encrypting.
//
	include ("check_session.php");
	include ("encrypt_decrypt.php");

	$user_name = $_POST['user_name'];
	$password = $_POST['password'];
	$AccessLevel = $_POST['AccessLevel'];
	$email = (isset($_POST['email']) ? $_POST['email'] : "");
	$first_name = (isset($_POST['first_name']) ? $_POST['first_name'] : "");
	$last_name = (isset($_POST['last_name']) ? $_POST['last_name'] : "");
	$table = $_POST['table'];
	$no_prefix = $_REQUEST['no_prefix'];
	
	//First check to see if user exists.
	if (!isset($table) || ($table == "-not selected-") || ($table == ""))
	{
		echo MANAGE_USERS_NO_TABLE_TO_ADD_USER_TO_1_ERR . " " . CLICK_WORD . " <a href=\"manage_page_access.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . MANAGE_USERS_NO_TABLE_TO_ADD_USER_TO_2_ERR;
		exit;
	}
	
	if (isset($no_prefix) && ($no_prefix == 1))
		$prefix = "";
	else
		$prefix = BWB_TABLE_PREFIX;
			
	$query = "SELECT * FROM `" . $prefix . $table . "` WHERE `UserID` = '$user_name'";
		
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$tmp_user_name = $row["UserID"];
	if (isset($tmp_user_name))
	{
		if (!isset($table) || ($table == "users") || ($table == ""))
			echo $user_name . " " . CLASSES_ADD_CLASS_ADD_ERR . " " . CLICK_WORD . " <a href=\"users.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . MANAGE_USERS_USER_ALREADY_EXISTS_ERR;
		else
			echo $user_name . " " . CLASSES_ADD_CLASS_ADD_ERR . " " . CLICK_WORD . " <a href=\"manage_page_access.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . MANAGE_USERS_USER_ALREADY_EXISTS_ERR;
		exit;
	}
	
	// Insert salt into password.
	$pos = rand(0, (strlen($password)-1) );
	$pass1 = substr($password, 0, $pos);
	$pass2 = substr($password, $pos);
	if ($_POST['website_user'] == 1)
		$salted_pass = $pass1 . BWB_PUB_SALT . $pass2;
	else
		$salted_pass = $pass1 . BWB_SALT . $pass2;
	// Encrypt password using user name as key.
	$enc_password = doEncrypt($salted_pass, $user_name);
	
	// Add user to database.
	$query = "INSERT INTO `" . $prefix . $table . "` SET `UserID`='$user_name', `password`='$enc_password', `AccessLevel`='$AccessLevel', `email`='$email', `first_name`='$first_name', `last_name`='$last_name'";
			
	$cnt = $bwb_dbh->exec($query);
	
	$_SESSION['last_user'] = $user_name;
	
	if ($cnt == 1)
		echo "user_name=$user_name@@@@@password=$password@@@@@AccessLevel=$AccessLevel@@@@@email=$email@@@@@first_name=$first_name@@@@@last_name=$last_name";
	else
		echo "-no data-";
?>
