<?php
include($O__libPath . "/functions/server/O__tableMaker.php");
include($O__libPath . "/functions/server/O__backupData.php");

$O__userIDtarget = $O__URLpath[1];
if($O__URLpath[1] == "default"){ $O__userIDtarget  = O__xCrypt($O__userID,"e"); } // if user is editing themself
$O__output = "";

function O__checkEditAccess(){
	global $O__usersDataPath, $O__URLpath, $O__PT, $O__AT, $O__userID, $O__signLog, $O__logNotes;
	
	$O__fileData = O__XMLdata($O__usersDataPath . "users/" . O__xCrypt($O__userID,"e") . ".xml", 0, 0);
	$O__userGroups = explode(",", trim($O__fileData->groups));
	unset($O__fileData);	
	
	// Load user and user's groups permisions
	for($i=0;$i<count($O__userGroups);$i++){
		$O__groupPath = $O__usersDataPath . "groups/" . strtolower($O__userGroups[$i]) . ".xml";
		$O__manageAccess = 0;
		$O__PTcount = 0;
		$O__PTpermission = 0;
		$O__ATpermission = 0;
		
		if (file_exists($O__groupPath)){ // If user group exists
			$O__fileData = O__XMLdata($O__groupPath, 0, 0);

			// Check PageType Permission
			foreach($O__fileData->permissions->pageType as $PTpermissions) {
				if ($PTpermissions->name == "O__users") { $O__PTpermission = 1; break; }
				$O__PTcount++;
			}
			
			// Check ActionType Permission
			if ($O__PTpermission == 1){ // if PageType permission found
				$O__ATpermissions = $O__fileData->permissions->pageType[$O__PTcount]->actions;
				$O__actionPermissions = explode("," , $O__ATpermissions);					
				foreach($O__actionPermissions as $O__action){
					$O__action = trim($O__action);
					if ($O__action == "manage") { $O__ATpermission = 1; break; }
				}
			}
			
		}
		
		if (($O__PTpermission == 1)&&($O__ATpermission == 1)){
			$O__manageAccess = 1;
			break; // Permission to edit all users found.  Stop looking through granted permissions.
		}
	
	}
	
	// Now check if user is editing self or someone else	
	if(($O__manageAccess == 0)&&(O__xCrypt($O__userID,"e") != $O__URLpath[1])){
		if ($O__signLog == 1){ O__logger("access",$_SERVER["REQUEST_URI"],"Access Denied",$O__userID,$O__logNotes); }
		O__pageResponse("403");
	}
}

