mod_http_errors: Add a newline after end of HTML
[prosody.git] / plugins / mod_http_errors.lua
1 module:set_global();
2
3 local server = require "net.http.server";
4 local codes = require "net.http.codes";
5
6 local show_private = module:get_option_boolean("http_errors_detailed", false);
7 local always_serve = module:get_option_boolean("http_errors_always_show", true);
8 local default_message = { module:get_option_string("http_errors_default_message", "That's all I know.") };
9 local default_messages = {
10         [400] = { "What kind of request do you call that??" };
11         [403] = { "You're not allowed to do that." };
12         [404] = { "Whatever you were looking for is not here. %";
13                 "Where did you put it?", "It's behind you.", "Keep looking." };
14         [500] = { "% Check your error log for more info.";
15                 "Gremlins.", "It broke.", "Don't look at me." };
16 };
17
18 local messages = setmetatable(module:get_option("http_errors_messages", {}), { __index = default_messages });
19
20 local html = [[
21 <!DOCTYPE html>
22 <html>
23 <head>
24         <meta charset="utf-8">
25         <style>
26                 body{
27                         margin-top:14%;
28                         text-align:center;
29                         background-color:#F8F8F8;
30                         font-family:sans-serif;
31                 }
32                 h1{
33                         font-size:xx-large;
34                 }
35                 p{
36                         font-size:x-large;
37                 }
38                 p+p { font-size: large; font-family: courier }
39         </style>
40 </head>
41 <body>
42         <h1>$title</h1>
43         <p>$message</p>
44         <p>$extra</p>
45 </body>
46 </html>
47 ]];
48 html = html:gsub("%s%s+", "");
49
50 local entities = {
51         ["<"] = "&lt;", [">"] = "&gt;", ["&"] = "&amp;",
52         ["'"] = "&apos;", ["\""] = "&quot;", ["\n"] = "<br/>",
53 };
54
55 local function tohtml(plain)
56         return (plain:gsub("[<>&'\"\n]", entities));
57
58 end
59
60 local function get_page(code, extra)
61         local message = messages[code];
62         if always_serve or message then
63                 message = message or default_message;
64                 return (html:gsub("$(%a+)", {
65                         title = rawget(codes, code) or ("Code "..tostring(code));
66                         message = message[1]:gsub("%%", function ()
67                                 return message[math.random(2, math.max(#message,2))];
68                         end);
69                         extra = tohtml(extra or "");
70                 }));
71         end
72 end
73
74 module:hook_object_event(server, "http-error", function (event)
75         return get_page(event.code, (show_private and event.private_message) or event.message);
76 end);