import pyHook, time,sys,os,xml.dom.minidom,shutil, getopt
from Tkinter import StringVar
from time import localtime
#import pythoncom
import types
import threading
import win32con
import win32gui
import win32api
import win32evtlog
import win32api
import win32file
import win32con
import win32security # To translate NT Sids to account names.
import pyAA
import wmi
from win32com.shell import shell, shellcon
#import MySQLdb
import win32evtlogutil

global logfile, resac, bvariable,do,rept,crept

def Twrite(string):
   global rept
   logfile = open(rept, mode ='a+')
   def MTwrite(data):
      logfile.write(data)
   MTwrite(string)
   logfile.close()
def Cwrite(string):
   global crept
   clogfile = open(crept, mode ='a+')
   def cMTwrite(data):
      clogfile.write(data)
   cMTwrite(string)
   clogfile.close()   
class WatchDirectory(object):
   global logfile
   """
   This method was adapted from example by Tim Golden:
   http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html
 
   Watches for changes to any file/dir inside specified directory.
   Instantiating this class spawns the watcher function in a separate thread.
   self.changeList accumulates changes until client requests list using the check() method.
 
   Calling that method returns the changeList then empties it.
 
   The watching thread will self-terminate when the WatchDirectory instance is destroyed
   or falls out-of-scope.
 
   Usage Examples:
      watcher = WatchDirectory(r'D:\myStuff')
 
      # Typically you'd have a main loop here somewhere, inside of which you'd make occasional
      # calls to watcher.check, like so:
      while (not doneWithLoop):
         changes = watcher.check()
         for c in changes:
            # do something to each modified file, etc...
            print "file: %s, change: %s" % c
 
   See self.ACTIONS below for a list of possible change strings.
 
   Also, the "onlyExtensions" keyword arg can be used to only watch certain filetypes:
      watcher = WatchDirectory(r'D:\myStuff', onlyExtensions=('.jpg', '.xml') 
 
   NOTES:
   ChangeList returned is chronological, oldest to newest.  A file that's modified early in the list
   could show up as deleted later.  Your client code is responsible for verifying files still
   exist, etc.
 
   The win32 method used here seems very reliable.  I did notice that it fails to report
   deleted files if they were inside a subdir that was deleted in its entirety, however.
   Seems like a border case, however, so I'm inclined to leave it as-is for now.
   Also, deleted subdirs still sometimes show up as a change with watchSubdirs=False.
 
   TODO:
   - Maybe add option to not multithread, making it a blocking call.
 
   Adam Pletcher
   adam@volition-inc.com
   Volition, Inc./THQ
   """
   def __init__(self, dirToWatch, bufferSize=1024, watchSubdirs=True, onlyExtensions=None):
      self.dirToWatch = dirToWatch
      self.changeList = []
      self.bufferSize = bufferSize
      self.watchSubdirs = watchSubdirs
      if (type(onlyExtensions) == types.StringType):
         onlyExtensions = onlyExtensions.split(',')
      self.onlyExtensions = onlyExtensions
      # Constants for making win32file stuff readable
      self.ACTIONS = {
         1 : "Created",
         2 : "Deleted",
         3 : "Modified",
         4 : 'Renamed to something',
         5 : 'Renamed from "%s"'
      }
      # Start watching in a separate thread
      self.thread = threading.Thread(target=self._checkInThread).start()
 
   def _checkInThread(self):
      global logfile
      """
      Watch for changes in specified directory.  Designed to be run in a
      separate thread, since ReadDirectoryChangesW is a blocking call.
      Don't call this directly.
      """
      while (1):
         FILE_LIST_DIRECTORY = 0x0001
         hDir = win32file.CreateFile (
            self.dirToWatch,
            FILE_LIST_DIRECTORY,
            win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
            None,
            win32con.OPEN_EXISTING,
            win32con.FILE_FLAG_BACKUP_SEMANTICS,
            None
         )
         # The following is a blocking call.  Which is why we run this in its own thread.
         newChanges = win32file.ReadDirectoryChangesW (
            hDir,                # Previous handle to directory
            self.bufferSize,     # Buffer to hold results
            self.watchSubdirs,   # Watch subdirs?
            win32con.FILE_NOTIFY_CHANGE_FILE_NAME |   # What to watch for
            win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
            win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
            win32con.FILE_NOTIFY_CHANGE_SIZE |
            win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
            win32con.FILE_NOTIFY_CHANGE_SECURITY,
            None,
            None
         )
         # Changes found, process them
         finalChanges = []
         oldFilename = None
         for change in newChanges:
            if (change[0] == 4):   # renamed to something
               oldFilename = os.path.split(change[1])[1]
               pass
            else:
               file = os.path.join(self.dirToWatch, change[1])
               skip = False
               # Verify a few things first
               if (not self.watchSubdirs) and (os.path.isdir(file)):
                  skip = True
               elif (self.onlyExtensions) and (not os.path.splitext(file)[1] in self.onlyExtensions):
                  skip = True
               if (not skip):  # passed checks, so use it
                  action = self.ACTIONS.get (change[0], "Unknown")
                  if (change[0] == 5): # renamed from something
                     # Insert old filename, prior to being renamed
                     action = action % (oldFilename)
                     oldFilename = None
                  # Add change tuple to list
                  timec=time.strftime('%m/%d/%y %H:%M:%S')
                  resac= timec + '\t' + 'file change'+'\t'+file+'\t'+ action+'\n'
                  Twrite(resac)
                  finalChanges.append((file, action))
         # Add processed changes to running list
         self.changeList += finalChanges
 
   def check(self):
      """
      Fetches list of changes our watcher thread has accumulated.
      """
      changes = self.changeList
      self.changeList = []  # clear changeList
      return changes
