<?php
/*
 * This file is part of a larger software package. Please read the License file 
 * in the root of this installation for terms of usage and distribution.
 * 
 * @author The Web Pro Miami, Inc. <info@thewebpro.com>
 * @copyright The Web Pro Miami, Inc. <info@thewebpro.com>, http://www.thewebpro.com/
 * 
 * CORE: manage/edit/user.php - version 1.0
*/

// Secure and connect
require("../../inc/dbconnect.php");
require("../inc/secure_page.php");

// bring in other required files
require("../../inc/config.php");
require("../inc/lang.php");
include("../inc/calendar.php");
include("../inc/rc4.php");

// Get passed-in vars
$nRecID = (isset($_GET['id']) ? $_GET['id'] : NULL);
if(!$nRecID){ $nRecID = (isset($_POST['id']) ? $_POST['id'] : NULL); }
$nEditMode = (isset($_GET['editMode']) ? $_GET['editMode'] : NULL);
if(!$nEditMode){ $nEditMode = (isset($_POST['editMode']) ? $_POST['editMode'] : NULL); }

// Additional security check if this account is a limited user (give only self access)
$nMyUserID = nGetUserIDFromName($ValidUser);
if(!$nAdminAccess && $nRecID!=$nMyUserID){ exit; }

// AJAX Specific vars
$nPassThru = "?id=$nRecID";
$nDivToUpdate = "ajaxUserEdit"; // must be same as parent edit page
$nPageInDiv = "edit/user.php";

// Get info
if($nRecID){
	$nSQL = "SELECT * FROM nEditor WHERE nID='$nRecID' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"];
		$nUser = $Row["nUser"];
		$nPass = $Row["nPass"];
		$nEmail = $Row["nEmail"];
		//$nPass = rc4Decrypt("xyz123",$Row["nPass"]);
		$nAdmin = $Row["nAdmin"];
		$nUserLang = $Row["nUserLang"];
		switch($nUserLang){
			case "en": $nUserLangText = "English"; break;
			case "es": $nUserLangText = "Espa&ntilde;ol"; break;
			default:
				$nUserLangText = "";
				if($nDefaultLang){ $nUserLangText = nGetLangName($nDefaultLang); }
				break;
		}
		if($nAdmin){ $nAdminText = "<em>"._("Administrator")."</em>"; } else { $nAdminText = "<em>"._("Editor")."</em>"; }
		$nLoginDT = $Row["nLastLoginDate"];
		if($nLoginDT && $nLoginDT!="0000-00-00 00:00:00"){
			$nLoginDTARRAY = explode(" ",$nLoginDT);
			$nDateDiff = nGetDateDiffDays($nLoginDTARRAY[0]);
			switch($nDateDiff){
				case 0: $nLoginDT = _("Today").", ".date("g:i A",strtotime($nLoginDT)); break;
				case 1: $nLoginDT = _("Yesterday").", ".date("g:i A",strtotime($nLoginDT)); break;
				default: $nLoginDT = nDateToDisplay($nLoginDT)." - ".date("g:i A",strtotime($nLoginDT));
			}
		} else {
			$nLoginDT = "<span class=\"caption\"><em>&lt;"._("never")."&gt;</em></span>";
		}
		if(!$nUser){ $nUserText="<span class=\"caption\"><em>&lt;"._("unnamed")."&gt;</em></span>"; } else { $nUserText = $nUser; }
		if($nPass){ $nPassText = "********"; } else { $nPassText = "<em>&lt;"._("not set")."&gt;</em>"; }
		if(!$nEmail){ $nEmailText="<span class=\"caption\"><em>&lt;"._("not set")."&gt;</em></span>"; } else { $nEmailText = $nEmail; }
	} else { echo "<div align=\"center\" style=\"padding:20px;\"><em>"._("No record found.")."</em></div>"; }
} else { echo "<div align=\"center\" style=\"padding:20px;\"><em>"._("No record available. Invalid ID.")."</em></div>"; }
?>