function O__operation(){
	global $O__DBpath, $O__usersDataPath, $O__userIDtarget, $O__PTATmsg, $O__logNotes;
	if (isset($_POST["O__name"])){ $O__name = $_POST["O__name"]; }
	if (isset($_POST["O__nameFirst"])){ $O__nameFirst = $_POST["O__nameFirst"]; }
	if (isset($_POST["O__nameLast"])){ $O__nameLast = $_POST["O__nameLast"]; }
	if (isset($_POST["O__passwordNew"])){ $O__passwordNew = $_POST["O__passwordNew"]; }
	if (isset($_POST["O__passwordVerify"])){ $O__passwordVerify = $_POST["O__passwordVerify"]; }
	$O__target = $_POST["O__target"];
	$O__source = $_POST["O__source"];
	$O__operation = $_POST["O__operation"];
	$O__nameEncrypted = O__xCrypt($O__name,"e");
	
	switch($O__operation){
		case "identityUpdate":
			$O__fileData = O__XMLdata($O__usersDataPath . "users/" . $O__userIDtarget . ".xml", 0, 0);
			
			$O__sysMsgHeadline = "Identity Update";
			if (($O__name == "")||($O__nameFirst == "")||($O__nameLast == "")) {
				$O__sysMsgBody = "Failed. Fields can't be left blank. No changes made.";
				$O__PTATmsg = O__sysMsg($O__sysMsgHeadline, $O__sysMsgBody, "O__sysMsgAlert");
			} else if((strpos($O__name, " ") !== false)||(strpos($O__nameFirst, " ") !== false)||(strpos($O__nameLast, " ") !== false)){
				$O__sysMsgBody = "Failed. Fields may not contain spaces. No changes made.";
				$O__PTATmsg = O__sysMsg($O__sysMsgHeadline, $O__sysMsgBody, "O__sysMsgAlert");
			} else if (($O__userIDtarget != $O__nameEncrypted)&&(file_exists($O__usersDataPath . "users/" . $O__nameEncrypted . ".xml"))){
				$O__sysMsgBody = "Failed. New username you have provided is not available. No changes made.";
				$O__PTATmsg = O__sysMsg($O__sysMsgHeadline, $O__sysMsgBody, "O__sysMsgAlert");
			} else {
				// Update the identity fields
				$O__fileData->name = $O__name;
				$O__fileData->nameFirst = $O__nameFirst;
				$O__fileData->nameLast = $O__nameLast;				
				$O__fileData = $O__fileData->asXML();

				// Backup and the old user file
				O__backupData($O__usersDataPath . "users/" . $O__userIDtarget . ".xml",0);

				// If new username
				if ($O__userIDtarget != $O__nameEncrypted){
					O__dataWrite($O__usersDataPath . "users/" . $O__nameEncrypted . ".xml",$O__fileData); // write new user file
					unlink($O__usersDataPath . "users/" . $O__userIDtarget . ".xml"); // delete the old one
					$O__userIDtarget = $O__nameEncrypted; // update target ID to the new one
				} else { // otherwise, update existing user file
					O__dataWrite($O__usersDataPath . "users/" . $O__userIDtarget . ".xml",$O__fileData);
				}		

				clearstatcache(); // clear cache so newest version can be loaded
				$O__sysMsgBody = "Success. '" . $O__name . "' identity has been updated.";
				$O__PTATmsg = O__sysMsg($O__sysMsgHeadline, $O__sysMsgBody, "O__sysMsgNeutral");
			}
			$O__logNotes .= $O__sysMsgHeadline . ". " . $O__sysMsgBody;

			break;
		case "passwordUpdate":
			$O__fileData = O__XMLdata($O__usersDataPath . "users/" . $O__userIDtarget . ".xml", 0, 0);

			$O__sysMsgHeadline = "Password Update";
			if (($O__passwordNew == "")||($O__passwordVerify == "")) { 
				$O__sysMsgBody = "Failed. Password fields can't be left blank.";
				$O__PTATmsg = O__sysMsg($O__sysMsgHeadline, $O__sysMsgBody, "O__sysMsgAlert");
			} else if(strpos($O__passwordNew, " ") !== false){
				$O__sysMsgBody = "Failed. Passwords may not contain spaces.";
				$O__PTATmsg = O__sysMsg($O__sysMsgHeadline, $O__sysMsgBody, "O__sysMsgAlert");
			} else if($O__passwordNew != $O__passwordVerify){
				$O__sysMsgBody = "Failed. New and verified passwords don't match.";
				$O__PTATmsg = O__sysMsg($O__sysMsgHeadline, $O__sysMsgBody, "O__sysMsgAlert");
			} else {
				$O__fileData->pw = O__xCrypt($O__passwordNew,"e");
				$O__fileData = $O__fileData->asXML();			
				O__dataWrite($O__usersDataPath . "users/" . $O__userIDtarget . ".xml",$O__fileData);
				clearstatcache(); // clear cache so newest version can be loaded
				$O__sysMsgBody = "Success.";
				$O__PTATmsg = O__sysMsg($O__sysMsgHeadline, $O__sysMsgBody, "O__sysMsgNeutral");
			}				
				
			$O__logNotes .= $O__sysMsgHeadline . ". " . $O__sysMsgBody;
			break;
			
		case "pageTypeAdd":
			$O__fileData = O__XMLdata($O__usersDataPath . "users/" . $O__userIDtarget . ".xml", 0, 0);
			
			// Add new permission
			$O__permissionAdd = $O__fileData->permissions->addChild("pageType");
				$O__permissionAdd->addChild("name",$O__source);
				$O__permissionAdd->addChild("actions","none");
			$O__fileData = $O__fileData->asXML();
			O__dataWrite($O__usersDataPath . "users/" . $O__userIDtarget . ".xml",$O__fileData);
			clearstatcache(); // clear cache so newest version can be loaded
					
			$O__sysMsgHeadline = "PageType Add";
			$O__sysMsgBody = "Success. '" . $O__source . "' pagetype has been added.";
			$O__PTATmsg = O__sysMsg($O__sysMsgHeadline, $O__sysMsgBody, "O__sysMsgNeutral");
			$O__logNotes .= $O__sysMsgHeadline . ". " . $O__sysMsgBody;
			break;
			
		case "pageTypeRemove":
			$O__fileData = O__XMLdata($O__usersDataPath . "users/" . $O__userIDtarget . ".xml", 0, 0);
			
			for ($j=0; $j<count($O__fileData->permissions->pageType); $j++){
				if($O__fileData->permissions->pageType[$j]->name == $O__target){
					unset($O__fileData->permissions->pageType[$j]);
					break;
				}
			}
			
			$O__fileData = $O__fileData->asXML();			
			O__dataWrite($O__usersDataPath . "users/" . $O__userIDtarget . ".xml",$O__fileData);
			clearstatcache(); // clear cache so newest version can be loaded
					
			$O__sysMsgHeadline = "PageType Remove";
			$O__sysMsgBody = "Success. '" . $O__target . "' pagetype has been removed.";
			$O__PTATmsg = O__sysMsg($O__sysMsgHeadline, $O__sysMsgBody, "O__sysMsgNeutral");
			$O__logNotes .= $O__sysMsgHeadline . ". " . $O__sysMsgBody;
			break;
			
		case "pageTypeUpdate":
			
			$O__fileData = O__XMLdata($O__usersDataPath . "users/" . $O__userIDtarget . ".xml", 0, 0);
			
			for ($j=0; $j<count($O__fileData->permissions->pageType); $j++){
				if($O__fileData->permissions->pageType[$j]->name == $O__target){
					$O__fileData->permissions->pageType[$j]->actions = $O__source;
					break;
				}
			}
			
			$O__fileData = $O__fileData->asXML();			
			O__dataWrite($O__usersDataPath . "users/" . $O__userIDtarget . ".xml",$O__fileData);
			clearstatcache(); // clear cache so newest version can be loaded
			
			$O__sysMsgHeadline = "PageType Actions Update";
			$O__sysMsgBody = "Success. Actions for '" . $O__target . "' pagetype have been updated.";
			$O__PTATmsg = O__sysMsg($O__sysMsgHeadline, $O__sysMsgBody, "O__sysMsgNeutral");
			$O__logNotes .= $O__sysMsgHeadline . ". " . $O__sysMsgBody;
			break;
	}
}

