/*********************************************************************************************
 * Copyright 2004 - Volian Enterprises, Inc. All rights reserved.
 * Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE
 * ------------------------------------------------------------------------------
 * $Workfile: Security.cs $     $Revision: 4 $
 * $Author: Jsj $   $Date: 5/17/05 11:52a $
 *
 * $History: Security.cs $
 * 
 * *****************  Version 4  *****************
 * User: Jsj          Date: 5/17/05    Time: 11:52a
 * Updated in $/LibSource/Utils
 * cleanup
 * 
 * *****************  Version 3  *****************
 * User: Kathy        Date: 1/24/05    Time: 2:44p
 * Updated in $/LibSource/Utils
 * B2005-004 fixes
 * 
 * *****************  Version 2  *****************
 * User: Kathy        Date: 1/14/05    Time: 10:38a
 * Updated in $/LibSource/Utils
 * B2004-061: fix security options
 * 
 * *****************  Version 1  *****************
 * User: Kathy        Date: 7/27/04    Time: 8:34a
 * Created in $/LibSource/Utils
 *********************************************************************************************/

using System;
using System.IO;
using System.Collections;
using System.Windows.Forms;
using System.Text;

namespace Utils
{
	/// <summary>
	/// Summary description for Security.
	/// </summary>
	public class Security
	{
		public const long  VIEW				=0x00000001L;
		public const long  PRINT			=0x00000002L;
		public const long  PRINTDRAFT		=0x00000004L;
		public const long  PRINTCHANGES		=0x00000008L;
		public const long  EDIT				=0x00000010L;
		public const long  SEARCH			=0x00000020L;
		public const long  STANDARDSTEPS	=0x00000040L;
		public const long  APPROVE			=0x00000080L;
		public const long  APPROVESINGLE	=0x00000100L;
		public const long  LIBRARYDOCS		=0x00000200L;
		public const long  ADDMODDEL		=0x00000400L;
		public const long  CLEAN			=0x00000800L;
		public const long  LOCKPROC			=0x00001000L;
		public const long  LOCKSET			=0x00000001L;
		public const long  UCF				=0x00000002L;
		public const long  LOCKSYSTEM		=0x00000001L;
		public const long  DOCMAINT			=0x00000002L;
		public const long  ROEDITOR			=0x00000004L;
		public const long  SYSADMIN			=0x00000008L;

		public const int   SUPERUSER		=1000;
		public const long  SUPERACCESS		=0xFFFFFFFFL;

		// the following four flags are system security options,
		// read in for the user from the security file (vesam.opt)
		private bool BlockAccessFlag=false;
		public bool PermissionToManageFlag=false;
		public bool SystemAdminFlag=false;
		public bool PermissionToLockFlag=false;

//		private string optFileName;
		private int numsets = 0;
		private long uoptions;	// user options
		private Int16 blockAccess = 0;
		private long oldpos;
		public int userid = -1;
//		private int plantid = -1;
//		private int procid = -1;
		private string ident;
		public string initials;
		private const string samoptname = "vesam.opt";
		public string optfilename;
		private ArrayList psets;    // 
		public FileStream fs;
		public BinaryReader bw;
		public bool isDemoMode=false;

		public Security(string pathname)
		{
			if (File.Exists(pathname + "\\" + samoptname) == false)
			{
				MessageBox.Show("Could not locate the Security Options file:\n\n" + pathname+"\\"+samoptname,"Security Access Error");
				optfilename = null;
				return;
			}
			optfilename = pathname + "\\" + samoptname;
			psets = new ArrayList();
		}

		public bool OpenFile()
		{
			try
			{
				fs = new FileStream(optfilename,FileMode.Open,FileAccess.Read,FileShare.Read,1,false);
				bw = new BinaryReader(fs);
				return true;
			}
			catch (Exception e)
			{
				MessageBox.Show(e.Message,"Security File");
				return false;
			}
		}

		public void CloseFile()
		{
			bw.Close();
			fs.Close();
			bw=null;
			fs=null;
		}