def ReadLog(computer, logType="Security", dumpEachRecord = 1):
    global resac,logfile,nmes
    def Twrite(data):
        logfile.write(data)
##    def get_main_dir():
##        try:
##            sys.frozen
##        except AttributeError:
##            path = sys.argv[0]
##        else:
##            path = sys.executable
##        return os.path.dirname(os.path.abspath(path))
    datePrefix = time.strftime("%Y%m%d", time.localtime(time.time()))
    fileExists = 1
    retry = 0
    while fileExists:
            if retry == 0:
                    index = ""
            else:
                    index = "-%d" % retry
            try:
                    fname = os.path.join(win32api.GetTempPath(), "%s%s-%s" % (datePrefix, index, logType) + ".evt")
                    os.stat(fname)
            except os.error:
                    fileExists = 0
            retry = retry + 1
##    oscurdir=get_main_dir()
##    rept=str(oscurdir)+os.sep+'securitylogfile.csv'
##    logfile = open(rept, mode ='w+')
##    resac=""
    # read the entire log back.
    h=win32evtlog.OpenEventLog(computer, logType)
    numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
    #print "There are %d records" % numRecords
    cont=True
    num=0
    nfile={}
    o=0
    p=0
    q=0
    
    while 1:
        objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
        if not objects:
            break
        for object in objects:
            # get it for testing purposes, but dont print it.
            msg = win32evtlogutil.SafeFormatMessage(object, logType)
            #timob=object.TimeGenerated.Format()
            #timcu=time.strftime('%m/%d/%y %H:%M:%S')
            find=True
            imsg=""
            found=False
            #print repr(msg)
##            for t in range(0,nmes[0,'q']):
##                if nmes[t,'time']==timob and repr(nmes[t,'mes'])==repr(msg):
##                    found=True
##            if found==True:continue
##            else:
##                nmes[q,'time']=timob
##                nmes[q,'mes']=msg
##                nmes[0,'q']=q
##                q+=1
            #print timob[0:13],'-',timcu[0:13]
            #return 1
##            if str(timob[0:14])==str(timcu[0:14]):
##                #print 'hu'
##                if (int(timcu[13:14])-int(timob[13:14]))<2:
                    #print 'ho'

            if msg[0:12]=="Objet ouvert" :
                #print 'yrerl'
                u = len(msg)
                i=0
                o+=1
                find=True
                imsg="Fichier Ouvert : \t "
                nomer =False
                nomfichier=""
                imager=False
                handler=False
                procer=False