function O__createOutput(){
	global $O__DBpath, $O__usersDataPath, $O__userIDtarget, $O__PT, $O__AT, $O__PTATmsg;

	$O__fileData = O__XMLdata($O__usersDataPath . "users/" . $O__userIDtarget . ".xml", 0, 0);
		
	$O__output = "<h2>Users & Groups Manager</h2>";
	$O__output .= $O__PTATmsg;
	$O__output .= "<form name=\"O__userEdit\" action=\"/" . $O__PT . "/" . $O__userIDtarget . "/" . $O__AT . "\" method=\"post\">";
	$O__output .= "<input type=\"hidden\" name=\"O__target\" value=\"\">";
	$O__output .= "<input type=\"hidden\" name=\"O__source\" value=\"\">";
	$O__output .= "<input type=\"hidden\" name=\"O__operation\" value=\"\">";
	$O__output .= "<input type=\"hidden\" name=\"O__userIDtarget\" value=\"" . $O__userIDtarget . "\">";
	
	// ID
	$O__output .= "<b>User Identity</b>";
	$O__data[0][0] = "<input type=\"text\" name=\"O__name\"  value=\"" . $O__fileData->name . "\">";
	$O__data[0][1] = "<input type=\"text\" name=\"O__nameFirst\"  value=\"" . $O__fileData->nameFirst . "\">";
	$O__data[0][2] = "<input type=\"text\" name=\"O__nameLast\"  value=\"" . $O__fileData->nameLast . "\">";
	
	$O__colLabels = array("Username","First Name","Last Name");
	$O__output .= O__tableMaker($O__colLabels,$O__data,"O__table","O__tableIdentity",0);
	//$O__output .="<input type=\"button\" value=\"Update Identity\" href=\"javascript:O__operation('identityUpdate');\" />";
	$O__output .="<a href=\"#\" onclick=\"javascript:O__operation('identityUpdate')\">Update Identity</a>";
	$O__output .= "<br><br>";	
	unset($O__data);
	
	// Password
	$O__data[0][1] = "<input type=\"password\" name=\"O__passwordNew\"  value=\"\">";
	$O__data[0][2] = "<input type=\"password\" name=\"O__passwordVerify\"  value=\"\">";	
	$O__colLabels = array("New Password","New Password Verify");
	$O__output .= O__tableMaker($O__colLabels,$O__data,"O__table","O__tablePW",0);
	//$O__output .="<input type=\"button\" value=\"Update Password\" onclick=\"javascript:O__operation('passwordUpdate')\">";
	$O__output .="<a href=\"#\" onclick=\"javascript:O__operation('passwordUpdate')\">Update Password</a>";
	$O__output .= "<br><br>";	
	unset($O__data);

	$O__output .= "</form>";
	
	return $O__output;
}

O__checkEditAccess(); // Block user from editing other users, if they don't have manage access
if(isset($_POST["O__operation"])){ O__operation(); }
$O__output .= O__createOutput();
?>

<script>
function O__operation(O__action, O__target){
	var O__form = document.forms["O__userEdit"];
	O__form.O__target.value = O__target;
	
	switch (O__action){
		case "identityUpdate":
			O__form.O__operation.value = O__action;
			O__form.submit();
			break;
		case "passwordUpdate":
			O__form.O__operation.value = O__action;
			O__form.submit();
			break;
		case "pageTypeAdd":
			var O__input = prompt("Please enter a PageType.");
			if (O__input == ""){
				alert("You need to enter a name for a PageType.  Please try again.");
			} else if (O__input != null){
				O__form.O__source.value = O__input;
				O__form.O__operation.value = O__action;
				O__form.submit();
			}
			break;
		case "pageTypeUpdate":
			var O__input = confirm("Are you sure you want to update permissions for the PageType '" + O__target + "'?");
			if (O__input == 1){
				O__actionsNew = O__target + "-actions";
				O__form.O__source.value = document.getElementById(O__actionsNew).value;
				O__form.O__operation.value = O__action;
				O__form.submit();
			}
			break;
		case "pageTypeRemove":
			var O__input = confirm("Are you sure you want to remove permissions for the PageType '" + O__target + "'?");
			if (O__input == 1){
				O__form.O__target.value = O__target;
				O__form.O__operation.value = O__action;
				O__form.submit();
			}
			break;
	}

}
</script>