<?php if(!$nEditMode){ ?>

		<table width="100%" border="0" cellspacing="0" cellpadding="0">
		  <tr>
			<td width="75" valign="top" style="padding-right:10px;"><img src="assets/images/lock.png" alt="" width="65" height="63" border="0"></td>
			<td valign="top" style="padding-right:40px;">
				<?php if($nUserText){ echo "<strong>"._("Username").":</strong> $nUserText<BR><BR>"; } ?>
				<?php if($nPassText){ echo "<strong>"._("Password").":</strong> $nPassText<BR><BR>"; } ?>
				<?php if($nEmailText){ echo "<strong>"._("E-mail").":</strong> $nEmailText<BR><BR>"; } ?>
			</td>
			<td valign="top">
				<?php if($nUserLangText){ echo "<strong>"._("Language:")."</strong> $nUserLangText<BR><BR>"; } ?>
				<?php if($nAdminText){ echo "<strong>"._("Access Level").":</strong> $nAdminText<BR><BR>"; } ?>
				<?php if($nLoginDT){ echo "<span class=\"caption\"><strong>"._("Last Login").":</strong> $nLoginDT</span><BR><BR>"; } ?>
			</td>
		  </tr>
		</table><BR>
		<div class="clearfix grey-highlight">
			<div class="input" style="text-align:center;">
				<?php if($nAdminAccess){ ?>
				<input type="button" name="nEdit" value="<?php echo _("Edit"); ?>" class="blue button" onClick="loadContent('<?php echo $nDivToUpdate?>','<?php echo $nPageInDiv.$nPassThru?>&editMode=1');"></input> 
				<input type="button" name="nDelete" value="<?php echo _("Delete User"); ?>" class="button" onClick="openDeleteDialog('usr',<?=$nRecID?>,'<?php echo _("Delete User"); ?>');"></input>
				<?php } else { ?>
				<input type="button" name="nEdit" value="<?php echo _("Edit My Account"); ?>" class="blue button" onClick="loadContent('<?php echo $nDivToUpdate?>','<?php echo $nPageInDiv.$nPassThru?>&editMode=1');"></input> 
				<?php } ?>
			</div>
		</div>

<?php } ?>