##                nfile[int(o),'open','file']=""
##                nfile[o,'open','handleid']=""
##                nfile[o,'open','process']=""
##                nfile[o,'open','processid']=""
##                nfile[o,'open','handleid']=""
                while i<u:
                    if msg[i:i+12]=="explorer.exe":
                        find=True
                        break
                    elif msg[i:  i+16]=="Nom de l'objet :" or nomer==True:
                        #print 'yourl'
                        if nomer ==False:no=i
                        nomer=True
                        imsg=imsg+msg[i]
                        nomfichier=nomfichier+msg[i]
                        if msg[i:i+2]=="\r\n":
                            nomer=False
                            #print repr(msg)
                            for char in nomfichier:
                                if char=='.':
                                    print 'yop'
                                    find=False
                                    #nfile[int(o),'open','file']=msg[int(no)+16:int(i)-1]
                                    imsg=imsg+' \t '
                        i+=1
                    elif msg[i:i+22]=="Nom du fichier image :" or imager==True:
                        if imager==False:im=i
                        imager=True
                        imsg=imsg+msg[i]
                        i+=1
                        if msg[i:i+1]=="\r":
                            imager=False
                            #nfile[o,'open','process']=msg[im+22:i-1]
##                    elif msg[i:i+27]=="Identificateur du handle : " or handler==True:
##                        if handler==False:ha=i
##                        handler=True
##                        imsg=imsg+msg[i]
##                        i+=1
##                        if msg[i:i+1]=="\r":
##                            handler=False
##                            nfile[o,'open','handleid']=msg[ha+27:i-1]
##                    elif msg[i:i+20]=="Id. du processus  : " or procer==True:
##                        if procer==False:pr=i
##                        procer=True
##                        imsg=imsg+msg[i]
##                        i+=1
##                        if msg[i:i+1]=="\r":
##                            procer=False
##                            nfile[o,'open','processid']=msg[pr+20:i-1]
                    else:
                        i+=1
##                    if msg[0:11]=="Handle ferm" :
##                        p+=1
##                        u = len(msg)
##                        i=0
##                        find=False
##                        imsg="Fichier ferme : "
##                        nomer =False
##                        imager=False
##                        handler=False
##                        procer=False
##                        nfile[p,'close','handleid']=""
##                        nfile[p,'close','process']=""
##                        nfile[p,'close','processid']=""
##                        nfile[p,'close','handleid']=""
##                        while i<u:
##                            if msg[i:i+12]=="explorer.exe":
##                                find=True
##                                break
##                            elif msg[i:i+22]=="Nom du fichier image :" or imager==True:
##                                if imager==False:im=i
##                                imager=True
##                                imsg=imsg+msg[i]
##                                i+=1
##                                if msg[i:i+1]=="\r":
##                                    imager=False
##                                    nfile[p,'close','process']=msg[im+22:i-1]
##                            elif msg[i:i+16]=="Id. du handle : " or handler==True:
##                                if handler==False:ha=i
##                                handler=True
##                                imsg=imsg+msg[i]
##                                i+=1
##                                if msg[i:i+1]=="\r":
##                                    handler=False
##                                    nfile[p,'close','handleid']=msg[int(ha)+16:int(i)-1]
##                            elif msg[i:i+19]=="Id. de processus : " or procer==True:
##                                if procer==False:pr=i
##                                procer=True
##                                imsg=imsg+msg[i]
##                                i+=1
##                                if msg[i:i+1]=="\r":
##                                    procer=False
##                                    nfile[p,'close','processid']=msg[pr+19:i-1]
##                            else:
##                                i+=1
##                        find=True
##                        for x in range(1,o):
##                            if nfile[x,'open','file']=="":continue
##                            if nfile[x,'open','handleid']==nfile[p,'close','handleid'] and nfile[x,'open','processid']==nfile[p,'close','processid']:
##                                imsg=imsg+' fichier :'+ nfile[x,'open','file']
##                                find=False
##                                break
##                            if find==False:break
                            #print 'hmmf'
            if find==False:
                print 'year'
                resac=object.TimeGenerated.Format()+'\t'+imsg.encode('latin-1')+'\n'

                if object.Sid is not None:
                    try:
                        domain, user, typ = win32security.LookupAccountSid(computer, object.Sid)
                        sidDesc = "%s/%s" % (domain, user)
                        #print 'domain:',domain,'user',user,'sid',sidDesc,'msg:',msg
                    except win32security.error:
                        sidDesc = str(object.Sid)
                    user_desc = "Event associated with user %s" % (sidDesc,)
                else:
                    user_desc = None
                if dumpEachRecord:
                    print "Event record from %r generated at %s" % (object.SourceName, object.TimeGenerated.Format())
                    if user_desc:
                        print user_desc
                    try:
                        print msg
                    except UnicodeError:
                        print "(unicode error printing message: repr() follows...)"
                        print repr(msg)

        num = num + len(objects)
    if numRecords == num:
        pass
        #print "Successfully read all", numRecords, "records"
    else:
        print "Couldn't get all records - reported %d, but found %d" % (numRecords, num)
        print "(Note that some other app may have written records while we were running!)"
    try:
        Twrite(resac)
        win32evtlog.ClearEventLog(h, fname)
        win32evtlog.CloseEventLog(h)
    except:
        print "Couldn't clear and close event log"

