webmcp
view framework/cgi-bin/webmcp.lua @ 78:bff7194ea72c
Added tag v1.2.2 for changeset 727a10edeb8d
| author | jbe | 
|---|---|
| date | Thu Jun 21 17:18:44 2012 +0200 (2012-06-21) | 
| parents | 727a10edeb8d | 
| children | 6ab448e71d66 | 
 line source
     1 #!/usr/bin/env lua
     3 _WEBMCP_VERSION = "1.2.2"
     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
    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 mondelefant atom connector
    78 require 'mondelefant_atom_connector'
    80 --[[--
    81 cloned_table =  -- newly generated table
    82 table.new(
    83   table_or_nil  -- keys of a given table will be copied to the new table
    84 )
    86 If a table is given, then a cloned table is returned.
    87 If nil is given, then a new empty table is returned.
    89 --]]--
    90 function table.new(tbl)
    91   new_tbl = {}
    92   if tbl then
    93     for key, value in pairs(tbl) do
    94       new_tbl[key] = value
    95     end
    96   end
    97   return new_tbl
    98 end
    99 --//--
   101 --[[--
   102 at_exit(
   103   func  -- function to be called before the process is ending
   104 )
   106 Registers a function to be called before the CGI process is exiting.
   107 --]]--
   108 do
   109   local exit_handlers = {}
   110   function at_exit(func)
   111     table.insert(exit_handlers, func)
   112   end
   113   function exit(code)
   114     for i = #exit_handlers, 1, -1 do
   115       exit_handlers[i]()
   116     end
   117     os.exit(code)
   118   end
   119 end
   120 --//--
   122 --[[--
   123 app  -- table to store an application state
   125 'app' is a global table for storing any application state data
   126 --]]--
   127 app = {}
   128 --//--
   130 --[[--
   131 config  -- table to store application configuration
   133 'config' is a global table, which can be modified by a config file of an application to modify the behaviour of that application.
   134 --]]--
   135 config = {}
   136 --//--
   138 -- autoloader system for WebMCP environment "../env/",
   139 -- application environment extensions "$WEBMCP_APP_BASE/env/"
   140 -- and models "$WEBMCP_APP_BASE/model/"
   141 do
   142   local app_base = os.getenv("WEBMCP_APP_BASEPATH")
   143   if not app_base then
   144     error(
   145       "Failed to initialize autoloader " ..
   146       "due to unset WEBMCP_APP_BASEPATH environment variable."
   147     )
   148   end
   149   local weakkey_mt = { __mode = "k" }
   150   local autoloader_category = setmetatable({}, weakkey_mt)
   151   local autoloader_path     = setmetatable({}, weakkey_mt)
   152   local autoloader_mt       = {}
   153   local function install_autoloader(self, category, path)
   154     autoloader_category[self] = category
   155     autoloader_path[self]     = path
   156     setmetatable(self, autoloader_mt)
   157   end
   158   local function try_exec(filename)
   159     local file = io.open(filename, "r")
   160     if file then
   161       local filedata = file:read("*a")
   162       io.close(file)
   163       local func, errmsg = load(filedata, "=" .. filename)
   164       if func then
   165         func()
   166         return true
   167       else
   168         error(errmsg, 0)
   169       end
   170     else
   171       return false
   172     end
   173   end
   174   local function compose_path_string(base, path, key)
   175     return string.gsub(
   176       base .. table.concat(path, "/") .. "/" .. key, "/+", "/"
   177     )
   178   end
   179   function autoloader_mt.__index(self, key)
   180     local category, base_path, merge_base_path, file_key
   181     local merge = false
   182     if
   183       string.find(key, "^[a-z_][A-Za-z0-9_]*$") and
   184       not string.find(key, "^__")
   185     then
   186       category        = "env"
   187       base_path       = WEBMCP_PATH .. "/env/"
   188       merge           = true
   189       merge_base_path = app_base .. "/env/"
   190       file_key        = key
   191     elseif string.find(key, "^[A-Z][A-Za-z0-9]*$") then
   192       category        = "model"
   193       base_path       = app_base .. "/model/"
   194       local first = true
   195       file_key = string.gsub(key, "[A-Z]",
   196         function(c)
   197           if first then
   198             first = false
   199             return string.lower(c)
   200           else
   201             return "_" .. string.lower(c)
   202           end
   203         end
   204       )
   205     else
   206       return
   207     end
   208     local required_category = autoloader_category[self]
   209     if required_category and required_category ~= category then return end
   210     local path = autoloader_path[self]
   211     local path_string = compose_path_string(base_path, path, file_key)
   212     local merge_path_string
   213     if merge then
   214       merge_path_string = compose_path_string(
   215         merge_base_path, path, file_key
   216       )
   217     end
   218     local function try_dir(dirname)
   219       local dir = io.open(dirname)
   220       if dir then
   221         io.close(dir)
   222         local obj = {}
   223         local sub_path = {}
   224         for i, v in ipairs(path) do sub_path[i] = v end
   225         table.insert(sub_path, file_key)
   226         install_autoloader(obj, category, sub_path)
   227         rawset(self, key, obj)
   228         try_exec(path_string .. "/__init.lua")
   229         if merge then try_exec(merge_path_string .. "/__init.lua") end
   230         return true
   231       else
   232         return false
   233       end
   234     end
   235     if merge and try_exec(merge_path_string .. ".lua") then
   236     elseif merge and try_dir(merge_path_string .. "/") then
   237     elseif try_exec(path_string .. ".lua") then
   238     elseif try_dir(path_string .. "/") then
   239     else end
   240     return rawget(self, key)
   241   end
   242   install_autoloader(_G, nil, {})
   243   try_exec(WEBMCP_PATH .. "env/__init.lua")
   244 end
   246 -- interactive console mode
   247 if not cgi then
   248   local config_name = request.get_config_name()
   249   if config_name then
   250     execute.config(config_name)
   251   end
   252   return
   253 end
   255 local success, error_info = xpcall(
   256   function()
   258     -- execute configuration file
   259     do
   260       local config_name = request.get_config_name()
   261       if config_name then
   262         execute.config(config_name)
   263       end
   264     end
   266     -- restore slots if coming from http redirect
   267     if cgi.params.tempstore then
   268       trace.restore_slots{}
   269       local blob = tempstore.pop(cgi.params.tempstore)
   270       if blob then slot.restore_all(blob) end
   271     end
   273     local function file_exists(filename)
   274       local file = io.open(filename, "r")
   275       if file then
   276         io.close(file)
   277         return true
   278       else
   279         return false
   280       end
   281     end
   283     if cgi.params["_webmcp_404"] then
   284       request.force_absolute_baseurl()
   285       request.set_status("404 Not Found")
   286       if request.get_404_route() then
   287         request.forward(request.get_404_route())
   288       else
   289         error("No 404 page set.")
   290       end
   291     elseif request.get_action() then
   292       trace.request{
   293         module = request.get_module(),
   294         action = request.get_action()
   295       }
   296       if
   297         request.get_404_route() and
   298         not file_exists(
   299           encode.action_file_path{
   300             module = request.get_module(),
   301             action = request.get_action()
   302           }
   303         )
   304       then
   305         request.set_status("404 Not Found")
   306         request.forward(request.get_404_route())
   307       else
   308         if cgi.method ~= "POST" then
   309           request.set_status("405 Method Not Allowed")
   310           cgi.add_header("Allow: POST")
   311           error("Tried to invoke an action with a GET request.")
   312         end
   313         local action_status = execute.filtered_action{
   314           module = request.get_module(),
   315           action = request.get_action(),
   316         }
   317         if not request.is_rerouted() then
   318           local routing_mode, routing_module, routing_view
   319           routing_mode   = cgi.params["_webmcp_routing." .. action_status .. ".mode"]
   320           routing_module = cgi.params["_webmcp_routing." .. action_status .. ".module"]
   321           routing_view   = cgi.params["_webmcp_routing." .. action_status .. ".view"]
   322           if not (routing_mode or routing_module or routing_view) then
   323             action_status = "default"
   324             routing_mode   = cgi.params["_webmcp_routing.default.mode"]
   325             routing_module = cgi.params["_webmcp_routing.default.module"]
   326             routing_view   = cgi.params["_webmcp_routing.default.view"]
   327           end
   328           assert(routing_module, "Routing information has no module.")
   329           assert(routing_view,   "Routing information has no view.")
   330           if routing_mode == "redirect" then
   331             local routing_params = {}
   332             for key, value in pairs(cgi.params) do
   333               local status, stripped_key = string.match(
   334                 key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   335               )
   336               if status == action_status then
   337                 routing_params[stripped_key] = value
   338               end
   339             end
   340             request.redirect{
   341               module = routing_module,
   342               view   = routing_view,
   343               id     = cgi.params["_webmcp_routing." .. action_status .. ".id"],
   344               params = routing_params
   345             }
   346           elseif routing_mode == "forward" then
   347             request.forward{ module = routing_module, view = routing_view }
   348           else
   349             error("Missing or unknown routing mode in request parameters.")
   350           end
   351         end
   352       end
   353     else
   354       -- no action
   355       trace.request{
   356         module = request.get_module(),
   357         view   = request.get_view()
   358       }
   359       if
   360         request.get_404_route() and
   361         not file_exists(
   362           encode.view_file_path{
   363             module = request.get_module(),
   364             view   = request.get_view()
   365           }
   366         )
   367       then
   368         request.set_status("404 Not Found")
   369         request.forward(request.get_404_route())
   370       end
   371     end
   373     if not request.get_redirect_data() then
   374       request.process_forward()
   375       local view = request.get_view()
   376       if string.find(view, "^_") then
   377         error("Tried to call a private view (prefixed with underscore).")
   378       end
   379       execute.filtered_view{
   380         module = request.get_module(),
   381         view   = view,
   382       }
   383     end
   385     -- force error due to missing absolute base URL until its too late to display error message
   386     --if request.get_redirect_data() then
   387     --  request.get_absolute_baseurl()
   388     --end
   390   end,
   392   function(errobj)
   393     return {
   394       errobj = errobj,
   395       stacktrace = string.gsub(
   396         debug.traceback('', 2),
   397         "^\r?\n?stack traceback:\r?\n?", ""
   398       )
   399     }
   400   end
   401 )
   403 if not success then trace.error{} end
   405 -- laufzeitermittlung
   406 trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
   408 slot.select('trace', trace.render)  -- render trace information
   410 local redirect_data = request.get_redirect_data()
   412 -- log error and switch to error layout, unless success
   413 if not success then
   414   local errobj     = error_info.errobj
   415   local stacktrace = error_info.stacktrace
   416   if not request.get_status() and not request.get_json_request_slots() then
   417     request.set_status("500 Internal Server Error")
   418   end
   419   slot.set_layout('system_error')
   420   slot.select('system_error', function()
   421     if getmetatable(errobj) == mondelefant.errorobject_metatable then
   422       slot.put(
   423         "<p>Database error of class <b>",
   424         encode.html(errobj.code),
   425         "</b> occured:<br/><b>",
   426         encode.html(errobj.message),
   427         "</b></p>"
   428       )
   429     else
   430       slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   431     end
   432     slot.put("<p>Stack trace follows:<br/>")
   433     slot.put(encode.html_newlines(encode.html(stacktrace)))
   434     slot.put("</p>")
   435   end)
   436 elseif redirect_data then
   437   local redirect_params = {}
   438   for key, value in pairs(redirect_data.params) do
   439     redirect_params[key] = value
   440   end
   441   local slot_dump = slot.dump_all()
   442   if slot_dump ~= "" then
   443     redirect_params.tempstore = tempstore.save(slot_dump)
   444   end
   445   local json_request_slots = request.get_json_request_slots()
   446   if json_request_slots then
   447     redirect_params["_webmcp_json_slots[]"] = json_request_slots  
   448   end
   449   cgi.redirect(
   450     encode.url{
   451       base   = request.get_absolute_baseurl(),
   452       module = redirect_data.module,
   453       view   = redirect_data.view,
   454       id     = redirect_data.id,
   455       params = redirect_params
   456     }
   457   )
   458   cgi.send_data()
   459 end
   461 if not success or not redirect_data then
   463   local http_status = request.get_status()
   464   if http_status then
   465     cgi.set_status(http_status)
   466   end
   468   local json_request_slots = request.get_json_request_slots()
   469   if json_request_slots then
   470     cgi.set_content_type('application/json')
   471     local data = {}
   472     for idx, slot_ident in ipairs(json_request_slots) do
   473       data[slot_ident] = slot.get_content(slot_ident)
   474     end
   475     cgi.send_data(encode.json(data))
   476   else
   477     cgi.set_content_type(slot.get_content_type())
   478     cgi.send_data(slot.render_layout())
   479   end
   480 end
   482 exit()
