|
1 -- Prosody IM |
|
2 -- Copyright (C) 2013 Florian Zeitz |
|
3 -- |
|
4 -- This project is MIT/X11 licensed. Please see the |
|
5 -- COPYING file in the source package for more information. |
|
6 -- |
|
7 |
|
8 local format, char = string.format, string.char; |
|
9 local pairs, ipairs, tonumber = pairs, ipairs, tonumber; |
|
10 local t_insert, t_concat = table.insert, table.concat; |
|
11 |
|
12 local function urlencode(s) |
|
13 return s and (s:gsub("[^a-zA-Z0-9.~_-]", function (c) return format("%%%02x", c:byte()); end)); |
|
14 end |
|
15 local function urldecode(s) |
|
16 return s and (s:gsub("%%(%x%x)", function (c) return char(tonumber(c,16)); end)); |
|
17 end |
|
18 |
|
19 local function _formencodepart(s) |
|
20 return s and (s:gsub("%W", function (c) |
|
21 if c ~= " " then |
|
22 return format("%%%02x", c:byte()); |
|
23 else |
|
24 return "+"; |
|
25 end |
|
26 end)); |
|
27 end |
|
28 |
|
29 local function formencode(form) |
|
30 local result = {}; |
|
31 if form[1] then -- Array of ordered { name, value } |
|
32 for _, field in ipairs(form) do |
|
33 t_insert(result, _formencodepart(field.name).."=".._formencodepart(field.value)); |
|
34 end |
|
35 else -- Unordered map of name -> value |
|
36 for name, value in pairs(form) do |
|
37 t_insert(result, _formencodepart(name).."=".._formencodepart(value)); |
|
38 end |
|
39 end |
|
40 return t_concat(result, "&"); |
|
41 end |
|
42 |
|
43 local function formdecode(s) |
|
44 if not s:match("=") then return urldecode(s); end |
|
45 local r = {}; |
|
46 for k, v in s:gmatch("([^=&]*)=([^&]*)") do |
|
47 k, v = k:gsub("%+", "%%20"), v:gsub("%+", "%%20"); |
|
48 k, v = urldecode(k), urldecode(v); |
|
49 t_insert(r, { name = k, value = v }); |
|
50 r[k] = v; |
|
51 end |
|
52 return r; |
|
53 end |
|
54 |
|
55 local function contains_token(field, token) |
|
56 field = ","..field:gsub("[ \t]", ""):lower()..","; |
|
57 return field:find(","..token:lower()..",", 1, true) ~= nil; |
|
58 end |
|
59 |
|
60 return { |
|
61 urlencode = urlencode, urldecode = urldecode; |
|
62 formencode = formencode, formdecode = formdecode; |
|
63 contains_token = contains_token; |
|
64 }; |