Merge 0.10->trunk
[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 local next = next;
13 local setmetatable = setmetatable;
14
15 local dataform = require "util.dataforms";
16 local iterators = require "util.iterators";
17 local jid_split = require "util.jid".split;
18 local jid_bare = require "util.jid".bare;
19 local jid_prep = require "util.jid".prep;
20 local jid_join = require "util.jid".join;
21 local st = require "util.stanza";
22 local log = require "util.logger".init("mod_muc");
23 local base64 = require "util.encodings".base64;
24 local md5 = require "util.hashes".md5;
25
26 local occupant_lib = module:require "muc/occupant"
27 local muc_util = module:require "muc/util";
28 local is_kickable_error = muc_util.is_kickable_error;
29 local valid_roles, valid_affiliations = muc_util.valid_roles, muc_util.valid_affiliations;
30
31 local room_mt = {};
32 room_mt.__index = room_mt;
33
34 function room_mt:__tostring()
35         return "MUC room ("..self.jid..")";
36 end
37
38 function room_mt:get_occupant_jid(real_jid)
39         return self._jid_nick[real_jid]
40 end
41
42 function room_mt:get_default_role(affiliation)
43         local role = module:fire_event("muc-get-default-role", {
44                 room = self;
45                 affiliation = affiliation;
46                 affiliation_rank = valid_affiliations[affiliation or "none"];
47         });
48         return role, valid_roles[role or "none"];
49 end
50 module:hook("muc-get-default-role", function(event)
51         if event.affiliation_rank >= valid_affiliations.admin then
52                 return "moderator";
53         elseif event.affiliation_rank >= valid_affiliations.none then
54                 return "participant";
55         end
56 end);
57
58 --- Occupant functions
59 function room_mt:new_occupant(bare_real_jid, nick)
60         local occupant = occupant_lib.new(bare_real_jid, nick);
61         local affiliation = self:get_affiliation(bare_real_jid);
62         occupant.role = self:get_default_role(affiliation);
63         return occupant;
64 end
65
66 function room_mt:get_occupant_by_nick(nick)
67         local occupant = self._occupants[nick];
68         if occupant == nil then return nil end
69         return occupant_lib.copy(occupant);
70 end
71
72 do
73         local function next_copied_occupant(occupants, occupant_jid)
74                 local next_occupant_jid, raw_occupant = next(occupants, occupant_jid);
75                 if next_occupant_jid == nil then return nil end
76                 return next_occupant_jid, occupant_lib.copy(raw_occupant);
77         end
78         function room_mt:each_occupant(read_only)
79                 return next_copied_occupant, self._occupants, nil;
80         end
81 end
82
83 function room_mt:has_occupant()
84         return next(self._occupants, nil) ~= nil
85 end
86
87 function room_mt:get_occupant_by_real_jid(real_jid)
88         local occupant_jid = self:get_occupant_jid(real_jid);
89         if occupant_jid == nil then return nil end
90         return self:get_occupant_by_nick(occupant_jid);
91 end
92
93 function room_mt:save_occupant(occupant)
94         occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
95         local id = occupant.nick
96
97         -- Need to maintain _jid_nick secondary index
98         local old_occupant = self._occupants[id];
99         if old_occupant then
100                 for real_jid in old_occupant:each_session() do
101                         self._jid_nick[real_jid] = nil;
102                 end
103         end
104
105         local has_live_session = false
106         if occupant.role ~= nil then
107                 for real_jid, presence in occupant:each_session() do
108                         if presence.attr.type == nil then
109                                 has_live_session = true
110                                 self._jid_nick[real_jid] = occupant.nick;
111                         end
112                 end
113                 if not has_live_session then
114                         -- Has no live sessions left; they have left the room.
115                         occupant.role = nil
116                 end
117         end
118         if not has_live_session then
119                 occupant = nil
120         end
121         self._occupants[id] = occupant
122 end
123
124 function room_mt:route_to_occupant(occupant, stanza)
125         local to = stanza.attr.to;
126         for jid, pr in occupant:each_session() do
127                 stanza.attr.to = jid;
128                 self:route_stanza(stanza);
129         end
130         stanza.attr.to = to;
131 end
132
133 -- actor is the attribute table
134 local function add_item(x, affiliation, role, jid, nick, actor_nick, actor_jid, reason)
135         x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
136         if actor_nick or actor_jid then
137                 x:tag("actor", {nick = actor_nick; jid = actor_jid;}):up()
138         end
139         if reason then
140                 x:tag("reason"):text(reason):up()
141         end
142         x:up();
143         return x
144 end
145
146 -- actor is (real) jid
147 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor_nick, actor_jid, reason)
148         local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
149         local role = occupant.role or "none";
150         if is_anonymous then
151                 add_item(x, affiliation, role, nil, nick, actor_nick, actor_jid, reason);
152         else
153                 for real_jid, session in occupant:each_session() do
154                         add_item(x, affiliation, role, real_jid, nick, actor_nick, actor_jid, reason);
155                 end
156         end
157         return x
158 end
159
160 function room_mt:broadcast_message(stanza)
161         if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
162                 return true;
163         end
164         self:broadcast(stanza);
165         return true;
166 end
167
168 -- Broadcast a stanza to all occupants in the room.
169 -- optionally checks conditional called with (nick, occupant)
170 function room_mt:broadcast(stanza, cond_func)
171         for nick, occupant in self:each_occupant() do
172                 if cond_func == nil or cond_func(nick, occupant) then
173                         self:route_to_occupant(occupant, stanza)
174                 end
175         end
176 end
177
178 local function can_see_real_jids(whois, occupant)
179         if whois == "anyone" then
180                 return true;
181         elseif whois == "moderators" then
182                 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
183         end
184 end
185
186 -- Broadcasts an occupant's presence to the whole room
187 -- Takes the x element that goes into the stanzas
188 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
189         -- Build real jid and (optionally) occupant jid template presences
190         local base_presence do
191                 -- Try to use main jid's presence
192                 local pr = occupant:get_presence();
193                 if pr and (pr.attr.type ~= "unavailable" or occupant.role == nil) then
194                         base_presence = st.clone(pr);
195                 else -- user is leaving but didn't send a leave presence. make one for them
196                         base_presence = st.presence {from = occupant.nick; type = "unavailable";};
197                 end
198         end
199
200         -- Fire event (before full_p and anon_p are created)
201         local event = {
202                 room = self; stanza = base_presence; x = base_x;
203                 occupant = occupant; nick = nick; actor = actor;
204                 reason = reason;
205         }
206         module:fire_event("muc-broadcast-presence", event);
207
208         -- Allow muc-broadcast-presence listeners to change things
209         nick = event.nick;
210         actor = event.actor;
211         reason = event.reason;
212
213         local whois = self:get_whois();
214
215         local actor_nick;
216         if actor then
217                 actor_nick = select(3, jid_split(self:get_occupant_jid(actor)));
218         end
219
220         local full_p, full_x;
221         local function get_full_p()
222                 if full_p == nil then
223                         full_x = st.clone(base_x);
224                         self:build_item_list(occupant, full_x, false, nick, actor_nick, actor, reason);
225                         full_p = st.clone(base_presence):add_child(full_x);
226                 end
227                 return full_p, full_x;
228         end
229
230         local anon_p, anon_x;
231         local function get_anon_p()
232                 if anon_p == nil then
233                         anon_x = st.clone(base_x);
234                         self:build_item_list(occupant, anon_x, true, nick, actor_nick, nil, reason);
235                         anon_p = st.clone(base_presence):add_child(anon_x);
236                 end
237                 return anon_p, anon_x;
238         end
239
240         local self_p, self_x;
241         if can_see_real_jids(whois, occupant) then
242                 self_p, self_x = get_full_p();
243         else
244                 -- Can always see your own full jids
245                 -- But not allowed to see actor's
246                 self_x = st.clone(base_x);
247                 self:build_item_list(occupant, self_x, false, nick, actor_nick, nil, reason);
248                 self_p = st.clone(base_presence):add_child(self_x);
249         end
250
251         -- General populance
252         for nick, n_occupant in self:each_occupant() do
253                 if nick ~= occupant.nick then
254                         local pr;
255                         if can_see_real_jids(whois, n_occupant) then
256                                 pr = get_full_p();
257                         elseif occupant.bare_jid == n_occupant.bare_jid then
258                                 pr = self_p;
259                         else
260                                 pr = get_anon_p();
261                         end
262                         self:route_to_occupant(n_occupant, pr);
263                 end
264         end
265
266         -- Presences for occupant itself
267         self_x:tag("status", {code = "110";}):up();
268         if occupant.role == nil then
269                 -- They get an unavailable
270                 self:route_to_occupant(occupant, self_p);
271         else
272                 -- use their own presences as templates
273                 for full_jid, pr in occupant:each_session() do
274                         pr = st.clone(pr);
275                         pr.attr.to = full_jid;
276                         pr:add_child(self_x);
277                         self:route_stanza(pr);
278                 end
279         end
280 end
281
282 function room_mt:send_occupant_list(to, filter)
283         local to_bare = jid_bare(to);
284         local is_anonymous = false;
285         local whois = self:get_whois();
286         if whois ~= "anyone" then
287                 local affiliation = self:get_affiliation(to);
288                 if affiliation ~= "admin" and affiliation ~= "owner" then
289                         local occupant = self:get_occupant_by_real_jid(to);
290                         if not (occupant and can_see_real_jids(whois, occupant)) then
291                                 is_anonymous = true;
292                         end
293                 end
294         end
295         for occupant_jid, occupant in self:each_occupant() do
296                 if filter == nil or filter(occupant_jid, occupant) then
297                         local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
298                         self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
299                         local pres = st.clone(occupant:get_presence());
300                         pres.attr.to = to;
301                         pres:add_child(x);
302                         self:route_stanza(pres);
303                 end
304         end
305 end
306
307 function room_mt:get_disco_info(stanza)
308         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
309         local form = dataform.new {
310                 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
311         };
312         module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
313         reply:add_child(form:form(nil, "result"));
314         return reply;
315 end
316 module:hook("muc-disco#info", function(event)
317         event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
318 end);
319 module:hook("muc-disco#info", function(event)
320         local count = iterators.count(event.room:each_occupant());
321         table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
322 end);
323
324 function room_mt:get_disco_items(stanza)
325         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
326         for room_jid in self:each_occupant() do
327                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
328         end
329         return reply;
330 end
331
332 function room_mt:handle_kickable(origin, stanza)
333         local real_jid = stanza.attr.from;
334         local occupant = self:get_occupant_by_real_jid(real_jid);
335         if occupant == nil then return nil; end
336         local type, condition, text = stanza:get_error();
337         local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
338         if text then
339                 error_message = error_message..": "..text;
340         end
341         occupant:set_session(real_jid, st.presence({type="unavailable"})
342                 :tag('status'):text(error_message));
343         self:save_occupant(occupant);
344         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
345                 :tag("status", {code = "307"})
346         self:publicise_occupant_status(occupant, x);
347         if occupant.jid == real_jid then -- Was last session
348                 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
349         end
350         return true;
351 end
352
353 -- Give the room creator owner affiliation
354 module:hook("muc-room-pre-create", function(event)
355         event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
356 end, -1);
357
358 -- check if user is banned
359 module:hook("muc-occupant-pre-join", function(event)
360         local room, stanza = event.room, event.stanza;
361         local affiliation = room:get_affiliation(stanza.attr.from);
362         if affiliation == "outcast" then
363                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
364                 reply.tags[1].attr.code = "403";
365                 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
366                 return true;
367         end
368 end, -10);
369
370 function room_mt:handle_presence_to_occupant(origin, stanza)
371         local type = stanza.attr.type;
372         if type == "error" then -- error, kick em out!
373                 return self:handle_kickable(origin, stanza)
374         elseif type == nil or type == "unavailable" then
375                 local real_jid = stanza.attr.from;
376                 local bare_jid = jid_bare(real_jid);
377                 local orig_occupant, dest_occupant;
378                 local is_new_room = next(self._affiliations) == nil;
379                 if is_new_room then
380                         if type == "unavailable" then return true; end -- Unavailable from someone not in the room
381                         if module:fire_event("muc-room-pre-create", {
382                                         room = self;
383                                         origin = origin;
384                                         stanza = stanza;
385                                 }) then return true; end
386                 else
387                         orig_occupant = self:get_occupant_by_real_jid(real_jid);
388                         if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
389                 end
390                 local is_first_dest_session;
391                 if type == "unavailable" then
392                         -- dest_occupant = nil
393                 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
394                         log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
395                         dest_occupant = orig_occupant;
396                 else
397                         local dest_jid = stanza.attr.to;
398                         dest_occupant = self:get_occupant_by_nick(dest_jid);
399                         if dest_occupant == nil then
400                                 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
401                                 is_first_dest_session = true;
402                                 dest_occupant = self:new_occupant(bare_jid, dest_jid);
403                         else
404                                 is_first_dest_session = false;
405                         end
406                 end
407                 local is_last_orig_session;
408                 if orig_occupant ~= nil then
409                         -- Is there are least 2 sessions?
410                         local iter, ob, last = orig_occupant:each_session();
411                         is_last_orig_session = iter(ob, iter(ob, last)) == nil;
412                 end
413
414                 local event, event_name = {
415                         room = self;
416                         origin = origin;
417                         stanza = stanza;
418                         is_first_session = is_first_dest_session;
419                         is_last_session = is_last_orig_session;
420                 };
421                 if orig_occupant == nil then
422                         event_name = "muc-occupant-pre-join";
423                         event.is_new_room = is_new_room;
424                         event.occupant = dest_occupant;
425                 elseif dest_occupant == nil then
426                         event_name = "muc-occupant-pre-leave";
427                         event.occupant = orig_occupant;
428                 else
429                         event_name = "muc-occupant-pre-change";
430                         event.orig_occupant = orig_occupant;
431                         event.dest_occupant = dest_occupant;
432                 end
433                 if module:fire_event(event_name, event) then return true; end
434
435                 -- Check for nick conflicts
436                 if dest_occupant ~= nil and not is_first_dest_session and bare_jid ~= jid_bare(dest_occupant.bare_jid) then -- new nick or has different bare real jid
437                         log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
438                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
439                         reply.tags[1].attr.code = "409";
440                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
441                         return true;
442                 end
443
444                 -- Send presence stanza about original occupant
445                 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
446                         local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
447                         local dest_nick;
448                         if dest_occupant == nil then -- Session is leaving
449                                 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
450                                 if is_last_orig_session then
451                                         orig_occupant.role = nil;
452                                 end
453                                 orig_occupant:set_session(real_jid, stanza);
454                         else
455                                 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
456                                 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
457                                 orig_occupant:set_session(real_jid, generated_unavail);
458                                 dest_nick = select(3, jid_split(dest_occupant.nick));
459                                 if not is_first_dest_session then -- User is swapping into another pre-existing session
460                                         log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
461                                         -- Show the other session leaving
462                                         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
463                                                 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
464                                         add_item(x, self:get_affiliation(bare_jid), "none");
465                                         local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
466                                                 :add_child(x);
467                                         self:route_stanza(pr);
468                                 end
469                                 if is_first_dest_session and is_last_orig_session then -- Normal nick change
470                                         log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
471                                         orig_x:tag("status", {code = "303";}):up();
472                                 else -- The session itself always needs to see a nick change
473                                         -- don't want to get our old nick's available presence,
474                                         -- so remove our session from there, and manually generate an unavailable
475                                         orig_occupant:remove_session(real_jid);
476                                         log("debug", "generating nick change for %s", real_jid);
477                                         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
478                                         -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
479                                         add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
480                                         x:tag("status", {code = "303";}):up();
481                                         x:tag("status", {code = "110";}):up();
482                                         self:route_stanza(generated_unavail:add_child(x));
483                                         dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
484                                 end
485                         end
486                         self:save_occupant(orig_occupant);
487                         self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
488
489                         if is_last_orig_session then
490                                 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick; occupant = orig_occupant;});
491                         end
492                 end
493
494                 if dest_occupant ~= nil then
495                         dest_occupant:set_session(real_jid, stanza);
496                         local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
497                         if is_new_room then
498                                 dest_x:tag("status", {code = "201"}):up();
499                         end
500                         if orig_occupant == nil and self:get_whois() == "anyone" then
501                                 dest_x:tag("status", {code = "100"}):up();
502                         end
503                         self:save_occupant(dest_occupant);
504
505                         if orig_occupant == nil then
506                                 -- Send occupant list to newly joined user
507                                 self:send_occupant_list(real_jid, function(nick, occupant)
508                                         -- Don't include self
509                                         return occupant:get_presence(real_jid) == nil;
510                                 end)
511                         end
512                         self:publicise_occupant_status(dest_occupant, dest_x);
513
514                         if orig_occupant ~= nil and orig_occupant ~= dest_occupant and not is_last_orig_session then -- If user is swapping and wasn't last original session
515                                 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
516                                 -- Show the original nick joining again
517                                 local pr = st.clone(orig_occupant:get_presence());
518                                 pr.attr.to = real_jid;
519                                 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
520                                 self:build_item_list(orig_occupant, x, false);
521                                 -- TODO: new status code to inform client this was the multi-session it left?
522                                 pr:add_child(x);
523                                 self:route_stanza(pr);
524                         end
525
526                         if orig_occupant == nil then
527                                 if is_first_dest_session then
528                                         module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; occupant = dest_occupant;});
529                                 end
530                                 module:fire_event("muc-occupant-session-new", {room = self; nick = dest_occupant.nick; occupant = dest_occupant; stanza = stanza; jid = real_jid;});
531                         end
532                 end
533         elseif type ~= 'result' then -- bad type
534                 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
535                         origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
536                 end
537         end
538         return true;
539 end
540
541 function room_mt:handle_iq_to_occupant(origin, stanza)
542         local from, to = stanza.attr.from, stanza.attr.to;
543         local type = stanza.attr.type;
544         local id = stanza.attr.id;
545         local occupant = self:get_occupant_by_nick(to);
546         if (type == "error" or type == "result") then
547                 do -- deconstruct_stanza_id
548                         if not occupant then return nil; end
549                         local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(%Z+)%z(%Z*)%z(.+)$");
550                         if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
551                         local from_occupant_jid = self:get_occupant_jid(from_jid);
552                         if from_occupant_jid == nil then return nil; end
553                         local session_jid
554                         for to_jid in occupant:each_session() do
555                                 if md5(to_jid) == to_jid_hash then
556                                         session_jid = to_jid;
557                                         break;
558                                 end
559                         end
560                         if session_jid == nil then return nil; end
561                         stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, id;
562                 end
563                 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
564                 self:route_stanza(stanza);
565                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
566                 return true;
567         else -- Type is "get" or "set"
568                 local current_nick = self:get_occupant_jid(from);
569                 if not current_nick then
570                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
571                         return true;
572                 end
573                 if not occupant then -- recipient not in room
574                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
575                         return true;
576                 end
577                 do -- construct_stanza_id
578                         stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
579                 end
580                 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
581                 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
582                 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
583                         stanza.attr.to = jid_bare(stanza.attr.to);
584                 end
585                 self:route_stanza(stanza);
586                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
587                 return true;
588         end
589 end
590
591 function room_mt:handle_message_to_occupant(origin, stanza)
592         local from, to = stanza.attr.from, stanza.attr.to;
593         local current_nick = self:get_occupant_jid(from);
594         local type = stanza.attr.type;
595         if not current_nick then -- not in room
596                 if type ~= "error" then
597                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
598                 end
599                 return true;
600         end
601         if type == "groupchat" then -- groupchat messages not allowed in PM
602                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
603                 return true;
604         elseif type == "error" and is_kickable_error(stanza) then
605                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
606                 return self:handle_kickable(origin, stanza); -- send unavailable
607         end
608
609         local o_data = self:get_occupant_by_nick(to);
610         if not o_data then
611                 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
612                 return true;
613         end
614         log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
615         stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
616         stanza.attr.from = current_nick;
617         self:route_to_occupant(o_data, stanza)
618         -- TODO: Remove x tag?
619         stanza.attr.from = from;
620         return true;
621 end
622
623 function room_mt:send_form(origin, stanza)
624         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
625                 :add_child(self:get_form_layout(stanza.attr.from):form())
626         );
627 end
628
629 function room_mt:get_form_layout(actor)
630         local form = dataform.new({
631                 title = "Configuration for "..self.jid,
632                 instructions = "Complete and submit this form to configure the room.",
633                 {
634                         name = 'FORM_TYPE',
635                         type = 'hidden',
636                         value = 'http://jabber.org/protocol/muc#roomconfig'
637                 }
638         });
639         return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
640 end
641
642 function room_mt:process_form(origin, stanza)
643         local form = stanza.tags[1]:get_child("x", "jabber:x:data");
644         if form.attr.type == "cancel" then
645                 origin.send(st.reply(stanza));
646         elseif form.attr.type == "submit" then
647                 local fields, errors, present;
648                 if form.tags[1] == nil then -- Instant room
649                         fields, present = {}, {};
650                 else
651                         fields, errors, present = self:get_form_layout(stanza.attr.from):data(form);
652                         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
653                                 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
654                                 return true;
655                         end
656                 end
657
658                 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
659                 function event.update_option(name, field, allowed)
660                         local new = fields[field];
661                         if new == nil then return; end
662                         if allowed and not allowed[new] then return; end
663                         if new == self["get_"..name](self) then return; end
664                         event.status_codes["104"] = true;
665                         self["set_"..name](self, new);
666                         return true;
667                 end
668                 module:fire_event("muc-config-submitted", event);
669                 for submitted_field in pairs(present) do
670                         event.field, event.value = submitted_field, fields[submitted_field];
671                         module:fire_event("muc-config-submitted/"..submitted_field, event);
672                 end
673                 event.field, event.value = nil, nil;
674
675                 if self.save then self:save(true); end
676                 origin.send(st.reply(stanza));
677
678                 if next(event.status_codes) then
679                         local msg = st.message({type='groupchat', from=self.jid})
680                                 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
681                         for code in pairs(event.status_codes) do
682                                 msg:tag("status", {code = code;}):up();
683                         end
684                         msg:up();
685                         self:broadcast_message(msg);
686                 end
687         else
688                 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
689         end
690         return true;
691 end
692
693 -- Removes everyone from the room
694 function room_mt:clear(x)
695         x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
696         local occupants_updated = {};
697         for nick, occupant in self:each_occupant() do
698                 occupant.role = nil;
699                 self:save_occupant(occupant);
700                 occupants_updated[occupant] = true;
701         end
702         for occupant in pairs(occupants_updated) do
703                 self:publicise_occupant_status(occupant, x);
704                 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
705         end
706 end
707
708 function room_mt:destroy(newjid, reason, password)
709         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
710                 :tag("item", { affiliation='none', role='none' }):up()
711                 :tag("destroy", {jid=newjid});
712         if reason then x:tag("reason"):text(reason):up(); end
713         if password then x:tag("password"):text(password):up(); end
714         x:up();
715         self:clear(x);
716         module:fire_event("muc-room-destroyed", { room = self });
717 end
718
719 function room_mt:handle_disco_info_get_query(origin, stanza)
720         origin.send(self:get_disco_info(stanza));
721         return true;
722 end
723
724 function room_mt:handle_disco_items_get_query(origin, stanza)
725         origin.send(self:get_disco_items(stanza));
726         return true;
727 end
728
729 function room_mt:handle_admin_query_set_command(origin, stanza)
730         local item = stanza.tags[1].tags[1];
731         if not item then
732                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
733         end
734         if item.attr.jid then -- Validate provided JID
735                 item.attr.jid = jid_prep(item.attr.jid);
736                 if not item.attr.jid then
737                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
738                         return true;
739                 end
740         end
741         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
742                 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
743                 if occupant then item.attr.jid = occupant.jid; end
744         elseif not item.attr.nick and item.attr.jid then
745                 local nick = self:get_occupant_jid(item.attr.jid);
746                 if nick then item.attr.nick = select(3, jid_split(nick)); end
747         end
748         local actor = stanza.attr.from;
749         local reason = item:get_child_text("reason");
750         local success, errtype, err
751         if item.attr.affiliation and item.attr.jid and not item.attr.role then
752                 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
753         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
754                 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
755         else
756                 success, errtype, err = nil, "cancel", "bad-request";
757         end
758         if not success then
759                 origin.send(st.error_reply(stanza, errtype, err));
760         else
761                 origin.send(st.reply(stanza));
762         end
763         return true;
764 end
765
766 function room_mt:handle_admin_query_get_command(origin, stanza)
767         local actor = stanza.attr.from;
768         local affiliation = self:get_affiliation(actor);
769         local item = stanza.tags[1].tags[1];
770         local _aff = item.attr.affiliation;
771         local _aff_rank = valid_affiliations[_aff or "none"];
772         local _rol = item.attr.role;
773         if _aff and _aff_rank and not _rol then
774                 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
775                 -- e.g. an admin can't ask for a list of owners
776                 local affiliation_rank = valid_affiliations[affiliation or "none"];
777                 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
778                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
779                         for jid in self:each_affiliation(_aff or "none") do
780                                 reply:tag("item", {affiliation = _aff, jid = jid}):up();
781                         end
782                         origin.send(reply:up());
783                         return true;
784                 else
785                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
786                         return true;
787                 end
788         elseif _rol and valid_roles[_rol or "none"] and not _aff then
789                 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
790                 if valid_roles[role or "none"] >= valid_roles.moderator then
791                         if _rol == "none" then _rol = nil; end
792                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
793                         -- TODO: whois check here? (though fully anonymous rooms are not supported)
794                         for occupant_jid, occupant in self:each_occupant() do
795                                 if occupant.role == _rol then
796                                         local nick = select(3,jid_split(occupant_jid));
797                                         self:build_item_list(occupant, reply, false, nick);
798                                 end
799                         end
800                         origin.send(reply:up());
801                         return true;
802                 else
803                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
804                         return true;
805                 end
806         else
807                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
808                 return true;
809         end
810 end
811
812 function room_mt:handle_owner_query_get_to_room(origin, stanza)
813         if self:get_affiliation(stanza.attr.from) ~= "owner" then
814                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
815                 return true;
816         end
817
818         self:send_form(origin, stanza);
819         return true;
820 end
821 function room_mt:handle_owner_query_set_to_room(origin, stanza)
822         if self:get_affiliation(stanza.attr.from) ~= "owner" then
823                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
824                 return true;
825         end
826
827         local child = stanza.tags[1].tags[1];
828         if not child then
829                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
830                 return true;
831         elseif child.name == "destroy" then
832                 local newjid = child.attr.jid;
833                 local reason = child:get_child_text("reason");
834                 local password = child:get_child_text("password");
835                 self:destroy(newjid, reason, password);
836                 origin.send(st.reply(stanza));
837                 return true;
838         elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
839                 return self:process_form(origin, stanza);
840         else
841                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
842                 return true;
843         end
844 end
845
846 function room_mt:handle_groupchat_to_room(origin, stanza)
847         local from = stanza.attr.from;
848         local occupant = self:get_occupant_by_real_jid(from);
849         if module:fire_event("muc-occupant-groupchat", {
850                 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
851         }) then return true; end
852         stanza.attr.from = occupant.nick;
853         self:broadcast_message(stanza);
854         stanza.attr.from = from;
855         return true;
856 end
857
858 -- Role check
859 module:hook("muc-occupant-groupchat", function(event)
860         local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
861         if role_rank <= valid_roles.none then
862                 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
863                 return true;
864         elseif role_rank <= valid_roles.visitor then
865                 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
866                 return true;
867         end
868 end, 50);
869
870 -- hack - some buggy clients send presence updates to the room rather than their nick
871 function room_mt:handle_presence_to_room(origin, stanza)
872         local current_nick = self:get_occupant_jid(stanza.attr.from);
873         local handled
874         if current_nick then
875                 local to = stanza.attr.to;
876                 stanza.attr.to = current_nick;
877                 handled = self:handle_presence_to_occupant(origin, stanza);
878                 stanza.attr.to = to;
879         end
880         return handled;
881 end
882
883 -- Need visitor role or higher to invite
884 module:hook("muc-pre-invite", function(event)
885         local room, stanza = event.room, event.stanza;
886         local _from, _to = stanza.attr.from, stanza.attr.to;
887         local inviter = room:get_occupant_by_real_jid(_from);
888         local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
889         if valid_roles[role or "none"] <= valid_roles.visitor then
890                 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
891                 return true;
892         end
893 end);
894
895 function room_mt:handle_mediated_invite(origin, stanza)
896         local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
897         local invitee = jid_prep(payload.attr.to);
898         if not invitee then
899                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
900                 return true;
901         elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
902                 return true;
903         end
904         local invite = muc_util.filter_muc_x(st.clone(stanza));
905         invite.attr.from = self.jid;
906         invite.attr.to = invitee;
907         invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
908                         :tag('invite', {from = stanza.attr.from;})
909                                 :tag('reason'):text(payload:get_child_text("reason")):up()
910                         :up()
911                 :up();
912         if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
913                 self:route_stanza(invite);
914         end
915         return true;
916 end
917
918 -- COMPAT: Some older clients expect this
919 module:hook("muc-invite", function(event)
920         local room, stanza = event.room, event.stanza;
921         local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
922         local reason = invite:get_child_text("reason");
923         stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
924                 :text(reason or "")
925         :up();
926 end);
927
928 -- Add a plain message for clients which don't support invites
929 module:hook("muc-invite", function(event)
930         local room, stanza = event.room, event.stanza;
931         if not stanza:get_child("body") then
932                 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
933                 local reason = invite:get_child_text("reason") or "";
934                 stanza:tag("body")
935                         :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
936                 :up();
937         end
938 end);
939
940 function room_mt:handle_mediated_decline(origin, stanza)
941         local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
942         local declinee = jid_prep(payload.attr.to);
943         if not declinee then
944                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
945                 return true;
946         elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
947                 return true;
948         end
949         local decline = muc_util.filter_muc_x(st.clone(stanza));
950         decline.attr.from = self.jid;
951         decline.attr.to = declinee;
952         decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
953                         :tag("decline", {from = stanza.attr.from})
954                                 :tag("reason"):text(payload:get_child_text("reason")):up()
955                         :up()
956                 :up();
957         if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
958                 local declinee = decline.attr.to; -- re-fetch, in case event modified it
959                 local occupant
960                 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
961                         occupant = self:get_occupant_by_nick(declinee);
962                 end
963                 if occupant then
964                         self:route_to_occupant(occupant, decline);
965                 else
966                         self:route_stanza(decline);
967                 end
968         end
969         return true;
970 end
971
972 -- Add a plain message for clients which don't support declines
973 module:hook("muc-decline", function(event)
974         local room, stanza = event.room, event.stanza;
975         if not stanza:get_child("body") then
976                 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
977                 local reason = decline:get_child_text("reason") or "";
978                 stanza:tag("body")
979                         :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
980                 :up();
981         end
982 end);
983
984 function room_mt:handle_message_to_room(origin, stanza)
985         local type = stanza.attr.type;
986         if type == "groupchat" then
987                 return self:handle_groupchat_to_room(origin, stanza)
988         elseif type == "error" and is_kickable_error(stanza) then
989                 return self:handle_kickable(origin, stanza)
990         elseif type == nil then
991                 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
992                 if x then
993                         local payload = x.tags[1];
994                         if payload == nil then
995                                 -- fallthrough
996                         elseif payload.name == "invite" and payload.attr.to then
997                                 return self:handle_mediated_invite(origin, stanza)
998                         elseif payload.name == "decline" and payload.attr.to then
999                                 return self:handle_mediated_decline(origin, stanza)
1000                         end
1001                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1002                         return true;
1003                 end
1004         end
1005 end
1006
1007 function room_mt:route_stanza(stanza)
1008         module:send(stanza);
1009 end
1010
1011 function room_mt:get_affiliation(jid)
1012         local node, host, resource = jid_split(jid);
1013         local bare = node and node.."@"..host or host;
1014         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1015         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1016         return result;
1017 end
1018
1019 -- Iterates over jid, affiliation pairs
1020 function room_mt:each_affiliation(with_affiliation)
1021         if not with_affiliation then
1022                 return pairs(self._affiliations);
1023         else
1024                 return function(_affiliations, jid)
1025                         local affiliation;
1026                         repeat -- Iterate until we get a match
1027                                 jid, affiliation = next(_affiliations, jid);
1028                         until jid == nil or affiliation == with_affiliation
1029                         return jid, affiliation;
1030                 end, self._affiliations, nil
1031         end
1032 end
1033
1034 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1035         if not actor then return nil, "modify", "not-acceptable"; end;
1036
1037         local node, host, resource = jid_split(jid);
1038         if not host then return nil, "modify", "not-acceptable"; end
1039         jid = jid_join(node, host); -- Bare
1040         local is_host_only = node == nil;
1041
1042         if valid_affiliations[affiliation or "none"] == nil then
1043                 return nil, "modify", "not-acceptable";
1044         end
1045         affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1046
1047         local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1048         local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1049
1050         if actor == true then
1051                 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1052         else
1053                 local actor_affiliation = self:get_affiliation(actor);
1054                 if actor_affiliation == "owner" then
1055                         if jid_bare(actor) == jid then -- self change
1056                                 -- need at least one owner
1057                                 local is_last = true;
1058                                 for j in self:each_affiliation("owner") do
1059                                         if j ~= jid then is_last = false; break; end
1060                                 end
1061                                 if is_last then
1062                                         return nil, "cancel", "conflict";
1063                                 end
1064                         end
1065                         -- owners can do anything else
1066                 elseif affiliation == "owner" or affiliation == "admin"
1067                         or actor_affiliation ~= "admin"
1068                         or target_affiliation == "owner" or target_affiliation == "admin" then
1069                         -- Can't demote owners or other admins
1070                         return nil, "cancel", "not-allowed";
1071                 end
1072         end
1073
1074         -- Set in 'database'
1075         self._affiliations[jid] = affiliation;
1076
1077         -- Update roles
1078         local role = self:get_default_role(affiliation);
1079         local role_rank = valid_roles[role or "none"];
1080         local occupants_updated = {}; -- Filled with old roles
1081         for nick, occupant in self:each_occupant() do
1082                 if occupant.bare_jid == jid or (
1083                         -- Outcast can be by host.
1084                         is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1085                 ) then
1086                         -- need to publcize in all cases; as affiliation in <item/> has changed.
1087                         occupants_updated[occupant] = occupant.role;
1088                         if occupant.role ~= role and (
1089                                 is_downgrade or
1090                                 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1091                         ) then
1092                                 occupant.role = role;
1093                                 self:save_occupant(occupant);
1094                         end
1095                 end
1096         end
1097
1098         -- Tell the room of the new occupant affiliations+roles
1099         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1100         if not role then -- getting kicked
1101                 if affiliation == "outcast" then
1102                         x:tag("status", {code="301"}):up(); -- banned
1103                 else
1104                         x:tag("status", {code="321"}):up(); -- affiliation change
1105                 end
1106         end
1107         local is_semi_anonymous = self:get_whois() == "moderators";
1108         for occupant, old_role in pairs(occupants_updated) do
1109                 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1110                 if occupant.role == nil then
1111                         module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1112                 elseif is_semi_anonymous and
1113                         (old_role == "moderator" and occupant.role ~= "moderator") or
1114                         (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1115                         -- Send everyone else's presences (as jid visibility has changed)
1116                         for real_jid in occupant:each_session() do
1117                                 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1118                                         return occupant.bare_jid ~= jid;
1119                                 end);
1120                         end
1121                 end
1122         end
1123
1124         if self.save then self:save(); end
1125
1126         module:fire_event("muc-set-affiliation", {
1127                 room = self;
1128                 actor = actor;
1129                 jid = jid;
1130                 affiliation = affiliation or "none";
1131                 reason = reason;
1132                 previous_affiliation = target_affiliation;
1133                 in_room = next(occupants_updated) ~= nil;
1134         });
1135
1136         return true;
1137 end
1138
1139 function room_mt:get_role(nick)
1140         local occupant = self:get_occupant_by_nick(nick);
1141         return occupant and occupant.role or nil;
1142 end
1143
1144 function room_mt:set_role(actor, occupant_jid, role, reason)
1145         if not actor then return nil, "modify", "not-acceptable"; end
1146
1147         local occupant = self:get_occupant_by_nick(occupant_jid);
1148         if not occupant then return nil, "modify", "not-acceptable"; end
1149
1150         if valid_roles[role or "none"] == nil then
1151                 return nil, "modify", "not-acceptable";
1152         end
1153         role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1154
1155         if actor == true then
1156                 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1157         else
1158                 -- Can't do anything to other owners or admins
1159                 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1160                 if occupant_affiliation == "owner" or occupant_affiliation == "admin" then
1161                         return nil, "cancel", "not-allowed";
1162                 end
1163
1164                 -- If you are trying to give or take moderator role you need to be an owner or admin
1165                 if occupant.role == "moderator" or role == "moderator" then
1166                         local actor_affiliation = self:get_affiliation(actor);
1167                         if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1168                                 return nil, "cancel", "not-allowed";
1169                         end
1170                 end
1171
1172                 -- Need to be in the room and a moderator
1173                 local actor_occupant = self:get_occupant_by_real_jid(actor);
1174                 if not actor_occupant or actor_occupant.role ~= "moderator" then
1175                         return nil, "cancel", "not-allowed";
1176                 end
1177         end
1178
1179         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1180         if not role then
1181                 x:tag("status", {code = "307"}):up();
1182         end
1183         occupant.role = role;
1184         self:save_occupant(occupant);
1185         self:publicise_occupant_status(occupant, x, nil, actor, reason);
1186         if role == nil then
1187                 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1188         end
1189         return true;
1190 end
1191
1192 local whois = module:require "muc/whois";
1193 room_mt.get_whois = whois.get;
1194 room_mt.set_whois = whois.set;
1195
1196 local _M = {}; -- module "muc"
1197
1198 function _M.new_room(jid, config)
1199         return setmetatable({
1200                 jid = jid;
1201                 _jid_nick = {};
1202                 _occupants = {};
1203                 _data = {
1204                 };
1205                 _affiliations = {};
1206         }, room_mt);
1207 end
1208
1209 _M.room_mt = room_mt;
1210
1211 return _M;