<?php if($nEditMode){

include("../inc/form_class.php");

$nFormName = "FormUserEdit";
$nForm1 = new Form();
$nForm1->Name = $nFormName;
$nForm1->Action = $_SERVER['PHP_SELF'];
if($nRecID){
	$nForm1->SubmitText = _("Update");
	$nForm1->CancelText = _("Cancel");
	$nForm1->CancelRedirect = "loadContent('$nDivToUpdate','$nPageInDiv$nPassThru');";
	$nForm1->CancelRedirectIsJS = true;
	// Form DB settings
	$nForm1->ModifyDBTable = "nEditor";
	$nForm1->ModifyDBField = "nID";
	$nForm1->ModifyDBID = "'$nRecID'";
	$nForm1->DBLink = $Link;
	$nForm1->nUseADODB = false;
	// AJAX settings
	$nForm1->SubmitToJS = "return submitForm('$nDivToUpdate','$nPageInDiv$nPassThru',this.name);return false;";
}
$nForm1->DontProcess = "id,editMode,nSendEmail";
// Form styling
$nForm1->FormClass = "form no-border";
$nForm1->CleanMarkup = true;
$nForm1->SubmitClass = "button blue";
$nForm1->CancelClass = "button";
$nForm1->ButtonTemplate = "<div class=\"clearfix grey-highlight\"><div class=\"input no-label\">[#Buttons#]</div></div>\n";
$nForm1->FieldTemplate = "<div id=\"[#RowID#]\" class=\"clearfix\" style=\"[#RowStyle#]\">[#Label#]<div class=\"input\" style=\"[#ItemStyle#]\">[#BeforeField#][#Field#][#AfterField#]<span class=\"info\">[#Caption#]</span></div></div>\n";
$nForm1->GroupTemplate = "<div id=\"[#ID#]\" style=\"[#Style#]\" class=\"[#Class#]\">\n[#Name#][#FieldCode#]\n</div>\n";

// Create groups
$nFormGroup1 = new FormGroup();

// Create fields
$nFormField = new FormField("hidden","id");
$nFormField->Value = $nRecID;
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("hidden","editMode");
$nFormField->Value = "1";
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("text","nUser",_("Login Username:"));
$nFormField->Value = $nUser;
$nFormField->Caption = _("(max. 50 characters)");
$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormField = $nForm1->AddValidation("minlength",$nFormField,4);
$nFormField = $nForm1->AddValidation("maxlength",$nFormField,50);
$nFormField->Class = "large";
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("password","nPass",_("Login Password:"));
$nFormField->Value = $nPass;
$nFormField->Caption = _("(max. 16 characters)");
$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormField = $nForm1->AddValidation("minlength",$nFormField,4);
$nFormField = $nForm1->AddValidation("maxlength",$nFormField,16);
//$nFormField = $nForm1->AddEncoding("RC4",$nFormField);
$nFormField->Class = "large";
$nFormGroup1->AddField($nFormField);

if($nAdminAccess){
	$nFormField = new FormField("select","nAdmin",_("Access Level:"));
	$nEditorText = _("Editor");
	$nAdminText = _("Administrator");
	$nFormField->DataARRAY = array(
		"0" => $nEditorText,
		"1" => $nAdminText);
	if($nAdmin){ $nFormField->SelectedARRAY = array("1" => "selected"); }
	$nFormField->Class = "large";
	$nFormGroup1->AddField($nFormField);
}

$nFormField = new FormField("select","nUserLang",_("Language:"));
$nFormField->DataARRAY = array(
	"en" => "English",
	"es" => "Espa&ntilde;ol");
if($nUserLang){ $nFormField->SelectedARRAY = array("$nUserLang" => "selected"); }
$nFormField->Class = "xlarge";
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("text","nEmail",_("E-mail Address:"));
$nFormField->Value = $nEmail;
$nFormField = $nForm1->AddValidation("email",$nFormField);
$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormField->Class = "xlarge";
$nFormGroup1->AddField($nFormField);

if($nAdminAccess){
	$nFormField = new FormField("checkbox","nSendEmail","");
	$nFormField->DataARRAY = array(
		"nSendEmail" => _("Send this new user an email with their login information now.<BR><BR>")
	);
	//$nFormField->SelectedARRAY["nSendEmail"] = "selected";
	$nFormField->LabelStyle = "width:auto;";
	$nFormGroup1->AddField($nFormField);
}

// Finalize and display form
$nForm1->AddGroup($nFormGroup1);
$nFormToDisplay = $nForm1->GetForm();

// AJAX redirect if form submitted w/o error, otherwise display form (again, if necessary)
if($nForm1->HasProcessed){
	// change back-end language preference
	$nUserLangChoice = $_POST['nUserLang'];
	$_SESSION['nUserLang'] = $nUserLangChoice;
	
	// Post-processing
	$nEmail = $_POST["nEmail"];
	$nSendEmail = $_POST["nSendEmail"];
	
	if($nSendEmail){
		//////////////////////////////
		$nSubject = _("Your login information for")." $nSiteName";
		$nHdr  = 'MIME-Version: 1.0' . "\r\n";
		$nHdr .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$nHdr .= 'From: Web Pro Manager <info@thewebpro.com>' . "\r\n";
		// Mail it
		$nBody = _("<strong>You are now an editor of the $nCoName website!</strong><BR><BR>A new user has been setup for you:")."<BR><BR><div align=\"center\" style=\"font-size:larger;\">"._("Username").": <strong style=\"font-size:larger;color:#777;\">$nUser</strong><BR>"._("Password").": <strong style=\"font-size:larger;color:#777;\">$nPass</strong></div><BR>"._("You can login here:")." <a href=\"".$nFullSitePath."manage/\">".$nFullSitePath."manage/</a><BR><BR>"._("Once logged in, you can change your username/password.")."<BR><BR>";
		if(!@mail($nEmail,$nSubject,$nBody,$nHdr)){ echo "<strong style=\"color:red;\">"._("UNABLE TO EMAIL: There was a problem e-mailing the new user login information.  Please check your server settings.")."</strong><BR><BR>"; }
		//////////////////////////////
	}
	
	// log system event
	$nSystemEventDesc = "User settings updated: [nUserID:$nRecID]";
	$Query = "INSERT INTO nSystemEventLog (nEventTime,nEventDesc,nEditorUser) VALUES ('".date("Y-m-d H:i:s")."','$nSystemEventDesc','$ValidUser')";
	mysql_select_db($DBName); mysql_query($Query, $Link);
	
	echo "<script>loadContent('$nDivToUpdate','$nPageInDiv$nPassThru');</script>";
} else {
	echo $nFormToDisplay;
}

} ?>
<?php
function nGetUserIDFromName($nUserName){
	global $DBName,$Link;
	if(!$nUserName){ return; }
	$Query = "SELECT nID FROM nEditor WHERE nUser='$nUserName' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	if($Row = mysql_fetch_array($Result)) {
		$nUserID = $Row["nID"];
	}
	return $nUserID;
}
function nGetLangName($nLangCode){
	if(!$nLangCode){ return; }
	// Get lang file
	$path = "../../lang/def/$nLangCode.php";
	if(file_exists("$path")){ require("$path"); }
	return $nLang;
}
?>
<?php require("../../inc/db_close.php"); ?>
