44d1a925c42d2963f8dba2319bb741640f8b7fc3
[project/luci.git] / core / src / ffluci / http.lua
1 --[[
2 FFLuCI - HTTP-Interaction
3
4 Description:
5 HTTP-Header manipulator and form variable preprocessor
6
7 FileId:
8 $Id$
9
10 ToDo:
11 - Cookie handling
12
13 License:
14 Copyright 2008 Steven Barth <steven@midlink.org>
15
16 Licensed under the Apache License, Version 2.0 (the "License");
17 you may not use this file except in compliance with the License.
18 You may obtain a copy of the License at 
19
20         http://www.apache.org/licenses/LICENSE-2.0 
21
22 Unless required by applicable law or agreed to in writing, software
23 distributed under the License is distributed on an "AS IS" BASIS,
24 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25 See the License for the specific language governing permissions and
26 limitations under the License.
27
28 ]]--
29
30 module("ffluci.http", package.seeall)
31
32 require("ffluci.util")
33
34 -- Sets HTTP-Status-Header
35 function status(code, message)
36         print("Status: " .. tostring(code) .. " " .. message)
37 end
38
39
40 -- Asks the browser to redirect to "url"
41 function redirect(url, qs)
42         if qs then
43                 url = url .. "?" .. qs
44         end
45         
46         status(302, "Found")
47         print("Location: " .. url .. "\n")
48 end
49
50
51 -- Same as redirect but accepts category, module and action for internal use
52 function request_redirect(category, module, action, ...)
53         category = category or "public"
54         module   = module   or "index"
55         action   = action   or "index"
56         
57         local pattern = script_name() .. "/%s/%s/%s"
58         redirect(pattern:format(category, module, action), ...)
59 end
60
61
62 -- Returns the User's IP
63 function remote_addr()
64         return ENV.REMOTE_ADDR
65 end
66
67
68 -- Returns the script name
69 function script_name()
70         return ENV.SCRIPT_NAME
71 end
72
73
74 -- Gets form value from key
75 function formvalue(key, default)
76         local c = formvalues()
77         
78         for match in key:gmatch("[%w-_]+") do
79                 c = c[match]
80                 if c == nil then
81                         return default
82                 end
83         end
84         
85         return c
86 end
87
88
89 -- Returns a table of all COOKIE, GET and POST Parameters
90 function formvalues()
91         return FORM
92 end
93
94
95 -- Prints plaintext content-type header
96 function textheader()
97         print("Content-Type: text/plain\n")
98 end
99
100
101 -- Prints html content-type header
102 function htmlheader()
103         print("Content-Type: text/html\n")
104 end
105
106
107 -- Prints xml content-type header
108 function xmlheader()
109         print("Content-Type: text/xml\n")
110 end