Merge 0.9->0.10
[prosody.git] / plugins / muc / muc.lib.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 local select = select;
10 local pairs, ipairs = pairs, ipairs;
11
12 local datetime = require "util.datetime";
13
14 local dataform = require "util.dataforms";
15
16 local jid_split = require "util.jid".split;
17 local jid_bare = require "util.jid".bare;
18 local jid_prep = require "util.jid".prep;
19 local st = require "util.stanza";
20 local log = require "util.logger".init("mod_muc");
21 local t_insert, t_remove = table.insert, table.remove;
22 local setmetatable = setmetatable;
23 local base64 = require "util.encodings".base64;
24 local md5 = require "util.hashes".md5;
25
26 local muc_domain = nil; --module:get_host();
27 local default_history_length, max_history_length = 20, math.huge;
28
29 ------------
30 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
31 local function presence_filter(tag)
32         if presence_filters[tag.attr.xmlns] then
33                 return nil;
34         end
35         return tag;
36 end
37
38 local function get_filtered_presence(stanza)
39         return st.clone(stanza):maptags(presence_filter);
40 end
41 local kickable_error_conditions = {
42         ["gone"] = true;
43         ["internal-server-error"] = true;
44         ["item-not-found"] = true;
45         ["jid-malformed"] = true;
46         ["recipient-unavailable"] = true;
47         ["redirect"] = true;
48         ["remote-server-not-found"] = true;
49         ["remote-server-timeout"] = true;
50         ["service-unavailable"] = true;
51         ["malformed error"] = true;
52 };
53
54 local function get_error_condition(stanza)
55         local _, condition = stanza:get_error();
56         return condition or "malformed error";
57 end
58
59 local function is_kickable_error(stanza)
60         local cond = get_error_condition(stanza);
61         return kickable_error_conditions[cond] and cond;
62 end
63 -----------
64
65 local room_mt = {};
66 room_mt.__index = room_mt;
67
68 function room_mt:__tostring()
69         return "MUC room ("..self.jid..")";
70 end
71
72 function room_mt:get_default_role(affiliation)
73         if affiliation == "owner" or affiliation == "admin" then
74                 return "moderator";
75         elseif affiliation == "member" then
76                 return "participant";
77         elseif not affiliation then
78                 if not self:get_members_only() then
79                         return self:get_moderated() and "visitor" or "participant";
80                 end
81         end
82 end
83
84 function room_mt:broadcast_presence(stanza, sid, code, nick)
85         stanza = get_filtered_presence(stanza);
86         local occupant = self._occupants[stanza.attr.from];
87         stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
88                 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
89         if code then
90                 stanza:tag("status", {code=code}):up();
91         end
92         self:broadcast_except_nick(stanza, stanza.attr.from);
93         local me = self._occupants[stanza.attr.from];
94         if me then
95                 stanza:tag("status", {code='110'}):up();
96                 stanza.attr.to = sid;
97                 self:_route_stanza(stanza);
98         end
99 end
100 function room_mt:broadcast_message(stanza, historic)
101         local to = stanza.attr.to;
102         for occupant, o_data in pairs(self._occupants) do
103                 for jid in pairs(o_data.sessions) do
104                         stanza.attr.to = jid;
105                         self:_route_stanza(stanza);
106                 end
107         end
108         stanza.attr.to = to;
109         if historic then -- add to history
110                 return self:save_to_history(stanza)
111         end
112 end
113 function room_mt:save_to_history(stanza)
114         local history = self._data['history'];
115         if not history then history = {}; self._data['history'] = history; end
116         stanza = st.clone(stanza);
117         stanza.attr.to = "";
118         local stamp = datetime.datetime();
119         stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
120         stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
121         local entry = { stanza = stanza, stamp = stamp };
122         t_insert(history, entry);
123         while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
124 end
125 function room_mt:broadcast_except_nick(stanza, nick)
126         for rnick, occupant in pairs(self._occupants) do
127                 if rnick ~= nick then
128                         for jid in pairs(occupant.sessions) do
129                                 stanza.attr.to = jid;
130                                 self:_route_stanza(stanza);
131                         end
132                 end
133         end
134 end
135
136 function room_mt:send_occupant_list(to)
137         local current_nick = self._jid_nick[to];
138         for occupant, o_data in pairs(self._occupants) do
139                 if occupant ~= current_nick then
140                         local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
141                         pres.attr.to, pres.attr.from = to, occupant;
142                         pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
143                                 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
144                         self:_route_stanza(pres);
145                 end
146         end
147 end
148 function room_mt:send_history(to, stanza)
149         local history = self._data['history']; -- send discussion history
150         if history then
151                 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
152                 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
153
154                 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
155                 if maxchars then maxchars = math.floor(maxchars); end
156
157                 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
158                 if not history_tag then maxstanzas = 20; end
159
160                 local seconds = history_tag and tonumber(history_tag.attr.seconds);
161                 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
162
163                 local since = history_tag and history_tag.attr.since;
164                 if since then since = datetime.parse(since); since = since and datetime.datetime(since); end
165                 if seconds and (not since or since < seconds) then since = seconds; end
166
167                 local n = 0;
168                 local charcount = 0;
169
170                 for i=#history,1,-1 do
171                         local entry = history[i];
172                         if maxchars then
173                                 if not entry.chars then
174                                         entry.stanza.attr.to = "";
175                                         entry.chars = #tostring(entry.stanza);
176                                 end
177                                 charcount = charcount + entry.chars + #to;
178                                 if charcount > maxchars then break; end
179                         end
180                         if since and since > entry.stamp then break; end
181                         if n + 1 > maxstanzas then break; end
182                         n = n + 1;
183                 end
184                 for i=#history-n+1,#history do
185                         local msg = history[i].stanza;
186                         msg.attr.to = to;
187                         self:_route_stanza(msg);
188                 end
189         end
190 end
191 function room_mt:send_subject(to)
192         if self._data['subject'] then
193                 self:_route_stanza(st.message({type='groupchat', from=self._data['subject_from'] or self.jid, to=to}):tag("subject"):text(self._data['subject']));
194         end
195 end
196
197 function room_mt:get_disco_info(stanza)
198         local count = 0; for _ in pairs(self._occupants) do count = count + 1; end
199         return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
200                 :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
201                 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
202                 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
203                 :tag("feature", {var=self:get_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
204                 :tag("feature", {var=self:get_members_only() and "muc_membersonly" or "muc_open"}):up()
205                 :tag("feature", {var=self:get_persistent() and "muc_persistent" or "muc_temporary"}):up()
206                 :tag("feature", {var=self:get_hidden() and "muc_hidden" or "muc_public"}):up()
207                 :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
208                 :add_child(dataform.new({
209                         { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
210                         { name = "muc#roominfo_description", label = "Description", value = "" },
211                         { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) }
212                 }):form({["muc#roominfo_description"] = self:get_description()}, 'result'))
213         ;
214 end
215 function room_mt:get_disco_items(stanza)
216         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
217         for room_jid in pairs(self._occupants) do
218                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
219         end
220         return reply;
221 end
222 function room_mt:set_subject(current_nick, subject)
223         if subject == "" then subject = nil; end
224         self._data['subject'] = subject;
225         self._data['subject_from'] = current_nick;
226         if self.save then self:save(); end
227         local msg = st.message({type='groupchat', from=current_nick})
228                 :tag('subject'):text(subject):up();
229         self:broadcast_message(msg, false);
230         return true;
231 end
232
233 local function build_unavailable_presence_from_error(stanza)
234         local type, condition, text = stanza:get_error();
235         local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
236         if text then
237                 error_message = error_message..": "..text;
238         end
239         return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
240                 :tag('status'):text(error_message);
241 end
242
243 function room_mt:set_name(name)
244         if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
245         if self._data.name ~= name then
246                 self._data.name = name;
247                 if self.save then self:save(true); end
248         end
249 end
250 function room_mt:get_name()
251         return self._data.name or jid_split(self.jid);
252 end
253 function room_mt:set_description(description)
254         if description == "" or type(description) ~= "string" then description = nil; end
255         if self._data.description ~= description then
256                 self._data.description = description;
257                 if self.save then self:save(true); end
258         end
259 end
260 function room_mt:get_description()
261         return self._data.description;
262 end
263 function room_mt:set_password(password)
264         if password == "" or type(password) ~= "string" then password = nil; end
265         if self._data.password ~= password then
266                 self._data.password = password;
267                 if self.save then self:save(true); end
268         end
269 end
270 function room_mt:get_password()
271         return self._data.password;
272 end
273 function room_mt:set_moderated(moderated)
274         moderated = moderated and true or nil;
275         if self._data.moderated ~= moderated then
276                 self._data.moderated = moderated;
277                 if self.save then self:save(true); end
278         end
279 end
280 function room_mt:get_moderated()
281         return self._data.moderated;
282 end
283 function room_mt:set_members_only(members_only)
284         members_only = members_only and true or nil;
285         if self._data.members_only ~= members_only then
286                 self._data.members_only = members_only;
287                 if self.save then self:save(true); end
288         end
289 end
290 function room_mt:get_members_only()
291         return self._data.members_only;
292 end
293 function room_mt:set_persistent(persistent)
294         persistent = persistent and true or nil;
295         if self._data.persistent ~= persistent then
296                 self._data.persistent = persistent;
297                 if self.save then self:save(true); end
298         end
299 end
300 function room_mt:get_persistent()
301         return self._data.persistent;
302 end
303 function room_mt:set_hidden(hidden)
304         hidden = hidden and true or nil;
305         if self._data.hidden ~= hidden then
306                 self._data.hidden = hidden;
307                 if self.save then self:save(true); end
308         end
309 end
310 function room_mt:get_hidden()
311         return self._data.hidden;
312 end
313 function room_mt:get_public()
314         return not self:get_hidden();
315 end
316 function room_mt:set_public(public)
317         return self:set_hidden(not public);
318 end
319 function room_mt:set_changesubject(changesubject)
320         changesubject = changesubject and true or nil;
321         if self._data.changesubject ~= changesubject then
322                 self._data.changesubject = changesubject;
323                 if self.save then self:save(true); end
324         end
325 end
326 function room_mt:get_changesubject()
327         return self._data.changesubject;
328 end
329 function room_mt:get_historylength()
330         return self._data.history_length or default_history_length;
331 end
332 function room_mt:set_historylength(length)
333         length = math.min(tonumber(length) or default_history_length, max_history_length or math.huge);
334         if length == default_history_length then
335                 length = nil;
336         end
337         self._data.history_length = length;
338 end
339
340
341 local valid_whois = { moderators = true, anyone = true };
342
343 function room_mt:set_whois(whois)
344         if valid_whois[whois] and self._data.whois ~= whois then
345                 self._data.whois = whois;
346                 if self.save then self:save(true); end
347         end
348 end
349
350 function room_mt:get_whois()
351         return self._data.whois;
352 end
353
354 local function construct_stanza_id(room, stanza)
355         local from_jid, to_nick = stanza.attr.from, stanza.attr.to;
356         local from_nick = room._jid_nick[from_jid];
357         local occupant = room._occupants[to_nick];
358         local to_jid = occupant.jid;
359
360         return from_nick, to_jid, base64.encode(to_jid.."\0"..stanza.attr.id.."\0"..md5(from_jid));
361 end
362 local function deconstruct_stanza_id(room, stanza)
363         local from_jid_possiblybare, to_nick = stanza.attr.from, stanza.attr.to;
364         local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
365         local from_nick = room._jid_nick[from_jid];
366
367         if not(from_nick) then return; end
368         if not(from_jid_possiblybare == from_jid or from_jid_possiblybare == jid_bare(from_jid)) then return; end
369
370         local occupant = room._occupants[to_nick];
371         for to_jid in pairs(occupant and occupant.sessions or {}) do
372                 if md5(to_jid) == to_jid_hash then
373                         return from_nick, to_jid, id;
374                 end
375         end
376 end
377
378
379 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
380         local from, to = stanza.attr.from, stanza.attr.to;
381         local room = jid_bare(to);
382         local current_nick = self._jid_nick[from];
383         local type = stanza.attr.type;
384         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
385         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
386         if stanza.name == "presence" then
387                 local pr = get_filtered_presence(stanza);
388                 pr.attr.from = current_nick;
389                 if type == "error" then -- error, kick em out!
390                         if current_nick then
391                                 log("debug", "kicking %s from %s", current_nick, room);
392                                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
393                         end
394                 elseif type == "unavailable" then -- unavailable
395                         if current_nick then
396                                 log("debug", "%s leaving %s", current_nick, room);
397                                 self._jid_nick[from] = nil;
398                                 local occupant = self._occupants[current_nick];
399                                 local new_jid = next(occupant.sessions);
400                                 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
401                                 if new_jid then
402                                         local jid = occupant.jid;
403                                         occupant.jid = new_jid;
404                                         occupant.sessions[from] = nil;
405                                         pr.attr.to = from;
406                                         pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
407                                                 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
408                                                 :tag("status", {code='110'}):up();
409                                         self:_route_stanza(pr);
410                                         if jid ~= new_jid then
411                                                 pr = st.clone(occupant.sessions[new_jid])
412                                                         :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
413                                                         :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
414                                                 pr.attr.from = current_nick;
415                                                 self:broadcast_except_nick(pr, current_nick);
416                                         end
417                                 else
418                                         occupant.role = 'none';
419                                         self:broadcast_presence(pr, from);
420                                         self._occupants[current_nick] = nil;
421                                 end
422                         end
423                 elseif not type then -- available
424                         if current_nick then
425                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
426                                         if current_nick == to then -- simple presence
427                                                 log("debug", "%s broadcasted presence", current_nick);
428                                                 self._occupants[current_nick].sessions[from] = pr;
429                                                 self:broadcast_presence(pr, from);
430                                         else -- change nick
431                                                 local occupant = self._occupants[current_nick];
432                                                 local is_multisession = next(occupant.sessions, next(occupant.sessions));
433                                                 if self._occupants[to] or is_multisession then
434                                                         log("debug", "%s couldn't change nick", current_nick);
435                                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
436                                                         reply.tags[1].attr.code = "409";
437                                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
438                                                 else
439                                                         local data = self._occupants[current_nick];
440                                                         local to_nick = select(3, jid_split(to));
441                                                         if to_nick then
442                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
443                                                                 local p = st.presence({type='unavailable', from=current_nick});
444                                                                 self:broadcast_presence(p, from, '303', to_nick);
445                                                                 self._occupants[current_nick] = nil;
446                                                                 self._occupants[to] = data;
447                                                                 self._jid_nick[from] = to;
448                                                                 pr.attr.from = to;
449                                                                 self._occupants[to].sessions[from] = pr;
450                                                                 self:broadcast_presence(pr, from);
451                                                         else
452                                                                 --TODO malformed-jid
453                                                         end
454                                                 end
455                                         end
456                                 --else -- possible rejoin
457                                 --      log("debug", "%s had connection replaced", current_nick);
458                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
459                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
460                                 --      self:handle_to_occupant(origin, stanza); -- resend available
461                                 --end
462                         else -- enter room
463                                 local new_nick = to;
464                                 local is_merge;
465                                 if self._occupants[to] then
466                                         if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
467                                                 new_nick = nil;
468                                         end
469                                         is_merge = true;
470                                 end
471                                 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
472                                 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
473                                 password = password and password[1] ~= "" and password[1];
474                                 if self:get_password() and self:get_password() ~= password then
475                                         log("debug", "%s couldn't join due to invalid password: %s", from, to);
476                                         local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
477                                         reply.tags[1].attr.code = "401";
478                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
479                                 elseif not new_nick then
480                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
481                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
482                                         reply.tags[1].attr.code = "409";
483                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
484                                 else
485                                         log("debug", "%s joining as %s", from, to);
486                                         if not next(self._affiliations) then -- new room, no owners
487                                                 self._affiliations[jid_bare(from)] = "owner";
488                                                 if self.locked and not stanza:get_child("x", "http://jabber.org/protocol/muc") then
489                                                         self.locked = nil; -- Older groupchat protocol doesn't lock
490                                                 end
491                                         elseif self.locked then -- Deny entry
492                                                 origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
493                                                 return;
494                                         end
495                                         local affiliation = self:get_affiliation(from);
496                                         local role = self:get_default_role(affiliation)
497                                         if role then -- new occupant
498                                                 if not is_merge then
499                                                         self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
500                                                 else
501                                                         self._occupants[to].sessions[from] = get_filtered_presence(stanza);
502                                                 end
503                                                 self._jid_nick[from] = to;
504                                                 self:send_occupant_list(from);
505                                                 pr.attr.from = to;
506                                                 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
507                                                         :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
508                                                 if not is_merge then
509                                                         self:broadcast_except_nick(pr, to);
510                                                 end
511                                                 pr:tag("status", {code='110'}):up();
512                                                 if self._data.whois == 'anyone' then
513                                                         pr:tag("status", {code='100'}):up();
514                                                 end
515                                                 if self.locked then
516                                                         pr:tag("status", {code='201'}):up();
517                                                 end
518                                                 pr.attr.to = from;
519                                                 self:_route_stanza(pr);
520                                                 self:send_history(from, stanza);
521                                                 self:send_subject(from);
522                                         elseif not affiliation then -- registration required for entering members-only room
523                                                 local reply = st.error_reply(stanza, "auth", "registration-required"):up();
524                                                 reply.tags[1].attr.code = "407";
525                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
526                                         else -- banned
527                                                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
528                                                 reply.tags[1].attr.code = "403";
529                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
530                                         end
531                                 end
532                         end
533                 elseif type ~= 'result' then -- bad type
534                         if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
535                                 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
536                         end
537                 end
538         elseif not current_nick then -- not in room
539                 if (type == "error" or type == "result") and stanza.name == "iq" then
540                         local id = stanza.attr.id;
541                         stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
542                         if stanza.attr.id then
543                                 self:_route_stanza(stanza);
544                         end
545                         stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
546                 elseif type ~= "error" then
547                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
548                 end
549         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
550                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
551         elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
552                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
553                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
554         else -- private stanza
555                 local o_data = self._occupants[to];
556                 if o_data then
557                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
558                         if stanza.name == "iq" then
559                                 local id = stanza.attr.id;
560                                 if stanza.attr.type == "get" or stanza.attr.type == "set" then
561                                         stanza.attr.from, stanza.attr.to, stanza.attr.id = construct_stanza_id(self, stanza);
562                                 else
563                                         stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
564                                 end
565                                 if type == 'get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then
566                                         stanza.attr.to = jid_bare(stanza.attr.to);
567                                 end
568                                 if stanza.attr.id then
569                                         self:_route_stanza(stanza);
570                                 end
571                                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
572                         else -- message
573                                 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
574                                 stanza.attr.from = current_nick;
575                                 for jid in pairs(o_data.sessions) do
576                                         stanza.attr.to = jid;
577                                         self:_route_stanza(stanza);
578                                 end
579                                 stanza.attr.from, stanza.attr.to = from, to;
580                         end
581                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
582                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
583                 end
584         end
585 end
586
587 function room_mt:send_form(origin, stanza)
588         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
589                 :add_child(self:get_form_layout(stanza.attr.from):form())
590         );
591 end
592
593 function room_mt:get_form_layout(actor)
594         local form = dataform.new({
595                 title = "Configuration for "..self.jid,
596                 instructions = "Complete and submit this form to configure the room.",
597                 {
598                         name = 'FORM_TYPE',
599                         type = 'hidden',
600                         value = 'http://jabber.org/protocol/muc#roomconfig'
601                 },
602                 {
603                         name = 'muc#roomconfig_roomname',
604                         type = 'text-single',
605                         label = 'Name',
606                         value = self:get_name() or "",
607                 },
608                 {
609                         name = 'muc#roomconfig_roomdesc',
610                         type = 'text-single',
611                         label = 'Description',
612                         value = self:get_description() or "",
613                 },
614                 {
615                         name = 'muc#roomconfig_persistentroom',
616                         type = 'boolean',
617                         label = 'Make Room Persistent?',
618                         value = self:get_persistent()
619                 },
620                 {
621                         name = 'muc#roomconfig_publicroom',
622                         type = 'boolean',
623                         label = 'Make Room Publicly Searchable?',
624                         value = not self:get_hidden()
625                 },
626                 {
627                         name = 'muc#roomconfig_changesubject',
628                         type = 'boolean',
629                         label = 'Allow Occupants to Change Subject?',
630                         value = self:get_changesubject()
631                 },
632                 {
633                         name = 'muc#roomconfig_whois',
634                         type = 'list-single',
635                         label = 'Who May Discover Real JIDs?',
636                         value = {
637                                 { value = 'moderators', label = 'Moderators Only', default = self._data.whois == 'moderators' },
638                                 { value = 'anyone',     label = 'Anyone',          default = self._data.whois == 'anyone' }
639                         }
640                 },
641                 {
642                         name = 'muc#roomconfig_roomsecret',
643                         type = 'text-private',
644                         label = 'Password',
645                         value = self:get_password() or "",
646                 },
647                 {
648                         name = 'muc#roomconfig_moderatedroom',
649                         type = 'boolean',
650                         label = 'Make Room Moderated?',
651                         value = self:get_moderated()
652                 },
653                 {
654                         name = 'muc#roomconfig_membersonly',
655                         type = 'boolean',
656                         label = 'Make Room Members-Only?',
657                         value = self:get_members_only()
658                 },
659                 {
660                         name = 'muc#roomconfig_historylength',
661                         type = 'text-single',
662                         label = 'Maximum Number of History Messages Returned by Room',
663                         value = tostring(self:get_historylength())
664                 }
665         });
666         return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
667 end
668
669 function room_mt:process_form(origin, stanza)
670         local query = stanza.tags[1];
671         local form;
672         for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
673         if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
674         if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
675         if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
676
677         local fields = self:get_form_layout(stanza.attr.from):data(form);
678         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration")); return; end
679
680
681         local changed = {};
682
683         local function handle_option(name, field, allowed)
684                 local new = fields[field];
685                 if new == nil then return; end
686                 if allowed and not allowed[new] then return; end
687                 if new == self["get_"..name](self) then return; end
688                 changed[name] = true;
689                 self["set_"..name](self, new);
690         end
691
692         local event = { room = self, fields = fields, changed = changed, stanza = stanza, origin = origin, update_option = handle_option };
693         module:fire_event("muc-config-submitted", event);
694
695         handle_option("name", "muc#roomconfig_roomname");
696         handle_option("description", "muc#roomconfig_roomdesc");
697         handle_option("persistent", "muc#roomconfig_persistentroom");
698         handle_option("moderated", "muc#roomconfig_moderatedroom");
699         handle_option("members_only", "muc#roomconfig_membersonly");
700         handle_option("public", "muc#roomconfig_publicroom");
701         handle_option("changesubject", "muc#roomconfig_changesubject");
702         handle_option("historylength", "muc#roomconfig_historylength");
703         handle_option("whois", "muc#roomconfig_whois", valid_whois);
704         handle_option("password", "muc#roomconfig_roomsecret");
705
706         if self.save then self:save(true); end
707         if self.locked then
708                 module:fire_event("muc-room-unlocked", { room = self });
709                 self.locked = nil;
710         end
711         origin.send(st.reply(stanza));
712
713         if next(changed) then
714                 local msg = st.message({type='groupchat', from=self.jid})
715                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
716                                 :tag('status', {code = '104'}):up();
717                 if changed.whois then
718                         local code = (self:get_whois() == 'moderators') and "173" or "172";
719                         msg.tags[1]:tag('status', {code = code}):up();
720                 end
721                 self:broadcast_message(msg, false)
722         end
723 end
724
725 function room_mt:destroy(newjid, reason, password)
726         local pr = st.presence({type = "unavailable"})
727                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
728                         :tag("item", { affiliation='none', role='none' }):up()
729                         :tag("destroy", {jid=newjid})
730         if reason then pr:tag("reason"):text(reason):up(); end
731         if password then pr:tag("password"):text(password):up(); end
732         for nick, occupant in pairs(self._occupants) do
733                 pr.attr.from = nick;
734                 for jid in pairs(occupant.sessions) do
735                         pr.attr.to = jid;
736                         self:_route_stanza(pr);
737                         self._jid_nick[jid] = nil;
738                 end
739                 self._occupants[nick] = nil;
740         end
741         self:set_persistent(false);
742         module:fire_event("muc-room-destroyed", { room = self });
743 end
744
745 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
746         local type = stanza.attr.type;
747         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
748         if stanza.name == "iq" then
749                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" and not stanza.tags[1].attr.node then
750                         origin.send(self:get_disco_info(stanza));
751                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" and not stanza.tags[1].attr.node then
752                         origin.send(self:get_disco_items(stanza));
753                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
754                         local actor = stanza.attr.from;
755                         local affiliation = self:get_affiliation(actor);
756                         local current_nick = self._jid_nick[actor];
757                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
758                         local item = stanza.tags[1].tags[1];
759                         if item and item.name == "item" then
760                                 if type == "set" then
761                                         local callback = function() origin.send(st.reply(stanza)); end
762                                         if item.attr.jid then -- Validate provided JID
763                                                 item.attr.jid = jid_prep(item.attr.jid);
764                                                 if not item.attr.jid then
765                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
766                                                         return;
767                                                 end
768                                         end
769                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
770                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
771                                                 if occupant then item.attr.jid = occupant.jid; end
772                                         elseif not item.attr.nick and item.attr.jid then
773                                                 local nick = self._jid_nick[item.attr.jid];
774                                                 if nick then item.attr.nick = select(3, jid_split(nick)); end
775                                         end
776                                         local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
777                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
778                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
779                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
780                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
781                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
782                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
783                                         else
784                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
785                                         end
786                                 elseif type == "get" then
787                                         local _aff = item.attr.affiliation;
788                                         local _rol = item.attr.role;
789                                         if _aff and not _rol then
790                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
791                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
792                                                         for jid, affiliation in pairs(self._affiliations) do
793                                                                 if affiliation == _aff then
794                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
795                                                                 end
796                                                         end
797                                                         origin.send(reply);
798                                                 else
799                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
800                                                 end
801                                         elseif _rol and not _aff then
802                                                 if role == "moderator" then
803                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
804                                                         if _rol == "none" then _rol = nil; end
805                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
806                                                         for occupant_jid, occupant in pairs(self._occupants) do
807                                                                 if occupant.role == _rol then
808                                                                         reply:tag("item", {
809                                                                                 nick = select(3, jid_split(occupant_jid)),
810                                                                                 role = _rol or "none",
811                                                                                 affiliation = occupant.affiliation or "none",
812                                                                                 jid = occupant.jid
813                                                                                 }):up();
814                                                                 end
815                                                         end
816                                                         origin.send(reply);
817                                                 else
818                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
819                                                 end
820                                         else
821                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
822                                         end
823                                 end
824                         elseif type == "set" or type == "get" then
825                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
826                         end
827                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
828                         if self:get_affiliation(stanza.attr.from) ~= "owner" then
829                                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
830                         elseif stanza.attr.type == "get" then
831                                 self:send_form(origin, stanza);
832                         elseif stanza.attr.type == "set" then
833                                 local child = stanza.tags[1].tags[1];
834                                 if not child then
835                                         origin.send(st.error_reply(stanza, "modify", "bad-request"));
836                                 elseif child.name == "destroy" then
837                                         local newjid = child.attr.jid;
838                                         local reason, password;
839                                         for _,tag in ipairs(child.tags) do
840                                                 if tag.name == "reason" then
841                                                         reason = #tag.tags == 0 and tag[1];
842                                                 elseif tag.name == "password" then
843                                                         password = #tag.tags == 0 and tag[1];
844                                                 end
845                                         end
846                                         self:destroy(newjid, reason, password);
847                                         origin.send(st.reply(stanza));
848                                 else
849                                         self:process_form(origin, stanza);
850                                 end
851                         end
852                 elseif type == "set" or type == "get" then
853                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
854                 end
855         elseif stanza.name == "message" and type == "groupchat" then
856                 local from = stanza.attr.from;
857                 local current_nick = self._jid_nick[from];
858                 local occupant = self._occupants[current_nick];
859                 if not occupant then -- not in room
860                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
861                 elseif occupant.role == "visitor" then
862                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
863                 else
864                         local from = stanza.attr.from;
865                         stanza.attr.from = current_nick;
866                         local subject = stanza:get_child_text("subject");
867                         if subject then
868                                 if occupant.role == "moderator" or
869                                         ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
870                                         self:set_subject(current_nick, subject);
871                                 else
872                                         stanza.attr.from = from;
873                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
874                                 end
875                         else
876                                 self:broadcast_message(stanza, self:get_historylength() > 0 and stanza:get_child("body"));
877                         end
878                         stanza.attr.from = from;
879                 end
880         elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
881                 local current_nick = self._jid_nick[stanza.attr.from];
882                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
883                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
884         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
885                 local to = stanza.attr.to;
886                 local current_nick = self._jid_nick[stanza.attr.from];
887                 if current_nick then
888                         stanza.attr.to = current_nick;
889                         self:handle_to_occupant(origin, stanza);
890                         stanza.attr.to = to;
891                 elseif type ~= "error" and type ~= "result" then
892                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
893                 end
894         elseif stanza.name == "message" and not(type == "chat" or type == "error" or type == "groupchat" or type == "headline") and #stanza.tags == 1
895                 and self._jid_nick[stanza.attr.from] and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
896                 local x = stanza.tags[1];
897                 local payload = (#x.tags == 1 and x.tags[1]);
898                 if payload and payload.name == "invite" and payload.attr.to then
899                         local _from, _to = stanza.attr.from, stanza.attr.to;
900                         local _invitee = jid_prep(payload.attr.to);
901                         if _invitee then
902                                 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
903                                 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
904                                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
905                                                 :tag('invite', {from=_from})
906                                                         :tag('reason'):text(_reason or ""):up()
907                                                 :up();
908                                                 if self:get_password() then
909                                                         invite:tag("password"):text(self:get_password()):up();
910                                                 end
911                                         invite:up()
912                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
913                                                 :text(_reason or "")
914                                         :up()
915                                         :tag('body') -- Add a plain message for clients which don't support invites
916                                                 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
917                                         :up();
918                                 if self:get_members_only() and not self:get_affiliation(_invitee) then
919                                         log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
920                                         self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
921                                 end
922                                 self:_route_stanza(invite);
923                         else
924                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
925                         end
926                 else
927                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
928                 end
929         else
930                 if type == "error" or type == "result" then return; end
931                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
932         end
933 end
934
935 function room_mt:handle_stanza(origin, stanza)
936         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
937         if to_resource then
938                 self:handle_to_occupant(origin, stanza);
939         else
940                 self:handle_to_room(origin, stanza);
941         end
942 end
943
944 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
945
946 function room_mt:get_affiliation(jid)
947         local node, host, resource = jid_split(jid);
948         local bare = node and node.."@"..host or host;
949         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
950         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
951         return result;
952 end
953 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
954         jid = jid_bare(jid);
955         if affiliation == "none" then affiliation = nil; end
956         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
957                 return nil, "modify", "not-acceptable";
958         end
959         if actor ~= true then
960                 local actor_affiliation = self:get_affiliation(actor);
961                 local target_affiliation = self:get_affiliation(jid);
962                 if target_affiliation == affiliation then -- no change, shortcut
963                         if callback then callback(); end
964                         return true;
965                 end
966                 if actor_affiliation ~= "owner" then
967                         if affiliation == "owner" or affiliation == "admin" or actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
968                                 return nil, "cancel", "not-allowed";
969                         end
970                 elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
971                         local is_last = true;
972                         for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
973                         if is_last then
974                                 return nil, "cancel", "conflict";
975                         end
976                 end
977         end
978         self._affiliations[jid] = affiliation;
979         local role = self:get_default_role(affiliation);
980         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
981                         :tag("item", {affiliation=affiliation or "none", role=role or "none"})
982                                 :tag("reason"):text(reason or ""):up()
983                         :up();
984         local presence_type = nil;
985         if not role then -- getting kicked
986                 presence_type = "unavailable";
987                 if affiliation == "outcast" then
988                         x:tag("status", {code="301"}):up(); -- banned
989                 else
990                         x:tag("status", {code="321"}):up(); -- affiliation change
991                 end
992         end
993         local modified_nicks = {};
994         for nick, occupant in pairs(self._occupants) do
995                 if jid_bare(occupant.jid) == jid then
996                         if not role then -- getting kicked
997                                 self._occupants[nick] = nil;
998                         else
999                                 occupant.affiliation, occupant.role = affiliation, role;
1000                         end
1001                         for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
1002                                 if not role then self._jid_nick[jid] = nil; end
1003                                 local p = st.clone(pres);
1004                                 p.attr.from = nick;
1005                                 p.attr.type = presence_type;
1006                                 p.attr.to = jid;
1007                                 p:add_child(x);
1008                                 self:_route_stanza(p);
1009                                 if occupant.jid == jid then
1010                                         modified_nicks[nick] = p;
1011                                 end
1012                         end
1013                 end
1014         end
1015         if self.save then self:save(); end
1016         if callback then callback(); end
1017         for nick,p in pairs(modified_nicks) do
1018                 p.attr.from = nick;
1019                 self:broadcast_except_nick(p, nick);
1020         end
1021         return true;
1022 end
1023
1024 function room_mt:get_role(nick)
1025         local session = self._occupants[nick];
1026         return session and session.role or nil;
1027 end
1028 function room_mt:can_set_role(actor_jid, occupant_jid, role)
1029         local occupant = self._occupants[occupant_jid];
1030         if not occupant or not actor_jid then return nil, "modify", "not-acceptable"; end
1031
1032         if actor_jid == true then return true; end
1033
1034         local actor = self._occupants[self._jid_nick[actor_jid]];
1035         if actor and actor.role == "moderator" then
1036                 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
1037                         if actor.affiliation == "owner" or actor.affiliation == "admin" then
1038                                 return true;
1039                         elseif occupant.role ~= "moderator" and role ~= "moderator" then
1040                                 return true;
1041                         end
1042                 end
1043         end
1044         return nil, "cancel", "not-allowed";
1045 end
1046 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
1047         if role == "none" then role = nil; end
1048         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
1049         local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
1050         if not allowed then return allowed, err_type, err_condition; end
1051         local occupant = self._occupants[occupant_jid];
1052         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1053                         :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
1054                                 :tag("reason"):text(reason or ""):up()
1055                         :up();
1056         local presence_type = nil;
1057         if not role then -- kick
1058                 presence_type = "unavailable";
1059                 self._occupants[occupant_jid] = nil;
1060                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
1061                         self._jid_nick[jid] = nil;
1062                 end
1063                 x:tag("status", {code = "307"}):up();
1064         else
1065                 occupant.role = role;
1066         end
1067         local bp;
1068         for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
1069                 local p = st.clone(pres);
1070                 p.attr.from = occupant_jid;
1071                 p.attr.type = presence_type;
1072                 p.attr.to = jid;
1073                 p:add_child(x);
1074                 self:_route_stanza(p);
1075                 if occupant.jid == jid then
1076                         bp = p;
1077                 end
1078         end
1079         if callback then callback(); end
1080         if bp then
1081                 self:broadcast_except_nick(bp, occupant_jid);
1082         end
1083         return true;
1084 end
1085
1086 function room_mt:_route_stanza(stanza)
1087         local muc_child;
1088         local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1089         local from_occupant = self._occupants[stanza.attr.from];
1090         if stanza.name == "presence" then
1091                 if to_occupant and from_occupant then
1092                         if self._data.whois == 'anyone' then
1093                             muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1094                         else
1095                                 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1096                                         muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1097                                 end
1098                         end
1099                 end
1100         end
1101         if muc_child then
1102                 for _, item in pairs(muc_child.tags) do
1103                         if item.name == "item" then
1104                                 if from_occupant == to_occupant then
1105                                         item.attr.jid = stanza.attr.to;
1106                                 else
1107                                         item.attr.jid = from_occupant.jid;
1108                                 end
1109                         end
1110                 end
1111         end
1112         self:route_stanza(stanza);
1113         if muc_child then
1114                 for _, item in pairs(muc_child.tags) do
1115                         if item.name == "item" then
1116                                 item.attr.jid = nil;
1117                         end
1118                 end
1119         end
1120 end
1121
1122 local _M = {}; -- module "muc"
1123
1124 function _M.new_room(jid, config)
1125         return setmetatable({
1126                 jid = jid;
1127                 _jid_nick = {};
1128                 _occupants = {};
1129                 _data = {
1130                     whois = 'moderators';
1131                     history_length = math.min((config and config.history_length)
1132                         or default_history_length, max_history_length);
1133                 };
1134                 _affiliations = {};
1135         }, room_mt);
1136 end
1137
1138 function _M.set_max_history_length(_max_history_length)
1139         max_history_length = _max_history_length or math.huge;
1140 end
1141
1142 _M.room_mt = room_mt;
1143
1144 return _M;