		public int CheckUserId(string Name, string Pass)
		{
			// check for default superuser username/password.
			if ((Name=="vlnmsp") && (Pass=="575")) 
			{
				userid = SUPERUSER;
				ident = "vlnmsp";
				initials = Name;
				return userid;
			}
			
			if (bw==null)
			{
				bool op;
				if ((op = OpenFile()) == false) return -1;
			}
			byte x;
			// read past some header stuff.
			for (int jj=0;jj<16;jj++)
				x=bw.ReadByte();
			long nxtUs;
			uint nmUser;
			nxtUs=bw.ReadUInt32();
			nmUser=bw.ReadUInt16();

			int uid, tmp;
			string fName, fPass;
			for (int i = 0; i < nmUser; i++)
			{
				fs.Seek((long)nxtUs,SeekOrigin.Begin);
				nxtUs=bw.ReadUInt32();
				uid = bw.ReadUInt16();
				tmp = bw.ReadUInt16();
				byte [] test = new byte[10];
				test = bw.ReadBytes(10);
				fName = Encoding.ASCII.GetString(test,0,10);
				int indx = fName.IndexOf("\0");
				string fNameTrim = fName.Substring(0,indx);
				if (fNameTrim == Name)
				{
					test = bw.ReadBytes(10);
					fPass = Encoding.ASCII.GetString(test,0,10);
					indx = fPass.IndexOf("\0");
					string fPassTrim = fPass.Substring(0,indx);
					if (fPassTrim == Pass)
					{
						userid = uid;
						ident = Name;
						initials = Name;
						break;
					}
				}
			}
			CloseFile();

			return userid;
		}

		public void SetUserSystemRights()
		{
			BlockAccessFlag=BlockAccess();
			long userAccessFlags=GetUserSecurity();
			PermissionToManageFlag=(userAccessFlags&Security.DOCMAINT)==0?false:true;
			PermissionToLockFlag=(userAccessFlags&Security.LOCKSYSTEM)==0?false:true;
			SystemAdminFlag=(userAccessFlags&Security.SYSADMIN)==0?false:true;
		}

		public void LoadUserSecurity()
		{
			//
			// get the system level security options for this user here
			//
			bool op = OpenFile();
			if (op==false) return;

			if( userid == 1000 ) 
			{ // super user priviledge
				uoptions = 0xFFFFFFFFL;
				SetUserSystemRights();
				CloseFile();
				return;
			}

			fs.Seek(32,SeekOrigin.Begin);
			blockAccess=bw.ReadInt16();
			
			fs.Seek(0,SeekOrigin.Begin);
			byte x;
			// read past some header stuff.
			for (int jj=0;jj<16;jj++)
				x=bw.ReadByte();
			
			long nxtUs;
			uint nmUser;
			nxtUs=bw.ReadUInt32();
			nmUser=bw.ReadUInt16();

			int uid;
			for (int i = 0; i < nmUser; i++)
			{
				oldpos = nxtUs;
				fs.Seek((long)nxtUs,SeekOrigin.Begin);
				nxtUs=bw.ReadUInt32();
				uid = bw.ReadUInt16();
				if (uid == userid)
				{
					string junk = new string (bw.ReadChars(22));
					uoptions=bw.ReadUInt16();
					break;
				}
			}
			SetUserSystemRights();
			CloseFile();
		}

		public void SetUpDemoMode()
		{
			userid=Security.SUPERUSER; // super user so that demo data can be anywhere (doesn't check vesamp.opt)
			ident="demo";
			initials="demo";
			isDemoMode = true;
		}
		public int GetPlantSecurityIndex(string Location)
		{
			for (int i=0;i<psets.Count;i++)
			{
				SecurityPlantSets sps = (SecurityPlantSets) psets[i];
				if (Location.ToUpper() == sps.GetPath().ToUpper()) return i;
			}
			return -1;
		}

		public bool PlantHasSecurity(int idx)
		{
			if (userid == SUPERUSER) return true;
			if (idx<0 || idx>psets.Count-1)return false;
			SecurityPlantSets sps = (SecurityPlantSets) psets[idx];
			return sps.HasSecurity;
		}

		public bool ProcSetHasSecurity(int idx, string procset)
		{
			if (userid == SUPERUSER) return true;
			if (idx<0 || idx>psets.Count-1)return false;
			SecurityPlantSets sps = (SecurityPlantSets) psets[idx];
			return sps.ProcSetHasSecurity(procset);
		}

		public long GetPlantSecurity(int idx)
		{
			if(userid == SUPERUSER ) return SUPERACCESS;
			if (idx<0 || idx>psets.Count-1) return 0L;
			SecurityPlantSets sps = (SecurityPlantSets) psets[idx];
			return (sps.GetSecurity());
		}

		public bool AnyOptionsSet(int idx)
		{
			if(userid==SUPERUSER) return true;
			if (idx<0 || idx>psets.Count-1) return false;
			SecurityPlantSets sps = (SecurityPlantSets) psets[idx];
			return sps.AnyOptionsSet();
		}

		public long GetUserSecurity()
		{
			if(userid == SUPERUSER) return SUPERACCESS;
			return(uoptions);
		}

		public bool BlockAccess()
		{
			if (userid == SUPERUSER) return false;
			if(blockAccess!=0) return true;
			return false;
		}

		public bool IsAllowed(long mask)
		{
			if(userid == SUPERUSER) return true;
			return (uoptions&mask) != 0;
		}

