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