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