webmcp
view framework/env/request/handler.lua @ 360:785ff282af16
Changed version string to "2.0.1"
| author | jbe | 
|---|---|
| date | Thu Mar 26 20:51:35 2015 +0100 (2015-03-26) | 
| parents | 545ec2e3eafa | 
| children | 4e03ecb28665 | 
 line source
     1 --[[--
     2 success =         -- false if an error occurred, true otherwise
     3 request.handler(
     4   http_request    -- HTTP request object
     5 )
     7 Called by mcp.lua to process an HTTP request. Calls request.router() and handles the request. Note: request initializers (see request.initialize()) are to be executed by mcp.lua before this function is invoked by mcp.lua.
     9 --]]--
    11 function request.handler(http_request)
    12   request._http_request = http_request
    13   local path = http_request.path
    14   if path then
    15     local relative_baseurl_elements = {}
    16     for match in string.gmatch(path, "/") do
    17       relative_baseurl_elements[#relative_baseurl_elements+1] = "../"
    18     end
    19     if #relative_baseurl_elements > 0 then
    20       request._relative_baseurl = table.concat(relative_baseurl_elements)
    21     else
    22       request._relative_baseurl = "./"
    23     end
    24   else
    25     request._relative_baseurl = nil
    26   end
    27   request._route = request.router()
    28   do
    29     local post_id = http_request.post_params["_webmcp_id"]
    30     if post_id then
    31       request._route.id = post_id
    32     end
    33   end
    35   local success, error_info = xpcall(
    36     function()
    38       if not request._route then
    39         request._route = {}
    40         if request.get_404_route() then
    41           request.set_status("404 Not Found")
    42           request.forward(request.get_404_route())
    43         else
    44           error("Could not route request URL")
    45         end
    46       end
    48       if request._route.static then
    49         local subpath = request._route.static
    50         for element in string.gmatch(subpath, "[^/]+") do
    51           if element == "." or element == ".." then
    52             subpath = nil
    53             break
    54           end
    55         end
    56         local fstat, f, errmsg
    57         if subpath then
    58           local filename = WEBMCP_BASE_PATH .. "static/" .. subpath
    59           fstat, errmsg = extos.stat(filename)
    60           if fstat then
    61             if fstat.isdir then
    62               errmsg = "Is a directory"
    63             elseif not fstat.isreg then
    64               errmsg = "Not a regular file"
    65             else
    66               f, errmsg = io.open(filename, "r")
    67             end
    68           end
    69         end
    70         if not f then
    71           if request.get_404_route() then
    72             request.set_status("404 Not Found")
    73             request.forward(request.get_404_route())
    74           else
    75             error('Could not open static file "' .. subpath .. '": ' .. errmsg)
    76           end
    77         else
    78           local d = assert(f:read("*a"))
    79           f:close()
    80           slot.put_into("data", d)
    81           local filename_extension = string.match(subpath, "%.([^.]+)$")
    82           slot.set_layout(nil, request._mime_types[filename_extension] or "application/octet-stream")
    83           request.allow_caching()
    84           return
    85         end
    86       end
    88       -- restore slots if coming from http redirect
    89       do
    90         local tempstore_value = http_request.get_params["_tempstore"]
    91         if tempstore_value then
    92           trace.restore_slots{}
    93           local blob = tempstore.pop(tempstore_value)
    94           if blob then slot.restore_all(blob) end
    95         end
    96       end
    98       if request.get_action() then
    99         trace.request{
   100           module = request.get_module(),
   101           action = request.get_action()
   102         }
   103         if
   104           not execute.action{
   105             module = request.get_module(),
   106             action = request.get_action(),
   107             test_existence = true
   108           } and
   109           request.get_404_route()
   110         then
   111           request.set_status("404 Not Found")
   112           request.forward(request.get_404_route())
   113         else
   114           if http_request.method ~= "POST" then
   115             request.set_status("405 Method Not Allowed")
   116             request.add_header("Allow", "POST")
   117             error("Tried to invoke an action with a GET request.")
   118           end
   119           local action_status = execute.filtered_action{
   120             module = request.get_module(),
   121             action = request.get_action(),
   122           }
   123           if not request.is_rerouted() then
   124             local routing_mode, routing_module, routing_view, routing_anchor
   125             routing_mode   = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
   126             routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
   127             routing_view   = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
   128             routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
   129             if not (routing_mode or routing_module or routing_view) then
   130               action_status = "default"
   131               routing_mode   = http_request.post_params["_webmcp_routing.default.mode"]
   132               routing_module = http_request.post_params["_webmcp_routing.default.module"]
   133               routing_view   = http_request.post_params["_webmcp_routing.default.view"]
   134               routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
   135             end
   136             assert(routing_module, "Routing information has no module.")
   137             assert(routing_view,   "Routing information has no view.")
   138             if routing_mode == "redirect" then
   139               local routing_params = {}
   140               for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
   141                 local status, stripped_key = string.match(
   142                   key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   143                 )
   144                 if status == action_status then
   145                   routing_params[stripped_key] = value
   146                 end
   147               end
   148               request.redirect{
   149                 module = routing_module,
   150                 view   = routing_view,
   151                 id     = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
   152                 params = routing_params,
   153                 anchor = routing_anchor
   154               }
   155             elseif routing_mode == "forward" then
   156               request.forward{ module = routing_module, view = routing_view }
   157             else
   158               error("Missing or unknown routing mode in request parameters.")
   159             end
   160           end
   161         end
   162       else
   163         -- no action
   164         trace.request{
   165           module = request.get_module(),
   166           view   = request.get_view()
   167         }
   168         if
   169           not execute.view{
   170             module = request.get_module(),
   171             view   = request.get_view(),
   172             test_existence = true
   173           } and request.get_404_route()
   174         then
   175           request.set_status("404 Not Found")
   176           request.forward(request.get_404_route())
   177         end
   178       end
   180       if not request.get_redirect_data() then
   181         request.process_forward()
   182         local view = request.get_view()
   183         if string.find(view, "^_") then
   184           error("Tried to call a private view (prefixed with underscore).")
   185         end
   186         execute.filtered_view{
   187           module = request.get_module(),
   188           view   = view,
   189         }
   190       end
   192     end,
   194     function(errobj)
   195       return {
   196         errobj = errobj,
   197         stacktrace = string.gsub(
   198           debug.traceback('', 2),
   199           "^\r?\n?stack traceback:\r?\n?", ""
   200         )
   201       }
   202     end
   203   )
   205   if not success then trace.error{} end
   207   slot.select('trace', trace.render)  -- render trace information
   209   local redirect_data = request.get_redirect_data()
   211   -- log error and switch to error layout, unless success
   212   if not success then
   213     local errobj     = error_info.errobj
   214     local stacktrace = error_info.stacktrace
   215     if not request._status then
   216       request._status = "500 Internal Server Error"
   217     end
   218     http_request:close_after_finish()
   219     slot.set_layout('system_error')
   220     slot.select('system_error', function()
   221       if getmetatable(errobj) == mondelefant.errorobject_metatable then
   222         slot.put(
   223           "<p>Database error of class <b>",
   224           encode.html(errobj.code),
   225           "</b> occured:<br/><b>",
   226           encode.html(errobj.message),
   227           "</b></p>"
   228         )
   229       else
   230         slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   231       end
   232       slot.put("<p>Stack trace follows:<br/>")
   233       slot.put(encode.html_newlines(encode.html(stacktrace)))
   234       slot.put("</p>")
   235     end)
   236   elseif redirect_data then
   237     redirect_data = table.new(redirect_data)
   238     redirect_data.params = table.new(redirect_data.params)
   239     local slot_dump = slot.dump_all()
   240     if slot_dump ~= "" then
   241       redirect_data.params._tempstore = tempstore.save(slot_dump)
   242     end
   243     http_request:send_status("303 See Other")
   244     for i, header in ipairs(request._response_headers) do
   245       http_request:send_header(header[1], header[2])
   246     end
   247     http_request:send_header("Location", encode.url(redirect_data))
   248     http_request:finish()
   249   end
   251   if not success or not redirect_data then
   253     http_request:send_status(request._status or "200 OK")
   254     for i, header in ipairs(request._response_headers) do
   255       http_request:send_header(header[1], header[2])
   256     end
   257     if not request._cache_manual then
   258       local cache_time = request._cache_time
   259       if request._cache and cache_time and cache_time > 0 then
   260         http_request:send_header("Cache-Control", "max-age=" .. cache_time)
   261       else
   262         http_request:send_header("Cache-Control", "no-cache")
   263       end
   264     end
   265     http_request:send_header("Content-Type", slot.get_content_type())
   266     http_request:send_data(slot.render_layout())
   267     http_request:finish()
   268   end
   270   return success
   272 end
