'----------------------------------------------------------------------
' QuickLoggerPlus v2006091202
' Appends the date and a line of text to a file. Who knew it could get this complicated?
' Based on QuickLogger:
' 	Credits from original QuickLogger:
' 		Based on code written by Joshua Fitzgerald, 7/2005.
' 		Modified by Gina Trapani, 7/2006.
'	http://lifehacker.com/software/capture-tools/geek-to-live-quicklog-your-work-day-189772.php
'----------------------------------------------------------------------
' LICENSE
' No license was specified for the original lifehacker release. Because of this, I (Kirk Friggstad)
' am unable to specify a particular license for my changes to the original script. If the license
' for the original release is an OSI-certified license (GPL, MPL, MIT, Artistic, etc.), then my
' changes will be under the same license. Until the license for the original is determined, please
' do not redistribute my changes without the permission of the copyright holder(s) of the original
' release. Please keep these comments in any redistribution, unless a requirement to do so
' conflicts with the license used for the original release. I am not a lawyer, this so-called
' "license" section will probably not hold up in court, but I'm trying to do the right thing. Work
' with me here, people.
' UPDATE 2006-07-28
' Gina Trapani has informed me that she does not have contact information for Joshua Fitzgerald.
' I'm releasing my changes to the public domain. If you make changes, I'd appreciate a copy
' back, but it's not required.
'----------------------------------------------------------------------
' CHANGELOG:
' 2006-09-12 - Kirk Friggstad (friggstadk@gmail.com)
'       added entryTemplate configuration variable
'       added expansion of environment strings in file paths i.e. %HOMEPATH% etc.
'       removed useISOtimestamp configuration variable (deprecated by entryTemplate functions)
'       removed rotatefiles configuration variable (now just controlled by rotationPeriod)
'       added username/domain information to logging
'       added duration to logging
' 2006-07-28 - Kirk Friggstad (friggstadk@gmail.com)
'	updated license information (contact info for JF)
'	first public release (please be kind!) - posted to comments on Lifehacker
' 2006-07-27 - Kirk Friggstad (friggstadk@gmail.com)
'	added CurrentTimestamp global variable
'	fixed bug (adding blank line to log when Cancel pressed or nothing entered)
'	added License section to documentation
'	added file rotation periods (daily, weekly, monthly, quarterly, yearly)
'	added automatic creation of non-existent directories
' 2006-07-26 - Kirk Friggstad - (friggstadk@gmail.com)
'	added ISO timestamp option
'	added file rotation option
'	added shortcut to current log file option
'	added comments / documentation
'	changed simple little 23-line script to semi-bloated 100+ line monster
'----------------------------------------------------------------------
' TODO:
'	high priority
'               feature: header string (i.e. CSV column headers, etc.)
'	medium priority
'               feature: move configuration information to INI file?
'		feature: logging to online service (XMLRPC? AJAX? OMGWTFLOLBBQ?)
'	low priority
'		feature: configure more options for shortcut (custom icon,
'			preferred text viewer, hotkey, etc.)
'               feature: create installation script?
'               feature: rewrite as a .NET application using C# (as a learning exercise)?
'----------------------------------------------------------------------
Option Explicit

'	set the following variables to fit your preferences and installation:
Dim logFilePath, filename, useISOtimestamp, useShortcut, shortcutPath, _
        shortcutDescription, rotationPeriod, firstdayofweek, entryTemplate

'               logFilePath: String - path to log file
'                       can include environment strings i.e. %HOMEPATH%
'                       see http://www.wilsonmar.com/1envvars.htm for more info
'                       extension (i.e. ".txt") required
logFilePath = "%HOMEPATH%\My Documents\Worklog\worklog.txt"

'		rotationPeriod: Character - time period for rotating files
'			valid values are "D", "W", "M", "Q", or "Y"
'			if NULL, no rotation is done
rotationPeriod = "W"
'		firstDayOfWeek: Integer - what day is first day of the week
'			1 = Sunday, 2 = Monday, etc.
firstdayofweek = 1

'		useShortcut: Boolean - maintain a shortcut to current file
'			(useful in conjunction with rotatefiles=True)
useShortcut = False
'		shortcutPath: String - full path to shortcut (.lnk) file 
shortcutPath = "%HOMEPATH%\My Documents\My Toolbars\Quick Access\Work Log.lnk"
'		shortcutDescription: String - description of shortcut (shows on hover, etc.)
shortcutDescription = "Current QuickLoggerPlus log file"

'               entryTemplate: String - template for log entry
'                       tokens are CASE-SENSITIVE
'                       valid tokens include:
'                               [[ISO_DATE]]:    ISO formatted datestamp
'                               [[LOCAL_DATE]]:  local format datestamp
'                               [[ISO_TIME]]:    24-hour timestamp
'                               [[LOCAL_TIME]]:  local format timestamp
'                               [[USER_DOMAIN]]: Windows domain of logged in user
'                               [[USER_NAME]]:   name of logged in user
'                               [[ENTRY]]:       text entered by user
'                       examples: 
'                               "[[LOCAL_DATE]] [[LOCAL_TIME]] [[ENTRY]]"
'                               "[[ISO_DATE]]" & VbTab & "[[ISO_TIME]]" & VbTab & "[[ENTRY]]"
entryTemplate = "[[ISO_DATE]]" & VbTab & "[[ISO_TIME]]" & VbTab & "[[USER_DOMAIN]]\[[USER_NAME]]" & VbTab & "[[DURATION_MINUTES]]" & VbTab & "[[ENTRY]]"