texte=''
win=''
timec=''
nombrecliq=0
winame=""
nmes={}
nmes[0,'time']=""
nmes[0,'mes']=""
nmes[0,'q']=0
##def OnKeyboardEvent(event):
##  global texte,win,timec,resac,logile,resac
##  if (win!=event.WindowName and win!='' and win!="None" and win!="FolderView"):
##    resac=str(timec)+'\t'+'window change - keyboard'+'\t'+str(len(texte))+'\t'+str(win)+'\t'+str(texte[0:10])+'\n'
##    Twrite(resac)
##    #print 'Heure:',timec
##    #print 'Application',win
##    #print 'Texte:', texte##.encode('latin1')
##    texte=''
##  texte=texte+event.Key
##  win=event.WindowName
##  timec=time.strftime('%m/%d/%y %H:%M:%S')
##  return True


def OnMouseEvent(event):
  global texte,logfile,resac,win,timec,resac,nombrecliq,processactif

  #processEndLog()
  if (win!=event.WindowName and win!='' and win!="None" and win!="FolderView"):
##    hwnd = win32gui.GetForegroundWindow()
##    # we want the desktop window
##    objid = pyAA.Constants.OBJID_WINDOW
##    # get the object
##    ao = pyAA.AccessibleObjectFromWindow(hwnd, objid)
##    pr= ao.GetProcessAndThreadID()
##    c=wmi.WMI()
##    for process in c.Win32_Process():
##       if process.ProcessId in pr:
##           pname = process.Name
    resac=str(timec)+'\t'+'window change - mouse'+'\t'+str(nombrecliq)+'\t'+str(win)+'\t'+str(processactif)+'\n'
    Twrite(resac)
    nombrecliq=0
  # called when mouse events are received
  #print 'click souris'
  #print 'Time:',time.ctime()
  #print 'WindowName:',event.WindowName
  #print 'texte:',texte
# return True to pass the event to other handlerspy
  win=event.WindowName
  nombrecliq=nombrecliq+1
  timec=time.strftime('%m/%d/%y %H:%M:%S')
  return True
def processEndLog():
   global pprocess,prs,processactif
   hwnd = win32gui.GetForegroundWindow()
   # we want the desktop window
   objid = pyAA.Constants.OBJID_WINDOW
   # get the object
   ao = pyAA.AccessibleObjectFromWindow(hwnd, objid)
   pr= ao.GetProcessAndThreadID()
   c=wmi.WMI()
   p=0
   for t in range(0,prs):
      Trmbl=True
      for process in c.Win32_Process():
         if pprocess[t]==process :trmbl=False
      if Trmbl==True:
         timec=time.strftime('%m/%d/%y %H:%M:%S')
         resac=str(timec)+'\t'+'process end'+'\t'+str(pprocess[t])+'\n'
         Twrite(resac)
   for process in c.Win32_Process():
      pprocess[p]=process
      if process.ProcessId in pr:
          processactif=process.Name
      prs=p
      p+=1
  #winmodame=win32api.GetModuleFileName(hwnd)
  #print winame#,winmodname
  #return True

def get_main_dir():
    try:
        sys.frozen
    except AttributeError:
        path = sys.argv[0]
    else:
        path = sys.executable
    return os.path.dirname(os.path.abspath(path))

oscurdir=get_main_dir()
jour=time.strftime('%d')
mois=time.strftime('%m')
annee=time.strftime('%Y')
pprocess={}
pr=0
def ifexist(rept):
    try:
        trylogfile = open(rept, mode ='r')
        trylogfile.close()
        return True
    except:
        return False
rep=oscurdir+os.sep+"LoGs"+os.sep+mois+annee+os.sep+jour+mois+annee
t=0
r=True
if os.access(oscurdir+os.sep+"LoGs"+os.sep+mois+annee,os.F_OK)==True:
    while r==True:
        t=t+1
        rept=str(rep)+str(t)+'.csv'
        r=ifexist(rept)
    r=True
    t=0
    while r==True:
        t=t+1
        crept=str(rep)+str(t)+'condensed.csv'
        r=ifexist(crept)
    #logfile = open(rept, mode ='a+')
    #clogfile = open(crept, mode ='a+')
             
