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(%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, errors, present = self:get_form_layout(stanza.attr.from):data(form);
678         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
679                 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
680                 return;
681         end
682
683         local changed = {};
684
685         local function handle_option(name, field, allowed)
686                 if not present[field] then return; end
687                 local new = fields[field];
688                 if allowed and not allowed[new] then return; end
689                 if new == self["get_"..name](self) then return; end
690                 changed[name] = true;
691                 self["set_"..name](self, new);
692         end
693
694         local event = { room = self, fields = fields, changed = changed, stanza = stanza, origin = origin, update_option = handle_option };
695         module:fire_event("muc-config-submitted", event);
696
697         handle_option("name", "muc#roomconfig_roomname");
698         handle_option("description", "muc#roomconfig_roomdesc");
699         handle_option("persistent", "muc#roomconfig_persistentroom");
700         handle_option("moderated", "muc#roomconfig_moderatedroom");
701         handle_option("members_only", "muc#roomconfig_membersonly");
702         handle_option("public", "muc#roomconfig_publicroom");
703         handle_option("changesubject", "muc#roomconfig_changesubject");
704         handle_option("historylength", "muc#roomconfig_historylength");
705         handle_option("whois", "muc#roomconfig_whois", valid_whois);
706         handle_option("password", "muc#roomconfig_roomsecret");
707
708         if self.save then self:save(true); end
709         if self.locked then
710                 module:fire_event("muc-room-unlocked", { room = self });
711                 self.locked = nil;
712         end
713         origin.send(st.reply(stanza));
714
715         if next(changed) then
716                 local msg = st.message({type='groupchat', from=self.jid})
717                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
718                                 :tag('status', {code = '104'}):up();
719                 if changed.whois then
720                         local code = (self:get_whois() == 'moderators') and "173" or "172";
721                         msg.tags[1]:tag('status', {code = code}):up();
722                 end
723                 self:broadcast_message(msg, false)
724         end
725 end
726
727 function room_mt:destroy(newjid, reason, password)
728         local pr = st.presence({type = "unavailable"})
729                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
730                         :tag("item", { affiliation='none', role='none' }):up()
731                         :tag("destroy", {jid=newjid})
732         if reason then pr:tag("reason"):text(reason):up(); end
733         if password then pr:tag("password"):text(password):up(); end
734         for nick, occupant in pairs(self._occupants) do
735                 pr.attr.from = nick;
736                 for jid in pairs(occupant.sessions) do
737                         pr.attr.to = jid;
738                         self:_route_stanza(pr);
739                         self._jid_nick[jid] = nil;
740                 end
741                 self._occupants[nick] = nil;
742         end
743         self:set_persistent(false);
744         module:fire_event("muc-room-destroyed", { room = self });
745 end
746
747 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
748         local type = stanza.attr.type;
749         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
750         if stanza.name == "iq" then
751                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" and not stanza.tags[1].attr.node then
752                         origin.send(self:get_disco_info(stanza));
753                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" and not stanza.tags[1].attr.node then
754                         origin.send(self:get_disco_items(stanza));
755                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
756                         local actor = stanza.attr.from;
757                         local affiliation = self:get_affiliation(actor);
758                         local current_nick = self._jid_nick[actor];
759                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
760                         local item = stanza.tags[1].tags[1];
761                         if item and item.name == "item" then
762                                 if type == "set" then
763                                         local callback = function() origin.send(st.reply(stanza)); end
764                                         if item.attr.jid then -- Validate provided JID
765                                                 item.attr.jid = jid_prep(item.attr.jid);
766                                                 if not item.attr.jid then
767                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
768                                                         return;
769                                                 end
770                                         end
771                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
772                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
773                                                 if occupant then item.attr.jid = occupant.jid; end
774                                         elseif not item.attr.nick and item.attr.jid then
775                                                 local nick = self._jid_nick[item.attr.jid];
776                                                 if nick then item.attr.nick = select(3, jid_split(nick)); end
777                                         end
778                                         local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
779                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
780                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
781                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
782                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
783                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
784                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
785                                         else
786                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
787                                         end
788                                 elseif type == "get" then
789                                         local _aff = item.attr.affiliation;
790                                         local _rol = item.attr.role;
791                                         if _aff and not _rol then
792                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
793                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
794                                                         for jid, affiliation in pairs(self._affiliations) do
795                                                                 if affiliation == _aff then
796                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
797                                                                 end
798                                                         end
799                                                         origin.send(reply);
800                                                 else
801                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
802                                                 end
803                                         elseif _rol and not _aff then
804                                                 if role == "moderator" then
805                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
806                                                         if _rol == "none" then _rol = nil; end
807                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
808                                                         for occupant_jid, occupant in pairs(self._occupants) do
809                                                                 if occupant.role == _rol then
810                                                                         reply:tag("item", {
811                                                                                 nick = select(3, jid_split(occupant_jid)),
812                                                                                 role = _rol or "none",
813                                                                                 affiliation = occupant.affiliation or "none",
814                                                                                 jid = occupant.jid
815                                                                                 }):up();
816                                                                 end
817                                                         end
818                                                         origin.send(reply);
819                                                 else
820                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
821                                                 end
822                                         else
823                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
824                                         end
825                                 end
826                         elseif type == "set" or type == "get" then
827                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
828                         end
829                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
830                         if self:get_affiliation(stanza.attr.from) ~= "owner" then
831                                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
832                         elseif stanza.attr.type == "get" then
833                                 self:send_form(origin, stanza);
834                         elseif stanza.attr.type == "set" then
835                                 local child = stanza.tags[1].tags[1];
836                                 if not child then
837                                         origin.send(st.error_reply(stanza, "modify", "bad-request"));
838                                 elseif child.name == "destroy" then
839                                         local newjid = child.attr.jid;
840                                         local reason, password;
841                                         for _,tag in ipairs(child.tags) do
842                                                 if tag.name == "reason" then
843                                                         reason = #tag.tags == 0 and tag[1];
844                                                 elseif tag.name == "password" then
845                                                         password = #tag.tags == 0 and tag[1];
846                                                 end
847                                         end
848                                         self:destroy(newjid, reason, password);
849                                         origin.send(st.reply(stanza));
850                                 else
851                                         self:process_form(origin, stanza);
852                                 end
853                         end
854                 elseif type == "set" or type == "get" then
855                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
856                 end
857         elseif stanza.name == "message" and type == "groupchat" then
858                 local from = stanza.attr.from;
859                 local current_nick = self._jid_nick[from];
860                 local occupant = self._occupants[current_nick];
861                 if not occupant then -- not in room
862                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
863                 elseif occupant.role == "visitor" then
864                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
865                 else
866                         local from = stanza.attr.from;
867                         stanza.attr.from = current_nick;
868                         local subject = stanza:get_child_text("subject");
869                         if subject then
870                                 if occupant.role == "moderator" or
871                                         ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
872                                         self:set_subject(current_nick, subject);
873                                 else
874                                         stanza.attr.from = from;
875                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
876                                 end
877                         else
878                                 self:broadcast_message(stanza, self:get_historylength() > 0 and stanza:get_child("body"));
879                         end
880                         stanza.attr.from = from;
881                 end
882         elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
883                 local current_nick = self._jid_nick[stanza.attr.from];
884                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
885                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
886         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
887                 local to = stanza.attr.to;
888                 local current_nick = self._jid_nick[stanza.attr.from];
889                 if current_nick then
890                         stanza.attr.to = current_nick;
891                         self:handle_to_occupant(origin, stanza);
892                         stanza.attr.to = to;
893                 elseif type ~= "error" and type ~= "result" then
894                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
895                 end
896         elseif stanza.name == "message" and not(type == "chat" or type == "error" or type == "groupchat" or type == "headline") and #stanza.tags == 1
897                 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
898                 local x = stanza.tags[1];
899                 local payload = (#x.tags == 1 and x.tags[1]);
900                 if payload and payload.name == "invite" and payload.attr.to then
901                         local _from, _to = stanza.attr.from, stanza.attr.to;
902                         local _invitee = jid_prep(payload.attr.to);
903                         if _invitee then
904                                 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
905                                 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
906                                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
907                                                 :tag('invite', {from=_from})
908                                                         :tag('reason'):text(_reason or ""):up()
909                                                 :up();
910                                                 if self:get_password() then
911                                                         invite:tag("password"):text(self:get_password()):up();
912                                                 end
913                                         invite:up()
914                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
915                                                 :text(_reason or "")
916                                         :up()
917                                         :tag('body') -- Add a plain message for clients which don't support invites
918                                                 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
919                                         :up();
920                                 if self:get_members_only() and not self:get_affiliation(_invitee) then
921                                         log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
922                                         self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
923                                 end
924                                 self:_route_stanza(invite);
925                         else
926                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
927                         end
928                 else
929                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
930                 end
931         else
932                 if type == "error" or type == "result" then return; end
933                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
934         end
935 end
936
937 function room_mt:handle_stanza(origin, stanza)
938         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
939         if to_resource then
940                 self:handle_to_occupant(origin, stanza);
941         else
942                 self:handle_to_room(origin, stanza);
943         end
944 end
945
946 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
947
948 function room_mt:get_affiliation(jid)
949         local node, host, resource = jid_split(jid);
950         local bare = node and node.."@"..host or host;
951         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
952         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
953         return result;
954 end
955 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
956         jid = jid_bare(jid);
957         if affiliation == "none" then affiliation = nil; end
958         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
959                 return nil, "modify", "not-acceptable";
960         end
961         if actor ~= true then
962                 local actor_affiliation = self:get_affiliation(actor);
963                 local target_affiliation = self:get_affiliation(jid);
964                 if target_affiliation == affiliation then -- no change, shortcut
965                         if callback then callback(); end
966                         return true;
967                 end
968                 if actor_affiliation ~= "owner" then
969                         if affiliation == "owner" or affiliation == "admin" or actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
970                                 return nil, "cancel", "not-allowed";
971                         end
972                 elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
973                         local is_last = true;
974                         for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
975                         if is_last then
976                                 return nil, "cancel", "conflict";
977                         end
978                 end
979         end
980         self._affiliations[jid] = affiliation;
981         local role = self:get_default_role(affiliation);
982         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
983                         :tag("item", {affiliation=affiliation or "none", role=role or "none"})
984                                 :tag("reason"):text(reason or ""):up()
985                         :up();
986         local presence_type = nil;
987         if not role then -- getting kicked
988                 presence_type = "unavailable";
989                 if affiliation == "outcast" then
990                         x:tag("status", {code="301"}):up(); -- banned
991                 else
992                         x:tag("status", {code="321"}):up(); -- affiliation change
993                 end
994         end
995         local modified_nicks = {};
996         for nick, occupant in pairs(self._occupants) do
997                 if jid_bare(occupant.jid) == jid then
998                         if not role then -- getting kicked
999                                 self._occupants[nick] = nil;
1000                         else
1001                                 occupant.affiliation, occupant.role = affiliation, role;
1002                         end
1003                         for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
1004                                 if not role then self._jid_nick[jid] = nil; end
1005                                 local p = st.clone(pres);
1006                                 p.attr.from = nick;
1007                                 p.attr.type = presence_type;
1008                                 p.attr.to = jid;
1009                                 p:add_child(x);
1010                                 self:_route_stanza(p);
1011                                 if occupant.jid == jid then
1012                                         modified_nicks[nick] = p;
1013                                 end
1014                         end
1015                 end
1016         end
1017         if self.save then self:save(); end
1018         if callback then callback(); end
1019         for nick,p in pairs(modified_nicks) do
1020                 p.attr.from = nick;
1021                 self:broadcast_except_nick(p, nick);
1022         end
1023         return true;
1024 end
1025
1026 function room_mt:get_role(nick)
1027         local session = self._occupants[nick];
1028         return session and session.role or nil;
1029 end
1030 function room_mt:can_set_role(actor_jid, occupant_jid, role)
1031         local occupant = self._occupants[occupant_jid];
1032         if not occupant or not actor_jid then return nil, "modify", "not-acceptable"; end
1033
1034         if actor_jid == true then return true; end
1035
1036         local actor = self._occupants[self._jid_nick[actor_jid]];
1037         if actor and actor.role == "moderator" then
1038                 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
1039                         if actor.affiliation == "owner" or actor.affiliation == "admin" then
1040                                 return true;
1041                         elseif occupant.role ~= "moderator" and role ~= "moderator" then
1042                                 return true;
1043                         end
1044                 end
1045         end
1046         return nil, "cancel", "not-allowed";
1047 end
1048 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
1049         if role == "none" then role = nil; end
1050         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
1051         local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
1052         if not allowed then return allowed, err_type, err_condition; end
1053         local occupant = self._occupants[occupant_jid];
1054         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1055                         :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
1056                                 :tag("reason"):text(reason or ""):up()
1057                         :up();
1058         local presence_type = nil;
1059         if not role then -- kick
1060                 presence_type = "unavailable";
1061                 self._occupants[occupant_jid] = nil;
1062                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
1063                         self._jid_nick[jid] = nil;
1064                 end
1065                 x:tag("status", {code = "307"}):up();
1066         else
1067                 occupant.role = role;
1068         end
1069         local bp;
1070         for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
1071                 local p = st.clone(pres);
1072                 p.attr.from = occupant_jid;
1073                 p.attr.type = presence_type;
1074                 p.attr.to = jid;
1075                 p:add_child(x);
1076                 self:_route_stanza(p);
1077                 if occupant.jid == jid then
1078                         bp = p;
1079                 end
1080         end
1081         if callback then callback(); end
1082         if bp then
1083                 self:broadcast_except_nick(bp, occupant_jid);
1084         end
1085         return true;
1086 end
1087
1088 function room_mt:_route_stanza(stanza)
1089         local muc_child;
1090         local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1091         local from_occupant = self._occupants[stanza.attr.from];
1092         if stanza.name == "presence" then
1093                 if to_occupant and from_occupant then
1094                         if self._data.whois == 'anyone' then
1095                             muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1096                         else
1097                                 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1098                                         muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1099                                 end
1100                         end
1101                 end
1102         end
1103         if muc_child then
1104                 for _, item in pairs(muc_child.tags) do
1105                         if item.name == "item" then
1106                                 if from_occupant == to_occupant then
1107                                         item.attr.jid = stanza.attr.to;
1108                                 else
1109                                         item.attr.jid = from_occupant.jid;
1110                                 end
1111                         end
1112                 end
1113         end
1114         self:route_stanza(stanza);
1115         if muc_child then
1116                 for _, item in pairs(muc_child.tags) do
1117                         if item.name == "item" then
1118                                 item.attr.jid = nil;
1119                         end
1120                 end
1121         end
1122 end
1123
1124 local _M = {}; -- module "muc"
1125
1126 function _M.new_room(jid, config)
1127         return setmetatable({
1128                 jid = jid;
1129                 _jid_nick = {};
1130                 _occupants = {};
1131                 _data = {
1132                     whois = 'moderators';
1133                     history_length = math.min((config and config.history_length)
1134                         or default_history_length, max_history_length);
1135                 };
1136                 _affiliations = {};
1137         }, room_mt);
1138 end
1139
1140 function _M.set_max_history_length(_max_history_length)
1141         max_history_length = _max_history_length or math.huge;
1142 end
1143
1144 _M.room_mt = room_mt;
1145
1146 return _M;