'''''''''''''''''''''''''''
'' vbscript_cgi.vbs      ''
'' Kevin DEHLINGER       ''
'' 2007 / dev.pulsed.net ''
'''''''''''''''''''''''''''

Set arguments = WScript.Arguments
If arguments.Count >=1 Then
Set FSO = CreateObject("Scripting.FileSystemObject")
	If FSO.FileExists(arguments(0)) Then
		Set cgi = FSO.OpenTextFile(arguments(0))
		cgi.ReadLine
		ExecuteGlobal cgi.ReadAll
		cgi.Close
	End If
	Set FSO = Nothing
End If
Set arguments = Nothing


sub print(v)
wscript.echo v
end sub

sub println(v)
wscript.echo v & vbcrlf
end sub


Function GetCgiVars

Set Shell = CreateObject( "WScript.Shell" )
reqmethod=Ucase( Shell.ExpandEnvironmentStrings("%REQUEST_METHOD%"))


Select Case reqmethod

Case "GET","HEAD" 
cgiinput=Shell.ExpandEnvironmentStrings("%QUERY_STRING%")& ""

Case "POST"
  
  content_length=Shell.ExpandEnvironmentStrings("%CONTENT_LENGTH%")
  
  If not IsNumeric(content_length) then
   print "Content-Type: text/plain" & vbcrlf
   print "No Content-Length was sent with the POST request" & vbcrlf
   Exit Function
  End If
  
cgiinput= WScript.StdIn.ReadAll


Case Else
   print "Content-Type: text/plain" & vbcrlf
   print "Unsupported REQUEST_METHOD (" & reqmethod & ")" & vbcrlf
   Exit Function

End Select

cgiinput=Replace(cgiinput,"+"," ")
cgiinput=Replace(cgiinput,"&",";")
cgiinput=Replace(cgiinput,"=","=;")

InputArray=Split(cgiinput,";")
Set CgiVars = CreateObject("Scripting.Dictionary")


status=0
Hash_Key=""

For Each value in InputArray
      If(Mid(value,Len(value),1)="=") Then
            Hash_Key=Mid(value,1,Len(value)-1)
      Else
            CgiVars.Add Unescape_Url(Hash_Key),Unescape_Url(value)
      End If
Next

Set GetCgiVars=CgiVars
End Function


Function Unescape_Url (url)
Set RegExp1 = New RegExp
RegExp1.IgnoreCase = True
RegExp1.Global = True
RegExp1.Pattern = "%([0-9A-F]{2})"


Set Matches = RegExp1.Execute(url)
For Each Match in Matches
url = Replace(url,"%" & Match,Hex2Char(Match)) 
Next
Unescape_Url=url
End Function

Function Hex2Char (hexx)
Hex2Char = Chr(1*CLng("&H" & hexx))
End Function

