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