<%
/*
*	Name				:	userprofilep.jsp
*	Version				:	eG 4.0
*	Purpose				:	This jsp interacts with UserBean to change the profile of users.
*	Creation Date		:	10/30/2006
*	Author				:	James Thomas.P
*/
%>

<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page import = "java.util.*"%>
<%@ page import = "com.egurkha.*"%>
<%@ page import = "com.eg.EgManagersIniForManager"%>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.eg.EgCrypt"%>
<%@ page import = "com.eg.EgInstallInfo"%>
<%@ page import = "com.eg.UpdateAndTransmitUserInfo"%>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "java.io.*"%>
<%@ page import = "com.eg.UploadCustomImage"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import ="egurkha.reporter.ErUtils"%>
<%@ page import ="net.sf.json.*"%>
<%@ page import = "com.egurkha.monitor.OneClickDashboardModel"%>
<%@ page import="com.egurkha.admin.mfa.EgMailHelper"%>
<%@ page import="com.egurkha.admin.mfa.GoogleAuthenticator"%>

<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>

<%
String queryStringForNewUI =(String)ErUtils.prepareQueryString(request.getParameterMap());
%>

<%
	JSONObject rootJson = new JSONObject();
	/* code for auditlog starts */
	AuditLogThread auditLogThread = new AuditLogThread();	
	auditLogThread.setValue("Category","Admin");
	auditLogThread.setValue("User_id",_user.getLoginID());
	auditLogThread.setValue("Host_ip",_user.getUserIP(session.getId()));
	auditLogThread.setValue("Session_id",session.getId());
	auditLogThread.setValue("Module","User Profile");
	auditLogThread.setValue("Activity","Update Profile");
	/* code for auditlog ends */
	ArrayList prevList = new ArrayList();
	ArrayList curList = new ArrayList();
	String prePass = request.getParameter("$_pwd");
	Vector resultVector = new Vector();
	String entry=request.getParameter("entry");
	String existingPassword = EgCrypt.decrypt(_user.getLoginPwd());
	String oldpwd=request.getParameter("oldpwd");
	if (oldpwd == null || oldpwd.length() == 0)
	{
		oldpwd = existingPassword;
	}
	oldpwd = oldpwd.trim();
	oldpwd = StringUtils.decodeSecurityChar(oldpwd);
	/*
	 * password history check - STARTS
	 * by Meena.V
	 */
	boolean pwdMatchFound = false;
	String user_name = _user.getLoginID();
	String user_pass = request.getParameter("pwd");
	user_pass = StringUtils.decodeSecurityChar(user_pass);
	IniFile egUiIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
	IniFile egMgrMiscIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");
	String pwdHistoryEnabled = egUiIni.getValue("MISC_ARGS","PwdMinHistoryEnable");
	String pwdHistoryCnt = egUiIni.getValue("MISC_ARGS","PwdMinHistory");
	String user_pass_his_vals = egMgrMiscIni.getValue("Password_History",user_name);
	if (user_name != null && !user_name.equalsIgnoreCase("null"))
	{
		if (user_name.indexOf("/Grp/") == -1 && user_name.indexOf("/") == -1)
		{
			if(pwdHistoryEnabled != null &&(pwdHistoryEnabled.equalsIgnoreCase("true") || pwdHistoryEnabled.equalsIgnoreCase("yes")))
			{
				if(user_pass_his_vals != null && user_pass_his_vals.length() > 0)
				{
					String userPwdHistoryArr[] = StringUtils.getTokens(user_pass_his_vals,",");
					int user_pass_his_count = Integer.parseInt(pwdHistoryCnt);
					if(userPwdHistoryArr != null)
					{
						int pwdHistoryLength = userPwdHistoryArr.length;
						if(user_pass_his_count > pwdHistoryLength)
						{
							user_pass_his_count = pwdHistoryLength;
						}
						for(int i=0; i<user_pass_his_count; i++)
						{
							userPwdHistoryArr[i] = userPwdHistoryArr[i].trim();
							userPwdHistoryArr[i] = EgCrypt.decrypt(userPwdHistoryArr[i]);
							if(user_pass.equals(userPwdHistoryArr[i]))
							{
								pwdMatchFound = true;
								break;
							}
						}
					}
				}
			}
		}
	}
	/*
	 * password history check - ENDS
	 */
	if (existingPassword != null && !existingPassword.equals(oldpwd))
	{
		resultVector.addElement("Please provide valid credentials to update your profile.");
		resultVector.addElement("/final/monitor/EgAlarms.jsp?entry="+entry);//modified on 08/08/07 to return to home page
		resultVector.addElement("UserProfile");
		session.setAttribute("resultVector",resultVector);
		session.setAttribute("entry",entry);
		/* code for auditlog starts */
		auditLogThread.setValue("Description","Please provide valid credentials to update your profile");
		auditLogThread.sendItToDB();
		/* code for auditlog ends */
		rootJson.put("Title",_mapping.getTextDescription("admin.user.User Profile"));
		rootJson.put("Msg",_mapping.getTextDescription("admin.user.Existing password is incorrect"));
	}
	else if (pwdMatchFound)
	{
		resultVector.addElement("Please provide valid credentials to update your profile.");
		resultVector.addElement("/final/monitor/EgAlarms.jsp?entry="+entry);//modified on 08/08/07 to return to home page
		resultVector.addElement("UserProfile");
		session.setAttribute("resultVector",resultVector);
		session.setAttribute("entry",entry);
		/* code for auditlog starts */
		auditLogThread.setValue("Description","Please provide valid credentials to update your profile");
		auditLogThread.sendItToDB();
		/* code for auditlog ends */
		rootJson.put("Title",_mapping.getTextDescription("admin.user.User Profile"));
		String msg = _mapping.getTextDescription("admin.user.Please enter a new password") + ". " + _mapping.getTextDescription("admin.user.The given password matches one of the passwords in the password history") + ".";
		rootJson.put("Msg",msg);
	}
	else
	{
	if (prePass != null && prePass.length()>0)
	{	
		prePass = prePass.trim();
		prePass = prePass.substring(prePass.indexOf("$")+1);
		prePass = StringUtils.decodeSecurityChar(prePass);
		prevList.add(prePass);
	}
	User user = registry.getUser(session.getId());
	String loginID = user.getLoginID();
	String upass = request.getParameter("pwd");
	if (upass == null || upass.length() == 0)
	{
		upass = existingPassword;
	}
	upass = upass.trim();
	upass = StringUtils.decodeSecurityChar(upass);
	curList.add(upass);
	upass=EgCrypt.encrypt(upass);
	String mailid = null;
	String comma=",";
	String colon = ":";
	String totemp="";
	String cctemp="";
	String existId="";
	String bcctemp="";
	String scpttemp="";
	String ESC = "Esc";
	String tomailid=request.getParameter("tomailid");
	String ccmailid=request.getParameter("ccmailid");
	String bccmailid=request.getParameter("bccmailid");
	String escmailid=request.getParameter("escmailid");
	String customScript=request.getParameter("customScript");
	String high=request.getParameter("high");
	String low=request.getParameter("low");
	String medium=request.getParameter("medium");
	String notify=request.getParameter("notify");
	String msgmode=request.getParameter("msgmode");
	if(msgmode != null && msgmode.equals("HTML"))
	{
			msgmode = "H";
	}
	String alerttype = "";
	String temp=request.getParameter("size");
	String monitorHomePageOption = request.getParameter("monitorHomePageOption");
	
	if(StringUtils.isNull(monitorHomePageOption))
		monitorHomePageOption="default";



	// 2fa - starts here
	IniFile egMFAIniFile = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_mfa.ini",true);
	String isAdminEnabled2FA = egMFAIniFile.getValue("2FA_SETTINGS","Is2FAEnabled");

	if (isAdminEnabled2FA != null && isAdminEnabled2FA.trim().length() > 0 && (isAdminEnabled2FA.equalsIgnoreCase("yes") || isAdminEnabled2FA.equalsIgnoreCase("true")))
	{
		boolean isAuditChange = false;
		boolean saveMFAIniFile = false;
		String twofaEnableFlagVal = request.getParameter("twofaEnableFlagVal");
		String twofaOTPModeFlagVal = request.getParameter("twofaOTPModeFlagVal");
		String encryptedUserID = EgCrypt.encrypt(loginID.toLowerCase());

		String all2faEnabledUsrs[] = egMFAIniFile.getVariables("2FAEnabledUsers");
		ArrayList twoFAEnabledUsrsList = new ArrayList();
		if (all2faEnabledUsrs != null && all2faEnabledUsrs.length > 0)
		{
			for (int i = 0 ; i < all2faEnabledUsrs.length ; i++)
			{
				String userStr = EgCrypt.decrypt(all2faEnabledUsrs[i]);
				twoFAEnabledUsrsList.add(userStr);
			}
		}

		if (twofaEnableFlagVal != null && twofaEnableFlagVal.trim().length() > 0 && (twofaEnableFlagVal.equalsIgnoreCase("yes") || twofaEnableFlagVal.equalsIgnoreCase("true")))
		{
			if (!twoFAEnabledUsrsList.contains(loginID.toLowerCase()))
			{
				egMFAIniFile.setValue("2FAEnabledUsers",encryptedUserID,encryptedUserID);
				saveMFAIniFile = true;

				isAuditChange = true;
				String displayName = "Enable Two Factor Authentication(2FA)";
				auditLogThread.setPreviousValue(displayName,"no");
				auditLogThread.setCurrentValue(displayName,"yes");
			}

			String secretKey = EgCrypt.decrypt(egMFAIniFile.getValue(encryptedUserID,"SecretKey"));
			String otpModeIniVal = EgCrypt.decrypt(egMFAIniFile.getValue(encryptedUserID,"EnabledMode"));
			if (secretKey.trim().length() == 0)
			{
				secretKey = GoogleAuthenticator.getRandomSecretKey();
				String encryptedSecretKey = EgCrypt.encrypt(secretKey);
				egMFAIniFile.setValue(encryptedUserID,"SecretKey",encryptedSecretKey);
				saveMFAIniFile = true;
			}


			String loginMailID = _user.getLoginMailID();
			String cc = "cc:", bcc = "bcc:", at = "@";
			ArrayList tos = new ArrayList();

			if (loginMailID != null && !loginMailID.equalsIgnoreCase("null") && loginMailID.trim().length()>0)
			{
				String to = loginMailID;
				StringTokenizer st0 = null;
				StringTokenizer st = new StringTokenizer(to, ",");
				int x = st.countTokens();
				for (int r = 0; r < x; r++)
				{
					String ss2 = st.nextToken().trim();
					String mailStr = null;
					if(ss2.startsWith("cmd:") && ss2.indexOf(":")>1)
					{
						mailStr=ss2.substring(ss2.indexOf(":")+1,ss2.length());
					}
					else
					{
						st0 = new StringTokenizer(ss2, ":");
						if (st0.countTokens() > 1)
							st0.nextToken(); // ignore the to
						mailStr = st0.nextToken().trim();
					}
					if (!ss2.startsWith(cc) && !ss2.startsWith(bcc) && ss2.indexOf(at) >= 0)
					{
						tos.add(mailStr);
					}
				}
			}

			String userNewMailIDs = "";
			String userMailID = request.getParameter("tomailVal");
			if (userMailID != null && userMailID.trim().length() > 0)
			{
				ArrayList userMailIDList = StringUtils.egTokenizer(userMailID,",");
				userMailIDList.removeAll(tos);
				if (userMailIDList != null && userMailIDList.size() > 0)
				{
					userNewMailIDs = userMailIDList.toString();
					userNewMailIDs = userNewMailIDs.substring(1,userNewMailIDs.indexOf("]"));
				}
			}

			if (!otpModeIniVal.equalsIgnoreCase(twofaOTPModeFlagVal))
			{
				if (twofaOTPModeFlagVal != null && twofaOTPModeFlagVal.trim().length() > 0 && twofaOTPModeFlagVal.equalsIgnoreCase("ga") && userMailID != null && userMailID.trim().length() > 0)
				{
					String mailSubject = "Two Factor Authentication";
					String bodyContent = "You have enabled 2-step verification for securing your accesses to the eG Enterprise system. The secret key assigned to your eG Enterprise user name '"+loginID+"' is <b>"+secretKey+"</b>. Please refer to the attached document to know how to register this secret key in the Google Authenticator app for generating a time-based OTP. Use the OTP generated by Google authenticator as verification code to validate your eG Enterprise login.";

					EgMailHelper mailObj = new EgMailHelper(userMailID);
					mailObj.setAttachmentFile(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/docs/GoogleAuthenticatorGuide.docx");
					int mailStatus = mailObj.sendMail(mailSubject, bodyContent);
				}
				else if (twofaOTPModeFlagVal != null && twofaOTPModeFlagVal.trim().length() > 0 && twofaOTPModeFlagVal.equalsIgnoreCase("mail") && userMailID != null && userMailID.trim().length() > 0)
				{
					String mailSubject = "Two Factor Authentication";
					String bodyContent = "You have enabled 2-step verification for securing your accesses to the eG Enterprise system. When logging into the eG web console, use the time-based verification code sent to this email ID to validate your user login.";

					EgMailHelper mailObj = new EgMailHelper(userMailID);
					int mailStatus = mailObj.sendMail(mailSubject, bodyContent);
				}
				egMFAIniFile.setValue(encryptedUserID,"EnabledMode",EgCrypt.encrypt(twofaOTPModeFlagVal));
				saveMFAIniFile = true;

				isAuditChange = true;
				String displayName = "OTP Mode";
				String tempOtpVal1 = otpModeIniVal;
				if (tempOtpVal1.equalsIgnoreCase("ga"))
				{
					tempOtpVal1 = "Google Authenticator";
				}

				String tempOtpVal2 = twofaOTPModeFlagVal;
				if (tempOtpVal2.equalsIgnoreCase("ga"))
				{
					tempOtpVal2 = "Google Authenticator";
				}

				auditLogThread.setPreviousValue(displayName,tempOtpVal1);
				auditLogThread.setCurrentValue(displayName,tempOtpVal2);
			}
			else if (userNewMailIDs != null && userNewMailIDs.trim().length() > 0)
			{
				if (twofaOTPModeFlagVal != null && twofaOTPModeFlagVal.trim().length() > 0 && twofaOTPModeFlagVal.equalsIgnoreCase("ga"))
				{
					String mailSubject = "Two Factor Authentication";
					String bodyContent = "You have changed your email ID in the eG Enterprise system. The secret key assigned to your eG Enterprise user name '"+loginID+"' is <b>"+secretKey+"</b>. Please refer to the attached document to know how to register this secret key in the Google Authenticator app for generating a time-based OTP. Use the OTP generated by Google authenticator as verification code to validate your eG Enterprise login.";

					EgMailHelper mailObj = new EgMailHelper(userNewMailIDs);
					mailObj.setAttachmentFile(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/docs/GoogleAuthenticatorGuide.docx");
					int mailStatus = mailObj.sendMail(mailSubject, bodyContent);
				}
				else if (twofaOTPModeFlagVal != null && twofaOTPModeFlagVal.trim().length() > 0 && twofaOTPModeFlagVal.equalsIgnoreCase("mail"))
				{
					String mailSubject = "Two Factor Authentication";
					String bodyContent = "You have changed your email ID in the eG Enterprise system. When logging into the eG web console, use the time-based verification code sent to this email ID to validate your user login.";

					EgMailHelper mailObj = new EgMailHelper(userNewMailIDs);
					int mailStatus = mailObj.sendMail(mailSubject, bodyContent);
				}
			}
		}
		else if (twofaEnableFlagVal != null && twofaEnableFlagVal.trim().length() > 0 && (twofaEnableFlagVal.equalsIgnoreCase("no") || twofaEnableFlagVal.equalsIgnoreCase("false")))
		{
			saveMFAIniFile = true;
			egMFAIniFile.deleteValue("2FAEnabledUsers",encryptedUserID);
			egMFAIniFile.deleteSubject(encryptedUserID);

			isAuditChange = true;
			String displayName = "Enable Two Factor Authentication(2FA)";
			auditLogThread.setPreviousValue(displayName,"yes");
			auditLogThread.setCurrentValue(displayName,"no");
		}

		if (saveMFAIniFile)
		{
			egMFAIniFile.saveFile();
		}

		if (isAuditChange)
		{
			auditLogThread.sendItToDB();
		}
	}
	EgConfigFilesSync.releaseInstance(egMFAIniFile);
	// 2fa - ends here

	EgUserRole userRole = EgUserRole.getRoleObject(user.getLoginType());
	EgUuidInfo eguuidinfo = new EgUuidInfo();
	boolean isSuperOrg = eguuidinfo.isSuperOrg(loginID);
	IniFile clsIni = new IniFile (EgInstallInfo.getInstallDir()+"/manager/config/eg_ls_portal.ini");
	String cloudModel = clsIni.getValue("LS_TRIAL_SETTINGS","cloudModel");
	if (cloudModel != null && cloudModel.equalsIgnoreCase("phoenix"))
	{
		if (!loginID.equalsIgnoreCase("egenterprise") && isSuperOrg)
		{
			boolean isAuditChange = false;
			String useProxyYes = request.getParameter("useProxyYes");
			IniFile eguuidwrite = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() +"/manager/config/eg_uuid.ini",true);

			String agentProxyDetails = eguuidwrite.getValue("AGENT_PROXY_DETAILS",loginID);
			String prevuseProxyYes = "no";
			String previsAuthenticationYes = "no";
			String prevproxyHost = "-";
			String prevproxyPort = "-";
			String prevproxyUsername = "-";
			String prevproxyPassword = "-";
			if (agentProxyDetails != null && agentProxyDetails.trim().length() > 0)
			{
				if (agentProxyDetails.indexOf("~#~") > -1)
				{
					ArrayList valueList = new ArrayList(Arrays.asList(StringUtils.getTokens(agentProxyDetails,"~#~")));
					if (valueList.size() > 0)
					{
						prevuseProxyYes = "yes";
						prevproxyHost = (String)valueList.get(0);
						prevproxyPort = (String)valueList.get(1);
						if (valueList.size() == 4)
						{
							previsAuthenticationYes = "yes";
							prevproxyUsername = (String)valueList.get(2);
							prevproxyPassword = (String)valueList.get(3);
						}
					}
				}
			}

			if (useProxyYes != null && useProxyYes.equalsIgnoreCase("yes"))
			{
				if (prevuseProxyYes.equalsIgnoreCase("no"))
				{
					isAuditChange = true;
					String displayName = "01~~Proxy Server enabled";
					auditLogThread.setPreviousValue(displayName,"no");
					auditLogThread.setCurrentValue(displayName,"yes");
				}

				String proxyHost = request.getParameter("proxyHost");
				String proxyPort = request.getParameter("proxyPort");

				if (!prevproxyHost.equalsIgnoreCase(proxyHost))
				{
					isAuditChange = true;
					String displayName = "02~~Proxy Server IP/Hostname";
					auditLogThread.setPreviousValue(displayName,prevproxyHost);
					auditLogThread.setCurrentValue(displayName,proxyHost);
				}
				if (!prevproxyPort.equalsIgnoreCase(proxyPort))
				{
					isAuditChange = true;
					String displayName = "03~~Proxy Server Port";
					auditLogThread.setPreviousValue(displayName,prevproxyPort);
					auditLogThread.setCurrentValue(displayName,proxyPort);
				}
				String isAuthenticationYes = request.getParameter("isAuthenticationYes");
				if (isAuthenticationYes != null && isAuthenticationYes.equalsIgnoreCase("yes"))
				{
					if (previsAuthenticationYes.equalsIgnoreCase("no"))
					{
						isAuditChange = true;
						String displayName = "04~~Proxy Server authentication enabled";
						auditLogThread.setPreviousValue(displayName,"no");
						auditLogThread.setCurrentValue(displayName,"yes");
					}

					String proxyUsername = request.getParameter("proxyUsername");
					String proxyPassword = request.getParameter("proxyPassword");
					proxyPassword = EgCrypt.olddecrypt(proxyPassword);
					proxyPassword = EgCrypt.oldencrypt(proxyPassword);

					if (!prevproxyUsername.equalsIgnoreCase(proxyUsername))
					{
						isAuditChange = true;
						String displayName = "05~~Proxy Server Username";
						auditLogThread.setPreviousValue(displayName,prevproxyUsername);
						auditLogThread.setCurrentValue(displayName,proxyUsername);
					}
					if (!prevproxyPassword.equalsIgnoreCase(proxyPassword))
					{
						isAuditChange = true;
						String displayName = "06~~Proxy Server Password";
						auditLogThread.setPreviousValue(displayName,(prevproxyPassword.equals("-"))?"-":"****");
						auditLogThread.setCurrentValue(displayName,"*****");
					}

					eguuidwrite.setValue("AGENT_PROXY_DETAILS",loginID,proxyHost+"~#~"+proxyPort+"~#~"+proxyUsername+"~#~"+proxyPassword);
				}
				else
				{
					eguuidwrite.setValue("AGENT_PROXY_DETAILS",loginID,proxyHost+"~#~"+proxyPort);
					if (previsAuthenticationYes.equalsIgnoreCase("yes"))
					{
						isAuditChange = true;
						String displayName = "04~~Proxy Server authentication enabled";
						auditLogThread.setPreviousValue(displayName,"yes");
						auditLogThread.setCurrentValue(displayName,"no");
					}
				}
			}
			else
			{
				eguuidwrite.setValue("AGENT_PROXY_DETAILS",loginID,"N/A");
				if (prevuseProxyYes.equalsIgnoreCase("yes"))
				{
					isAuditChange = true;
					String displayName = "01~~Proxy Server enabled";
					auditLogThread.setPreviousValue(displayName,"yes");
					auditLogThread.setCurrentValue(displayName,"no");
				}
			}

			eguuidwrite.saveFile();
			EgConfigFilesSync.releaseInstance(eguuidwrite);

			if (isAuditChange)
			{
				auditLogThread.setValue("Description","User profile has been updated for "+ loginID);
				auditLogThread.sendItToDB();
			}
		}
	}
	else
	{
		boolean isAuditChange = false;
		boolean isOrg = eguuidinfo.isOrg(loginID);
		boolean hasOURole = eguuidinfo.hasOURole(loginID);
		String userNameForProxy = loginID;

		EgUserPermission sas = EgUserPermission.getInstance();
		long perValue = userRole.getAdminPerm();
		String roleName     = userRole.getRoleName();
		ArrayList adminPermCheckList = sas.getPrivilegeList(roleName,perValue,0);//admin role privilege list.
		String[][] allGroupNames = sas.getAdminDesc();//all admin groups.
		boolean hasComponentMangamentEnabled = false;
		boolean hasExtRemAgentsEnabled = false;

		for (int i=0;i<allGroupNames.length;i++)
		{
			String tempGrpName = allGroupNames[i][0];
			if (!adminPermCheckList.contains(tempGrpName))
			{
				continue;
			}

			if (tempGrpName.equalsIgnoreCase("Component Management"))
			{
				hasComponentMangamentEnabled = true;
			}
			else if (tempGrpName.equalsIgnoreCase("External/Remote Agent Configuration"))
			{
				hasExtRemAgentsEnabled = true;
			}
		}

		boolean isEligibleUser = false;
		if ((userRole.hasAllComponentAccess() && (hasComponentMangamentEnabled || hasExtRemAgentsEnabled)) || isSuperOrg || isOrg || hasOURole)
		{
			isEligibleUser = true;
		}

		if (isEligibleUser)
		{
			if ((!isSuperOrg && !isOrg && hasOURole) || (userRole.hasAllComponentAccess() && (hasComponentMangamentEnabled || hasExtRemAgentsEnabled)))
			{
				userNameForProxy = eguuidinfo.getDirectDependentOU(loginID);
			}

			String useParentProxyNo = request.getParameter("useParentProxyNo");
			if ((useParentProxyNo == null || useParentProxyNo.trim().length() == 0) || (useParentProxyNo != null && useParentProxyNo.equalsIgnoreCase("null")))
			{
				useParentProxyNo = "no";
			}

			IniFile eguuidwrite = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() +"/manager/config/eg_uuid.ini",true);
			String agentProxyDetails = eguuidwrite.getValue("AGENT_PROXY_DETAILS",userNameForProxy);
			String prevuseParentProxy = "no";
			String prevuseProxyYes = "no";
			String previsAuthenticationYes = "no";
			String prevproxyHost = "-";
			String prevproxyPort = "-";
			String prevproxyUsername = "-";
			String prevproxyPassword = "-";
			if (agentProxyDetails != null && agentProxyDetails.trim().length() > 0)
			{
				if (agentProxyDetails.indexOf("~#~") > -1)
				{
					ArrayList valueList = new ArrayList(Arrays.asList(StringUtils.getTokens(agentProxyDetails,"~#~")));
					if (valueList.size() > 0)
					{
						prevuseProxyYes = "yes";
						prevproxyHost = (String)valueList.get(0);
						prevproxyPort = (String)valueList.get(1);
						if (valueList.size() == 4)
						{
							previsAuthenticationYes = "yes";
							prevproxyUsername = (String)valueList.get(2);
							prevproxyPassword = (String)valueList.get(3);
						}
					}
				}
				else if (!agentProxyDetails.equalsIgnoreCase("N/A"))
				{
					agentProxyDetails = eguuidinfo.getAgentProxyDetails(userNameForProxy);
					if (agentProxyDetails != null && agentProxyDetails.trim().length() > 0 && agentProxyDetails.indexOf("~#~") > -1)
					{
						prevuseParentProxy = "yes";
						ArrayList valueList = new ArrayList(Arrays.asList(StringUtils.getTokens(agentProxyDetails,"~#~")));
						if (valueList.size() > 0)
						{
							prevuseProxyYes = "yes";
							prevproxyHost = (String)valueList.get(0);
							prevproxyPort = (String)valueList.get(1);
							if (valueList.size() == 4)
							{
								previsAuthenticationYes = "yes";
								prevproxyUsername = (String)valueList.get(2);
								prevproxyPassword = (String)valueList.get(3);
							}
						}
					}
				}
			}

			String useProxyYes = request.getParameter("useProxyYes");
			if (!prevuseProxyYes.equalsIgnoreCase(useProxyYes))
			{
				isAuditChange = true;
				String displayName = "01~~Proxy Server enabled";
				auditLogThread.setPreviousValue(displayName,prevuseProxyYes);
				auditLogThread.setCurrentValue(displayName,useProxyYes);
			}

			if (useProxyYes.equalsIgnoreCase("yes") && !useParentProxyNo.equalsIgnoreCase(prevuseParentProxy))
			{
				isAuditChange = true;
				String displayName = "02~~Proxy is set to organization/organizational unit";
				auditLogThread.setPreviousValue(displayName,prevuseParentProxy);
				auditLogThread.setCurrentValue(displayName,useParentProxyNo);
			}

			if (useParentProxyNo.equalsIgnoreCase("no"))
			{
				if (useProxyYes != null && useProxyYes.equalsIgnoreCase("yes"))
				{
					String proxyHost = request.getParameter("proxyHost");
					String proxyPort = request.getParameter("proxyPort");
					if (!prevproxyHost.equalsIgnoreCase(proxyHost))
					{
						isAuditChange = true;
						String displayName = "03~~Proxy Server IP/Hostname";
						auditLogThread.setPreviousValue(displayName,prevproxyHost);
						auditLogThread.setCurrentValue(displayName,proxyHost);
					}
					if (!prevproxyPort.equalsIgnoreCase(proxyPort))
					{
						isAuditChange = true;
						String displayName = "04~~Proxy Server Port";
						auditLogThread.setPreviousValue(displayName,prevproxyPort);
						auditLogThread.setCurrentValue(displayName,proxyPort);
					}
					String isAuthenticationYes = request.getParameter("isAuthenticationYes");
					if (!previsAuthenticationYes.equalsIgnoreCase(isAuthenticationYes))
					{
						isAuditChange = true;
						String displayName = "05~~Proxy Server authentication enabled";
						auditLogThread.setPreviousValue(displayName,previsAuthenticationYes);
						auditLogThread.setCurrentValue(displayName,isAuthenticationYes);
					}
					if (isAuthenticationYes != null && isAuthenticationYes.equalsIgnoreCase("yes"))
					{
						String proxyUsername = request.getParameter("proxyUsername");
						String proxyPassword = request.getParameter("proxyPassword");
						proxyPassword = EgCrypt.olddecrypt(proxyPassword);
						proxyPassword = EgCrypt.oldencrypt(proxyPassword);
						if (!prevproxyUsername.equalsIgnoreCase(proxyUsername))
						{
							isAuditChange = true;
							String displayName = "06~~Proxy Server Username";
							auditLogThread.setPreviousValue(displayName,prevproxyUsername);
							auditLogThread.setCurrentValue(displayName,proxyUsername);
						}
						if (!prevproxyPassword.equalsIgnoreCase(proxyPassword))
						{
							isAuditChange = true;
							String displayName = "07~~Proxy Server Password";
							auditLogThread.setPreviousValue(displayName,"*****");
							auditLogThread.setCurrentValue(displayName,"******");
						}
						eguuidwrite.setValue("AGENT_PROXY_DETAILS",userNameForProxy,proxyHost+"~#~"+proxyPort+"~#~"+proxyUsername+"~#~"+proxyPassword);
					}
					else
					{
						eguuidwrite.setValue("AGENT_PROXY_DETAILS",userNameForProxy,proxyHost+"~#~"+proxyPort);
					}
				}
				else
				{
					eguuidwrite.setValue("AGENT_PROXY_DETAILS",userNameForProxy,"N/A");
				}
				auditLogThread.setValue("Description","Proxy Server details have been configured successfully");
			}
			else
			{
				String superUserNameForProxy = eguuidinfo.getDirectDependentOU(userNameForProxy);
				String superUserAgentProxyDetails = eguuidinfo.getAgentProxyDetails(superUserNameForProxy);
				eguuidwrite.setValue("AGENT_PROXY_DETAILS",userNameForProxy,superUserNameForProxy);
				if (superUserAgentProxyDetails != null && superUserAgentProxyDetails.trim().length() > 0 && superUserAgentProxyDetails.indexOf("~#~") > -1)
				{
					ArrayList valueList = new ArrayList(Arrays.asList(StringUtils.getTokens(superUserAgentProxyDetails,"~#~")));
					if (valueList.size() > 0)
					{
						String proxyHost = (String)valueList.get(0);
						String proxyPort = (String)valueList.get(1);
						if (!prevproxyHost.equalsIgnoreCase(proxyHost))
						{
							isAuditChange = true;
							String displayName = "03~~Proxy Server IP/Hostname";
							auditLogThread.setPreviousValue(displayName,prevproxyHost);
							auditLogThread.setCurrentValue(displayName,proxyHost);
						}
						if (!prevproxyPort.equalsIgnoreCase(proxyPort))
						{
							isAuditChange = true;
							String displayName = "04~~Proxy Server Port";
							auditLogThread.setPreviousValue(displayName,prevproxyPort);
							auditLogThread.setCurrentValue(displayName,proxyPort);
						}

						String isAuthenticationYes = "no";
						if (valueList.size() == 4)
						{
							isAuthenticationYes = "yes";
							String proxyUsername = (String)valueList.get(2);
							String proxyPassword = (String)valueList.get(3);
							if (!prevproxyUsername.equalsIgnoreCase(proxyUsername))
							{
								isAuditChange = true;
								String displayName = "06~~Proxy Server Username";
								auditLogThread.setPreviousValue(displayName,prevproxyUsername);
								auditLogThread.setCurrentValue(displayName,proxyUsername);
							}
							if (!prevproxyPassword.equalsIgnoreCase(proxyPassword))
							{
								isAuditChange = true;
								String displayName = "07~~Proxy Server Password";
								auditLogThread.setPreviousValue(displayName,"*****");
								auditLogThread.setCurrentValue(displayName,"******");
							}
						}

						if (!previsAuthenticationYes.equalsIgnoreCase(isAuthenticationYes))
						{
							isAuditChange = true;
							String displayName = "05~~Proxy Server authentication enabled";
							auditLogThread.setPreviousValue(displayName,previsAuthenticationYes);
							auditLogThread.setCurrentValue(displayName,isAuthenticationYes);
						}
					}
				}
				boolean isSuperUserSuperOrg = eguuidinfo.isSuperOrg(superUserNameForProxy);
				if (isSuperUserSuperOrg)
				{
					auditLogThread.setValue("Description","Proxy Server details have been configured with the proxy of the orgnaization");
				}
				else
				{
					auditLogThread.setValue("Description","Proxy Server details have been configured with the proxy of the orgnaizational unit");
				}
			}

			eguuidwrite.saveFile();
			EgConfigFilesSync.releaseInstance(eguuidwrite);

			if (isAuditChange)
			{
				auditLogThread.setValue("Description","User profile has been updated for "+ loginID);
				auditLogThread.sendItToDB();
			}
		}
	}

	ArrayList extensionList = new ArrayList();
	extensionList.add("gif");
	extensionList.add("jpeg");
	extensionList.add("jpg");
	extensionList.add("png");

	IniFile uiObject = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_ui.ini",true);
	String subjects[] = uiObject.getSubjects();
	String timeZone = request.getParameter("timeZone");
	String userDateFormat = request.getParameter("userDateFormat");
	timeZone=timeZone+"$@$"+userDateFormat;
	
	boolean isHKT_ThemeEnabled=trackerUI.isHKTThemeEnabled();
	StringBuffer existEscMail=new StringBuffer();
	String loginLogo=request.getParameter("loginImageUploadStatusForAudit");
	String monitorLogo=request.getParameter("monitorImageUploadStatusForAudit");
	String reporterLogo=request.getParameter("reporterImageUploadStatusForAudit");
	String configLogo=request.getParameter("configMgmtImageUploadStatusForAudit");
	String[] logoCheck = request.getParameterValues("logoCheck");

	String config_repo_image="s";
	if((reporterLogo!=null && reporterLogo.equals("yes")) || (configLogo!=null && configLogo.equals("yes")))
	{
		config_repo_image="d";
	}
	String tempUserForLogo=loginID;
	boolean updateHKT_ThemeSkinAndLogoPreference=false;

	if(isHKT_ThemeEnabled && (_user!=null && _user.getLoginType().equalsIgnoreCase("admin")))
	{
		updateHKT_ThemeSkinAndLogoPreference=true;
	}
	if(logoCheck!=null && logoCheck.length>0)
	{
		String check=logoCheck[0];
		if(tempUserForLogo!=null && tempUserForLogo.indexOf("samlsso/")>-1)
		{
			String tmpName = tempUserForLogo.substring(tempUserForLogo.indexOf("/")+1);
			String idpName = tmpName.substring(0,tmpName.indexOf("/"));
			String userName = tmpName.substring(tmpName.indexOf("/")+1,tmpName.length());
			tempUserForLogo = idpName.toLowerCase()+"_"+userName;
		}
		else if(tempUserForLogo!=null && tempUserForLogo.indexOf("/")>-1)
		{
			String domain=tempUserForLogo.substring(0,tempUserForLogo.indexOf("/"));
			String userName=tempUserForLogo.substring(tempUserForLogo.indexOf("/")+1,tempUserForLogo.length());
			if(userName.indexOf("Grp")>-1)
			{
				userName=userName.substring(userName.indexOf("/")+1,userName.length());
			}
			tempUserForLogo=domain.toLowerCase()+"_"+userName;
		}
		tempUserForLogo = StringUtils.replace(tempUserForLogo," ","");
		if(check.equals("yes"))
		{
			if(monitorLogo.equals("yes"))
			{
				reporterLogo="yes";
				configLogo="yes";
				config_repo_image="s";
				String extension = "";

				for (int ext = 0; ext < extensionList.size(); ext++)
				{
					String strExtension = (String)extensionList.get(ext);
					File sourceFile = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/monitor/eg_images/"+tempUserForLogo+"_monitor."+strExtension);
					if (sourceFile.exists())
					{
						extension = strExtension;
						break;
					}
				}

				String mointorPath=EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/monitor/eg_images/"+tempUserForLogo+"_monitor."+extension;
				String reporterPath=EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/reporter/images/"+tempUserForLogo+"_reporter."+extension;
				String configPath=EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/config/images/"+tempUserForLogo+"_config."+extension;
				try
				{
					File monitorFile=new File(mointorPath);
					File reporterFile=new File(reporterPath);
					File configFile=new File(configPath);
					
					InputStream inStream = new FileInputStream(monitorFile);
					OutputStream outStream1 =new FileOutputStream(reporterFile);
					OutputStream outStream2=new FileOutputStream(configFile);
					
					byte fileContent[] = new byte[(int)monitorFile.length()];
					int length=fileContent.length;
					inStream.read(fileContent);
					//baos.read(fileContent);
					outStream1.write(fileContent, 0, length);
					outStream2.write(fileContent, 0, length);

					inStream.close();
					outStream1.close();
					outStream2.close();

					if(EgInstallInfo.isClusterSupported)
					{
						//If clustering is supported inform other managers about the new Image.
						UploadCustomImage customImage = new UploadCustomImage();
						String s_dstFile1="manager/tomcat/webapps/final/reporter/images/"+tempUserForLogo+"_reporter."+extension;
						String s_dstFile2="manager/tomcat/webapps/final/config/images/"+tempUserForLogo+"_config."+extension;
						customImage.getCustomImage(s_dstFile1,fileContent);
						customImage.getCustomImage(s_dstFile2,fileContent);
						customImage = null;
					}
				}
				catch(Exception er)
				{
					er.printStackTrace();
					System.out.println("Error in creating duplicate logos for config "+er);
				}
			}
		}
		else
		{
			config_repo_image="d";
		}
	}
	else
	{
		config_repo_image="d";
	}
	int existSize=Integer.parseInt(temp);
	String esctemp = null;
	StringTokenizer stoken=null;
	int count=0;
	int cnt=0;
	for(int j=2;j<=(existSize+1);j++)
	{
		String mail=request.getParameter("escmailid"+j);		
		if(mail!=null)
		{
			stoken = new StringTokenizer (mail, comma);
			ESC = "Esc"+(j);
			count = stoken.countTokens();
			StringBuffer sb=new StringBuffer();
			
			for (int k=0;stoken.hasMoreTokens(); k++)
			{
				esctemp = stoken.nextToken();
				sb.append(ESC).append(colon).append(esctemp);
				if (k < count)
				sb.append (comma);
			}		
			existEscMail.append(sb.toString());					
		}		
	}

	String value=existEscMail.toString();
	if(value.lastIndexOf(",")>0)
	{
		existId=value.substring(0,value.lastIndexOf(","));	
	}
	else
	{
		existId	=value; 
	}
	if(high != null && !high.equalsIgnoreCase("null"))
	{
		alerttype += "H";
	}
	if(medium != null && !medium.equalsIgnoreCase("null"))
	{
		alerttype += "I";
	}
	if(low != null && !low.equalsIgnoreCase("null"))
	{
		alerttype += "L";
	}
	UpdateAndTransmitUserInfo updateAndTransmitUserInfo = new UpdateAndTransmitUserInfo();
	/* registry object is already available in included EgTrackerA.jsp. */
	

	//for getting permision
	String source = "JSP";
	boolean flag_changeuser = false;
	tomailid=(tomailid==null)?"":tomailid;
	stoken = new StringTokenizer (tomailid, comma);
	StringBuffer tomail = new StringBuffer();
	count = stoken.countTokens();
	String to = "To:";
	for (int i=0;stoken.hasMoreTokens(); i++)
	{
		totemp = stoken.nextToken();
		tomail.append (to);
		tomail.append (totemp);

		if (i < count)
			tomail.append (comma);
	}
	ccmailid=(ccmailid==null)?"":ccmailid;
	stoken = new StringTokenizer (ccmailid, comma);
	StringBuffer ccmail = new StringBuffer();
	count = stoken.countTokens();
	String cc = "cc:";
	for (int i=0;stoken.hasMoreTokens(); i++)
	{
		cctemp = stoken.nextToken();
		ccmail.append (cc);
		ccmail.append (cctemp);

		if (i < count)
			ccmail.append (comma);
	}
	bccmailid=(bccmailid==null)?"":bccmailid;
	stoken = new StringTokenizer (bccmailid, ",");
	StringBuffer bccmail = new StringBuffer();
	count = stoken.countTokens();
	String bcc = "bcc:";
	for (int i=0;stoken.hasMoreTokens(); i++)
	{
		bcctemp = stoken.nextToken();
		bccmail.append (bcc);
		bccmail.append (bcctemp);

		if (i < count)
			bccmail.append (comma);
	}
	escmailid=(escmailid==null)?"":escmailid;
	stoken = new StringTokenizer (escmailid, comma);
	StringBuffer escmail = new StringBuffer();
	count = stoken.countTokens();
	StringTokenizer colonTokens = null;
	String escColon = null, escStr = null;
	StringTokenizer tok = new StringTokenizer (escmailid, comma);
	count = tok.countTokens();
	for (int i=0;tok.hasMoreTokens(); i++)
	{
		esctemp = tok.nextToken();
		escmail.append("Esc1").append(colon).append(esctemp);
		if (i+1 < count)
			escmail.append (comma);
	}
	//add by sunder for custom script append in mail for mail manager.
	customScript=(customScript==null)?"":customScript;
	StringBuffer scptBuff = new StringBuffer();
	if(customScript!=null && !customScript.equals(""))
	{
		stoken = new StringTokenizer (customScript, ",");
		count = stoken.countTokens();
		String script = "cmd:";
		for (int i=0;stoken.hasMoreTokens(); i++)
		{
			scpttemp = stoken.nextToken();
			scptBuff.append (script);
			scptBuff.append (scpttemp);

			if (count!=(i+1))
				scptBuff.append (comma);
		}
	}
	String totalEsc="";
	if(!existId.equals(""))
		totalEsc=escmail+","+existId;
	else
		totalEsc=escmail.toString();

	String tostr = tomail.toString();
	String ccstr = ccmail.toString();
	String bccstr = bccmail.toString();
	String escstr = escmail.toString();
	String scptStr=scptBuff.toString();
	
	if (!ccstr.equals("") || !bccstr.equals("")|| ! totalEsc.equals("") || !scptStr.equals("") )
		mailid = tostr + ccstr + bccstr + totalEsc+scptStr;
	else
		mailid = tostr;		

	if(mailid!=null && mailid.endsWith(","))
		mailid=mailid.substring(0,mailid.lastIndexOf(","));
	
	IniFile egUi = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
	IniFile egServices = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.ini",true);
	egServices.setValue("MISC_ARGS","UserInfoUpdated","true");
	egServices.saveFile();


	Object languages[] = egUi.getVariables("COUNTRY_AND_LANGUAGE_CODE");
	mapping = new Hashtable();
	for(int i=0;i<languages.length;i++)
	{
		String code = egUi.getValue("COUNTRY_AND_LANGUAGE_CODE",(String)languages[i]);
		mapping.put(code.trim(),languages[i]);
	}
	String language = request.getParameter("languageName");
	String adminSkin = request.getParameter("adminSkin");
	String monitorSkin = request.getParameter("monitorSkin");
	String reporterSkin = request.getParameter("reporterSkin");
	String configSkin = request.getParameter("configurationSkin");
	String refreshFreq="";
	if(userRole.getMonitorPerm()>0)
		refreshFreq = request.getParameter("refreshFreq");
	String monitorHomePage = request.getParameter("monitorHomePage");
	String measureInMailMode = request.getParameter("measure_in_mail_mode");
	measureInMailMode = (measureInMailMode==null)?"NO":measureInMailMode;
	if(measureInMailMode!=null && measureInMailMode.trim().length()==0)
		measureInMailMode="NO";

	String ddInMailMode = request.getParameter("dd_in_mail_mode");
	ddInMailMode = (ddInMailMode==null)?"NO":ddInMailMode;
	if(ddInMailMode!=null && ddInMailMode.trim().length()==0)
		ddInMailMode="NO";

	boolean temp1 = true;

	String userName = registry.getUser(session.getId()).getLoginID();
	boolean superuser=false;
	
	if(userName!=null)
	{
		superuser=true;
	}
	else
	{
		superuser=false;
	}
	
	String updateUser_pref = "UPDATE USER_PREF SET LANGUAGE='"+language+"'";
	String insertUser_pref = " insert into user_pref values('"+loginID+"','"+language+"','";
	String updateHKT_Theme_settings="";
	StringBuffer sbHKTThemeStr=new StringBuffer();
	if(isHKT_ThemeEnabled && updateHKT_ThemeSkinAndLogoPreference)
	{
		sbHKTThemeStr.append("UPDATE USER_PREF SET ");
	}
		
	if( adminSkin!=null  && !adminSkin.equals("null"))
	{
		if(isHKT_ThemeEnabled)
		{
			if(updateHKT_ThemeSkinAndLogoPreference)
			{
				sbHKTThemeStr.append("ADMIN_SKIN='"+adminSkin+"'");
				updateUser_pref += ","+"ADMIN_SKIN='"+adminSkin+"'";
			}
		}
		else
		{
			updateUser_pref += ","+"ADMIN_SKIN='"+adminSkin+"'";
		}
		insertUser_pref +=adminSkin+"','";
	}
	else
	{
		String defaultAdminSkin = egUi.getValue("DEFAULT_SKINS","adminSkin");
		if(defaultAdminSkin !=null && defaultAdminSkin.length() > 0)
		{
			insertUser_pref +=defaultAdminSkin+"','";
		}
		else
		{
			insertUser_pref +="blue','";
		}
		temp1 = temp1 && false;
	}

	if(monitorSkin!=null && !monitorSkin.equals("null"))
	{
		if(isHKT_ThemeEnabled)
		{
			if(updateHKT_ThemeSkinAndLogoPreference)
			{
				sbHKTThemeStr.append(",MONITOR_SKIN='"+monitorSkin+"'");
				updateUser_pref += ","+"MONITOR_SKIN='"+monitorSkin+"'";
			}
		}
		else
		{
			updateUser_pref += ","+"MONITOR_SKIN='"+monitorSkin+"'";
		}
		insertUser_pref +=monitorSkin+"','";
	}
	else
	{
		String defaultMonitorSkin = egUi.getValue("DEFAULT_SKINS","monitorSkin");
		if(defaultMonitorSkin !=null && defaultMonitorSkin.length() > 0)
		{
			insertUser_pref +=defaultMonitorSkin+"','";
		}
		else
		{
			insertUser_pref +="blue','";
		}
		temp1 = temp1 && false;
	}

	if(reporterSkin!=null && !reporterSkin.equals("null"))
	{
		if(isHKT_ThemeEnabled)
		{
			if(updateHKT_ThemeSkinAndLogoPreference)
			{
				sbHKTThemeStr.append(",REPORTER_SKIN='"+reporterSkin+"'");
				updateUser_pref += ","+"REPORTER_SKIN='"+reporterSkin+"'";
			}
		}
		else
		{
			updateUser_pref += ","+"REPORTER_SKIN='"+reporterSkin+"'";
		}
		insertUser_pref +=reporterSkin+"','";
	}
	else
	{
		String defaultReporterSkin = egUi.getValue("DEFAULT_SKINS","reporterSkin");
		if(defaultReporterSkin !=null && defaultReporterSkin.length() > 0)
		{
			insertUser_pref +=defaultReporterSkin+"','";
		}
		else
		{
			insertUser_pref +="blue','";
		}
		temp1 = temp1 && false;
	}

	if(configSkin!=null && !configSkin.equals("null"))
	{
		if(isHKT_ThemeEnabled)
		{
			if(updateHKT_ThemeSkinAndLogoPreference)
			{
				sbHKTThemeStr.append(",CONFIG_SKIN='"+configSkin+"'");
				updateUser_pref += ","+"CONFIG_SKIN='"+configSkin+"'";
			}
		}
		else
		{
			updateUser_pref += ","+"CONFIG_SKIN='"+configSkin+"'";
		}
		insertUser_pref +=configSkin+"','";
	}
	else
	{
		String defaultConfigSkin = egUi.getValue("DEFAULT_SKINS","configSkin");
		if(defaultConfigSkin !=null && defaultConfigSkin.length() > 0)
		{
			insertUser_pref +=defaultConfigSkin+"','";
		}
		else
		{
			insertUser_pref +="blue','";
		}
		temp1 = temp1 && false;
	}

	if(refreshFreq!=null && !refreshFreq.equals("null"))
	{
		updateUser_pref += ","+"REFRESH_FREQ='"+refreshFreq+"'";
		insertUser_pref +=refreshFreq+"','";
	}
	else
	{
		insertUser_pref +=refreshFreq+"','";
		temp1 = temp1 && false;
	}
	
	if(monitorHomePageOption!=null && monitorHomePageOption.equalsIgnoreCase("default"))
	{
		if(monitorHomePage!=null && !monitorHomePage.trim().equals("null") && monitorHomePage.trim().length()>0)
		{
			updateUser_pref += ","+"MONITOR_HOME='"+monitorHomePage+"'";
			insertUser_pref +=monitorHomePage+"','";
		}
		else
		{
			String user_role_name=userRole.getRoleName();
			if(user_role_name!=null && (user_role_name.equals("AlarmViewer") || user_role_name.equals("SuperAlarmViewer")))
			{
				updateUser_pref += ","+"MONITOR_HOME='AlarmViewer'";
				insertUser_pref +="AlarmViewer','";
			}
			else
			{
				updateUser_pref += ","+"MONITOR_HOME='Monitor Dashboard'";
				insertUser_pref +="Monitor Dashboard','";
			}

		}
	}

	String alarm_delete=request.getParameter("alarm_delete");
	String alarm_ack=request.getParameter("alarm_ack");
	
	// Update ALARM_DELETE,ALARM_ACKNOWLEDGEMENT only for Admin,supermonitor login type.

	String userLoginType=user.getLoginType();
	//if((user.getLoginID()).equalsIgnoreCase("Admin")  || (user.getLoginID()).equalsIgnoreCase("supermonitor") || superuser)
	if(userLoginType!=null && (userLoginType.equals("Admin") || userLoginType.equalsIgnoreCase("supermonitor") || userRole.hasAllComponentAccess()))
	{
		updateUser_pref += ","+"ALARM_DELETE='"+alarm_delete+"'";
		updateUser_pref += ","+"ALARM_ACKNOWLEDGEMENT='"+alarm_ack+"'";
	}

	if(registry.getUser(session.getId()).isDefaultUser(userName))
	{
		insertUser_pref +="true','true','false','";
	}
	else
	{
		if(userLoginType!=null && (userLoginType.equals("Admin") || userLoginType.equalsIgnoreCase("supermonitor")))
		{
			insertUser_pref +=alarm_delete+"','"+alarm_ack+"','false','";
		}
		else
		{
			insertUser_pref +="false','false','false','";
			
		}
	}

	//Update or insert time zone in user_pref table
	if(timeZone!=null && !timeZone.equals("null"))
	{
		updateUser_pref += ","+"TIMEZONE='"+timeZone+"'";
		insertUser_pref +=timeZone+"','";
	}
    else
	{
		updateUser_pref += ","+"TIMEZONE='NO'";
		insertUser_pref +="NO','";
	}

	String dSkin = egUi.getValue("DEFAULT_SKINS","desktopSkin");
	if(dSkin==null || dSkin.equals("")) dSkin = "blue";
	
	insertUser_pref +="default','"+dSkin+"','default','default','default','";

	if(measureInMailMode!=null && measureInMailMode.trim().length()>0)
	{
		updateUser_pref += ","+"MEASURE_IN_MAIL='"+measureInMailMode+"'";
		insertUser_pref +=measureInMailMode+"','";
	}
	else
	{
		updateUser_pref += ","+"MEASURE_IN_MAIL='NO'";
		insertUser_pref +="NO','";
	}

	if(ddInMailMode!=null && ddInMailMode.trim().length()>0)
	{
		updateUser_pref += ","+"DD_IN_MAIL='"+ddInMailMode+"'";
		insertUser_pref +=ddInMailMode+"','";
	}
	else
	{
		updateUser_pref += ","+"DD_IN_MAIL='NO'";
		insertUser_pref +="NO','";
	}

	insertUser_pref +="default','";
	
	if(isHKT_ThemeEnabled)
	{
		loginLogo="d";
		monitorLogo="d";
		reporterLogo="d";
		configLogo="d";
		sbHKTThemeStr.append(",Logo='"+loginLogo+"\\"+monitorLogo+"\\"+reporterLogo+"\\"+configLogo+"\\"+config_repo_image+"'");
	}
	else 
	{
		if(loginLogo!=null && loginLogo.equalsIgnoreCase("yes"))
		{
			loginLogo="c";
		}
		else
		{
			loginLogo="d";
			//when logo change to default, delete the logo if it exits
			if(tempUserForLogo!=null && !tempUserForLogo.equals(""))
			{
				for (int ext = 0; ext < extensionList.size(); ext++)
				{
					String strExtension = (String)extensionList.get(ext);
					File fi = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/admin/eg_images/"+tempUserForLogo+"_login."+strExtension);
					if (fi.exists())
					{
						boolean success = fi.delete();
					}
				}
			}
		}
		if(monitorLogo!=null && monitorLogo.equalsIgnoreCase("yes"))
		{
			monitorLogo="c";
		}
		else
		{
			monitorLogo="d";
			//when logo change to default, delete the logo if it exits
			if(tempUserForLogo!=null && !tempUserForLogo.equals(""))
			{
				for (int ext = 0; ext < extensionList.size(); ext++)
				{
					String strExtension = (String)extensionList.get(ext);
					File fi = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/monitor/eg_images/"+tempUserForLogo+"_monitor."+strExtension);
					if (fi.exists())
					{
						boolean success = fi.delete();
					}
				}
			}
		}
		if(reporterLogo!=null && reporterLogo.equalsIgnoreCase("yes"))
		{
			reporterLogo="c";
		}
		else
		{
			reporterLogo="d";
			if(tempUserForLogo!=null && !tempUserForLogo.equals(""))
			{
				for (int ext = 0; ext < extensionList.size(); ext++)
				{
					String strExtension = (String)extensionList.get(ext);
					File fi = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/reporter/images/"+tempUserForLogo+"_reporter."+strExtension);
					if (fi.exists())
					{
						boolean success = fi.delete();
					}
				}
			}
		}
		if(configLogo!=null && configLogo.equalsIgnoreCase("yes"))
		{
			configLogo="c";
		}
		else
		{
			configLogo="d";
			if(tempUserForLogo!=null && !tempUserForLogo.equals(""))
			{
				for (int ext = 0; ext < extensionList.size(); ext++)
				{
					String strExtension = (String)extensionList.get(ext);
					File fi = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/config/images/"+tempUserForLogo+"_config."+strExtension);
					if (fi.exists())
					{
						boolean success = fi.delete();
					}
				}
			}
		}
		updateUser_pref +=",Logo='"+loginLogo+"\\"+monitorLogo+"\\"+reporterLogo+"\\"+configLogo+"\\"+config_repo_image+"'";
		insertUser_pref +=loginLogo+"\\"+monitorLogo+"\\"+reporterLogo+"\\"+configLogo+"\\"+config_repo_image+"','";
	}

	updateUser_pref +=",monitor_home_option='"+monitorHomePageOption+"'";
	insertUser_pref +=monitorHomePageOption+"')";

	updateUser_pref += " WHERE USER_ID='"+loginID+"'";
	boolean result = updateAndTransmitUserInfo.updateDB(updateUser_pref,"JSP");

	if(!result)
	{
		result = updateAndTransmitUserInfo.updateDB(insertUser_pref,"JSP");
	}
	com.egurkha.User.lastProfileUpdateTime = System.currentTimeMillis();

	flag_changeuser = updateAndTransmitUserInfo.updateLoginProfile(upass,mailid,msgmode,notify,alerttype,loginID,source);

	String modifyTimeOpt = request.getParameter("chgTimeOpt");
	if (modifyTimeOpt != null && modifyTimeOpt.trim().length() > 0 && !modifyTimeOpt.equalsIgnoreCase("null"))
	{
		String updateUser_info = "Update user_info SET rept_timeline='"+modifyTimeOpt+"' WHERE USER_ID='"+loginID+"'";
		updateAndTransmitUserInfo.updateDB(updateUser_info,"JSP");
	}
	
	if(isHKT_ThemeEnabled && updateHKT_ThemeSkinAndLogoPreference)
	{
		updateHKT_Theme_settings=sbHKTThemeStr.toString();
		result = updateAndTransmitUserInfo.updateDB(updateHKT_Theme_settings,"JSP");
		if(result)
		{
			uiObject.setValue("DEFAULT_SKINS","adminSkin",adminSkin);
			uiObject.setValue("DEFAULT_SKINS","monitorSkin",monitorSkin);
			uiObject.setValue("DEFAULT_SKINS","reporterSkin",reporterSkin);
			uiObject.setValue("DEFAULT_SKINS","configSkin",configSkin);
			uiObject.saveFile();
		}
		if(uiObject!=null)
		{
			EgConfigFilesSync.releaseInstance(uiObject);
		}
	}
	
	if (flag_changeuser && result)
	{
		if(monitorHomePageOption!=null && monitorHomePageOption.equalsIgnoreCase("dynamic"))
		{
			OneClickDashboardModel oneClickModel=new OneClickDashboardModel(user);
			if(!StringUtils.isNull(monitorHomePage))
			{
				String dynamicDashboardURL=oneClickModel.setDynamicDashboard(monitorHomePage);
			}
		}
		if(EgInstallInfo.isSuperManager && loginID.equals("egsm"))
		{
			com.eg.supermanager.EgSmSuperInfo superInfo = com.eg.supermanager.EgSmSuperInfo.getInstance();
			superInfo.setValue("SM_USER_LOGIN","SMPASS",upass);
			superInfo.saveFile();
		}
		resultVector.addElement("User profile updated successfully.");
		//resultVector.addElement("/final/admin/userProfile.jsp?entry="+entry);//removed on 08/08/07
		resultVector.addElement("/final/monitor/EgAlarms.jsp?entry="+entry);//modified on 08/08/07 to return to home page
		resultVector.addElement("UserProfile");
		session.setAttribute("resultVector",resultVector);
		session.setAttribute("entry",entry);

		/* code for auditlog starts */
		Hashtable prevHash = new Hashtable();
		Hashtable curHash = new Hashtable();
		String previousPassword = "";
		boolean isSamePassword=true;
		Enumeration en = request.getParameterNames();
		while(en.hasMoreElements())
		{
			String name = ((String) en.nextElement()).toString().trim();
			if(name != null && !name.equalsIgnoreCase("null") && name.length()>0 && name.startsWith("$_"))
			{
				String pValue = request.getParameter(name);
				if(pValue != null && !pValue.equalsIgnoreCase("null") && pValue.length()>0 && pValue.indexOf("$") !=-1)
				{
					String label = null;
					String labelValue = null;
					StringTokenizer stokens = new StringTokenizer(pValue,"$");
					if(stokens.countTokens()==2)
					{
						label = stokens.nextToken().toString();
						labelValue = stokens.nextToken();
					}
					else
					{
						label = stokens.nextToken();
						labelValue = "";
					}
					if(labelValue.equalsIgnoreCase("undefined"))
					{
						continue;
					}
					if (label.equals("Maximum timeline for reports") && (modifyTimeOpt == null || modifyTimeOpt.trim().length() == 0 || modifyTimeOpt.equalsIgnoreCase("null")))
					{
						continue;
					}
					if(label.equalsIgnoreCase("Alarms by Mail/SMS")){
						if(labelValue.trim().length()==0){
							prevHash.put(label+name.substring(1), "null");
						}
						else{
							prevHash.put(label+name.substring(1), getValue(labelValue.startsWith("_")?labelValue.substring(1):labelValue));
						}
					}
					if(label != null && labelValue != null && !labelValue.equalsIgnoreCase("null") && labelValue.trim().length()>0)
					{
						if(labelValue.equals("H"))
						{
							labelValue = "HTML";
						}
						if (label.equals("Maximum timeline for reports") && labelValue.equals("-1"))
						{
							labelValue = "Unlimited";
						}
						if(label.equals("Password"))
						{
							previousPassword = labelValue.startsWith("_")?labelValue.substring(1):labelValue;
							auditLogThread.setPreviousValue(label,"*****");	

						}
						else if(label.equals("Supported Screens For TV Mode Monitor")||label.equals("Supported Screens For TV Mode Reporter")||label.equals("Supported Screens For TV Mode Config"))
						{
							StringTokenizer TvModetokens1 = new StringTokenizer(labelValue,",");
							int limit = TvModetokens1.countTokens();
							int limitafter=1;
							StringBuffer TvKey1 = new StringBuffer();
							while (TvModetokens1.hasMoreTokens())
							{
								String TvModetokenstok=TvModetokens1.nextToken();
								StringTokenizer stokens1 = new StringTokenizer(TvModetokenstok,"#");
								if(stokens1.countTokens()==2)
								{
									String TvKey = ((String)stokens1.nextToken()).toString();
									String TvValue = ((String)stokens1.nextToken()).toString();
									TvKey1.append(TvKey);
									if (limit > limitafter) {
										TvKey1.append(',');
									}
								}
								limitafter++;
							}
								 labelValue =TvKey1.toString();
								prevHash.put(label, getValue(labelValue.startsWith("_")?labelValue.substring(1):labelValue));
								auditLogThread.setPreviousValue(label, getValue(labelValue.startsWith("_")?labelValue.substring(1):labelValue));
						}
						else
						{
							prevHash.put(label, getValue(labelValue.startsWith("_")?labelValue.substring(1):labelValue));
							auditLogThread.setPreviousValue(label, getValue(labelValue.startsWith("_")?labelValue.substring(1):labelValue));
						}
					}

					String currentValue = request.getParameter(name.substring(2));
					if(currentValue == null || currentValue.equalsIgnoreCase("null") && currentValue.trim().length()==0)
						continue;
					currentValue = currentValue.trim();
					if(label != null && label.equals("Password"))
					{
						if (currentValue.length() == 0)
						{
							currentValue = previousPassword;
						}
						currentValue = EgCrypt.decrypt(currentValue);
						if(currentValue.equals(previousPassword)){
							currentValue= "*****";
							isSamePassword=false;
						}
						else{
							currentValue= "******";
						}
					}
					if(label.equals("Supported Screens For TV Mode Monitor")||label.equals("Supported Screens For TV Mode Reporter")||label.equals("Supported Screens For TV Mode Config"))
					{
						StringTokenizer TvModetokens1 = new StringTokenizer(currentValue,",");
						int limit = TvModetokens1.countTokens();
						int limitafter=1;
						StringBuffer TvKey1 = new StringBuffer();
						while (TvModetokens1.hasMoreTokens())
						{
							String TvModetokenstok=TvModetokens1.nextToken();
							StringTokenizer stokens1 = new StringTokenizer(TvModetokenstok,"#");
							if(stokens1.countTokens()==2)
							{
								String TvKey = ((String)stokens1.nextToken()).toString();
								String TvValue = ((String)stokens1.nextToken()).toString();
								TvKey1.append(TvKey);
								if (limit >limitafter) {
									TvKey1.append(',');
								}
							}
							limitafter++;
						}
							 currentValue =TvKey1.toString();
					}
					if (label.equals("Maximum timeline for reports") && currentValue.equals("-1"))
					{
						currentValue = "Unlimited";
					}
					boolean isAlarmsExists=true;					
					if(label.equalsIgnoreCase("Alarms by Mail/SMS") && currentValue.equalsIgnoreCase("null") && labelValue.trim().length()== 0 ){
						isAlarmsExists=false;
					}
					if(label.equalsIgnoreCase("Alarms by Mail/SMS")){
						curHash.put(label+name.substring(1), getValue(currentValue));
					}
					if(label.equalsIgnoreCase("Mail ID / Mobile No To") && !(labelValue.trim().length()==0 && currentValue.trim().length()==0)){											
						curHash.put(label, "null");
					} 
					if(label.equalsIgnoreCase("Mail ID / Mobile No  Cc") && !(labelValue.trim().length()==0 && currentValue.trim().length()==0)){											
						curHash.put(label, "null");
					}  
					if(label.equalsIgnoreCase("Mail ID / Mobile No  Bcc") && !(labelValue.trim().length()==0 && currentValue.trim().length()==0)){											
						curHash.put(label, "null");
					} 
					if(currentValue.length()>0 && isAlarmsExists && !currentValue.equalsIgnoreCase("null") && !currentValue.equalsIgnoreCase(" ") && !(currentValue==null) )
					{
						curHash.put(label, getValue(currentValue));
						auditLogThread.setCurrentValue(label, getValue(currentValue));
					}
				}
			}
		}
		/*if(curHash.containsKey("Password"))
			curHash.remove("Password");

		Enumeration prevEnum = prevHash.elements();
		Enumeration curEnum = curHash.elements();
		while(prevEnum.hasMoreElements())
		{
			String preStr = (String) prevEnum.nextElement();
			prevList.add(preStr);
		}

		while(curEnum.hasMoreElements())
		{
			String preStr = (String) curEnum.nextElement();
			curList.add(preStr);
		}*/
		auditLogThread.setValue("Description","User profile has been updated for "+ loginID);

		/* User Password History Storage - STARTS 
		 * by Meena.V
		 */
		String userAuthentication = "Domain";
		if(loginID.indexOf("samlsso")!=-1 )
		{
			userAuthentication="SAML";
		}
		else if (loginID.indexOf("/")==-1 || !isValidDomainUser(loginID))
		{
			userAuthentication="Eg";
		}
		if (userAuthentication != null && userAuthentication.equalsIgnoreCase("Eg"))
		{
			String isPwdHistoryEnabled = egUi.getValue("MISC_ARGS","PwdMinHistoryEnable");
			if(isPwdHistoryEnabled != null && (isPwdHistoryEnabled.equalsIgnoreCase("yes") || isPwdHistoryEnabled.equalsIgnoreCase("true")))
			{
				String userPass=request.getParameter("pwd");
				if (userPass == null || userPass.length() == 0)
				{
					userPass = existingPassword;
				}
				userPass = userPass.trim();
				userPass = StringUtils.decodeSecurityChar(userPass);
				String pwdHistory = egUi.getValue("MISC_ARGS","PwdMinHistory");
				if(pwdHistory != null && pwdHistory.length()>0)
				{
					IniFile egMgrMiscWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini",true);
					String userFinalPwdHistoryVal = "";
					ArrayList userPwdTokens = new ArrayList();
					int pwdHistoryCount = Integer.parseInt(pwdHistory);
					String userPwdHistory = egMgrMiscWr.getValue("Password_History",loginID);
					if(userPwdHistory != null && userPwdHistory.length()>0)
					{
						userPwdTokens = StringUtils.egTokenizer(userPwdHistory,",",true,true,true);
						int userCurrentPwdHistoryCnt = userPwdTokens.size();
						if(pwdHistoryCount <= userCurrentPwdHistoryCnt)
						{
							for(int m=userCurrentPwdHistoryCnt; m>=pwdHistoryCount; m--)
							{
								userPwdTokens.remove(m-1);
							}
						}
					}
					userPass = EgCrypt.encrypt(userPass);
					userPwdTokens.add(0,userPass);
					userFinalPwdHistoryVal = userPwdTokens.toString();
					userFinalPwdHistoryVal = userFinalPwdHistoryVal.substring(1,userFinalPwdHistoryVal.length()-1);
					egMgrMiscWr.setValue("Password_History",loginID,userFinalPwdHistoryVal);
					egMgrMiscWr.saveFile();
					EgConfigFilesSync.releaseInstance(egMgrMiscWr);
				}
			}
		}
		/* User Password History Storage - ENDS */
		
		boolean isSame=true;
		int curValCount=0;		
		Iterator itr = curHash.keySet().iterator();
		while(itr.hasNext())
		{
			String key = (String)itr.next();
			String curValue=(String)curHash.get(key);
			String preValue=(String)prevHash.get(key);			
		 	if(!curValue.equalsIgnoreCase(preValue)){
				isSame=false;
				curValCount++;
			}
		}
		if(isSamePassword == false && curValCount == 1){
			isSamePassword=false;
			isSame=true;
		}
		else{
			isSamePassword=true;
		}	
		if(!isSame){
			if(isSamePassword ){
				auditLogThread.sendItToDB();
			}
		}

		/*if(!prevList.containsAll(curList))
			auditLogThread.sendItToDB();*/
		/* code for auditlog ends */
		 	
		
		uiObject.saveFile();
		EgConfigFilesSync.releaseInstance(uiObject);
		rootJson.put("Title",_mapping.getTextDescription("admin.user.User Profile"));
		rootJson.put("Msg",_mapping.getTextDescription("admin.user.User profile settings updated successfully"));
	}
	else
	{
		rootJson.put("Title",_mapping.getTextDescription("admin.user.User Profile"));
		rootJson.put("Msg",_mapping.getTextDescription("admin.user.Error in updating user profile"));

		resultVector.addElement("Error in updating user profile");
		//resultVector.addElement("/final/admin/userProfile.jsp");//removed on 08/08/07
		resultVector.addElement("/final/monitor/EgAlarms.jsp");//modified on 08/08/07 to return to home page
		resultVector.addElement("UserProfile");
		session.setAttribute("resultVector",resultVector);

		/* code for auditlog starts */
		auditLogThread.setValue("Description","Error while updating user profile for " + loginID);
		auditLogThread.sendItToDB();
		/* code for auditlog ends */
		
	}
	}
	out.println(rootJson.toString());
