2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
9 local setmetatable = setmetatable;
10 local pairs, ipairs = pairs, ipairs;
11 local tostring, type = tostring, type;
12 local t_concat = table.concat;
14 local st = require "util.stanza";
18 local xmlns_forms = 'jabber:x:data';
21 local form_mt = { __index = form_t };
24 return setmetatable(layout, form_mt);
27 function form_t.form(layout, data)
28 local form = st.stanza("x", { xmlns = xmlns_forms, type = "form" });
30 form:tag("title"):text(layout.title):up();
32 if layout.instructions then
33 form:tag("instructions"):text(layout.instructions):up();
35 for n, field in ipairs(layout) do
36 local field_type = field.type or "text-single";
38 form:tag("field", { type = field_type, var = field.name, label = field.label });
40 local value = data[field.name] or field.value;
42 -- Add value, depending on type
43 if field_type == "hidden" then
44 if type(value) == "table" then
45 -- Assume an XML snippet
50 form:tag("value"):text(tostring(value)):up();
52 elseif field_type == "boolean" then
53 form:tag("value"):text((value and "1") or "0"):up();
54 elseif field_type == "fixed" then
56 elseif field_type == "jid-multi" then
57 for _, jid in ipairs(value) do
58 form:tag("value"):text(jid):up();
60 elseif field_type == "jid-single" then
61 form:tag("value"):text(value):up();
62 elseif field_type == "text-single" or field_type == "text-private" then
63 form:tag("value"):text(value):up();
64 elseif field_type == "text-multi" then
65 -- Split into multiple <value> tags, one for each line
66 for line in value:gmatch("([^\r\n]+)\r?\n*") do
67 form:tag("value"):text(line):up();
71 if field.required then
72 form:tag("required"):up();
75 -- Jump back up to list of fields
81 local field_readers = {};
83 function form_t.data(layout, stanza)
86 for field_tag in stanza:childtags() do
87 local field_type = field_tag.attr.type;
89 local reader = field_readers[field_type];
91 data[field_tag.attr.var] = reader(field_tag);
98 field_readers["text-single"] =
100 local value = field_tag:child_with_name("value");
106 field_readers["text-private"] =
107 field_readers["text-single"];
109 field_readers["text-multi"] =
112 for value_tag in field_tag:childtags() do
113 if value_tag.name == "value" then
114 result[#result+1] = value_tag[1];
117 return t_concat(result, "\n");
120 field_readers["boolean"] =
122 local value = field_tag:child_with_name("value");
124 if value[1] == "1" or value[1] == "true" then
132 field_readers["hidden"] =
134 local value = field_tag:child_with_name("value");
148 title = "MUC Configuration",
149 instructions = [[Use this form to configure options for this MUC room.]],
151 { name = "FORM_TYPE", type = "hidden", required = true };
152 { name = "field-name", type = "field-type", required = false };