		public bool IsAllowed(string plantpath, string procpath, long mask)
		{
			bool retval = false;
			if(userid == SUPERUSER) return true;
			for(int i=0; i<numsets; i++) 
			{
				SecurityPlantSets sps = (SecurityPlantSets) psets[i];
				if(sps.IsAllowed(plantpath,procpath,mask)==true) 
				{
					retval = true;
					break;
				}
			}
			return retval;
		}

		public long GetProcSecurity(string fullpath)
		{
			long mask=0L;
			string plantpath;
			string fullprocpath;
			string procpath;
			string tmpchg=null;
			string apr=null;

			if(userid == SUPERUSER) return SUPERACCESS;
			plantpath = fullpath;
			procpath = plantpath.Substring(plantpath.LastIndexOf("\\"),plantpath.Length-plantpath.LastIndexOf("\\"));
			if (procpath.Substring(1,procpath.Length-1).ToUpper() == "TMPCHG")
			{
				// we have a Temporary Change directory, store it
				tmpchg=procpath;
				// remove the tmpchg text from the plantpath string
				plantpath=plantpath.Substring(0,plantpath.Length-tmpchg.Length);
				// Get the procedure subdirectory
				procpath = plantpath.Substring(plantpath.LastIndexOf("\\"),plantpath.Length-plantpath.LastIndexOf("\\"));
			}
			if(procpath.Substring(1,procpath.Length-1).ToUpper() == "APPROVED") 
			{
				// we have an approved dir, store it
				apr = procpath;
				// remove the approved text from the plantpath string
				plantpath=plantpath.Substring(0,plantpath.Length-apr.Length);
				// Get the procedure subdirectory
				procpath = plantpath.Substring(plantpath.LastIndexOf("\\"),plantpath.Length-plantpath.LastIndexOf("\\"));
			}

			// at this point, tmpchg & apr will be set if we have a tmpchg or approved directory,
			// plantpath will contain the plant directory & procedure set subdirectory, and 
			// procpath will be the procedure set subdirectory name (with the preceeding '\').
			// Now set plantpath to be the plant level directory. Make fullprocpath from the 
			// procedure set subdirectory & any approved/tmpchg directories that were part
			// of the path that was passed in.
			plantpath=plantpath.Substring(0,plantpath.Length-procpath.Length);
			procpath=procpath.Substring(1,procpath.Length-1);  // remove '\' prefix
			fullprocpath=procpath+apr+tmpchg;
			for(int i=0; i<numsets; i++) 
			{
				SecurityPlantSets sps = (SecurityPlantSets) psets[i];
				if( sps.GetProcSecurity(plantpath,fullprocpath,ref mask) ) break;
			}
			return mask;
		}

		public void AddPlant(int nTab, string path)
		{
			SecurityPlantSets sps = new SecurityPlantSets(path, oldpos, this);
			psets.Insert(nTab,sps);
			numsets = psets.Count;
		}
	}

	public class SecurityProcSets
	{
		private long[] procoptions;
		private string path;

		public SecurityProcSets(string pth, Security security, long userPos, int procid, int numplants, int pid)
		{
			procoptions = new long[4];
			path = pth;
			// read in proc options
			if (security.userid == Security.SUPERUSER)
			{
				for(int i=0;i<4;i++) procoptions[i]=0xff;
				return;
			}
			security.fs.Seek(userPos+38L,SeekOrigin.Begin);

			short tpid;
			for (int i=0;i<numplants;i++)
			{
				tpid = security.bw.ReadInt16();
				security.fs.Seek(8L,SeekOrigin.Current);
				short nProcSets;
				nProcSets = security.bw.ReadInt16();
				for (int j=0; j<nProcSets;j++)
				{
					short tprocid;
					tprocid = security.bw.ReadInt16();
					if (tprocid==procid && tpid==pid)
					{
						tprocid = security.bw.ReadInt16();
						for(int k=0;k<4;k++) procoptions[k]=security.bw.ReadInt32();
						return;
					}
					else
						security.fs.Seek(18,SeekOrigin.Current);
				}
			}
		}

		public bool AnyOptionsSet()
		{
			for(int k=0;k<4;k++) if(procoptions[k]!=0L)return true;
			return false;
		}

		public bool IsAllowed(string procpath, long mask)
		{
			bool retval = false;
			if (path==procpath) retval = (procoptions[0]&mask) !=0;
			return retval;
		}

		public string GetPath()
		{
			return path;
		}

		public bool GetProcSecurity(string procpath, ref long mask)
		{
			bool retval = false;
			if (path.ToUpper()==procpath.ToUpper())
			{
				mask = procoptions[0];
				retval = true;
			}
			return retval;
		}
	}

