webmcp

view framework/cgi-bin/webmcp.lua @ 196:ce8fd7767b38

Fix in inline documentation of atom.integer.invalid
author jbe
date Mon Aug 11 21:29:46 2014 +0200 (2014-08-11)
parents 8d7665e0d490
children
line source
1 #!/usr/bin/env lua
3 _WEBMCP_VERSION = "1.2.6"
5 -- Lua 5.1 compatibility
6 if not table.unpack then
7 table.unpack = unpack
8 end
9 do
10 local old_load = load
11 function load(ld, ...)
12 if type(ld) == "string" then
13 local done = false
14 local func = function()
15 if not done then
16 done = true
17 return ld
18 end
19 end
20 return old_load(func, ...)
21 else
22 return old_load(ld, ...)
23 end
24 end
25 end
27 -- include "../lib/" in search path for libraries
28 if not WEBMCP_PATH then
29 WEBMCP_PATH = "../"
30 end
31 do
32 package.path = WEBMCP_PATH .. 'lib/?.lua;' .. package.path
33 -- find out which file name extension shared libraries have
34 local slib_exts = {}
35 for ext in string.gmatch(package.cpath, "%?%.([A-Za-z0-9_-]+)") do
36 slib_exts[ext] = true
37 end
38 local paths = {}
39 for ext in pairs(slib_exts) do
40 paths[#paths+1] = WEBMCP_PATH .. "accelerator/?." .. ext
41 end
42 for ext in pairs(slib_exts) do
43 paths[#paths+1] = WEBMCP_PATH .. "lib/?." .. ext
44 end
45 paths[#paths+1] = package.cpath
46 package.cpath = table.concat(paths, ";")
47 end
49 -- load os extensions for lua
50 -- (should happen as soon as possible due to run time measurement)
51 extos = require 'extos'
53 -- load nihil library
54 nihil = require 'nihil'
56 -- load random generator library
57 multirand = require 'multirand'
59 -- load rocketcgi library and map it to cgi, unless interactive
60 do
61 local option = os.getenv("WEBMCP_INTERACTIVE")
62 if option and option ~= "" and option ~= "0" then
63 cgi = nil
64 else
65 rocketcgi = require 'rocketcgi' -- TODO: no "rocketcgi" alias
66 cgi = rocketcgi
67 end
68 end
70 -- load database access library with object relational mapper
71 mondelefant = require 'mondelefant'
72 mondelefant.connection_prototype.error_objects = true
74 -- load type system "atom"
75 atom = require 'atom'
77 -- load JSON library
78 json = require 'json'
80 -- load mondelefant atom connector
81 require 'mondelefant_atom_connector'
83 --[[--
84 cloned_table = -- newly generated table
85 table.new(
86 table_or_nil -- keys of a given table will be copied to the new table
87 )
89 If a table is given, then a cloned table is returned.
90 If nil is given, then a new empty table is returned.
92 --]]--
93 function table.new(tbl)
94 new_tbl = {}
95 if tbl then
96 for key, value in pairs(tbl) do
97 new_tbl[key] = value
98 end
99 end
100 return new_tbl
101 end
102 --//--
104 --[[--
105 at_exit(
106 func -- function to be called before the process is ending
107 )
109 Registers a function to be called before the CGI process is exiting.
110 --]]--
111 do
112 local exit_handlers = {}
113 function at_exit(func)
114 table.insert(exit_handlers, func)
115 end
116 function exit(code)
117 for i = #exit_handlers, 1, -1 do
118 exit_handlers[i]()
119 end
120 os.exit(code)
121 end
122 end
123 --//--
125 --[[--
126 app -- table to store an application state
128 'app' is a global table for storing any application state data
129 --]]--
130 app = {}
131 --//--
133 --[[--
134 config -- table to store application configuration
136 'config' is a global table, which can be modified by a config file of an application to modify the behaviour of that application.
137 --]]--
138 config = {}
139 --//--
141 -- autoloader system for WebMCP environment "../env/",
142 -- application environment extensions "$WEBMCP_APP_BASE/env/"
143 -- and models "$WEBMCP_APP_BASE/model/"
144 do
145 local app_base = os.getenv("WEBMCP_APP_BASEPATH")
146 if not app_base then
147 error(
148 "Failed to initialize autoloader " ..
149 "due to unset WEBMCP_APP_BASEPATH environment variable."
150 )
151 end
152 local weakkey_mt = { __mode = "k" }
153 local autoloader_category = setmetatable({}, weakkey_mt)
154 local autoloader_path = setmetatable({}, weakkey_mt)
155 local autoloader_mt = {}
156 local function install_autoloader(self, category, path)
157 autoloader_category[self] = category
158 autoloader_path[self] = path
159 setmetatable(self, autoloader_mt)
160 end
161 local function try_exec(filename)
162 local file = io.open(filename, "r")
163 if file then
164 local filedata = file:read("*a")
165 io.close(file)
166 local func, errmsg = load(filedata, "=" .. filename)
167 if func then
168 func()
169 return true
170 else
171 error(errmsg, 0)
172 end
173 else
174 return false
175 end
176 end
177 local function compose_path_string(base, path, key)
178 return string.gsub(
179 base .. table.concat(path, "/") .. "/" .. key, "/+", "/"
180 )
181 end
182 function autoloader_mt.__index(self, key)
183 local category, base_path, merge_base_path, file_key
184 local merge = false
185 if
186 string.find(key, "^[a-z_][A-Za-z0-9_]*$") and
187 not string.find(key, "^__")
188 then
189 category = "env"
190 base_path = WEBMCP_PATH .. "/env/"
191 merge = true
192 merge_base_path = app_base .. "/env/"
193 file_key = key
194 elseif string.find(key, "^[A-Z][A-Za-z0-9]*$") then
195 category = "model"
196 base_path = app_base .. "/model/"
197 local first = true
198 file_key = string.gsub(key, "[A-Z]",
199 function(c)
200 if first then
201 first = false
202 return string.lower(c)
203 else
204 return "_" .. string.lower(c)
205 end
206 end
207 )
208 else
209 return
210 end
211 local required_category = autoloader_category[self]
212 if required_category and required_category ~= category then return end
213 local path = autoloader_path[self]
214 local path_string = compose_path_string(base_path, path, file_key)
215 local merge_path_string
216 if merge then
217 merge_path_string = compose_path_string(
218 merge_base_path, path, file_key
219 )
220 end
221 local function try_dir(dirname)
222 local dir = io.open(dirname)
223 if dir then
224 io.close(dir)
225 local obj = {}
226 local sub_path = {}
227 for i, v in ipairs(path) do sub_path[i] = v end
228 table.insert(sub_path, file_key)
229 install_autoloader(obj, category, sub_path)
230 rawset(self, key, obj)
231 try_exec(path_string .. "/__init.lua")
232 if merge then try_exec(merge_path_string .. "/__init.lua") end
233 return true
234 else
235 return false
236 end
237 end
238 if merge and try_exec(merge_path_string .. ".lua") then
239 elseif merge and try_dir(merge_path_string .. "/") then
240 elseif try_exec(path_string .. ".lua") then
241 elseif try_dir(path_string .. "/") then
242 else end
243 return rawget(self, key)
244 end
245 install_autoloader(_G, nil, {})
246 try_exec(WEBMCP_PATH .. "env/__init.lua")
247 end
249 -- interactive console mode
250 if not cgi then
251 trace.disable() -- avoids memory leakage
252 local config_name = request.get_config_name()
253 if config_name then
254 execute.config(config_name)
255 end
256 return
257 end
259 local success, error_info = xpcall(
260 function()
262 -- execute configuration file
263 do
264 local config_name = request.get_config_name()
265 if config_name then
266 execute.config(config_name)
267 end
268 end
270 -- restore slots if coming from http redirect
271 if cgi.params.tempstore then
272 trace.restore_slots{}
273 local blob = tempstore.pop(cgi.params.tempstore)
274 if blob then slot.restore_all(blob) end
275 end
277 local function file_exists(filename)
278 local file = io.open(filename, "r")
279 if file then
280 io.close(file)
281 return true
282 else
283 return false
284 end
285 end
287 if request.is_404() then
288 request.set_status("404 Not Found")
289 if request.get_404_route() then
290 request.forward(request.get_404_route())
291 else
292 error("No 404 page set.")
293 end
294 elseif request.get_action() then
295 trace.request{
296 module = request.get_module(),
297 action = request.get_action()
298 }
299 if
300 request.get_404_route() and
301 not file_exists(
302 encode.action_file_path{
303 module = request.get_module(),
304 action = request.get_action()
305 }
306 )
307 then
308 request.set_status("404 Not Found")
309 request.forward(request.get_404_route())
310 else
311 if cgi.method ~= "POST" then
312 request.set_status("405 Method Not Allowed")
313 cgi.add_header("Allow: POST")
314 error("Tried to invoke an action with a GET request.")
315 end
316 local action_status = execute.filtered_action{
317 module = request.get_module(),
318 action = request.get_action(),
319 }
320 if not request.is_rerouted() then
321 local routing_mode, routing_module, routing_view
322 routing_mode = cgi.params["_webmcp_routing." .. action_status .. ".mode"]
323 routing_module = cgi.params["_webmcp_routing." .. action_status .. ".module"]
324 routing_view = cgi.params["_webmcp_routing." .. action_status .. ".view"]
325 routing_anchor = cgi.params["_webmcp_routing." .. action_status .. ".anchor"]
326 if not (routing_mode or routing_module or routing_view) then
327 action_status = "default"
328 routing_mode = cgi.params["_webmcp_routing.default.mode"]
329 routing_module = cgi.params["_webmcp_routing.default.module"]
330 routing_view = cgi.params["_webmcp_routing.default.view"]
331 routing_anchor = cgi.params["_webmcp_routing.default.anchor"]
332 end
333 assert(routing_module, "Routing information has no module.")
334 assert(routing_view, "Routing information has no view.")
335 if routing_mode == "redirect" then
336 local routing_params = {}
337 for key, value in pairs(cgi.params) do
338 local status, stripped_key = string.match(
339 key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
340 )
341 if status == action_status then
342 routing_params[stripped_key] = value
343 end
344 end
345 request.redirect{
346 module = routing_module,
347 view = routing_view,
348 id = cgi.params["_webmcp_routing." .. action_status .. ".id"],
349 params = routing_params,
350 anchor = routing_anchor
351 }
352 elseif routing_mode == "forward" then
353 request.forward{ module = routing_module, view = routing_view }
354 else
355 error("Missing or unknown routing mode in request parameters.")
356 end
357 end
358 end
359 else
360 -- no action
361 trace.request{
362 module = request.get_module(),
363 view = request.get_view()
364 }
365 if
366 request.get_404_route() and
367 not file_exists(
368 encode.view_file_path{
369 module = request.get_module(),
370 view = request.get_view()
371 }
372 )
373 then
374 request.set_status("404 Not Found")
375 request.forward(request.get_404_route())
376 end
377 end
379 if not request.get_redirect_data() then
380 request.process_forward()
381 local view = request.get_view()
382 if string.find(view, "^_") then
383 error("Tried to call a private view (prefixed with underscore).")
384 end
385 execute.filtered_view{
386 module = request.get_module(),
387 view = view,
388 }
389 end
391 -- force error due to missing absolute base URL until its too late to display error message
392 --if request.get_redirect_data() then
393 -- request.get_absolute_baseurl()
394 --end
396 end,
398 function(errobj)
399 return {
400 errobj = errobj,
401 stacktrace = string.gsub(
402 debug.traceback('', 2),
403 "^\r?\n?stack traceback:\r?\n?", ""
404 )
405 }
406 end
407 )
409 if not success then trace.error{} end
411 -- laufzeitermittlung
412 trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
414 slot.select('trace', trace.render) -- render trace information
416 local redirect_data = request.get_redirect_data()
418 -- log error and switch to error layout, unless success
419 if not success then
420 local errobj = error_info.errobj
421 local stacktrace = error_info.stacktrace
422 if not request.get_status() and not request.get_json_request_slots() then
423 request.set_status("500 Internal Server Error")
424 end
425 slot.set_layout('system_error')
426 slot.select('system_error', function()
427 if getmetatable(errobj) == mondelefant.errorobject_metatable then
428 slot.put(
429 "<p>Database error of class <b>",
430 encode.html(errobj.code),
431 "</b> occured:<br/><b>",
432 encode.html(errobj.message),
433 "</b></p>"
434 )
435 else
436 slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
437 end
438 slot.put("<p>Stack trace follows:<br/>")
439 slot.put(encode.html_newlines(encode.html(stacktrace)))
440 slot.put("</p>")
441 end)
442 elseif redirect_data then
443 local redirect_params = {}
444 for key, value in pairs(redirect_data.params) do
445 redirect_params[key] = value
446 end
447 local slot_dump = slot.dump_all()
448 if slot_dump ~= "" then
449 redirect_params.tempstore = tempstore.save(slot_dump)
450 end
451 local json_request_slots = request.get_json_request_slots()
452 if json_request_slots then
453 redirect_params["_webmcp_json_slots[]"] = json_request_slots
454 end
455 cgi.redirect(
456 encode.url{
457 base = request.get_absolute_baseurl(),
458 module = redirect_data.module,
459 view = redirect_data.view,
460 id = redirect_data.id,
461 params = redirect_params,
462 anchor = redirect_data.anchor
463 }
464 )
465 cgi.send_data()
466 end
468 if not success or not redirect_data then
470 local http_status = request.get_status()
471 if http_status then
472 cgi.set_status(http_status)
473 end
475 local json_request_slots = request.get_json_request_slots()
476 if json_request_slots then
477 cgi.set_content_type('application/json')
478 local data = {}
479 for idx, slot_ident in ipairs(json_request_slots) do
480 data[slot_ident] = slot.get_content(slot_ident)
481 end
482 cgi.send_data(encode.json(data))
483 else
484 cgi.set_content_type(slot.get_content_type())
485 cgi.send_data(slot.render_layout())
486 end
487 end
489 exit()

Impressum / About Us