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