	public class SecurityPlantSets 
	{
		private string path;
		private long setoption;
		private int numopts;
		private ArrayList procs;   // SecurityProcSets;
		private Security security;
		// Flag whether this plant has data in the security options file. (maybe newly
		// created since vesam was run).
		public bool HasSecurity;

		public SecurityPlantSets(string cptr, long userPos, Security sec)
		{
			string title;
			string pth;
			int pid=0;
			long plantpos;
			procs = new ArrayList();
			security = sec;
			path = cptr;
			HasSecurity=false;

			security.fs.Seek(8L,SeekOrigin.Begin);
			numopts = -1;
			plantpos = security.bw.ReadInt32();  // 1st plant set position
			short np;
			np = security.bw.ReadInt16();		// number of plant sets.
			long oldpos=0;
			short sz;
			for (int i=0;i<np;i++)
			{
				security.fs.Seek(plantpos,SeekOrigin.Begin);
				plantpos = security.bw.ReadInt32();
				pid = security.bw.ReadInt16();
				sz = security.bw.ReadInt16();
				title = new string(security.bw.ReadChars(sz));
				sz = security.bw.ReadInt16();
				pth=null;
				pth = new string(security.bw.ReadChars(sz));
				if (pth.ToUpper()==path.ToUpper())   // this is what we're looking for..
				{
					numopts = security.bw.ReadInt16();
					security.fs.Seek(4L,SeekOrigin.Current);
					oldpos = security.fs.Position;
					HasSecurity=true;
					break;
				}
			}

			// get the plant level options
			int currentUID = sec.userid;
			if (currentUID != Security.SUPERUSER)
			{
				security.fs.Seek(userPos,SeekOrigin.Begin);
				security.fs.Seek(38L,SeekOrigin.Current);
				short tpid;
				for (int i=0;i<np;i++)
				{
					tpid = security.bw.ReadInt16();
					if (tpid == pid)    // correct plant
					{
						setoption = security.bw.ReadInt32();
						break;
					}
					else
					{
						setoption = security.bw.ReadInt32();   //skip following data...
						setoption = security.bw.ReadInt32();
						tpid = security.bw.ReadInt16();
						for (int j=0;j<tpid;j++) security.fs.Seek(20L,SeekOrigin.Current);
					}
				}
			}
			else
				setoption = Security.SUPERACCESS;
			if (numopts>0)
				procs = new ArrayList(numopts);
			else
				procs = null;
			for(int i=0;i<numopts;i++)
			{
				security.fs.Seek(oldpos+4L,SeekOrigin.Begin);
				short procid;
				procid = security.bw.ReadInt16();
				sz = security.bw.ReadInt16();
				title = new string(security.bw.ReadChars(sz));
				sz = security.bw.ReadInt16();
				pth = new string(security.bw.ReadChars(sz));
				security.fs.Seek(4L,SeekOrigin.Current);
				oldpos = security.fs.Position;
				SecurityProcSets sps =  new SecurityProcSets(pth, security, userPos, procid, np, pid);
				procs.Insert(i,sps);
			}
		}
		
		public string GetPath()
		{
			return path;
		}

		public bool ProcSetHasSecurity(string procset)
		{
			if (procs==null)return false;    // if no procs for plant in security file.
			//see if this plant has a procedure set that matches the input string
			// this will tell us that it is included in the vesam.opt file.
			for (int i=0;i<procs.Count;i++)
			{
				SecurityProcSets sps = (SecurityProcSets) procs[i];
				if (sps.GetPath().ToUpper() == procset.ToUpper()) return true;
			}
			return false;
		}

		public bool AnyOptionsSet()
		{
			for (int i=0;i<numopts;i++)
			{
				SecurityProcSets sps = (SecurityProcSets) procs[i];
				if (sps.AnyOptionsSet())return true;
			}
			return false;
		}

		public bool IsAllowed(string plantpath, string procpath, long mask)
		{
			bool retval = false;
			if (path==plantpath)
			{
				for (int i=0;i<numopts;i++)
				{
					SecurityProcSets sps = (SecurityProcSets) procs[i];
					if (sps.IsAllowed(procpath, mask)==true)
					{
						retval = true;
						break;
					}
				}
			}
			return retval;
		}
		
		public long GetSecurity()
		{
			return (setoption);
		}

		public bool GetProcSecurity(string plantpath, string procpath, ref long mask)
		{
			bool retval = false;
			if(path.ToUpper() == plantpath.ToUpper())
			{
				if (security.userid!=Security.SUPERUSER)
				{
					for (int i=0; i<numopts; i++)
					{
						SecurityProcSets sps = (SecurityProcSets) procs[i];
						if (sps.GetProcSecurity(procpath,ref mask) == true)
						{
							retval = true;
							break;
						}
					}
				}
				else
				{
					retval = true;
					mask = Security.SUPERACCESS;
				}
			}
			return retval;
		}
	}
}
