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