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