else:
    os.mkdir(oscurdir+os.sep+"LoGs"+os.sep+mois+annee)
    while r==True:
        t=t+1
        rept=str(rep)+str(t)+'.csv'
        r=ifexist(rept)
    r=True
    t=0
    while r==True:
        t=t+1
        crept=str(rep)+str(t)+'condensed.csv'
        r=ifexist(crept)
    #logfile = open(rept, mode ='a+')
    #clogfile = open(crept, mode ='a+')
resac=""
#resac='moment'+'\t'+'application'+'\t'+'texte'+'\n'    
# create a hook manager
def minuteLoop():
  global nombrecliq,texte,computer,logType,verbose,winame,resac,logfile,do,watcher,start,pprocess,prs,processactif

  if start==True:
      hwnd = win32gui.GetForegroundWindow()
      # we want the desktop window
      objid = pyAA.Constants.OBJID_WINDOW
      # get the object
      ao = pyAA.AccessibleObjectFromWindow(hwnd, objid)
      pr= ao.GetProcessAndThreadID()
      c=wmi.WMI()
      p=0
      for t in range(0,prs):
         Trmbl=True
         for process in c.Win32_Process():
            if pprocess[t]==process.name :trmbl=False
         if Trmbl==True:
             try:
                timec=time.strftime('%m/%d/%y %H:%M:%S')
                resac=str(timec)+'\t'+'process end'+'\t'+str(pprocess[t])+'\n'
                Twrite(resac)
             except:
                pass
      for process in c.Win32_Process():
        pprocess[p]=process.name
        if process.ProcessId in pr:
            processactif=process.Name
        prs=p
        p+=1
      for process in c.Win32_Process():
          if process.ProcessId in pr:
              pname = process.Name
      timec=time.strftime('%m/%d/%y %H:%M:%S')
      #if (winame!=w.GetWindowText(hwnd) and winame!=''):
        #resac=str(timec)+'\t'+'minute maid'+'\t'+'cliques:'+str(nombrecliq)+'\t'+'keys:'+str(len(texte))+'\t'+str(winame)+'\n'
      resac=str(timec)+'\t'+'minute maid'+'\t'+'cliques:'+str(nombrecliq)+'\t'+str(ao.Name)+'\t'+str(pname)+'\n'
      Twrite(resac)
      Cwrite(resac)
      nombrecliq=0
      ReadLog(computer, logType, verbose > 0)
      #changes={}
      print 'loopminute'
  #if start==True:
      #time.sleep(58)
      #minuteLoop()
def userCreate():
  global i,root,UserButton,bvariable,d,dvariable
  def newUser():
    global i,root,UserButton,bvariable
    nam=namL.get()
    log=logL.get()
    if nam=="" or log=="":
      mes.set("ne laissez pas de champs vides")
      return
    try:
      chemFS= oscurdir + os.sep + "wok"+os.sep+"users.xml"
      ixim = open(chemFS,'r')

      xim = xml.dom.minidom.parse(ixim)

      ixim.close()

      racine=xim.documentElement
      element =xim.createElement("USER")
      element.setAttribute("NAM",nam)
      element.setAttribute("LOG",log)
      racine.appendChild(element)
      ixom = open(chemFS,'w')
      class TransPak:
          def write(self, data):
              ixom.write(data.encode("utf-8"))
      xim.writexml(TransPak(),encoding="utf-8")
      ixom.close()
      unlog()
      reinit()
    except:
      mes.set("erreur 4875, prevenez le service technique")
  def newDir():
    global i,root,UserButton,dvariable
    desktop_pidl = shell.SHGetFolderLocation (0, shellcon.CSIDL_DESKTOP, 0, 0)
    pidl, display_name, image_list = shell.SHBrowseForFolder (
      win32gui.GetDesktopWindow (),
      desktop_pidl,
      "Choissez un repertoire",
      0,
      None,
      None
    )
    if shell.SHGetPathFromIDList (pidl)=="":
      mes.set("aucun repertoire selectionne")
      return
    else:path=shell.SHGetPathFromIDList (pidl)
    try:
      chemFS= oscurdir + os.sep + "wok"+os.sep+"directory.xml"
      ixim = open(chemFS,'r')

      xim = xml.dom.minidom.parse(ixim)

      ixim.close()

      racine=xim.documentElement
      element =xim.createElement("DIR")
      element.setAttribute("PATH",path)
      racine.appendChild(element)
      ixom = open(chemFS,'w')
      class TransPak:
          def write(self, data):
              ixom.write(data.encode("utf-8"))
      xim.writexml(TransPak(),encoding="utf-8")
      ixom.close()
      dunlog()
      dreinit()      
