hoppfrosch
1/27/2014 - 10:39 AM

URIEncode / URIDecode #ahk #function

URIEncode / URIDecode #ahk #function

; By Jackieku - http://www.autohotkey.com/board/topic/35660-url-encoding-function/
; JavaScript encodeURI()
URI_Encode(sURI, sExcepts = "!#$&'()*+,-./:;=?@_~")
{
	Transform sUTF8, ToCodePage, 65001, %sURI%
	origFmt := A_FormatInteger
	SetFormat IntegerFast, hex

	sResult := ""
	Loop
	{
		if (!(b := NumGet(sUTF8, A_Index - 1, "UChar")))
			break
		ch := Chr(b)
		; "is alnum" is not used because it is locale dependent.
		if (b >= 0x41 && b <= 0x5A ; A-Z
			|| b >= 0x61 && b <= 0x7A ; a-z
			|| b >= 0x30 && b <= 0x39 ; 0-9
			|| InStr(sExcepts, Chr(b), true))
			sResult .= Chr(b)
		else
		{
			ch := SubStr(b, 3)
			if (StrLen(ch) < 2)
				ch = "0" ch
			sResult .= "%" ch
		}
	}
	SetFormat IntegerFast, %origFmt%
	return sResult
}

; JavaScript encodeURIComponent()
URI_EncodeComponent(sURI, sExcepts = "!'()*-._~")
{
	return URI_Encode(sURI, sExcepts)
}

; Decode precent encoding
URI_Decode(sURI)
{
	Transform sUTF8, ToCodePage, 65001, %sURI%
	; #define URL_UNESCAPE_INPLACE 0x00100000
	; NOTE: UrlUnescapeW() doesn't work as expected.
	DllCall("shlwapi\UrlUnescapeA", "UIntPtr", &sUTF8, "UIntPtr", 0, "UIntPtr", 0, "UInt", 0x00100000)
	Transform sURI, FromCodePage, 65001, %sUTF8%
	return sURI
}