%>

<%!
	Hashtable mapping = null;
	public String getValue(String value)
	{
		value = value.trim();
		if(value != null && (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")))
			value = "Yes";
		else if(value != null && (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("no")))
			value = "No";
		else if(value != null && value.equalsIgnoreCase("HTML"))
			value = "HTML";
		else if(value != null && value.equalsIgnoreCase("T"))
			value = "Text";
		else if(value != null && value.equalsIgnoreCase("H"))
			value = "Critical";
		else if(value != null && value.equalsIgnoreCase("I"))
			value = "Major";
		else if(value != null && value.equalsIgnoreCase("L"))
			value = "Minor";
		else if(value != null && value.equalsIgnoreCase("medium"))
			value = "Major";
		else if(value != null && value.equalsIgnoreCase("high"))
			value = "Critical";
		else if(value != null && value.equalsIgnoreCase("low"))
			value = "Minor";
		else if(value != null && value.equalsIgnoreCase("C"))
			value = "Complete";
		else if(value != null && value.equalsIgnoreCase("N"))
			value = "New";
		else if(value != null && value.equalsIgnoreCase("DATA"))
			value = "Data";
		else if(value != null && value.equalsIgnoreCase("GRAPH"))
			value = "Graph";
		else if(mapping != null && mapping.containsKey(value))
		{
			value = (String)mapping.get(value);
			value = value.trim();
		}
		else if(value != null && value.equalsIgnoreCase("Virtual"))
			value = "Virtual Dashboard";
		value = value.substring(0,1).toUpperCase() + value.substring(1);
		return value;
	}

	public boolean isValidDomainUser(String l_user)
	{
		IniFile iniFile=new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_authenticate.ini");
		if (iniFile != null && l_user != null && l_user.indexOf("/") != -1)
		{
			l_user = l_user.substring(0,l_user.indexOf("/")).trim();
			String subjs[]=iniFile.getSubjects();
			if (subjs!=null && subjs.length>0)
			{
				for (int i=0;i<subjs.length ; i++)
				{
					String domainDisName = subjs[i];
					if (domainDisName != null && domainDisName.equalsIgnoreCase(l_user))
					{
						return true;
					}
				}
			}
		}
		return false;
	}
%>