##      UserButton[i]=Button(root,text=nam)
##      UserButton[i].grid(row=i,column=0)
      
    except:
        mes.set('erreur 12571 prevenir le service technique')
  def dirDelete():
    global dvariable
    #try:
    chemFS= oscurdir + os.sep + "wok"+os.sep+"directory.xml"
    ixim = open(chemFS,'r')
    xim = xml.dom.minidom.parse(ixim)
    ixim.close()
    racine=xim.documentElement
    unem = xim.getElementsByTagName('DIR')
    x=3
    for unam in unem:
        Dnam[x]=unam.getAttribute('PATH')
        hlog=Dnam[x]
        if hlog==dvariable[x].get():
          racine.removeChild(unam)
        x+=1

    ixom = open(chemFS,'w')
    class TransPak:
        def write(self, data):
            ixom.write(data.encode("utf-8"))
    xim.writexml(TransPak(),encoding="utf-8")
    ixom.close()
    dunlog()
    dreinit()
    #except:
      #mes.set("erreur 1485, prevenez le service technique")
  def dunlog():
    for x in range(3,d):
      nameD[x].grid_forget()
      chekD[x].grid_forget()      
  def dreinit():
    global d,dvariable
    d=3
    chemFS= oscurdir + os.sep + "wok"+os.sep+"directory.xml"
    ixim = open(chemFS,'r')
    xim = xml.dom.minidom.parse(ixim)
    ixim.close()
    unem = xim.getElementsByTagName('DIR')
    for unam in unem:
        Dnam[d]=unam.getAttribute('PATH')
        logstring=Dnam[d]
        dvariable[d]=StringVar(ucr_create)
        nameD[d]=Label(ucr_create,text=Dnam[d])
        nameD[d].grid(row=d,column=3)
        chekD[d]=Checkbutton(ucr_create,variable=dvariable[d],onvalue=logstring,offvalue="None")
        chekD[d].grid(row=d,column=4)
          #UserButton[i]=Button(root,text=nam)
          #UserButton[i].grid(row=i,column=0)
        d+=1
    #except:
     #   mes.set('erreur 112,4 prevenez leservice technique')
  def userDelete():
    global bvariable
    try:
      chemFS= oscurdir + os.sep + "wok"+os.sep+"users.xml"
      ixim = open(chemFS,'r')
      xim = xml.dom.minidom.parse(ixim)
      ixim.close()
      racine=xim.documentElement
      unem = xim.getElementsByTagName('USER')
      x=3
      for unam in unem:
          Cnam[x]=unam.getAttribute('NAM')
          Clog[x]=unam.getAttribute('LOG')
          hlog=Cnam[x]+Clog[x]
          if hlog==bvariable[x].get():
            racine.removeChild(unam)
          x+=1

      ixom = open(chemFS,'w')
      class TransPak:
          def write(self, data):
              ixom.write(data.encode("utf-8"))
      xim.writexml(TransPak(),encoding="utf-8")
      ixom.close()
      unlog()
      reinit()
    except:
      mes.set("erreur 1485, prevenez le service technique")
  def unlog():
    for x in range(3,i):
      nameL[x].grid_forget()
      ClogL[x].grid_forget()
      chekL[x].grid_forget()      
  def reinit():
    global i,bvariable
    i=3
    chemFS= oscurdir + os.sep + "wok"+os.sep+"users.xml"
    ixim = open(chemFS,'r')
    xim = xml.dom.minidom.parse(ixim)
    ixim.close()
    unem = xim.getElementsByTagName('USER')
    for unam in unem:
        Cnam[i]=unam.getAttribute('NAM')
        Clog[i]=unam.getAttribute('LOG')
        logstring=Cnam[i]+Clog[i]
        bvariable[i]=StringVar(ucr_create)
        nameL[i]=Label(ucr_create,text=Cnam[i])
        nameL[i].grid(row=i,column=0)
        ClogL[i]=Label(ucr_create,text=Clog[i])
        ClogL[i].grid(row=i,column=1)
        chekL[i]=Checkbutton(ucr_create,variable=bvariable[i],onvalue=logstring,offvalue="None")
        chekL[i].grid(row=i,column=2)
          #UserButton[i]=Button(root,text=nam)
          #UserButton[i].grid(row=i,column=0)
        i+=1
    #except:
     #   mes.set('erreur 112,4 prevenez leservice technique')
  ucr_create=Tk()
  ucr_create.title('Chronos Monitor')
  namL=Entry(ucr_create)
  logL=Entry(ucr_create)
  namLB=Label(ucr_create,text="nom")
  logLB=Label(ucr_create,text="login")
  Cnam={}
  Dnam={}
  Clog={}
  nameL={}
  nameD={}
  ClogL={}
  i=3
  d=3
  chekL={}
  chekD={}
  bvariable={}
  dvariable={}
  createB=Button(ucr_create,text="create",command=newUser)
  deleteB=Button(ucr_create,text="delete",command=userDelete)
  dirB=Button(ucr_create,text="create",command=newDir)
  ddirB=Button(ucr_create,text="delete",command=dirDelete)
  mes.set('')
  messageL=Label(ucr_create,textvariable=mes)
  namL.grid(row=0,column=1)
  logL.grid(row=1,column=1)
  namLB.grid(row=0,column=0)
  logLB.grid(row=1,column=0)
  createB.grid(row=2,column=1)
  deleteB.grid(row=2,column=0)
  dirB.grid(row=2,column=4)
  ddirB.grid(row=2,column=5)
  reinit()
  dreinit()
  ucr_create.mainloop()
