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