'----------------------------------------------------------------------
' NO USER CONFIGURABLE VARIABLES BELOW THIS LINE
' ABANDON HOPE ALL YE WHO ENTER HERE
'----------------------------------------------------------------------
dim CurrentTimestamp
CurrentTimestamp = Now()
dim objWSH, objNet
set objWSH = CreateObject("WScript.Shell")
set objNet = CreateObject("WScript.Network")

filename = objWSH.ExpandEnvironmentStrings(logFilePath)
if len(rotationPeriod) > 0 then
	Dim dateforfilename, dateoffset
	select case rotationPeriod
		case "Y":
			dateoffset = DatePart("y", CurrentTimestamp) - 1
		case "Q":
			dateoffset = DateDiff("d", DateSerial(year(CurrentTimestamp), 1 + 3*(DatePart("q", CurrentTimestamp)-1), 1), CurrentTimestamp)
		case "M":
			dateoffset = Day(CurrentTimestamp) - 1
		case "W":
			dateoffset = Weekday(CurrentTimestamp, firstdayofweek) -1
		case "D":
			dateoffset = 0
	end select
	dateforfilename = DateAdd("d", (dateoffset * -1), CurrentTimestamp)
	filename = left(filename, InStrRev(filename, ".")) _
          & getISODate(dateforfilename) _
          & right(filename, len(filename)-InStrRev(filename, ".")+1)
end if

Dim text
text = InputBox("Add to " & filename & ":", "Quick Logger Plus")
if len(text) > 0 then
	WriteToFile(text)
	if useShortcut then UpdateShortcut
end if

Sub WriteToFile(text)
  Dim fso
  Dim textFile
  Set fso = CreateObject("Scripting.FileSystemObject")
  ' check for existence of directories
  dim arrFolderPath, myIndex, myFilepath
  filename = replace(filename, "/", "\")
  arrFolderPath = split(filename, "\")
  myFilePath = arrFolderPath(0)
  for myIndex = 1 to UBound(arrFolderPath) - 1
	if len(arrFolderPath(myIndex)) > 0 then
		myFilePath = myFilePath + "\" + arrFolderPath(myIndex)
		if not fso.FolderExists(myFilePath) then fso.CreateFolder myFilePath
	end if
  next
  dim validTokens, currentToken, newValue
  validTokens = Array("[[ISO_DATE]]", "[[ISO_TIME]]", "[[LOCAL_DATE]]", "[[LOCAL_TIME]]", "[[USER_NAME]]", "[[USER_DOMAIN]]", "[[DURATION_MINUTES]]", "[[ENTRY]]")
  for each currentToken in validTokens
    if InStr(entryTemplate, currentToken) > 0 then
      select case currentToken
        case "[[ISO_DATE]]":
          newValue = getISOdate(CurrentTimestamp)
        case "[[ISO_TIME]]":
          newValue = getISOtime(CurrentTimestamp)
        case "[[LOCAL_DATE]]":
          newValue = FormatDateTime(CurrentTimestamp, 2)        ' vbShortDate
        case "[[LOCAL_TIME]]":
          newValue = FormatDateTime(CurrentTimestamp, 3)        ' vbLongTime
        case "[[USER_DOMAIN]]":
          newValue = objNet.UserDomain
        case "[[USER_NAME]]":
          newValue = objNet.UserName
        case "[[DURATION_MINUTES]]":
          if fso.FileExists(filename) then
            dim objFile
            set objFile = fso.GetFile(filename)
            newValue = DateDiff("n", objFile.DateLastModified, CurrentTimestamp)
          else
            newValue = "n/a"
          end if
        case "[[ENTRY]]":
          newValue = text
      end select
      entryTemplate = Replace(entryTemplate, currentToken, newValue)
    end if
  next
  Set textFile = fso.OpenTextFile(filename, 8, True)
  textFile.WriteLine entryTemplate
  textFile.Close
End Sub

Function getISOdate(byVal myCurrentTimestamp)
	Dim myISOdate
	myISOdate = CStr(Year(myCurrentTimestamp))
	if Month(myCurrentTimestamp) < 10 then
		myISOdate = myISOdate & "-0" & Month(myCurrentTimestamp)
	else
		myISOdate = myISOdate & "-" & Month(myCurrentTimestamp)
	end if
	if Day(myCurrentTimestamp) < 10 then
		myISOdate = myISOdate & "-0" & Day(myCurrentTimestamp)
	else
		myISOdate = myISOdate & "-" & Day(myCurrentTimestamp)
	end if
	getISOdate = myISOdate
End Function

Function getISOtime(byVal myCurrentTimestamp)
	Dim myISOtime
	if Hour(CurrentTimestamp) < 10 then
		myISOtime = "0" & Hour(CurrentTimestamp)
	else
		myISOtime = Hour(CurrentTimestamp)
	end if
	if Minute(CurrentTimestamp) < 10 then
		myISOtime = myISOtime & ":0" & Minute(CurrentTimestamp)
	else
		myISOtime = myISOtime & ":" & Minute(CurrentTimestamp)
	end if
	if Second(CurrentTimestamp) < 10 then
		myISOtime = myISOtime & ":0" & Second(CurrentTimestamp)
	else
		myISOtime = myISOtime & ":" & Second(CurrentTimestamp)
	end if
	getISOtime = myISOtime
End Function

Sub UpdateShortcut
	Dim myShortcut
        shortcutPath = objWSH.ExpandEnvironmentStrings(shortcutPath)
	set myShortcut = objWSH.CreateShortcut(shortcutPath)
	myShortcut.TargetPath = objWSH.ExpandEnvironmentStrings(filename)
	myShortcut.Description = shortcutDescription
	myShortcut.Save
End Sub
'----------------------------------------------------------------------
' This is the end. Nothing else to see.
'----------------------------------------------------------------------












'----------------------------------------------------------------------
' No, really, nothing else to see. Stop already.
'----------------------------------------------------------------------