def userLogin():
    global pi,nam,log,logfile,resac,computer,logType,verbose,hm,do,watcher,usernam,start
    #userlg=userlog.get()
    found=False
    winame=''
    timec=time.strftime('%m/%d/%y %H:%M:%S')
    for x in range(1,pi):
        usernam=nam[x]
        found=True
    if found==False:
        #mes.set('erreuridentifiant')
        return
    else:
        resac=str(timec)+'\t'+'user begin'+'\t'+str(usernam)+'\n'
        Twrite(resac)
        Cwrite(resac)
    if win32api.GetVersion() & 0x80000000:
        print "This sample only runs on NT"
        return
    start=True
    opts, args = getopt.getopt(sys.argv[1:], "rwh?c:t:v")
    computer = None
    do_read = do_write = 1

    logType = "Security"
    verbose = 0

    if len(args)>0:
        print "Invalid args"
        usage()
        return 1
    for opt, val in opts:
        if opt == '-t':
            logType = val
        if opt == '-c':
            computer = val
        if opt in ['-h', '-?']:
            usage()
            return
        if opt=='-r':
            do_read = 0
        if opt=='-w':
            do_write = 0
        if opt=='-v':
            verbose = verbose + 1
    ##    if do_write:
    ##        ph=win32api.GetCurrentProcess()
    ##        th = win32security.OpenProcessToken(ph,win32con.TOKEN_READ)
    ##        my_sid = win32security.GetTokenInformation(th,win32security.TokenUser)[0]
    ##
    ##        win32evtlogutil.ReportEvent(logType, 2,
    ##            strings=["The message text for event 2","Another insert"],
    ##            data = "Raw\0Data".encode("ascii"), sid = my_sid)
    ##        win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE,
    ##            strings=["A warning","An even more dire warning"],
    ##            data = "Raw\0Data".encode("ascii"), sid = my_sid)
    ##        win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE,
    ##            strings=["An info","Too much info"],
    ##            data = "Raw\0Data".encode("ascii"), sid = my_sid)
    ##        print("Successfully wrote 3 records to the log")

        #if do_read:

        
        #w=win32gui
    #mes.set('connecte')
    hm = pyHook.HookManager()
    # watch for all mouse events
    hm.MouseLeftDown = OnMouseEvent
    # set the hook
    hm.HookMouse()
    # create a hook manager
    #hm = pyHook.HookManager()
    # watch for all mouse events
    #hm.KeyDown = OnKeyboardEvent
    #hm.WM_ACTIVATE=OnWindowsEvent
    # set the hook
    #hm.HookKeyboard()
    # wait forever
    
    #print 'minute loop'
    

    # Thanks to Claudio Grondi for the correct set of numbers
    
    chemFS= oscurdir + os.sep + "wok"+os.sep+"directory.xml"
    ixim = open(chemFS,'r')
    xim = xml.dom.minidom.parse(ixim)
    ixim.close()
    unem = xim.getElementsByTagName('DIR')
    watcher={}
    do=0
    for unam in unem:
        Dpath=unam.getAttribute('PATH')
        watcher[do] = WatchDirectory(Dpath)
        do+=1
    starter=True
    while starter==True:
        minuteLoop()
        time.sleep(58)
    #pythoncom.PumpMessages()
    #hm.UnHookMouse()
