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