util.stanza: Fixed some more nil global accesses.
[prosody.git] / util / stanza.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10 local t_insert      =  table.insert;
11 local t_concat      =  table.concat;
12 local t_remove      =  table.remove;
13 local t_concat      =  table.concat;
14 local s_format      = string.format;
15 local s_match       =  string.match;
16 local tostring      =      tostring;
17 local setmetatable  =  setmetatable;
18 local getmetatable  =  getmetatable;
19 local pairs         =         pairs;
20 local ipairs        =        ipairs;
21 local type          =          type;
22 local next          =          next;
23 local print         =         print;
24 local unpack        =        unpack;
25 local s_gsub        =   string.gsub;
26 local s_char        =   string.char;
27 local s_find        =   string.find;
28 local os            =            os;
29
30 local do_pretty_printing = not os.getenv("WINDIR");
31 local getstyle, getstring;
32 if do_pretty_printing then
33         local ok, termcolours = pcall(require, "util.termcolours");
34         if ok then
35                 getstyle, getstring = termcolours.getstyle, termcolours.getstring;
36         else
37                 do_pretty_printing = nil;
38         end
39 end
40
41 local xmlns_stanzas = "urn:ietf:params:xml:ns:xmpp-stanzas";
42
43 module "stanza"
44
45 stanza_mt = { __type = "stanza" };
46 stanza_mt.__index = stanza_mt;
47
48 function stanza(name, attr)
49         local stanza = { name = name, attr = attr or {}, tags = {}, last_add = {}};
50         return setmetatable(stanza, stanza_mt);
51 end
52
53 function stanza_mt:query(xmlns)
54         return self:tag("query", { xmlns = xmlns });
55 end
56
57 function stanza_mt:body(text, attr)
58         return self:tag("body", attr):text(text);
59 end
60
61 function stanza_mt:tag(name, attrs)
62         local s = stanza(name, attrs);
63         (self.last_add[#self.last_add] or self):add_direct_child(s);
64         t_insert(self.last_add, s);
65         return self;
66 end
67
68 function stanza_mt:text(text)
69         (self.last_add[#self.last_add] or self):add_direct_child(text);
70         return self; 
71 end
72
73 function stanza_mt:up()
74         t_remove(self.last_add);
75         return self;
76 end
77
78 function stanza_mt:reset()
79         local last_add = self.last_add;
80         for i = 1,#last_add do
81                 last_add[i] = nil;
82         end
83         return self;
84 end
85
86 function stanza_mt:add_direct_child(child)
87         if type(child) == "table" then
88                 t_insert(self.tags, child);
89         end
90         t_insert(self, child);
91 end
92
93 function stanza_mt:add_child(child)
94         (self.last_add[#self.last_add] or self):add_direct_child(child);
95         return self;
96 end
97
98 function stanza_mt:get_child(name, xmlns)
99         for _, child in ipairs(self.tags) do
100                 if (not name or child.name == name) 
101                         and ((not xmlns and self.attr.xmlns == child.attr.xmlns)
102                                 or child.attr.xmlns == xmlns) then
103                         
104                         return child;
105                 end
106         end
107 end
108
109 function stanza_mt:child_with_name(name)
110         for _, child in ipairs(self.tags) do    
111                 if child.name == name then return child; end
112         end
113 end
114
115 function stanza_mt:child_with_ns(ns)
116         for _, child in ipairs(self.tags) do    
117                 if child.attr.xmlns == ns then return child; end
118         end
119 end
120
121 function stanza_mt:children()
122         local i = 0;
123         return function (a)
124                         i = i + 1
125                         local v = a[i]
126                         if v then return v; end
127                 end, self, i;
128                                             
129 end
130 function stanza_mt:childtags()
131         local i = 0;
132         return function (a)
133                         i = i + 1
134                         local v = self.tags[i]
135                         if v then return v; end
136                 end, self.tags[1], i;
137                                             
138 end
139
140 local xml_escape
141 do
142         local escape_table = { ["'"] = "&apos;", ["\""] = "&quot;", ["<"] = "&lt;", [">"] = "&gt;", ["&"] = "&amp;" };
143         function xml_escape(str) return (s_gsub(str, "['&<>\"]", escape_table)); end
144         _M.xml_escape = xml_escape;
145 end
146
147 local function _dostring(t, buf, self, xml_escape, parentns)
148         local nsid = 0;
149         local name = t.name
150         t_insert(buf, "<"..name);
151         for k, v in pairs(t.attr) do
152                 if s_find(k, "\1", 1, true) then
153                         local ns, attrk = s_match(k, "^([^\1]*)\1?(.*)$");
154                         nsid = nsid + 1;
155                         t_insert(buf, " xmlns:ns"..nsid.."='"..xml_escape(ns).."' ".."ns"..nsid..":"..attrk.."='"..xml_escape(v).."'");
156                 elseif not(k == "xmlns" and v == parentns) then
157                         t_insert(buf, " "..k.."='"..xml_escape(v).."'");
158                 end
159         end
160         local len = #t;
161         if len == 0 then
162                 t_insert(buf, "/>");
163         else
164                 t_insert(buf, ">");
165                 for n=1,len do
166                         local child = t[n];
167                         if child.name then
168                                 self(child, buf, self, xml_escape, t.attr.xmlns);
169                         else
170                                 t_insert(buf, xml_escape(child));
171                         end
172                 end
173                 t_insert(buf, "</"..name..">");
174         end
175 end
176 function stanza_mt.__tostring(t)
177         local buf = {};
178         _dostring(t, buf, _dostring, xml_escape, nil);
179         return t_concat(buf);
180 end
181
182 function stanza_mt.top_tag(t)
183         local attr_string = "";
184         if t.attr then
185                 for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(" %s='%s'", k, xml_escape(tostring(v))); end end
186         end
187         return s_format("<%s%s>", t.name, attr_string);
188 end
189
190 function stanza_mt.get_text(t)
191         if #t.tags == 0 then
192                 return t_concat(t);
193         end
194 end
195
196 function stanza_mt.__add(s1, s2)
197         return s1:add_direct_child(s2);
198 end
199
200
201 do
202         local id = 0;
203         function new_id()
204                 id = id + 1;
205                 return "lx"..id;
206         end
207 end
208
209 function preserialize(stanza)
210         local s = { name = stanza.name, attr = stanza.attr };
211         for _, child in ipairs(stanza) do
212                 if type(child) == "table" then
213                         t_insert(s, preserialize(child));
214                 else
215                         t_insert(s, child);
216                 end
217         end
218         return s;
219 end
220
221 function deserialize(stanza)
222         -- Set metatable
223         if stanza then
224                 local attr = stanza.attr;
225                 for i=1,#attr do attr[i] = nil; end
226                 local attrx = {};
227                 for att in pairs(attr) do
228                         if s_find(att, "|", 1, true) and not s_find(att, "\1", 1, true) then
229                                 local ns,na = s_match(att, "^([^|]+)|(.+)$");
230                                 attrx[ns.."\1"..na] = attr[att];
231                                 attr[att] = nil;
232                         end
233                 end
234                 for a,v in pairs(attrx) do
235                         attr[a] = v;
236                 end
237                 setmetatable(stanza, stanza_mt);
238                 for _, child in ipairs(stanza) do
239                         if type(child) == "table" then
240                                 deserialize(child);
241                         end
242                 end
243                 if not stanza.tags then
244                         -- Rebuild tags
245                         local tags = {};
246                         for _, child in ipairs(stanza) do
247                                 if type(child) == "table" then
248                                         t_insert(tags, child);
249                                 end
250                         end
251                         stanza.tags = tags;
252                         if not stanza.last_add then
253                                 stanza.last_add = {};
254                         end
255                 end
256         end
257         
258         return stanza;
259 end
260
261 function clone(stanza)
262         local lookup_table = {};
263         local function _copy(object)
264                 if type(object) ~= "table" then
265                         return object;
266                 elseif lookup_table[object] then
267                         return lookup_table[object];
268                 end
269                 local new_table = {};
270                 lookup_table[object] = new_table;
271                 for index, value in pairs(object) do
272                         new_table[_copy(index)] = _copy(value);
273                 end
274                 return setmetatable(new_table, getmetatable(object));
275         end
276         
277         return _copy(stanza)
278 end
279
280 function message(attr, body)
281         if not body then
282                 return stanza("message", attr);
283         else
284                 return stanza("message", attr):tag("body"):text(body);
285         end
286 end
287 function iq(attr)
288         if attr and not attr.id then attr.id = new_id(); end
289         return stanza("iq", attr or { id = new_id() });
290 end
291
292 function reply(orig)
293         return stanza(orig.name, orig.attr and { to = orig.attr.from, from = orig.attr.to, id = orig.attr.id, type = ((orig.name == "iq" and "result") or orig.attr.type) });
294 end
295
296 do
297         local xmpp_stanzas_attr = { xmlns = xmlns_stanzas };
298         function error_reply(orig, type, condition, message)
299                 local t = reply(orig);
300                 t.attr.type = "error";
301                 t:tag("error", {type = type}) --COMPAT: Some day xmlns:stanzas goes here
302                         :tag(condition, xmpp_stanzas_attr):up();
303                 if (message) then t:tag("text", xmpp_stanzas_attr):text(message):up(); end
304                 return t; -- stanza ready for adding app-specific errors
305         end
306 end
307
308 function presence(attr)
309         return stanza("presence", attr);
310 end
311
312 if do_pretty_printing then
313         local style_attrk = getstyle("yellow");
314         local style_attrv = getstyle("red");
315         local style_tagname = getstyle("red");
316         local style_punc = getstyle("magenta");
317         
318         local attr_format = " "..getstring(style_attrk, "%s")..getstring(style_punc, "=")..getstring(style_attrv, "'%s'");
319         local top_tag_format = getstring(style_punc, "<")..getstring(style_tagname, "%s").."%s"..getstring(style_punc, ">");
320         --local tag_format = getstring(style_punc, "<")..getstring(style_tagname, "%s").."%s"..getstring(style_punc, ">").."%s"..getstring(style_punc, "</")..getstring(style_tagname, "%s")..getstring(style_punc, ">");
321         local tag_format = top_tag_format.."%s"..getstring(style_punc, "</")..getstring(style_tagname, "%s")..getstring(style_punc, ">");
322         function stanza_mt.pretty_print(t)
323                 local children_text = "";
324                 for n, child in ipairs(t) do
325                         if type(child) == "string" then 
326                                 children_text = children_text .. xml_escape(child);
327                         else
328                                 children_text = children_text .. child:pretty_print();
329                         end
330                 end
331
332                 local attr_string = "";
333                 if t.attr then
334                         for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(attr_format, k, tostring(v)); end end
335                 end
336                 return s_format(tag_format, t.name, attr_string, children_text, t.name);
337         end
338         
339         function stanza_mt.pretty_top_tag(t)
340                 local attr_string = "";
341                 if t.attr then
342                         for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(attr_format, k, tostring(v)); end end
343                 end
344                 return s_format(top_tag_format, t.name, attr_string);
345         end
346 else
347         -- Sorry, fresh out of colours for you guys ;)
348         stanza_mt.pretty_print = stanza_mt.__tostring;
349         stanza_mt.pretty_top_tag = stanza_mt.top_tag;
350 end
351
352 return _M;