def userExit():
  global usernam,resac,hm,logfile,start
  if start ==True:
      timec=time.strftime('%m/%d/%y %H:%M:%S')
      resac=str(timec)+'\t'+'user exit'+'\t'+str(usernam)+'\n'
      Twrite(resac)
      Cwrite(resac)
      #thm=pyHook.HookManager
      hm.UnhookMouse()
      #logfile.close()
      #mes.set('Deconnecte')
      start=False
##  else:
##      mes.set("vous n'etes pas connecte")
def synchronise():
   global rept,crept
##      chemFS= oscurdir + os.sep + "wok"+os.sep+"users.xml"
##      ixim = open(chemFS,'r')
##
##      xim = xml.dom.minidom.parse(ixim)
##
##      ixim.close()
##
##      racine=xim.documentElement
##      element =xim.createElement("USER")
##      element.setAttribute("NAM",nam)
##      element.setAttribute("LOG",log)
##      racine.appendChild(element)
##      ixom = open(chemFS,'w')
##      class TransPak:
##          def write(self, data):
##              ixom.write(data.encode("utf-8"))
##      xim.writexml(TransPak(),encoding="utf-8")
##      ixom.close()
##      unlog()
   rep=oscurdir+"LoGs"+ os.sep + date[3:4] + os.sep +date[0:1]+date[3:4]+os.sep+date[6:9]+'.csv'
   print rep
   result=curs.execute("select MAX (date) from lastlog where machine=machine and societe=societe" )
   result=curs.fetchone()
   print result
   conn = MySQLdb.connect('fldc315.serveursdns.net','qfz779','R0cheadmin69', 'qfz779')
   curs = conn.cursor()
   result=curs.execute("""
                       INSERT INTO logcondensed (userID, date, heure, nomfenetre, processus, chemin, client)
                       VALUES
                       ('snake', 'reptile'),
                       ('snake', 'reptile')
                       """ )

   ##result=curs.fetchone()
   ##print result
   ##result=curs.fetchall()
   ##print result
                                                                                                                                                                
   curs.close()
   conn.close() 
def Twrite(string):
   global rept
   logfile = open(rept, mode ='a+')
   def MTwrite(data):
      logfile.write(data)
   MTwrite(string)
   logfile.close()
def Cwrite(string):
   global crept
   clogfile = open(crept, mode ='a+')
   def cMTwrite(data):
      clogfile.write(data)
   cMTwrite(string)
   clogfile.close()
##   for log in [rept,crept]:
##      logfile = open(log, mode ='r')
##      lgac = os.stat(logfile).st_size
##      posac=0
##      while posac < lgac:
##         line = logfile.readline()
##         posac=logfile.tell()
         

##root=Tk()
##mes=StringVar()
##root.title('Chronos Monitor')
##UserCreateButton=Button(root,text="Configurer",command=userCreate)
##UserCreateButton.grid(row=1,column=0)
##userlog=Entry(root)
##userlog.grid(row=2,column=0)
##logbt=Button(root,text="login",command=userLogin)
##logbt.grid(row=3,column=0)
##unlogbt=Button(root,text="exit",command=userExit)
##unlogbt.grid(row=4,column=0)
##synclogbt=Button(root,text="synchronise",command=userExit)
##synclogbt.grid(row=6,column=0)
##messageLB=Label(root,textvariable=mes)
##messageLB.grid(row=0,column=0)
pi=1
prs=0
nam={}
log={}
win=''
processactif=""
try:
  chemFS= oscurdir + os.sep + "wok"+os.sep+"users.xml"
  ixim = open(chemFS,'r')
  xim = xml.dom.minidom.parse(ixim)
  ixim.close()
  unem = xim.getElementsByTagName('USER')
  for unam in unem:
      nam[pi]=unam.getAttribute('NAM')
      log[pi]=unam.getAttribute('LOG')
      #UserButton[i]=Button(root,text=nam)
      #UserButton[i].grid(row=i,column=0)
      pi+=1
except:
    pass
##    mes.set('erreur 112,4 prevenez leservice technique')
userLogin()    
##root.mainloop()


