1 local setmetatable = setmetatable;
2 local pairs, ipairs = pairs, ipairs;
3 local tostring, type = tostring, type;
4 local t_concat = table.concat;
6 local st = require "util.stanza";
10 local xmlns_forms = 'jabber:x:data';
13 local form_mt = { __index = form_t };
16 return setmetatable(layout, form_mt);
19 function form_t.form(layout, data)
20 local form = st.stanza("x", { xmlns = xmlns_forms, type = "form" });
22 form:tag("title"):text(layout.title):up();
24 if layout.instructions then
25 form:tag("instructions"):text(layout.instructions):up();
27 for n, field in ipairs(layout) do
28 local field_type = field.type or "text-single";
30 form:tag("field", { type = field_type, var = field.name, label = field.label });
32 local value = data[field.name] or field.value;
34 -- Add value, depending on type
35 if field_type == "hidden" then
36 if type(value) == "table" then
37 -- Assume an XML snippet
42 form:tag("value"):text(tostring(value)):up();
44 elseif field_type == "boolean" then
45 form:tag("value"):text((value and "1") or "0"):up();
46 elseif field_type == "fixed" then
48 elseif field_type == "jid-multi" then
49 for _, jid in ipairs(value) do
50 form:tag("value"):text(jid):up();
52 elseif field_type == "jid-single" then
53 form:tag("value"):text(value):up();
54 elseif field_type == "text-single" or field_type == "text-private" then
55 form:tag("value"):text(value):up();
56 elseif field_type == "text-multi" then
57 -- Split into multiple <value> tags, one for each line
58 for line in value:gmatch("([^\r\n]+)\r?\n*") do
59 form:tag("value"):text(line):up();
63 if field.required then
64 form:tag("required"):up();
67 -- Jump back up to list of fields
73 local field_readers = {};
75 function form_t.data(layout, stanza)
78 for field_tag in stanza:childtags() do
79 local field_type = field_tag.attr.type;
81 local reader = field_readers[field_type];
83 data[field_tag.attr.var] = reader(field_tag);
90 field_readers["text-single"] =
92 local value = field_tag:child_with_name("value");
98 field_readers["text-private"] =
99 field_readers["text-single"];
101 field_readers["text-multi"] =
104 for value_tag in field_tag:childtags() do
105 if value_tag.name == "value" then
106 result[#result+1] = value_tag[1];
109 return t_concat(result, "\n");
112 field_readers["boolean"] =
114 local value = field_tag:child_with_name("value");
116 if value[1] == "1" or value[1] == "true" then
124 field_readers["hidden"] =
126 local value = field_tag:child_with_name("value");
140 title = "MUC Configuration",
141 instructions = [[Use this form to configure options for this MUC room.]],
143 { name = "FORM_TYPE", type = "hidden", required = true };
144 { name = "field-name", type = "field-type", required = false };